code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
namespace DSInternals.Common.Interop
{
using System;
/// <summary>
/// Access rights for registry key objects.
/// </summary>
[Flags]
public enum RegistryKeyRights : int
{
/// <summary>
/// Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights.
/// </summary>
AllAccess = 0xF003F,
/// <summary>
/// Reserved for system use.
/// </summary>
CreateLink = 0x0020,
/// <summary>
/// Required to create a subkey of a registry key.
/// </summary>
CreateSubKey = 0x0004,
/// <summary>
/// Required to enumerate the subkeys of a registry key.
/// </summary>
EnumerateSubKeys = 0x0008,
/// <summary>
/// Equivalent to KEY_READ.
/// </summary>
Execute = Read,
/// <summary>
/// Required to request change notifications for a registry key or for subkeys of a registry key.
/// </summary>
Notify = 0x0010,
/// <summary>
/// Required to query the values of a registry key.
/// </summary>
QueryValue = 0x0001,
/// <summary>
/// Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
/// </summary>
Read = 0x20019,
/// <summary>
/// Required to create, delete, or set a registry value.
/// </summary>
SetValue = 0x0002,
/// <summary>
/// Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. This flag is ignored by 32-bit Windows.
/// </summary>
Wow6432Key = 0x0200,
/// <summary>
/// Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. This flag is ignored by 32-bit Windows.
/// </summary>
Wow6464Key = 0x0100,
/// <summary>
/// Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.
/// </summary>
Write = 0x20006
}
}
|
MichaelGrafnetter/DSInternals
|
Src/DSInternals.Common/Interop/Enums/RegistryKeyRights.cs
|
C#
|
mit
| 2,199
|
{% extends "base.html" %}
{% block head %}
{{ super() }}
<script>
function updatetemp() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/updatetemp",
success : function(result){
$('#indoorTempDiv').html(result);
}
})
};
function updateRH() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/updateRH",
success : function(result){
$('#indoorRHDiv').html(result);
}
})
};
function updateOuttemp() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/updateOuttemp",
success : function(result){
$('#outdoorTempDiv').html(result);
}
})
};
function updateOutRH() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/updateOutRH",
success : function(result){
$('#outdoorRHDiv').html(result);
}
})
};
function run_AC() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/run_AC",
success : function(result){
$('#run_AC').html(result);
}
})
};
function cpu_temp() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.ajax({
url : $SCRIPT_ROOT + "/cputemp",
success : function(result){
$('#cpu_temp').html(result);
}
})
};
window.setInterval(function(){
updatetemp()
updateRH()
updateOuttemp()
updateOutRH()
run_AC()
cpu_temp()
}, 100000);
updatetemp()
updateRH()
updateOuttemp()
updateOutRH()
run_AC()
cpu_temp()
</script>
{% endblock %}
{% block content %}
<div class="container">
<table class="table" style="width:50px">
<tr>
<th></th>
<th>Temp</th>
<th>Humidity</th>
</tr>
<tr>
<th>Indoor</th>
<td><span id="indoorTempDiv"></span>°F</td>
<td><span id="indoorRHDiv"></span>%</td>
</tr>
<tr>
<th>Outdoor</th>
<td><span id="outdoorTempDiv"></span>°F</td>
<td><span id="outdoorRHDiv"></span>%</td>
</tr>
</table>
<h3>System:</h3><span id="run_AC"></span>
<h3>CPU Temp:</h3><span id="cpu_temp"></span>°F/185°F
<form action="/index" method="POST" >
<h3>Mode</h3>
{% if mode == "cool" %}
<input type="radio" name="mode" value="cool" checked>Cool<br>
<input type="radio" name="mode" value="heat">Heat<br>
<input type="radio" name="mode" value="fan">Fan<br>
<input type="radio" name="mode" value="off">Off<br>
{% elif mode == "heat" %}
<input type="radio" name="mode" value="cool">Cool<br>
<input type="radio" name="mode" value="heat" checked>Heat<br>
<input type="radio" name="mode" value="fan">Fan<br>
<input type="radio" name="mode" value="off">Off<br>
{% elif mode == "fan" %}
<input type="radio" name="mode" value="cool">Cool<br>
<input type="radio" name="mode" value="heat">Heat<br>
<input type="radio" name="mode" value="fan" checked>Fan<br>
<input type="radio" name="mode" value="off">Off<br>
{% else %}
<input type="radio" name="mode" value="cool">Cool<br>
<input type="radio" name="mode" value="heat">Heat<br>
<input type="radio" name="mode" value="fan">Fan<br>
<input type="radio" name="mode" value="off" checked>Off<br>
{% endif %}
<br>
<h3>State</h3>
{% if state == "auto" %}
<input type="radio" name="state" value="auto" checked>Auto<br>
<input type="radio" name="state" value="here">Here<br>
<input type="radio" name="state" value="away">Away<br>
{% elif state == "here" %}
<input type="radio" name="state" value="auto">Auto<br>
<input type="radio" name="state" value="here" checked>Here<br>
<input type="radio" name="state" value="away">Away<br>
{% else %}
<input type="radio" name="state" value="auto">Auto<br>
<input type="radio" name="state" value="here">Here<br>
<input type="radio" name="state" value="away" checked>Away<br>
{% endif %}
<h3>Away Setting</h3>
{% if set_away == "auto" %}
<input type="radio" name="set_away" value="auto" checked>Auto<br>
<input type="radio" name="set_away" value="off">Off<br>
{% else %}
<input type="radio" name="set_away" value="auto">Auto<br>
<input type="radio" name="set_away" value="off" checked>Off<br>
{% endif %}
<br>
<div class="input-group imput-group-lg" style="padding:10px">
<span class="input-group-addon">Here</span>
<input type="text" style='width:4em' class="form-control" name="set_temp" size=2 value="{{set_temp}}"/>
</div>
<div class="input-group imput-group-lg" style="padding:10px">
<span class="input-group-addon">Away</span>
<input type="text" style='width:4em' class="form-control" name="set_away_temp" value="{{set_away_temp}}">
</div>
<button type="submit" name="submit" class="btn btn-primary btn-lg" style="padding:10px" value="temp">Go</button>
<button type="submit" name="submit" class="btn btn-primary btn-lg" style="padding:10px" value="Garage">Garage</button>
</form>
<img class="img-responsive" style="padding-top:10px; padding-bottom:10px" src="/static/image.jpg" alt="camera">
<img class="img-responsive" style="padding-top:10px; padding-bottom:10px" src="/static/graph.png" alt="graph">
</div>
{% endblock %}
|
mdarty/thermostat
|
templates/index.html
|
HTML
|
mit
| 5,997
|
exports.BattleScripts = {
init: function() {
for (var i in this.data.Pokedex) {
var template = this.getTemplate(i);
var newStats = {
hp: template.id === 'shedinja' ? 1 : this.clampIntRange(150 - template.baseStats.hp, 5, 145),
atk: this.clampIntRange(150 - template.baseStats.atk, 5, 145),
def: this.clampIntRange(150 - template.baseStats.def, 5, 145),
spa: this.clampIntRange(150 - template.baseStats.spa, 5, 145),
spd: this.clampIntRange(150 - template.baseStats.spd, 5, 145),
spe: this.clampIntRange(150 - template.baseStats.spe, 5, 145)
}
this.modData('Pokedex', i).baseStats = newStats;
}
}
};
|
Pikachuun/Joimmon-Showdown
|
mods/negative/scripts.js
|
JavaScript
|
mit
| 642
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
namespace Rally.RestApi
{
public class DynamicJsonSerializer
{
readonly JavaScriptSerializer deSerializer;
public DynamicJsonSerializer()
{
deSerializer = new JavaScriptSerializer();
deSerializer.MaxJsonLength = int.MaxValue;
deSerializer.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
}
// as dynamic
public DynamicJsonObject Deserialize(string json)
{
return deSerializer.Deserialize(json, typeof(object)) as DynamicJsonObject;
}
public string Serialize(DynamicJsonObject value)
{
return SerializeDictionary(value.Dictionary);
}
public string SerializeDictionary(IDictionary<string, object> dictionary)
{
var builder = new StringBuilder();
builder.Append("{");
var first = true;
foreach (var key in dictionary.Keys)
{
if (first) first = false;
else builder.Append(",");
builder.Append("\"");
builder.Append(key);
builder.Append("\"");
builder.Append(":");
if (dictionary[key] is IDictionary<string, object>)
builder.Append(SerializeDictionary(dictionary[key] as IDictionary<string, object>));
else if (dictionary[key] is ArrayList)
builder.Append(SerializeArray(dictionary[key] as ArrayList));
else
builder.Append(SerializeObject(dictionary[key]));
}
builder.Append("}");
return builder.ToString();
}
private string SerializeArray(ArrayList list)
{
var builder = new StringBuilder();
var first = true;
builder.Append("[");
foreach (var obj in list)
{
if (first) first = false;
else builder.Append(",");
if (obj is IDictionary<string, object>)
{
builder.Append(SerializeDictionary(obj as IDictionary<string, object>));
}
else if (obj is ArrayList)
{
builder.Append(SerializeArray(obj as ArrayList));
}
else
{
builder.Append(SerializeObject(obj));
}
}
builder.Append("]");
return builder.ToString();
}
private static string SerializeObject(object obj)
{
if (obj is string)
{
return "\"" + ((String)obj).Replace("\"", "\\\"") + "\"";
}
return obj.ToString();
}
}
}
|
Streeter1981/RallyRestToolkitFor.NET-master
|
Rally.RestApi/DynamicJsonSerializer.cs
|
C#
|
mit
| 2,959
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hoare-tut: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.0 / hoare-tut - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hoare-tut
<small>
8.6.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-09-25 05:58:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-25 05:58:45 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.0 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/hoare-tut"
license: "GNU LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/HoareTut"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: Hoare logic" "keyword: imperative program" "keyword: weakest precondition" "keyword: reflection" "category: Mathematics/Logic/See also" "category: Computer Science/Semantics and Compilation/Semantics" "date: 2007" ]
authors: [ "Sylvain Boulmé <Sylvain.Boulme@imag.fr> [http://www-verimag.imag.fr/~boulme]" ]
bug-reports: "https://github.com/coq-contribs/hoare-tut/issues"
dev-repo: "git+https://github.com/coq-contribs/hoare-tut.git"
synopsis: "A Tutorial on Reflecting in Coq the generation of Hoare proof obligations"
description: """
http://www-verimag.imag.fr/~boulme/HOARE_LOGIC_TUTORIAL/
This work is both an introduction to Hoare logic and a demo
illustrating Coq nice features. It formalizes the generation of PO
(proof obligations) in a Hoare logic for a very basic imperative
programming language. It proves the soundness and the completeness of
the PO generation both in partial and total correctness. At last, it
examplifies on a very simple example (a GCD computation) how the PO
generation can simplify concrete proofs. Coq is indeed able to compute
PO on concrete programs: we say here that the generation of proof
obligations is reflected in Coq. Technically, the PO generation is
here performed through Dijkstra's weakest-precondition calculus."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/hoare-tut/archive/v8.6.0.tar.gz"
checksum: "md5=4514a0cdd8defc05ecefd70133d27cef"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hoare-tut.8.6.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0).
The following dependencies couldn't be met:
- coq-hoare-tut -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hoare-tut.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.07.1-2.0.1/released/8.10.0/hoare-tut/8.6.0.html
|
HTML
|
mit
| 7,644
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.pipeline import ClientRawResponse
from .. import models
class Paths(object):
"""Paths operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def get_boolean_true(
self, bool_path=False, custom_headers=None, raw=False, **operation_config):
"""
Get true Boolean value on path
:param bool_path: true boolean value
:type bool_path: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/bool/true/{boolPath}'
path_format_arguments = {
'boolPath': self._serialize.url("bool_path", bool_path, 'bool')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_boolean_false(
self, bool_path=False, custom_headers=None, raw=False, **operation_config):
"""
Get false Boolean value on path
:param bool_path: false boolean value
:type bool_path: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/bool/false/{boolPath}'
path_format_arguments = {
'boolPath': self._serialize.url("bool_path", bool_path, 'bool')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_int_one_million(
self, int_path=1000000, custom_headers=None, raw=False, **operation_config):
"""
Get '1000000' integer value
:param int_path: '1000000' integer value
:type int_path: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/1000000/{intPath}'
path_format_arguments = {
'intPath': self._serialize.url("int_path", int_path, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_int_negative_one_million(
self, int_path=-1000000, custom_headers=None, raw=False, **operation_config):
"""
Get '-1000000' integer value
:param int_path: '-1000000' integer value
:type int_path: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/-1000000/{intPath}'
path_format_arguments = {
'intPath': self._serialize.url("int_path", int_path, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_ten_billion(
self, long_path=10000000000, custom_headers=None, raw=False, **operation_config):
"""
Get '10000000000' 64 bit integer value
:param long_path: '10000000000' 64 bit integer value
:type long_path: long
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/long/10000000000/{longPath}'
path_format_arguments = {
'longPath': self._serialize.url("long_path", long_path, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_negative_ten_billion(
self, long_path=-10000000000, custom_headers=None, raw=False, **operation_config):
"""
Get '-10000000000' 64 bit integer value
:param long_path: '-10000000000' 64 bit integer value
:type long_path: long
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/long/-10000000000/{longPath}'
path_format_arguments = {
'longPath': self._serialize.url("long_path", long_path, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def float_scientific_positive(
self, float_path=1.034E+20, custom_headers=None, raw=False, **operation_config):
"""
Get '1.034E+20' numeric value
:param float_path: '1.034E+20'numeric value
:type float_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/float/1.034E+20/{floatPath}'
path_format_arguments = {
'floatPath': self._serialize.url("float_path", float_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def float_scientific_negative(
self, float_path=-1.034E-20, custom_headers=None, raw=False, **operation_config):
"""
Get '-1.034E-20' numeric value
:param float_path: '-1.034E-20'numeric value
:type float_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/float/-1.034E-20/{floatPath}'
path_format_arguments = {
'floatPath': self._serialize.url("float_path", float_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def double_decimal_positive(
self, double_path=9999999.999, custom_headers=None, raw=False, **operation_config):
"""
Get '9999999.999' numeric value
:param double_path: '9999999.999'numeric value
:type double_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/double/9999999.999/{doublePath}'
path_format_arguments = {
'doublePath': self._serialize.url("double_path", double_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def double_decimal_negative(
self, double_path=-9999999.999, custom_headers=None, raw=False, **operation_config):
"""
Get '-9999999.999' numeric value
:param double_path: '-9999999.999'numeric value
:type double_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/double/-9999999.999/{doublePath}'
path_format_arguments = {
'doublePath': self._serialize.url("double_path", double_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_unicode(
self, string_path="啊齄丂狛狜隣郎隣兀﨩", custom_headers=None, raw=False, **operation_config):
"""
Get '啊齄丂狛狜隣郎隣兀﨩' multi-byte string value
:param string_path: '啊齄丂狛狜隣郎隣兀﨩'multi-byte string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/unicode/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_url_encoded(
self, string_path="begin!*'();:@ &=+$,/?#[]end", custom_headers=None, raw=False, **operation_config):
"""
Get 'begin!*'();:@ &=+$,/?#[]end
:param string_path: 'begin!*'();:@ &=+$,/?#[]end' url encoded string
value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_empty(
self, string_path="", custom_headers=None, raw=False, **operation_config):
"""
Get ''
:param string_path: '' string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/empty/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_null(
self, string_path, custom_headers=None, raw=False, **operation_config):
"""
Get null (should throw)
:param string_path: null string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/null/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def enum_valid(
self, enum_path, custom_headers=None, raw=False, **operation_config):
"""
Get using uri with 'green color' in path parameter
:param enum_path: send the value green. Possible values include: 'red
color', 'green color', 'blue color'
:type enum_path: str or :class:`UriColor
<fixtures.acceptancetestsurl.models.UriColor>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/enum/green%20color/{enumPath}'
path_format_arguments = {
'enumPath': self._serialize.url("enum_path", enum_path, 'UriColor')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def enum_null(
self, enum_path, custom_headers=None, raw=False, **operation_config):
"""
Get null (should throw on the client before the request is sent on
wire)
:param enum_path: send null should throw. Possible values include:
'red color', 'green color', 'blue color'
:type enum_path: str or :class:`UriColor
<fixtures.acceptancetestsurl.models.UriColor>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/null/{enumPath}'
path_format_arguments = {
'enumPath': self._serialize.url("enum_path", enum_path, 'UriColor')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_multi_byte(
self, byte_path, custom_headers=None, raw=False, **operation_config):
"""
Get '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array
:param byte_path: '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte
array
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/multibyte/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_empty(
self, byte_path=bytearray("", encoding="utf-8"), custom_headers=None, raw=False, **operation_config):
"""
Get '' as byte array
:param byte_path: '' as byte array
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/empty/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_null(
self, byte_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as byte array (should throw)
:param byte_path: null as byte array (should throw)
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/null/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_valid(
self, date_path, custom_headers=None, raw=False, **operation_config):
"""
Get '2012-01-01' as date
:param date_path: '2012-01-01' as date
:type date_path: date
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/date/2012-01-01/{datePath}'
path_format_arguments = {
'datePath': self._serialize.url("date_path", date_path, 'date')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_null(
self, date_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as date - this should throw or be unusable on the client
side, depending on date representation
:param date_path: null as date (should throw)
:type date_path: date
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/date/null/{datePath}'
path_format_arguments = {
'datePath': self._serialize.url("date_path", date_path, 'date')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_time_valid(
self, date_time_path, custom_headers=None, raw=False, **operation_config):
"""
Get '2012-01-01T01:01:01Z' as date-time
:param date_time_path: '2012-01-01T01:01:01Z' as date-time
:type date_time_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}'
path_format_arguments = {
'dateTimePath': self._serialize.url("date_time_path", date_time_path, 'iso-8601')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_time_null(
self, date_time_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as date-time, should be disallowed or throw depending on
representation of date-time
:param date_time_path: null as date-time
:type date_time_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/datetime/null/{dateTimePath}'
path_format_arguments = {
'dateTimePath': self._serialize.url("date_time_path", date_time_path, 'iso-8601')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def base64_url(
self, base64_url_path, custom_headers=None, raw=False, **operation_config):
"""
Get 'lorem' encoded value as 'bG9yZW0' (base64url)
:param base64_url_path: base64url encoded value
:type base64_url_path: bytes
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/bG9yZW0/{base64UrlPath}'
path_format_arguments = {
'base64UrlPath': self._serialize.url("base64_url_path", base64_url_path, 'base64')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def array_csv_in_path(
self, array_path, custom_headers=None, raw=False, **operation_config):
"""
Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' ,
null, ''] using the csv-array format
:param array_path: an array of string ['ArrayPath1', 'begin!*'();:@
&=+$,/?#[]end' , null, ''] using the csv-array format
:type array_path: list of str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}'
path_format_arguments = {
'arrayPath': self._serialize.url("array_path", array_path, '[str]', div=',')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def unix_time_url(
self, unix_time_url_path, custom_headers=None, raw=False, **operation_config):
"""
Get the date 2016-04-13 encoded value as '1460505600' (Unix time)
:param unix_time_url_path: Unix time encoded value
:type unix_time_url_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/1460505600/{unixTimeUrlPath}'
path_format_arguments = {
'unixTimeUrlPath': self._serialize.url("unix_time_url_path", unix_time_url_path, 'unix-time')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
|
sharadagarwal/autorest
|
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py
|
Python
|
mit
| 44,870
|
Objective
Today, we're learning about the Array data structure. Check out the [Tutorial](https://www.hackerrank.com/challenges/30-arrays/tutorial) tab for learning materials and an instructional video!
Task
Given an array,A , of N integers, print A's elements in reverse order as a single line of space-separated numbers.
Input Format
The first line contains an integer, N(the size of our array).
The second line contains N space-separated integers describing array A's elements.
Constraints
* 1<= N <= 1000
* 1<=Ai<=10000, where Ai is the ith integer in the array.
Output Format
Print the elements of array in reverse order as a single line of space-separated numbers.
Sample Input
4
1 4 3 2
Sample Output
2 3 4 1
|
pk-hackerrank/hr-tutorials
|
30-days-of-code/day-7-arrays/day-7-arrays.md
|
Markdown
|
mit
| 751
|
# socialclock
(Developing...)
Alarm and send Twitter.
## Demo

## Requirement
Android API 21
[Fablic](https://get.fabric.io/) (Twitter SDK)
## Licence
[MIT](https://github.com/mapler/socialclock/blob/master/LICENSE)
## Author
[mapler](https://github.com/mapler)
|
mapler/socialclock
|
README.md
|
Markdown
|
mit
| 379
|
from pseudoregion import *
class Edge(PseudoRegion):
"""EDGE Fringe field and other kicks for hard-edged field models
1) edge type (A4) {SOL, DIP, HDIP, DIP3, QUAD, SQUA, SEX, BSOL, FACE}
2.1) model # (I) {1}
2.2-5) p1, p2, p3,p4 (R) model-dependent parameters
Edge type = SOL
p1: BS [T]
If the main solenoid field is B, use p1=-B for the entrance edge and p1=+B for the exit edge.
Edge type = DIP
p1: BY [T]
Edge type = HDIP
p1: BX [T]
Edge type = DIP3
p1: rotation angle [deg]
p2: BY0 [T]
p3: flag 1:in 2:out
Edge type = QUAD
p1: gradient [T/m]
Edge type = SQUA
p1: gradient [T/m]
Edge type = SEX
p1: b2 [T/m2] (cf. C. Wang & L. Teng, MC 207)
Edge type = BSOL
p1: BS [T]
p2: BY [T]
p3: 0 for entrance face, 1 for exit face
Edge type = FACE
This gives vertical focusing from rotated pole faces.
p1: pole face angle [deg]
p2: radius of curvature of reference particle [m]
p3: if not 0 => correct kick by factor 1/(1+delta)
p4: if not 0 ==> apply horizontal focus with strength = (-vertical strength)
If a FACE command is used before and after a sector dipole (DIP), you can approximate a rectangular dipole field.
The DIP, HDIP, QUAD, SQUA, SEX and BSOL edge types use Scott Berg's HRDEND routine to find the change in transverse
position and transverse momentum due to the fringe field.
"""
def __init__(
self,
edge_type,
model,
model_parameters_list,
name=None,
metadata=None):
PseudoRegion.__init__(self, name, metadata)
self.edge_type = edge_type
self.model = model
self.model_parameters = model_parameters
class Edge(Field):
"""
EDGE
1) edge type (A4) {SOL, DIP, HDIP,DIP3,QUAD,SQUA,SEX, BSOL,FACE}
2.1) model # (I) {1}
2.2-5) p1, p2, p3,p4 (R) model-dependent parameters
Edge type = SOL
p1: BS [T]
If the main solenoid field is B, use p1=-B for the entrance edge and p1=+B for the exit edge.
Edge type = DIP
p1: BY [T]
Edge type = HDIP
p1: BX [T]
Edge type = DIP3
p1: rotation angle [deg]
p2: BY0 [T]
p3: flag 1:in 2:out
Edge type = QUAD
p1: gradient [T/m]
Edge type = SQUA
p1: gradient [T/m]
Edge type = SEX
p1: b2 [T/m2] (cf. C. Wang & L. Teng, MC 207)
Edge type = BSOL
p1: BS [T]
p2: BY [T]
p3: 0 for entrance face, 1 for exit face
Edge type = FACE
This gives vertical focusing from rotated pole faces.
p1: pole face angle [deg]
p2: radius of curvature of reference particle [m]
p3: if not 0 => correct kick by the factor 1 / (1+δ)
p4: if not 0 => apply horizontal focus with strength = (-vertical strength)
If a FACE command is used before and after a sector dipole ( DIP ), you can approximate a rectangular dipole field.
The DIP, HDIP, QUAD, SQUA, SEX and BSOL edge types use Scott Berg’s HRDEND routine to find the change in
transverse position and transverse momentum due to the fringe field.
"""
begtag = 'EDGE'
endtag = ''
models = {
'model_descriptor': {
'desc': 'Name of model parameter descriptor',
'name': 'model',
'num_parms': 6,
'for001_format': {
'line_splits': [
1,
5]}},
'sol': {
'desc': 'Solenoid',
'doc': '',
'icool_model_name': 'SOL',
'parms': {
'model': {
'pos': 1,
'type': 'String',
'doc': ''},
'bs': {
'pos': 3,
'type': 'Real',
'doc': 'p1: BS [T] '
'If the main solenoid field is B, use p1=-B for the entrance edge and p1=+B for the '
'exit edge. (You can use this to get a tapered field profile)'}}},
}
def __init__(self, **kwargs):
Field.__init__(self, 'EDGE', kwargs)
def __call__(self, **kwargs):
Field.__call__(self, kwargs)
def __setattr__(self, name, value):
if name == 'ftag':
if value == 'EDGE':
object.__setattr__(self, name, value)
else:
# Should raise exception here
print '\n Illegal attempt to set incorrect ftag.\n'
else:
Field.__setattr__(self, name, value)
def __str__(self):
return Field.__str__(self)
def gen_fparm(self):
Field.gen_fparm(self)
|
jon2718/ipycool_2.0
|
edge.py
|
Python
|
mit
| 4,743
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-patch-twilio',
contentFor: function(type) {
var environment = this.app.env.toString();
if (type === 'head') {
if (environment === 'production') {
return '<script type="text/javascript" src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>';
} else {
return '<script type="text/javascript"> var Twilio = { disconnectCallback: false, Device: { error: function() {}, setup: function() {}, connect: function() {}, disconnect: function (callback) { if (callback) { this.disconnectCallback = callback; } else { this.disconnectCallback(); } }, disconnectAll: function() {} } }; </script>';
}
}
}
};
|
toranb/ember-cli-patch-twilio
|
index.js
|
JavaScript
|
mit
| 763
|
// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────
import React from 'react';
import { graphql } from 'gatsby';
import { RootContainer, BlogPreviewsContainer, SEOContainer } from '~containers';
import { Main, Section, H2 } from '~components';
import { renderBlocks, pagePropTypes } from '~utils';
// ─────────────────────────────────────────────────────────────────────────────
// query
// ─────────────────────────────────────────────────────────────────────────────
export const query = graphql`
{
page: mdx(frontmatter: { meta: { permalink: { eq: "/blog/" } } }) {
frontmatter {
...MetaFragment
blocks {
title
type
}
}
}
posts: allMdx(
filter: { fileAbsolutePath: { regex: "/cms/posts/" } }
sort: { fields: [frontmatter___date], order: DESC }
) {
nodes {
...BlogPreviewFragment
}
}
}
`;
// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────
export default function BlogPage({
data: {
page: {
frontmatter: { meta, blocks },
},
posts,
},
}) {
return (
<RootContainer>
<SEOContainer meta={meta} />
<Main
css={`
grid-template: 'hero' 'blog';
grid-gap: 10vh 4rem;
`}
>
{renderBlocks(blocks)}
<Section
id="blog"
css={`
grid-area: blog;
`}
>
<H2>All blog articles</H2>
<BlogPreviewsContainer posts={posts} />
</Section>
</Main>
</RootContainer>
);
}
BlogPage.propTypes = pagePropTypes;
|
mrozilla/mrozilla.cz
|
src/pages/blog.js
|
JavaScript
|
mit
| 2,755
|
<?php
namespace Setup\Form;
use Zend\Form\Form;
use Zend\InputFilter\Factory;
class OptionsForm extends Form
{
public static $definitions = array(
'client.name.full' => array('Ihr Name', 'Wird Ihren Besuchern als Betreiber angezeigt.<br>Erscheint z.B. ganz oben neben dem Logo.'),
'client.name.short' => array('Ihr Kürzel', 'Kurzform, Abkürzung oder Akronym Ihres Namens.<br>Erscheint z.B. in der Betreffzeile von E-Mails.'),
'client.contact.email' => array('Ihre E-Mail Adresse', 'Wird für Benachrichtigungen des Systems benötigt.<br>Kann auch Benutzern für Hilfe angezeigt werden.'),
'client.contact.phone' => array('Ihre Telefonnummer', 'Wird für die telefonische Buchung angezeigt.<br>Erscheint z.B. ganz oben in der Kopfleiste.'),
'client.website' => array('Ihre Webseite', 'Die Internetadresse Ihrer Webseite.<br>Erscheint z.B. ganz oben in der Kopfleiste.'),
'client.website.contact' => array('Ihre Kontaktseite', 'Die Internetadresse Ihrer Kontaktseite.<br>Erscheint z.B. ganz oben in der Kopfleiste.'),
'client.website.imprint' => array('Ihr Impressum', 'Die Internetadresse Ihres Impressums.'),
'service.name.full' => array('Name des Systems', 'Unter diesem Namen präsentiert sich das System.<br>Erscheint z.B. ganz oben neben dem Logo.'),
'service.name.short' => array('Kürzel des Systems', 'Kurzform, Abkürzung oder Akronym des Systems.<br>Erscheint z.B. in E-Mails.'),
'service.meta.description' => array('Kurzbeschreibung Ihres Angebotes', 'Am besten ein bis zwei Sätze über Ihr Angebot.'),
'service.meta.keywords' => array('Stichworte Ihres Angebotes', 'Am besten 10 bis 20 Stichworte über Ihr Angebot.'),
'subject.type' => array('Bezeichnung Ihrer Anlage', 'Erscheint z.B. in der Kopfleiste.<br>Bitte mit kleinem Artikelwort beginnen.'),
);
public function init()
{
$this->setName('cf');
/* Generate form elements */
foreach (self::$definitions as $key => $value) {
$key = str_replace('.', '_', $key);
$this->add(array(
'name' => 'cf-' . $key,
'type' => 'Text',
'attributes' => array(
'id' => 'cf-' . $key,
'style' => 'width: 380px;',
),
'options' => array(
'label' => $value[0],
'notes' => $value[1],
),
));
}
$this->add(array(
'name' => 'cf-submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Save',
'class' => 'default-button',
'style' => 'width: 200px;',
),
));
/* Generate input filters */
$filters = array();
foreach (self::$definitions as $key => $value) {
$formKey = str_replace('.', '_', $key);
$filters['cf-' . $formKey] = array(
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'message' => 'Bitte geben Sie hier etwas ein',
),
'break_chain_on_failure' => true,
),
array(
'name' => 'StringLength',
'options' => array(
'min' => 2,
'message' => 'Diese Eingabe muss mindestens drei Zeichen lang sein',
),
),
),
);
switch ($key) {
case 'client.contact.email':
$filters['cf-' . $formKey]['validators'][] = array(
'name' => 'EmailAddress',
'options' => array(
'useMxCheck' => true,
'message' => 'Bitte geben Sie eine richtige E-Mail Adresse ein.',
'messages' => array(
'emailAddressInvalidMxRecord' => 'Dieser E-Mail Anbieter existiert leider nicht.',
),
),
);
break;
}
}
$factory = new Factory();
$this->setInputFilter($factory->createInputFilter($filters));
}
}
|
tkrebs/ep3-hs
|
module/Setup/src/Setup/Form/OptionsForm.php
|
PHP
|
mit
| 4,698
|
import {getCurrentBusIteration} from '../get-current-bus-iteration'
import {processBusSchedule} from '../process-bus-line'
import {dayAndTime, time} from './moment.helper'
import type {UnprocessedBusSchedule, BusSchedule} from '../../types'
function buildBusSchedules(now): BusSchedule {
// prettier-ignore
let schedules: UnprocessedBusSchedule = {
days: ['Mo', 'Tu'],
coordinates: {},
stops: ['St. Olaf', 'Carleton', 'Food Co-op', 'Cub/Target', 'El Tequila', 'Food Co-op', 'Carleton', 'St. Olaf'],
times: [['1:00pm', '1:05pm', '1:10pm', '1:15pm', '1:20pm', '1:25pm', '1:30pm', '1:35pm'],
['2:00pm', '2:05pm', '2:10pm', '2:15pm', '2:20pm', '2:25pm', '2:30pm', '2:35pm'],
['3:00pm', '3:05pm', '3:10pm', '3:15pm', '3:20pm', '3:25pm', '3:30pm', '3:35pm'],
],
}
return processBusSchedule(now)(schedules)
}
test('returns the bus times index for the given time', () => {
let now = time('1:00pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('running')
expect(actual.index).toBe(0)
})
test('returns the bus times index for the given time', () => {
let now = time('2:05pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('running')
expect(actual.index).toBe(1)
})
test('handles the given time being after the last bus', () => {
let now = time('5:00pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('after-end')
expect(actual.index).toBe(null)
})
test('handles the given time being before the first bus', () => {
let now = time('12:00pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('before-start')
expect(actual.index).toBe(null)
})
test('ignores day-of-week', () => {
let now = dayAndTime('Mo 1:00pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('running')
expect(actual.index).toBe(0)
})
test('handles a schedule with no times', () => {
let now = time('1:00pm')
let schedule = {
days: ['Su'],
coordinates: {},
stops: [],
times: [[]],
}
let input = processBusSchedule(now)(schedule)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('none')
expect(actual.index).toBe(null)
})
test('handles the given time being between two iterations', () => {
let now = time('1:55pm')
let input = buildBusSchedules(now)
let actual = getCurrentBusIteration(input, now)
expect(actual.status).toBe('between-rounds')
expect(actual.index).toBe(1)
})
|
StoDevX/AAO-React-Native
|
source/views/transportation/bus/lib/__tests__/get-current-bus-iteration.test.ts
|
TypeScript
|
mit
| 2,738
|
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import { expect } from 'chai';
import {
FIREBASE_LOGOUT_BEGIN,
FIREBASE_LOGOUT_SUCCESS,
FIREBASE_LOGOUT_FAILURE,
FIREBASE_LOGOUT_DISMISS_ERROR,
} from 'features/common/redux/constants';
import {
firebaseLogout,
dismissFirebaseLogoutError,
reducer,
} from 'features/common/redux/firebaseLogout';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('common/redux/firebaseLogout', () => {
afterEach(() => {
nock.cleanAll();
});
it('action should handle firebaseLogout success', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} },
];
return store.dispatch(firebaseLogout({ error: false }))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle firebaseLogout failure', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: 'some error' } },
];
return store.dispatch(firebaseLogout({ error: true }))
.catch(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle dismissFirebaseLogoutError', () => {
const expectedAction = {
type: FIREBASE_LOGOUT_DISMISS_ERROR,
};
expect(dismissFirebaseLogoutError()).to.deep.equal(expectedAction);
});
it('reducer should handle FIREBASE_LOGOUT_BEGIN', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_BEGIN }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.true;
});
it('reducer should handle FIREBASE_LOGOUT_SUCCESS', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
});
it('reducer should handle FIREBASE_LOGOUT_FAILURE', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: new Error('some error') } }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
expect(state.firebaseLogoutError).to.exist;
});
it('reducer should handle FIREBASE_LOGOUT_DISMISS_ERROR', () => {
const prevState = { firebaseLogoutError: new Error('some error') };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_DISMISS_ERROR }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutError).to.be.null;
});
});
|
thehig/arpggio-firebase-client
|
test/app/features/common/redux/firebaseLogout.test.js
|
JavaScript
|
mit
| 3,073
|
//
// LoggingAPI.h
// libloggingapi
//
// Created by Andreoletti David on 26/09/2012.
// Copyright 2012 IO Stark. All rights reserved.
//
#ifndef INCLUDE_LOGGINGAPI_LOGGINGAPI_H_
#define INCLUDE_LOGGINGAPI_LOGGINGAPI_H_
#include <string>
#include <vector>
#include "loggingapi/LoggingAPIInterface.h"
#include "loggingapi/core/Core.h"
namespace loggingapi {
namespace core { class Core; }
namespace loggers { class LoggerInterface; }
/**
* Public Logging API
*/
class LoggingAPI : LoggingAPIInterface {
public:
// Inherited from LoggingAPIInterface
static loggers::LoggerInterface* getLogger(const std::string& name);
static bool addLogger(loggers::LoggerInterface* logger);
static loggers::LoggerInterface* removeLogger(const std::string& name);
private:
/**
* Logging Core
*/
static core::Core loggingCore_;
};
} // namespaces
#endif // INCLUDE_LOGGINGAPI_LOGGINGAPI_H_
|
davidandreoletti/loggingapi-core-lib
|
include/loggingapi/LoggingAPI.h
|
C
|
mit
| 923
|
require "bundler/setup"
require "twilio_api_mock"
require 'fakeredis'
require 'fakeredis/rspec'
require 'pry'
require 'ostruct'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
|
angelkbrown/twilio-api-mock
|
spec/spec_helper.rb
|
Ruby
|
mit
| 347
|
"""code_for_good URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^scraper/', include('scraper.urls')),
url(r'^admin/', admin.site.urls),
]
|
Spferical/cure-alzheimers-fund-tracker
|
code_for_good/urls.py
|
Python
|
mit
| 826
|
<?php
/**
* Created by PhpStorm.
* User: jair
* Date: 23/11/15
* Time: 12:26 PM
*/
class AuthorTest extends PHPUnit_Framework_TestCase{
/** @test */
function it_should_construct(){
$author = new \PlatziPHP\Author('jair@atypax.com','platzi','AUTOR_DE_PLATZI');
$this->assertInstanceOf(\PlatziPHP\Author::class,$author);
}
/** @test */
function it_should_fail_when_no_key_is_given(){
$this->setExpectedException(\InvalidArgumentException::class);
$author = new \PlatziPHP\Author('jair@atypax.com','platzi','hola');
$this->assertInstanceOf(\PlatziPHP\Author::class,$author);
}
}
|
jrevillaa/platzi_laravel
|
tests/AuthorTest.php
|
PHP
|
mit
| 651
|
2021-W02 をふりかえる。
# [2021-W02 の目標][2021-01-10] とその記事
目標。
- ☑ bouzuya/rust-social-bookmarking 0.2.0 をつくる
- ☑ 『エンジニアのための理論でわかるデザイン入門』を読む
記事。
- [2021-01-16 スーパーマリオサンシャイン エアポートを巡回している][2021-01-16]
- [2021-01-15 スーパーマリオサンシャインの急流下りをクリアした][2021-01-15]
- [2021-01-14 体調が悪い][2021-01-14]
- [2021-01-13 曲面ディスプレイが欲しくなっている][2021-01-13]
- [2021-01-12 いろいろ読んだ][2021-01-12]
- [2021-01-11 スーパーマリオサンシャインで残機を増やしている][2021-01-11]
- [2021-01-10 2021-W01 ふりかえり][2021-01-10]
# つくったもの
- [bouzuya/rust-social-bookmarking][] v0.2.0
# よんだもの
- 『涼宮ハルヒの陰謀』 ([2021-01-12][])
- 『エンジニアのための理論でわかるデザイン入門』 ([2021-01-12][])
- 『涼宮ハルヒの憤慨』 ([2021-01-14][])
- 『涼宮ハルヒの分裂』 ([2021-01-17][])
- 『涼宮ハルヒの驚愕 (前) 』 ([2021-01-17][])
- 『涼宮ハルヒの驚愕 (後) 』 ([2021-01-17][])
# みたもの
- 『進撃の巨人 シーズン 3 』 ([2021-01-11][])
- 『キャビン・イン・ザ・ウッズ』 ([2021-01-17][])
- 『 2012 』 ([2021-01-17][])
# その他
勉強会。なし。
おでかけ。雨の中の散歩。
ゲーム。スーパーマリオサンシャイン シャイン 120 個を集めてクリア。リングフィットアドベンチャー ワールド 29 レベル 239 。
買い物。なし。
体調。木曜日に体調不良で倒れていた。
育児。「あれー?」と『となりのトトロ』で 2 階への階段を探すシーンのまねをしながらものを探す。たまねぎ・かぼちゃ・にんじんはわかる。じゃがいもはわからない。
---
スーパーマリオ 3D コレクションの『スーパーマリオサンシャイン』をクリアした。シャイン 120 枚の収集を終えた。スーパーマリオ 64 とあわせて 65 時間以上プレイと表示されていた。
スーパーマリオ 64 ([2020-11-14][]) に比べて難しかった。 [2020-12-12][] にもメモしているが改めて書く。
青コインの隠し方は本気だと感じる。すべての人の話を聞いた上でヒントをうまく解釈できないと取れないものがある。結局ぼくは攻略サイトを見た。これも含めて全体的にナビゲーションの悪さを感じる。うまく誘導してくれないイメージがある。
ミスしたときの戻し作業が重い。例えば急流下りに行くためのヨッシーでの船の乗り継ぎやリコハーバーのヨッシーでの魚の足場の乗り継ぎなどだ。ちょっと踏み外して落下すると最初からやり直しさせられることが多い。練習させているつもりかもしれないがつらい。その結果のひとつとしてエアポートの繰り返しでの残機稼ぎが常態化した。
ふわふわとした感覚のジャンプが難しい。おそらく空中での移動量が多いのだと思う。思った以上に飛んだり飛ばなかったりする。先の例に挙げたヨッシーはジャンプ力が高いのでこれが顕著に出ている。ジャンプ制御の難しさが各種ヒミツの難易度の高さにつながっていると思う。これの微調整のためのポンプなのかもしれないが水の補充を含めて難易度を上げたいのか下げたいのかよく分からない。あといまだにスピンジャンプが狙った方向に出せない。
乗り物に不快なものが多い。例えばヨッシー・コースター・泥舟などだ。むしろ不快じゃない乗り物などなかったような気がする。
ギャラクシーを少なくとも今月ははじめない。既にゲームをしすぎている。
---
その他のメモ。
衝動的に買った ([2020-12-01][]) 涼宮ハルヒのシリーズを持っている分はひととおり読んだ。どうでもいいのだけど積まれていると気になるので。
[bouzuya/rust-social-bookmarking][] v0.2.0 をつくった。やっつけ気味。いろいろと直したい。モチベーションが下がって完成しない流れになっている。
# 2012-W03 の目標
- 『 GitHub Actions 実践入門』を読む
- bouzuya/rust-social-bookmarking v0.2.1 をつくる
[2020-11-14]: https://blog.bouzuya.net/2020/11/14/
[2020-12-01]: https://blog.bouzuya.net/2020/12/01/
[2020-12-12]: https://blog.bouzuya.net/2020/12/12/
[2021-01-10]: https://blog.bouzuya.net/2021/01/10/
[2021-01-11]: https://blog.bouzuya.net/2021/01/11/
[2021-01-12]: https://blog.bouzuya.net/2021/01/12/
[2021-01-13]: https://blog.bouzuya.net/2021/01/13/
[2021-01-14]: https://blog.bouzuya.net/2021/01/14/
[2021-01-15]: https://blog.bouzuya.net/2021/01/15/
[2021-01-16]: https://blog.bouzuya.net/2021/01/16/
[2021-01-17]: https://blog.bouzuya.net/2021/01/17/
[bouzuya/rust-social-bookmarking]: https://github.com/bouzuya/rust-social-bookmarking
|
bouzuya/blog.bouzuya.net
|
data/2021/01/2021-01-17.md
|
Markdown
|
mit
| 5,228
|
## [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/#/description)
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
|
ddki/my_study_project
|
algorithm/leetcode/finished/2/different-ways-to-add-parentheses/question.md
|
Markdown
|
mit
| 536
|
//
// GMImagePickerController.cs
// GMPhotoPicker.Xamarin
//
// Created by Roy Cornelissen on 23/03/16.
// Based on original GMImagePicker implementation by Guillermo Muntaner Perelló.
// https://github.com/guillermomuntaner/GMImagePicker
//
using System;
using UIKit;
using Photos;
using CoreGraphics;
using System.Collections.Generic;
using MobileCoreServices;
using System.Linq;
using Foundation;
using AssetsLibrary;
using System.Threading.Tasks;
using AVFoundation;
namespace GMImagePicker
{
/// <summary>
/// Enum to specify the sort order of the images in the gallery.
/// Images will be sorted by creation date. The default behavior is Ascending.
/// </summary>
public enum SortOrder
{
/// <summary>
/// Sort images in ascending order, i.e. the oldest images first.
/// </summary>
Ascending,
/// <summary>
/// Sort images in descending order, i.e. the newest images first.
/// </summary>
Descending
}
public class GMImagePickerController: UIViewController
{
//This is the default image picker size!
//public const CGSize PopoverContentSize = new CoreGraphics.CGSize(320, 480);
//static CGSize const kPopoverContentSize = {320, 480};
//However, the iPad is 1024x768 so it can allow popups up to 768!
public static readonly CGSize PopoverContentSize = new CGSize(480, 720);
internal UINavigationController _navigationController;
private GMAlbumsViewController _albumsViewController;
/// <summary>
/// Contains the selected 'PHAsset' objects. The order of the objects is the selection order.
/// You can add assets before presenting the picker to show the user some preselected assets.
/// </summary>
/// <value>The selected assets.</value>
private List<PHAsset> _selectedAssets;
#region Grid customizations
public IList<PHAsset> SelectedAssets
{
get { return _selectedAssets; }
}
/// <summary>
/// Number of columns in portrait mode (3 by default)
/// </summary>
public int ColsInPortrait { get; set; }
/// <summary>
/// Number of columns in landscape (5 by default).
/// </summary>
public int ColsInLandscape { get; set; }
/// <summary>
/// Horizontal and vertical minimum space between grid cells (2.0 by default)
/// </summary>
public nfloat MinimumInteritemSpacing { get; set; }
#endregion
#region UI Customizations
/// <summary>
/// Determines with smart collections are displayed (array of PHAssetCollectionSubtype)
/// The default smart collections are:
/// - Favorites
/// - RecentlyAdded
/// - Videos
/// - SlomoVideos
/// - Timelapses
/// - Bursts
/// - Panoramas
/// </summary>
/// <value>The custom smart collections.</value>
public PHAssetCollectionSubtype[] CustomSmartCollections { get; set; }
/// <summary>
/// Determines which media types are allowed (array of PHAssetMediaType)
/// </summary>
/// <remarks>
/// This defaults to all media types (view, audio and images)
/// This can override CustomSmartCollections behavior (ie, remove video-only smart collections)</remarks>
/// <value>The media types.</value>
public PHAssetMediaType[] MediaTypes { get; set; }
/// <summary>
/// If set, it displays this string instead of the localised default of "Done" on the Done button.
/// </summary>
/// <remarks>
/// Note also that this is not used when a single selection is active since the selection of the chosen photo
/// closes the VS thus rendering the button pointless.
/// </remarks>
/// <value>The custom done button title.</value>
public string CustomDoneButtonTitle { get; set; }
/// <summary>
/// If set, it displays this string instead of the localised default of "Cancel" on the cancel button.
/// </summary>
/// <value>The custom cancel button title.</value>
public string CustomCancelButtonTitle { get; set; }
/// <summary>
/// If set, it displays a prompt in the navigation bar.
/// </summary>
/// <value>The custom navigation bar prompt.</value>
public string CustomNavigationBarPrompt { get; set; }
/// <summary>
/// If set, it displays a UIAlert with this title when the user has denied access to photos.
/// </summary>
public string CustomPhotosAccessDeniedErrorTitle { get; set; }
/// <summary>
/// If set, it displays a this error message when the user has denied access to photos.
/// </summary>
public string CustomPhotosAccessDeniedErrorMessage { get; set; }
/// <summary>
/// If set, it displays a UIAlert with this title when the user has denied access to the camera.
/// </summary>
public string CustomCameraAccessDeniedErrorTitle { get; set; }
/// <summary>
/// If set, it displays a UIAlert with this title when the user has denied access to the camera.
/// </summary>
public string CustomCameraAccessDeniedErrorMessage { get; set; }
/// <summary>
/// Determines whether or not a toolbar with info about user selection is shown.
/// </summary>
/// <remarks>
/// The InfoToolbar is visible by default.
/// </remarks>
/// <value><c>true</c> if display selection info toolbar; otherwise, <c>false</c>.</value>
public bool DisplaySelectionInfoToolbar { get; set; }
/// <summary>
/// Determines whether or not the number of assets is shown in the Album list.
/// </summary>
/// <remarks>
/// The number of assets is visible by default.
/// </remarks>
/// <value><c>true</c> if display albums number of assets; otherwise, <c>false</c>.</value>
public bool DisplayAlbumsNumberOfAssets { get; set; }
/// <summary>
/// Automatically disables the "Done" button if nothing is selected.
/// </summary>
/// <remarks>
/// Defaults to <c>true</c>
/// </remarks>
/// <value><c>true</c> if auto disable done button; otherwise, <c>false</c>.</value>
public bool AutoDisableDoneButton { get; set; }
/// <summary>
/// Use the picker either for miltiple image selections, or just a single selection.
/// In the case of a single selection the VC is closed on selection so the Done button
/// is neither displayed or used.
/// </summary>
/// <remarks>Default is <c>true</c></remarks>
/// <value><c>true</c> if allows multiple selection; otherwise, <c>false</c>.</value>
public bool AllowsMultipleSelection { get; set; }
/// <summary>
/// In the case where allowsMultipleSelection = <c>false</c>, set this to <c>true</c> to have the user confirm their selection.
/// </summary>
/// <remarks>Default is <c>false</c></remarks>
/// <value><c>true</c> if confirm single selection; otherwise, <c>false</c>.</value>
public bool ConfirmSingleSelection { get; set; }
/// <summary>
/// If set, it displays this string (if ConfirmSingleSelection = <c>true</c>) instead of the localised default.
/// </summary>
/// <value>The confirm single selection prompt.</value>
public string ConfirmSingleSelectionPrompt { get; set; }
/// <summary>
/// True to always show the toolbar, with a camera button allowing new photos to be taken. False to auto show/hide the
/// toolbar, and have no camera button.
/// </summary>
/// <remarks>Default is <c>false</c>. If <c>true</c>, this renders DisplaySelectionInfoToolbar a no-op.</remarks>
/// <value><c>true</c> if show camera button; otherwise, <c>false</c>.</value>
public bool ShowCameraButton { get; set; }
/// <summary>
/// True to auto select the image(s) taken with the camera if ShowCameraButton = <c>true</c>.
/// In the case of AllowsMultipleSelection = <c>true</c>, this will trigger the selection handler too.
/// </summary>
public bool AutoSelectCameraImages { get; set; }
/// <summary>
/// If set, allows the user to edit camera images before selecting them.
/// </summary>
public bool AllowsEditingCameraImages { get; set; }
/// <summary>
/// The color for all backgrounds; behind the table and cells. Defaults to UIColor.White
/// </summary>
public UIColor PickerBackgroundColor { get; set; }
/// <summary>
/// The color for text in the views. This needs to work with PickerBackgroundColor! Default of UIColor.DarkTextColor
/// </summary>
public UIColor PickerTextColor { get; set; }
/// <summary>
/// The color for the background tint of the toolbar. Defaults to null.
/// </summary>
public UIColor ToolbarBarTintColor { get; set; }
/// <summary>
/// The color of the text on the toolbar
/// </summary>
public UIColor ToolbarTextColor { get; set; }
/// <summary>
/// The tint colour used for any buttons on the toolbar
/// </summary>
public UIColor ToolbarTintColor { get; set; }
/// <summary>
/// The background color of the toolbar. Defaults to null.
/// </summary>
public UIColor ToolbarBackgroundColor { get; set; }
/// <summary>
/// The background of the navigation bar. Defaults to null.
/// </summary>
public UIColor NavigationBarBackgroundColor { get; set; }
/// <summary>
/// The color for the text in the navigation bar. Defaults to UIColor.DarkTextColor
/// </summary>
public UIColor NavigationBarTextColor { get; set; }
/// <summary>
/// The tint color used for any buttons on the navigation Bar
/// </summary>
public UIColor NavigationBarTintColor { get; set; }
/// <summary>
/// The color for the background tint of the navigation bar. Defaults to null.
/// </summary>
public UIColor NavigationBarBarTintColor { get; set; }
/// <summary>
/// The font to use everywhere. Defaults to system font. It is advised if you set this to check, and possibly
/// set, appropriately the custom font sizes. For font information, check http://www.iosfonts.com/
/// </summary>
/// <value>The name of the picker font.</value>
public string PickerFontName { get; set; }
/// <summary>
/// The font to use everywhere. Defaults to bold system font. It is advised if you set this to check, and
/// possibly set, appropriately the custom font sizes.
/// </summary>
public string PickerBoldFontName { get; set; }
/// <summary>
/// Font size of regular text in the picker.
/// </summary>
public float PickerFontNormalSize { get; set ; }
/// <summary>
/// Font size of the header text in the picker.
/// </summary>
public float PickerFontHeaderSize { get; set; }
/// <summary>
/// On iPhones this will matter if custom navigation bar colours are being used.
/// Defaults to UIStatusBarStyle.Default
/// </summary>
/// <value>The picker status bar style.</value>
public UIStatusBarStyle PickerStatusBarStyle { get; set; }
/// <summary>
/// <c>true</c> to use the custom font (or its default) in the navigation bar, <c>false</c> to leave to iOS Defaults.
/// </summary>
public bool UseCustomFontForNavigationBar { get; set; }
/// <summary>
/// Gets or sets the sort order for the image grid.
/// Default is Ascending, i.e. the oldest images first.
/// </summary>
public SortOrder GridSortOrder { get; set; }
#endregion
/// <summary>
/// Adds one asset to the selection and updates the UI.
/// </summary>
public void SelectAsset (PHAsset asset)
{
if (!_selectedAssets.Exists(a => a.LocalIdentifier == asset.LocalIdentifier)) {
_selectedAssets.Add (asset);
UpdateDoneButton ();
if (!AllowsMultipleSelection) {
if (ConfirmSingleSelection) {
var message = ConfirmSingleSelectionPrompt ?? "picker.confirm.message".Translate (defaultValue: "Do you want to select the image you tapped on?");
var alert = UIAlertController.Create ("picker.confirm.title".Translate (defaultValue: "Are you sure?"), message, UIAlertControllerStyle.Alert);
alert.AddAction (UIAlertAction.Create ("picker.action.no".Translate (defaultValue: "No"), UIAlertActionStyle.Cancel, null));
alert.AddAction (UIAlertAction.Create ("picker.action.yes".Translate (defaultValue: "Yes"), UIAlertActionStyle.Default, action => {
FinishPickingAssets (this, EventArgs.Empty);
}));
PresentViewController (alert, true, null);
} else {
FinishPickingAssets (this, EventArgs.Empty);
}
}
else if (DisplaySelectionInfoToolbar || ShowCameraButton) {
UpdateToolbar ();
}
}
}
public void DeselectAsset (PHAsset asset)
{
_selectedAssets.Remove (asset);
if (!_selectedAssets.Any ()) {
UpdateDoneButton ();
}
if (DisplaySelectionInfoToolbar || ShowCameraButton) {
UpdateToolbar ();
}
}
public void Dismiss (object sender, EventArgs args)
{
// Explicitly unregister observers because we cannot predict when the GC cleans up
Unregister ();
Canceled?.Invoke(this, EventArgs.Empty);
PresentingViewController.DismissViewController (true, null);
}
public void FinishPickingAssets (object sender, EventArgs args)
{
// Explicitly unregister observers because we cannot predict when the GC cleans up
Unregister ();
FinishedPickingAssets?.Invoke(this, new MultiAssetEventArgs(_selectedAssets.ToArray()));
PresentingViewController.DismissViewController (true, null);
}
private void UpdateDoneButton()
{
if (!AllowsMultipleSelection) {
return;
}
var nav = ChildViewControllers [0] as UINavigationController;
if (nav != null) {
foreach (var vc in nav.ViewControllers) {
vc.NavigationItem.RightBarButtonItem.Enabled = !AutoDisableDoneButton || _selectedAssets.Any ();
}
}
}
private void UpdateToolbar()
{
if (!AllowsMultipleSelection && !ShowCameraButton) {
return;
}
var nav = ChildViewControllers [0] as UINavigationController;
if (nav != null) {
foreach (var vc in nav.ViewControllers) {
var index = 1;
if (ShowCameraButton) {
index++;
}
if (vc.ToolbarItems != null) {
vc.ToolbarItems [index].SetTitleTextAttributes (ToolbarTitleTextAttributes, UIControlState.Normal);
vc.ToolbarItems [index].SetTitleTextAttributes (ToolbarTitleTextAttributes, UIControlState.Disabled);
vc.ToolbarItems [index].Title = ToolbarTitle;
}
var toolbarHidden = !ShowCameraButton && !_selectedAssets.Any ();
vc.NavigationController.SetToolbarHidden (toolbarHidden, true);
}
}
}
private async void CameraButtonPressed(object sender, EventArgs e)
{
if (! await EnsureHasCameraAccess ())
{
return;
}
if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
var alert = UIAlertController.Create ("No Camera!",
"Sorry, this device does not have a camera.",
UIAlertControllerStyle.Alert);
alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
return;
}
// This allows the selection of the image taken to be better seen if the user is not already in that VC
if (AutoSelectCameraImages && _navigationController.TopViewController is GMAlbumsViewController) {
((GMAlbumsViewController)_navigationController.TopViewController).SelectAllAlbumsCell ();
}
var picker = new UIImagePickerController () {
SourceType = UIImagePickerControllerSourceType.Camera,
MediaTypes = new string [] { UTType.Image },
AllowsEditing = AllowsEditingCameraImages,
Delegate = new GMImagePickerDelegate (this),
ModalPresentationStyle = UIModalPresentationStyle.Popover
};
var popover = picker.PopoverPresentationController;
popover.PermittedArrowDirections = UIPopoverArrowDirection.Any;
popover.BarButtonItem = (UIBarButtonItem) sender;
PresentViewController (picker, false, null);
}
private class GMImagePickerDelegate : UIImagePickerControllerDelegate
{
private readonly GMImagePickerController _parent;
public GMImagePickerDelegate(GMImagePickerController parent)
{
_parent = parent;
}
public override async void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info)
{
await picker.PresentingViewController.DismissViewControllerAsync (true);
var mediaType = (NSString) info[UIImagePickerController.MediaType];
if (mediaType == UTType.Image) {
var image = (UIImage) (info[UIImagePickerController.EditedImage] ?? info[UIImagePickerController.OriginalImage]);
image.SaveToPhotosAlbum((img, error) => {
if (error != null) {
var alert = UIAlertController.Create("Image Not Saved",
"Sorry, unable to save the new image!",
UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
_parent.PresentViewController(alert, true, null);
}
// Note: The image view will auto refresh as the photo's are being observed in the other VCs
});
}
}
public override void Canceled (UIImagePickerController picker)
{
picker.PresentingViewController.DismissViewController (true, null);
}
}
#region Events
public delegate void MultiAssetEventHandler(object sender, MultiAssetEventArgs args);
public delegate void SingleAssetEventHandler(object sender, SingleAssetEventArgs args);
/// <summary>
/// Tells the delegate that the user finish picking photos or videos.
/// </summary>
public event MultiAssetEventHandler FinishedPickingAssets;
/// <summary>
/// Tells the delegate that the user cancelled the pick operation.
/// </summary>
public event EventHandler Canceled;
public delegate void CancellableAssetEventHandler(object sender, CancellableAssetEventArgs args);
/// <summary>
/// Ask the delegate if the specified asset should be shown.
/// </summary>
public event CancellableAssetEventHandler ShouldShowAsset;
/// <summary>
/// Ask the delegate if the specified asset should be enabled for selection.
/// </summary>
public event CancellableAssetEventHandler ShouldEnableAsset;
/// <summary>
/// Asks the delegate if the specified asset should be selected.
/// </summary>
public event CancellableAssetEventHandler ShouldSelectAsset;
/// <summary>
/// Tells the delegate that the asset was selected.
/// </summary>
public event SingleAssetEventHandler AssetSelected;
/// <summary>
/// Asks the delegate if the specified asset should be deselected.
/// </summary>
public event CancellableAssetEventHandler ShouldDeselectAsset;
/// <summary>
/// Tells the delegate that the item at the specified path was deselected.
/// </summary>
public event SingleAssetEventHandler AssetDeselected;
/// <summary>
/// Asks the delegate if the specified asset should be highlighted.
/// </summary>
public event CancellableAssetEventHandler ShouldHighlightAsset;
/// <summary>
/// Tells the delegate that asset was highlighted.
/// </summary>
public event SingleAssetEventHandler AssetHighlighted;
/// <summary>
/// Tells the delegate that the highlight was removed from the asset.
/// </summary>
public event SingleAssetEventHandler AssetUnhighlighted;
/// <summary>
/// Sets the tint color for the camera button image. defaults to UIColor.DarkTextColor.
/// </summary>
public UIColor CameraButtonTintColor { get; set; }
#endregion
public GMImagePickerController(IntPtr handle): base (handle)
{
}
public GMImagePickerController()
{
_selectedAssets = new List<PHAsset> ();
// Default values:
DisplaySelectionInfoToolbar = true;
DisplayAlbumsNumberOfAssets = true;
AutoDisableDoneButton = true;
AllowsMultipleSelection = true;
ConfirmSingleSelection = false;
ShowCameraButton = false;
// Grid configuration:
ColsInPortrait = 3;
ColsInLandscape = 5;
MinimumInteritemSpacing = 2.0f;
// Sample of how to select the collections you want to display:
CustomSmartCollections = new [] {
PHAssetCollectionSubtype.SmartAlbumRecentlyAdded,
PHAssetCollectionSubtype.SmartAlbumVideos,
PHAssetCollectionSubtype.SmartAlbumSlomoVideos,
PHAssetCollectionSubtype.SmartAlbumTimelapses,
PHAssetCollectionSubtype.SmartAlbumBursts,
PHAssetCollectionSubtype.SmartAlbumPanoramas
};
// If you don't want to show smart collections, just set CustomSmartCollections to null
// Which media types will display
MediaTypes = new[] {
PHAssetMediaType.Audio,
PHAssetMediaType.Video,
PHAssetMediaType.Image
};
PreferredContentSize = PopoverContentSize;
// UI Customization
PickerBackgroundColor = UIColor.White;
PickerTextColor = UIColor.DarkTextColor;
PickerFontName = UIFont.SystemFontOfSize (14.0f).Name;
PickerBoldFontName = UIFont.BoldSystemFontOfSize(17.0f).Name;
PickerFontNormalSize = 14.0f;
PickerFontHeaderSize = 17.0f;
CameraButtonTintColor = UIColor.DarkTextColor;
NavigationBarTextColor = UIColor.DarkTextColor;
NavigationBarTintColor = UIColor.DarkTextColor;
ToolbarTextColor = UIColor.DarkTextColor;
ToolbarTintColor = UIColor.DarkTextColor;
PickerStatusBarStyle = UIStatusBarStyle.Default;
SetupNavigationController ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
// Ensure nav and toolbar customisations are set. Defaults are in place, but the user may have changed them
View.BackgroundColor = PickerBackgroundColor;
_navigationController.Toolbar.Translucent = true;
_navigationController.Toolbar.BarTintColor = ToolbarBarTintColor;
_navigationController.Toolbar.TintColor = ToolbarTintColor;
_navigationController.Toolbar.BackgroundColor = ToolbarBackgroundColor;
_navigationController.NavigationBar.TintColor = NavigationBarTintColor;
_navigationController.NavigationBar.BarTintColor = NavigationBarBarTintColor;
_navigationController.NavigationBar.BackgroundColor = NavigationBarBackgroundColor;
UIStringAttributes attributes;
if (UseCustomFontForNavigationBar) {
attributes = new UIStringAttributes { ForegroundColor = NavigationBarTextColor,
Font = UIFont.FromName (PickerBoldFontName, PickerFontHeaderSize)
};
} else {
attributes = new UIStringAttributes { ForegroundColor = NavigationBarTextColor };
}
_navigationController.NavigationBar.TitleTextAttributes = attributes;
UpdateToolbar ();
}
/// <summary>
/// Checks if access to the Camera is granted, and if not (Denied), shows an error message.
/// </summary>
public async Task<bool> EnsureHasCameraAccess()
{
var status = AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video);
if (status == AVAuthorizationStatus.Denied) {
var alert = UIAlertController.Create (CustomCameraAccessDeniedErrorTitle ?? "picker.camera-access-denied.title".Translate (),
CustomCameraAccessDeniedErrorMessage ?? "picker.camera-access-denied.message".Translate (),
UIAlertControllerStyle.Alert);
alert.AddAction (UIAlertAction.Create ("picker.navigation.cancel-button".Translate("Cancel"), UIAlertActionStyle.Cancel, null));
alert.AddAction (UIAlertAction.Create ("picker.navigation.settings-button".Translate("Settings"), UIAlertActionStyle.Default, (action) => UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString))));
await PresentViewControllerAsync (alert, true);
return false;
} else if (status == AVAuthorizationStatus.NotDetermined) {
return await AVCaptureDevice.RequestAccessForMediaTypeAsync (AVMediaType.Video) &&
await EnsureHasPhotosPermission ();
}
return await EnsureHasPhotosPermission ();
}
/// <summary>
/// Checks if access to Photos is granted, and if not (Denied), shows an error message.
/// </summary>
public async Task<bool> EnsureHasPhotosPermission()
{
var status = ALAssetsLibrary.AuthorizationStatus;
if (status == ALAuthorizationStatus.Denied) {
var alert = UIAlertController.Create (CustomPhotosAccessDeniedErrorTitle ?? "picker.photo-access-denied.title".Translate (),
CustomPhotosAccessDeniedErrorMessage ?? "picker.photo-access-denied.message".Translate (),
UIAlertControllerStyle.Alert);
alert.AddAction (UIAlertAction.Create ("picker.navigation.cancel-button".Translate("Cancel"), UIAlertActionStyle.Cancel, null));
alert.AddAction (UIAlertAction.Create ("picker.navigation.settings-button".Translate("Settings"), UIAlertActionStyle.Default, (action) => UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString))));
await PresentViewControllerAsync (alert, true);
return false;
}
return true;
}
private void SetupNavigationController()
{
if (_albumsViewController == null) {
_albumsViewController = new GMAlbumsViewController ();
}
_navigationController = new UINavigationController (_albumsViewController);
_navigationController.Delegate = new GMNavigationControllerDelegate ();
_navigationController.NavigationBar.Translucent = true;
_navigationController.View.Frame = View.Frame;
_navigationController.WillMoveToParentViewController (this);
View.AddSubview (_navigationController.View);
AddChildViewController (_navigationController);
_navigationController.DidMoveToParentViewController (this);
}
internal void NotifyAssetSelected(PHAsset asset)
{
var e = AssetSelected;
if (e != null) {
e (this, new SingleAssetEventArgs (asset));
}
}
internal void NotifyAssetDeselected(PHAsset asset)
{
var e = AssetDeselected;
if (e != null) {
e (this, new SingleAssetEventArgs (asset));
}
}
internal void NotifyAssetHighlighted(PHAsset asset)
{
var e = AssetHighlighted;
if (e != null) {
e (this, new SingleAssetEventArgs (asset));
}
}
internal void NotifyAssetUnhighlighted(PHAsset asset)
{
var e = AssetUnhighlighted;
if (e != null) {
e (this, new SingleAssetEventArgs (asset));
}
}
internal bool VerifyShouldEnableAsset(PHAsset asset)
{
return VerifyCancellableAssetEventHandler (asset, ShouldEnableAsset);
}
internal bool VerifyShouldShowAsset(PHAsset asset)
{
return VerifyCancellableAssetEventHandler (asset, ShouldShowAsset);
}
internal bool VerifyShouldHighlightAsset(PHAsset asset)
{
return VerifyCancellableAssetEventHandler (asset, ShouldHighlightAsset);
}
internal bool VerifyShouldDeselectAsset(PHAsset asset)
{
return VerifyCancellableAssetEventHandler (asset, ShouldDeselectAsset);
}
internal bool VerifyShouldSelectAsset(PHAsset asset)
{
return VerifyCancellableAssetEventHandler (asset, ShouldSelectAsset);
}
private bool VerifyCancellableAssetEventHandler(PHAsset asset, CancellableAssetEventHandler del, bool defaultValue = true)
{
var result = defaultValue;
var e = del;
if (e != null) {
var args = new CancellableAssetEventArgs (asset);
e (this, args);
result = !args.Cancel;
}
return result;
}
private class GMNavigationControllerDelegate : UINavigationControllerDelegate
{
// Placeholder class to act as NavigationControllerDelegate
}
public override UIStatusBarStyle PreferredStatusBarStyle ()
{
return PickerStatusBarStyle;
}
private string ToolbarTitle
{
get {
if (!_selectedAssets.Any ()) {
return null;
}
var nImages = _selectedAssets.Count (a => a.MediaType == PHAssetMediaType.Image);
var nVideos = _selectedAssets.Count (a => a.MediaType == PHAssetMediaType.Video);
if (nImages > 0 && nVideos > 0) {
return string.Format ("picker.selection.multiple-items".Translate (defaultValue: "{0} items selected"), nImages + nVideos);
} else if (nImages > 1) {
return string.Format ("picker.selection.multiple-photos".Translate (defaultValue: "{0} photos selected"), nImages);
} else if (nImages == 1) {
return "picker.selection.single-photo".Translate (defaultValue: "1 photo selected");
} else if (nVideos > 1) {
return string.Format ("picker.selection.multiple-videos".Translate (defaultValue: "{0} videos selected"), nVideos);
} else if (nVideos == 1) {
return "picker.selection.single-video".Translate (defaultValue: "1 video selected");
} else {
return null;
}
}
}
private UITextAttributes ToolbarTitleTextAttributes
{
get {
return new UITextAttributes {
TextColor = ToolbarTextColor,
Font = UIFont.FromName (PickerFontName, PickerFontHeaderSize)
};
}
}
private UIBarButtonItem CreateTitleButtonItem ()
{
var title = new UIBarButtonItem (ToolbarTitle,
UIBarButtonItemStyle.Plain,
null, null);
var attributes = ToolbarTitleTextAttributes;
title.SetTitleTextAttributes (attributes, UIControlState.Normal);
title.SetTitleTextAttributes (attributes, UIControlState.Disabled);
title.Enabled = false;
return title;
}
private UIBarButtonItem CreateSpaceButtonItem ()
{
return new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace);
}
private UIBarButtonItem CreateCameraButtonItem ()
{
return new UIBarButtonItem(UIBarButtonSystemItem.Camera, CameraButtonPressed)
{
TintColor = CameraButtonTintColor
};
}
internal UIBarButtonItem[] GetToolbarItems ()
{
var title = CreateTitleButtonItem ();
var space = CreateSpaceButtonItem ();
var items = new List<UIBarButtonItem> ();
if (ShowCameraButton) {
items.Add (CreateCameraButtonItem());
}
items.Add (space);
items.Add (title);
items.Add (space);
return items.ToArray ();
}
private void Unregister ()
{
if (_albumsViewController != null) {
_albumsViewController.Dispose ();
_albumsViewController = null;
}
}
protected override void Dispose (bool disposing)
{
Unregister ();
base.Dispose (disposing);
}
}
}
|
Duranom/GMImagePicker.Xamarin
|
src/GMImagePicker/GMImagePickerController.cs
|
C#
|
mit
| 29,797
|
"""config URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cards/', include('cards.urls')),
url(r'^tournaments/', include('tournaments.urls')),
url(r'^stats/', include('stats.urls'))
]
|
thomasperrot/MTGTrader
|
mtg/config/urls.py
|
Python
|
mit
| 915
|
/**
Bit operation macros
@author Natesh Narain
*/
#ifndef BITUTIL_H
#define BITUTIL_H
//! Bit value
template<typename T>
inline T bv(T b)
{
return 1 << b;
}
//! set mask y in x
template<typename Tx, typename Ty>
inline void setMask(Tx& x, Ty y) noexcept
{
x |= (Tx)y;
}
//! clear mask y in x
template<typename Tx, typename Ty>
inline void clearMask(Tx& x, Ty y) noexcept
{
x &= ~((Tx)y);
}
//! toggle mask y in x
template<typename Tx, typename Ty>
inline void toggleMask(Tx& x, Ty y) noexcept
{
x ^= (Tx)y;
}
//! set bit y in x
template<typename Tx, typename Ty>
inline void setBit(Tx& x, Ty y) noexcept
{
setMask(x, bv(y));
}
//! clear bit y in x
template<typename Tx, typename Ty>
inline void clearBit(Tx& x, Ty y) noexcept
{
clearMask(x, bv(y));
}
//! toggle bit y in x
template<typename Tx, typename Ty>
inline void toggleBit(Tx& x, Ty y) noexcept
{
toggleMask(x, bv(y));
}
//!
template<typename Tx>
inline Tx lownybble(const Tx& x) noexcept
{
return x & 0x0F;
}
//!
template<typename T>
inline T highnybble(const T& t) noexcept
{
return (t >> 4);
}
//! Create a WORD
template<typename Tx, typename Ty>
inline uint16_t word(const Tx& hi, const Ty& lo) noexcept
{
return ((hi & 0xFFFF) << 8) | (lo & 0xFFFF);
}
//! Get bit
template<typename Tx, typename Ty>
inline Tx getBit(const Tx& x, const Ty& n) noexcept
{
return !!(x & bv(n));
}
//! check if mask y is set in x
template<typename Tx, typename Ty>
inline bool isSet(const Tx& x, const Ty& y) noexcept
{
return (x & y) != 0;
}
//! check if mask y is clear in x
template<typename Tx, typename Ty>
inline bool isClear(const Tx& x, const Ty& y) noexcept
{
return !(x & y);
}
//! check if bit y is set in x
//#define isBitSet(x,y) ( isSet(x, bv(y)) )
template<typename Tx, typename Ty>
inline bool isBitSet(const Tx& x, const Ty& y) noexcept
{
return isSet(x, bv(y));
}
//! check if bit y is clear in x
template<typename Tx, typename Ty>
inline bool isBitClear(const Tx& x, const Ty& y) noexcept
{
return isClear(x, bv(y));
}
/* Full and Half Carry */
template<typename Tx, typename Ty>
inline bool isHalfCarry(const Tx& x, const Ty& y) noexcept
{
return (((x & 0x0F) + (y & 0x0F)) & 0x10) != 0;
}
template<typename Tx, typename Ty>
inline bool isFullCarry(const Tx& x, const Ty& y) noexcept
{
return (((x & 0x0FF) + (y & 0x0FF)) & 0x100) != 0;
}
template<typename Tx, typename Ty>
inline bool isHalfCarry16(const Tx& x, const Ty& y) noexcept
{
return ((((x & 0x0FFF) + (y & 0x0FFF)) & 0x1000) != 0);
}
template<typename Tx, typename Ty>
inline bool isFullCarry16(const Tx& x, const Ty& y) noexcept
{
return ((((x & 0x0FFFF) + ((y & 0x0FFFF))) & 0x10000) != 0);
}
template<typename Tx, typename Ty>
inline bool isHalfBorrow(const Tx& x, const Ty& y) noexcept
{
return ((x & 0x0F) < (y & 0x0F));
}
template<typename Tx, typename Ty>
inline bool isFullBorrow(const Tx& x, const Ty& y) noexcept
{
return ((x & 0xFF) < (y & 0xFF));
}
#endif // BITUTIL_H
|
nnarain/GameBoyCore
|
src/gameboycore/src/bitutil.h
|
C
|
mit
| 3,019
|
<div>
<button class="backtohome" v-on="click: currentScreen = 'livenow'">☰</button>
<div class="app-screen" v-scroll>
<div class="page-content">
<h1 class="page-title">Classroom</h1>
<div style="position:absolute; top:0; left:0; z-index:9999;"><img src="img/overlay.png" width="1080" height="1920" /></div>
<object width="1000" height="821"><param name="movie" value="https://www.dropcam.com/e/01cc34940cb0409b971e779a054f5a1b?autoplay=true"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="opaque"></param><embed src="https://www.dropcam.com/e/01cc34940cb0409b971e779a054f5a1b?autoplay=true" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="1000" height="821" wmode="opaque"></embed></object>
</div><!-- ///// end.page-content////// -->
</div><!-- ///// end.app-screen////// -->
</div>
|
fresk/firehouse
|
src/views/camera3.html
|
HTML
|
mit
| 949
|
from OpenGLCffi.GL import params
@params(api='gl', prms=['pname', 'index', 'val'])
def glGetMultisamplefvNV(pname, index, val):
pass
@params(api='gl', prms=['index', 'mask'])
def glSampleMaskIndexedNV(index, mask):
pass
@params(api='gl', prms=['target', 'renderbuffer'])
def glTexRenderbufferNV(target, renderbuffer):
pass
|
cydenix/OpenGLCffi
|
OpenGLCffi/GL/EXT/NV/explicit_multisample.py
|
Python
|
mit
| 332
|
<!DOCTYPE html>
<html lang="en-us" dir="ltr" itemscope itemtype="http://schema.org/Article">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Adeus Primeiro Amor</title>
<meta name="author" content="" />
<meta name="description"
content="Apesar de toda a sutileza e competência visual ao contar o romance de dois jovens, primeiro amor de ambos, e a posterior separação e amadurecimento de ambos, acaba se tornando vazia quando percebemos..."/>
<meta name="yandex-verification" content="48a8210fc043c5e8" />
<meta name="generator" content="Hugo 0.54.0" />
<meta itemprop="name" content="Adeus Primeiro Amor"/>
<meta itemprop="description"
content="Apesar de toda a sutileza e competência visual ao contar o romance de dois jovens, primeiro amor de ambos, e a posterior separação e amadurecimento de ambos, acaba se tornando vazia quando percebemos..."/>
<meta itemprop="image"
content="/img/logo.svg"/>
<meta property="og:title" content="Adeus Primeiro Amor"/>
<meta property="og:type"
content="article"/>
<meta property="og:url" content="http://www.cinetenisverde.com.br/adeus-primeiro-amor/"/>
<meta property="og:image"
content="/img/logo.svg"/>
<meta property="og:description"
content="Apesar de toda a sutileza e competência visual ao contar o romance de dois jovens, primeiro amor de ambos, e a posterior separação e amadurecimento de ambos, acaba se tornando vazia quando percebemos..."/>
<meta property="og:site_name" content="Cine Tênis Verde"/>
<meta property="article:published_time"
content="2012-01-09T00:00:00+00:00"/>
<meta property="article:section" content="post"/>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:site"
content=""/>
<meta name="twitter:title" content="Adeus Primeiro Amor"/>
<meta name="twitter:description"
content="Apesar de toda a sutileza e competência visual ao contar o romance de dois jovens, primeiro amor de ambos, e a posterior separação e amadurecimento de ambos, acaba se tornando vazia quando percebemos..."/>
<meta name="twitter:creator"
content=""/>
<meta name="twitter:image:src"
content="/img/logo.svg"/>
<link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
<link rel="stylesheet" type="text/css" href="/css/custom.css"/>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-50557403-1', 'auto');
ga('send', 'pageview');
</script>
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
<link rel="icon" href="/img/favicon.ico"/>
</head>
<body style="min-height:100vh;display:flex;flex-direction:column">
<nav class="navbar has-shadow is-white"
role="navigation" aria-label="main navigation">
<div class="container">
<div class="navbar-brand">
<a class="navbar-item" href="/">
<img alt="Brand" src="/img/brand.svg">
<div class="title is-4"> Cine Tênis Verde</div>
</a>
<label class="button navbar-burger is-white" for="navbar-burger-state">
<span></span>
<span></span>
<span></span>
</label>
</div>
<input type="checkbox" id="navbar-burger-state"/>
<div class="navbar-menu">
<div class="navbar-end">
<a href="/post"
class="navbar-item
">search
</a>
<a href="https://twitter.com/cinetenisverde"
class="navbar-item
">twitter
</a>
<a href="/index.xml"
class="navbar-item
">rss
</a>
</div>
</div>
</div>
</nav>
<section class="section" style="flex:1">
<div class="container">
<p class="title">Adeus Primeiro Amor</p>
<p class="subtitle"><span class="entry-sidebar-stars">
★★★☆☆
</span>
Wanderley Caloni, <a href="https://github.com/Caloni/cinetenisverde/commits/master/content/post/adeus-primeiro-amor.md">January 9, 2012</a></p>
<p><p>
<div class="content">
<p>Apesar de toda a sutileza e competência visual ao contar o romance de dois jovens, primeiro amor de ambos, e a posterior separação e amadurecimento de ambos, acaba se tornando vazia quando percebemos que a experiência ditada pelo diretor/roteiro de Mia Hansen-Løve não há nada mais a oferecer senão uma trilha sonora bem escolhida e enquadramentos sublimes (sobretudo se aliado à competente fotografia, que não se intimida pelas diversas luzes escolhidas para os cenários). Além disso, temos surpreendentes três atuações medíocres, que não oferecem nada além do óbvio, o que é um assombro, principalmente ao notarmos o tempo de tela da protagonista Lola Créton, que constrói uma Camille convincentemente apaixonada no início para tornar-se insuportavelmente apática por todo o resto, como se o sinal óbvio de amadurecimento fosse se tornar um tédio.</p>
<a href="https://www.imdb.com/title/tt1618447/mediaviewer/" target="ctvimg">Imagens</a> e créditos no <a title="IMDB: Internet Movie DataBase" href="http://www.imdb.com/title/tt1618447">IMDB</a>.
</div>
<span class="entry-sidebar-stars">
★★★☆☆
</span>
Adeus Primeiro Amor ● Adeus Primeiro Amor. Un amour de jeunesse (France, 2011). Dirigido por Mia Hansen-Løve. Escrito por Mia Hansen-Løve. Com Lola Créton, Sebastian Urzendowsky, Magne-Håvard Brekke, Valérie Bonneton, Serge Renko, Özay Fecht, Max Ricat, Louis Dunbar, Philippe Paimblanc. ● Nota: 3/5. Categoria: movies. Publicado em 2012-01-09. Texto escrito por Wanderley Caloni.
<p><br>Quer <a href="https://twitter.com/search?q=@cinetenisverde Adeus%20Primeiro%20Amor">comentar</a>?<br></p>
</div>
</section>
<section class="section">
<br>
<div class="container">
<div class="is-flex">
<span>
<a class="button">Share</a>
</span>
<span>
<a class="button"
href="https://www.facebook.com/sharer/sharer.php?u=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f">
<span class="icon"><i class="fa fa-facebook"></i></span>
</a>
<a class="button"
href="https://twitter.com/intent/tweet?url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f&text=Adeus%20Primeiro%20Amor">
<span class="icon"><i class="fa fa-twitter"></i></span>
</a>
<a class="button"
href="https://news.ycombinator.com/submitlink?u=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f">
<span class="icon"><i class="fa fa-hacker-news"></i></span>
</a>
<a class="button"
href="https://reddit.com/submit?url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f&title=Adeus%20Primeiro%20Amor">
<span class="icon"><i class="fa fa-reddit"></i></span>
</a>
<a class="button"
href="https://plus.google.com/share?url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f">
<span class="icon"><i class="fa fa-google-plus"></i></span>
</a>
<a class="button"
href="https://www.linkedin.com/shareArticle?url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f&title=Adeus%20Primeiro%20Amor">
<span class="icon"><i class="fa fa-linkedin"></i></span>
</a>
<a class="button"
href="https://www.tumblr.com/widgets/share/tool?canonicalUrl=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f&title=Adeus%20Primeiro%20Amor&caption=">
<span class="icon"><i class="fa fa-tumblr"></i></span>
</a>
<a class="button"
href="https://pinterest.com/pin/create/bookmarklet/?media=%2fimg%2flogo.svg&url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f&description=Adeus%20Primeiro%20Amor">
<span class="icon"><i class="fa fa-pinterest"></i></span>
</a>
<a class="button"
href="whatsapp://send?text=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f">
<span class="icon"><i class="fa fa-whatsapp"></i></span>
</a>
<a class="button"
href="https://web.skype.com/share?url=http%3a%2f%2fwww.cinetenisverde.com.br%2fadeus-primeiro-amor%2f">
<span class="icon"><i class="fa fa-skype"></i></span>
</a>
</span>
</div>
</div>
<br>
</section>
<footer class="footer">
<div class="container">
<nav class="level">
<div class="level-right has-text-centered">
<div class="level-item">
<a class="button" href="http://www.cinetenisverde.com.br/">
<span class="icon"><i class="fa fa-home"></i></span>
</a>
<a class="button" href="/post">
<span class="icon"><i class="fa fa-search"></i></span>
</a>
<a class="button" href="https://twitter.com/cinetenisverde">
<span class="icon"><i class="fa fa-twitter"></i></span>
</a>
<a class="button" href="/index.xml">
<span class="icon"><i class="fa fa-rss"></i></span>
</a>
</div>
</div>
</nav>
</div>
</footer>
</body>
</html>
|
cinetenisverde/cinetenisverde.github.io
|
adeus-primeiro-amor/index.html
|
HTML
|
mit
| 10,245
|
class AddBodyUseridToTweet < ActiveRecord::Migration
def up
add_column :tweets, :body, :text
add_column :tweets, :user_id, :integer
end
def down
remove_column :tweets, :body, :text
remove_column :tweets, :user_id, :integer
end
end
|
lowellmower/twitter_map_v1
|
db/migrate/20150509155953_add_body_userid_to_tweet.rb
|
Ruby
|
mit
| 256
|
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
#include "dcgf.h"
#include "VidRendererDD.h"
//////////////////////////////////////////////////////////////////////////
CVidRendererDD::CVidRendererDD(CBGame* inGame):CVidRenderer(inGame)
{
}
//////////////////////////////////////////////////////////////////////////
CVidRendererDD::~CVidRendererDD()
{
}
//////////////////////////////////////////////////////////////////////////
HRESULT CVidRendererDD::ProcessFrame(LPBITMAPINFOHEADER Frame)
{
CBSurfaceDD* surf = (CBSurfaceDD*)m_Surface;
LONG BmpPitch = Frame->biWidth * (Frame->biBitCount >> 3);
surf->Lock();
BYTE* BmpBuffer = (BYTE*)Frame+Frame->biSize+Frame->biClrUsed * sizeof(RGBQUAD);
BYTE* TxtBuffer = (BYTE*)surf->m_SurfaceDesc.lpSurface;
// bitmap is bottom up...
BmpBuffer += BmpPitch * (Frame->biHeight - 1);
RenderFrame(BmpBuffer, TxtBuffer, BmpPitch, surf->m_SurfaceDesc.lPitch, Frame->biWidth, Frame->biHeight);
surf->Unlock();
return S_OK;
}
//////////////////////////////////////////////////////////////////////////
HRESULT CVidRendererDD::ProcessFrameSlow(LPBITMAPINFOHEADER Frame)
{
LPDIRECTDRAWSURFACE7 pDestSurface = ((CBSurfaceDD*)m_Surface)->m_Surface;
LPBITMAPINFO pBmpInfo = (LPBITMAPINFO)Frame;
LPBITMAPINFOHEADER pBmpInfoHeader = (LPBITMAPINFOHEADER)pBmpInfo;
HDC hdc;
pDestSurface->GetDC(&hdc);
LPBYTE pBmpBits = ((LPBYTE)pBmpInfo) + pBmpInfo->bmiHeader.biSize;
LPBYTE pGDIBits;
HBITMAP hBmp = CreateDIBSection(hdc, pBmpInfo, DIB_RGB_COLORS, (LPVOID*)&pGDIBits, NULL, 0);
memcpy(pGDIBits, pBmpBits, pBmpInfoHeader->biSizeImage);
HDC hBmpDC = CreateCompatibleDC(hdc);
HGDIOBJ pOldObj = SelectObject(hBmpDC, hBmp);
BitBlt(hdc, 0, 0, pBmpInfoHeader->biWidth, pBmpInfoHeader->biHeight, hBmpDC, 0, 0, SRCCOPY);
if(pOldObj) SelectObject(hBmpDC, pOldObj);
DeleteObject(hBmp);
DeleteDC(hBmpDC);
pDestSurface->ReleaseDC(hdc);
return S_OK;
}
//////////////////////////////////////////////////////////////////////////
HRESULT CVidRendererDD::GetTargetFormat(LPBITMAPV4HEADER Format)
{
CBSurfaceDD* surf = (CBSurfaceDD*)m_Surface;
Format->bV4BitCount = (WORD)surf->m_SurfaceDesc.ddpfPixelFormat.dwRGBBitCount;
Format->bV4V4Compression = BI_BITFIELDS;
if(Format->bV4BitCount==24) Format->bV4V4Compression = BI_RGB;
Format->bV4ClrUsed = 0;
Format->bV4RedMask = surf->m_SurfaceDesc.ddpfPixelFormat.dwRBitMask;
Format->bV4GreenMask = surf->m_SurfaceDesc.ddpfPixelFormat.dwGBitMask;
Format->bV4BlueMask = surf->m_SurfaceDesc.ddpfPixelFormat.dwBBitMask;
Format->bV4AlphaMask = surf->m_SurfaceDesc.ddpfPixelFormat.dwRGBAlphaBitMask;
Format->bV4SizeImage = ((Format->bV4Width+3)&0xFFFFFFFC)*Format->bV4Height * (Format->bV4BitCount>>3);
return S_OK;
}
|
segafan/wme1_jankavan_tlc_edition-repo
|
src/engine_core/wme_base/VidRendererDD.cpp
|
C++
|
mit
| 2,960
|
'use strict'
let models = require('../models')
let express = require('express')
let multer = require('multer')
let upload = multer({dest: 'uploads/'})
let router = express.Router()
let utils = require('./utils')
router.get('', (req, res, next) => {
let result = {
messages: []
}
models.File.findAndCountAll(
).then(files => {
result.data = files.rows
result.length = files.count
res.writeHead(200, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.get('/:id', (req, res, next) => {
let params = {}
let result = {
messages: []
}
params = req.query
models.File.findById(
req.params.id || -1,
utils.setWhere(params)
).then(file => {
result.data = file || {}
result.length = (file) ? 1 : 0
res.writeHead((file) ? 200 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.post('', upload.array('file', 10), (req, res, next) => {
let result = {}
let file = {
id: req.body.id || (new Date()).valueOf(),
originalName: req.files[0].originalname,
fileName: req.files[0].filename,
size: req.files[0].size
}
models.File.create(
file
).then(file => {
result = {
data: file,
length: 1,
messages: [{
type: 'success',
code: 201,
detail: 'Recurso criado com sucesso'
}]
}
res.writeHead(201, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`, 422, {})
})
})
router.delete('', (req, res, next) => {
utils.fnError405(res)
})
router.delete('/:id', (req, res, next) => {
let result = {
data: {},
length: 0,
messages: []
}
models.File.destroy({
where: {
id: req.params.id
}
}).then(file => {
if (file === 1) {
result.messages = [{
type: 'success',
code: 204,
detail: 'Recurso excluído com sucesso'
}]
} else {
result.messages = [{
type: 'warning',
code: 404,
detail: 'Recurso não encontrado'
}]
}
res.writeHead(file === 1 ? 204 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
module.exports = router
|
devtotvs/thf-sample-api
|
routes/files.js
|
JavaScript
|
mit
| 2,432
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sun Dec 11 02:01:58 EET 2011 -->
<TITLE>
edu.cmu.cs.stage3.alice.scripting.jython
</TITLE>
<META NAME="date" CONTENT="2011-12-11">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="edu.cmu.cs.stage3.alice.scripting.jython";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../../edu/cmu/cs/stage3/awt/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?edu/cmu/cs/stage3/alice/scripting/jython/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package edu.cmu.cs.stage3.alice.scripting.jython
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/Code.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">Code</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/Interpreter.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">Interpreter</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/Namespace.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">Namespace</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/PyElement.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">PyElement</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/PySandbox.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">PySandbox</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/jython/ScriptingFactory.html" title="class in edu.cmu.cs.stage3.alice.scripting.jython">ScriptingFactory</A></B></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../edu/cmu/cs/stage3/alice/scripting/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../../edu/cmu/cs/stage3/awt/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?edu/cmu/cs/stage3/alice/scripting/jython/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
ai-ku/langvis
|
doc/edu/cmu/cs/stage3/alice/scripting/jython/package-summary.html
|
HTML
|
mit
| 7,817
|
module Bwoken
VERSION = "2.1.0.rc.2" unless defined?(::Bwoken::VERSION)
end
|
bendyworks/bwoken
|
lib/bwoken/version.rb
|
Ruby
|
mit
| 78
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//require APPPATH . '/libraries/REST_Controller.php';
class CarMakes extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model("carmakes_model","cm");
}
public function index()
{
$this->load->model("carmakes_model");
$makes = $this->carmakes_model->getCarMake();
// die('<pre>'.print_r($makes, true));
$this->load->view("header", array("title" => "Car Makes"));
$this->load->view("carmakes/carmakes", $makes);
$this->load->view("carmakes/footer");
}
}
|
oscarsmartwave/l45fbl45t
|
application/controllers/Carmakes.php
|
PHP
|
mit
| 592
|
<!doctype html>
<html>
<head>
<title>CSS Ribbon Builder</title>
<!--link rel="shortcut icon" href="misc/ribbon.png" /-->
<link rel="icon" type="image/png" href="misc/ribbon.png" />
<style>
html, body {
margin: 0; padding: 0;
background-color: #e5e5e5;
color: #555;
text-align: center;
font-family: sans-serif;
font-size: .95em;
}
body{
width: 95%;
max-width: 600px;
margin: 0 auto;
z-index: 0;
}
.heading {
font-size: 2em;
margin: 15px;
}
.section {
margin: 15px 0;
}
.section .title {
font-size: 1.2em;
margin: 1.4em 0 0;
}
#locLeft, #locRight {
display: inline-block;
width: 200px;
}
#locLeft { text-align: right; }
#locRight { text-align: left; }
pre, input[type="text"] {
box-sizing: border-box;
width: 100%;
padding: 10px;
margin: 10px 0 0;
background-color: white;
border: 1px solid gray;
border-radius: 2px;
font-size: 1.2em;
}
input[type="text"] {
color: inherit;
}
input[name="hex"] { width: 100px; }
pre {
color: black;
font-weight: normal;
text-align: left;
white-space: pre-wrap;
}
#picker { width: 200px; height: 200px; display: inline-block; }
#slider { width: 20px; height: 200px; display: inline-block; }
#fork { z-index: 4; }
.CodeMirror.CodeMirror {
height: auto;
z-index: 1;
}
</style>
</head>
<body>
<a id="fork" class="" href="https://github.com/catdad/fork-ribbon-css-builder" style="display: none;">Fork me on GitHub</a>
<div class="heading">Pure CSS generator for the "Fork me on GitHub" ribbon</div>
<div class="section">
<div class="title">Ribbon color</div>
<div id="picker"></div>
<div id="slider"></div>
<br/>
<input type="text" name="hex" placeholder="color" />
</div>
<div class="section">
<div class="title">Position on the page</div>
<div id="locLeft">
<div>Top Left <input type="radio" name="position" value="top-left" /></div>
<div>Bottom Left <input type="radio" name="position" value="bottom-left" /></div>
</div>
<div id="locRight">
<div><input type="radio" name="position" value="top-right" checked /> Top Right</div>
<div><input type="radio" name="position" value="bottom-right" /> Bottom Right</div>
</div>
</div>
<div class="section">
<div class="title">Font color</div>
<input name="text" type="radio" value="#fff" checked /> White
<input name="text" type="radio" value="#e5e5e5" /> Gray
<input name="text" type="radio" value="#555" /> Dark
<input name="flat" type="checkbox" /> Flat
</div>
<div class="section">
<div class="title">Link URL</div>
<input type="text" name="link" placeholder="http://github.com/user/repo" />
</div>
<div class="section">
<div class="title">CSS Code</div>
<pre id="rawcss"></pre>
</div>
<div class="section">
<div class="title">Copy and Paste</div>
<pre id="copypaste"></pre>
</div>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/1.7.4/less.min.js"></script>
<script src="http://catdad.github.io/tiny.cdn/lib/request/0.3.0/request.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>
<script type="text/javascript" src="misc/colorpicker.min.js"></script>
<script type="text/javascript" src="misc/analytics.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
|
leonardohipolito/fork-ribbon-css-builder
|
index.html
|
HTML
|
mit
| 3,814
|
'use strict';
// MODULES //
var factory = require( './factory.js' );
// URLS //
/**
* FUNCTION: urls( options, clbk )
* Get repository URLs for one or more packages.
*
* @param {Object} options - function options
* @param {String[]} options.packages - package names
* @param {String} [options.registry="registry.npmjs.org"] - registry
* @param {Number} [options.port=443] - registry port
* @param {String} [options.protocol="https"] - registry protocol
* @param {Function} clbk - callback to invoke upon query completion
* @returns {Void}
*/
function urls( options, clbk ) {
factory( options, clbk )();
} // end FUNCTION urls()
// EXPORTS //
module.exports = urls;
|
kgryte/npm-repo-url
|
lib/urls.js
|
JavaScript
|
mit
| 674
|
# encoding: UTF-8
class Deck
# Represents a game deck containing 52 cards.
# plus helper methods to handle the deck.
# Creates a new ordered deck. 52 card deck of cards. 1 per suite
def self.build_deck
deck = []
FrenchDeck::SUIT.each do |suit|
FrenchDeck::TYPE.each do |type|
deck.push( Card.new(suit, type))
end
end
deck
end
# Returns a copy of a random shuffled deck.
def self.shuffle(deck)
deck.shuffle(random: Random.new(Time.now.to_i))
end
end
|
ivanmarcin/BJG
|
lib/blackjack/cards/deck.rb
|
Ruby
|
mit
| 503
|
// media query constants
(function() {
'use strict';
var MQ = {
SMALL: '(max-width: 767px)',
LARGE: '(min-width: 768px)'
};
angular
.module('rBox')
.constant('MQ', MQ);
}());
|
kmaida/mean-rBox
|
public/ng-app/core/ui/MQ.constant.js
|
JavaScript
|
mit
| 188
|
//
// AsyncVoidMethodBuilder.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Threading;
namespace System.Runtime.CompilerServices
{
public struct AsyncVoidMethodBuilder
{
static readonly SynchronizationContext null_context = new SynchronizationContext ();
readonly SynchronizationContext context;
IAsyncStateMachine stateMachine;
private AsyncVoidMethodBuilder (SynchronizationContext context)
{
this.context = context;
this.stateMachine = null;
}
public void AwaitOnCompleted<TAwaiter, TStateMachine> (ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
var action = new Action (stateMachine.MoveNext);
awaiter.OnCompleted (action);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine> (ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
var action = new Action (stateMachine.MoveNext);
awaiter.UnsafeOnCompleted (action);
}
public static AsyncVoidMethodBuilder Create ()
{
var ctx = SynchronizationContext.Current ?? null_context;
ctx.OperationStarted ();
return new AsyncVoidMethodBuilder (ctx);
}
public void SetException (Exception exception)
{
if (exception == null)
throw new ArgumentNullException ("exception");
try {
context.Post (l => { throw (Exception) l; }, exception);
} finally {
SetResult ();
}
}
public void SetStateMachine (IAsyncStateMachine stateMachine)
{
if (stateMachine == null)
throw new ArgumentNullException ("stateMachine");
if (this.stateMachine != null)
throw new InvalidOperationException ("The state machine was previously set");
this.stateMachine = stateMachine;
}
public void SetResult ()
{
context.OperationCompleted ();
}
public void Start<TStateMachine> (ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
if (stateMachine == null)
throw new ArgumentNullException ("stateMachine");
stateMachine.MoveNext ();
}
}
}
|
PalmStoneGames/ModernBcl
|
ModernBcl/Runtime.CompilerServices/AsyncVoidMethodBuilder.cs
|
C#
|
mit
| 3,359
|
import os, pickle, re, sys, rsa
from common.safeprint import safeprint
from common.call import parse
from multiprocessing import Lock
from hashlib import sha256
global bountyList
global bountyLock
global bountyPath
global masterKey
bountyList = []
bountyLock = Lock()
bounty_path = "data" + os.sep + "bounties.pickle"
masterKey = rsa.PublicKey(*pickle.load(open("master_public_key.pickle", "rb")))
def getUTC():
from calendar import timegm
from time import gmtime
return timegm(gmtime())
class Bounty(object):
"""An object representation of a Bounty
Parts:
ip -- The ip address of the requesting node
btc -- The Bitcoin address of the requesting party
reward -- The reward amount in satoshis to be given over 24 hours
(x == 0 or 1440 <= x <= 100000000) (1440 is 1 satoshi/min)
ident -- A value set by the issuer to help manage its related files
timeout -- Unix time at which the bounty expires (defaults to 24 hours)
data -- A dictionary containing optional, additional information
author -- String which represents the group providing the Bounty
reqs -- Dict containing requirements keyed by the related python call
("sys.platform":"win32")
perms -- Dict containing the minimum required security policies
(if empty, most restrictive assumed)
key -- A tuple which contains the RSA n and e values for this Bounty
(required only when reward is 0)
sig -- A Bytes object of str(Bounty) signed by the above key
(required only when reward is 0)
TDL -- More to be defined in later versions
"""
def __repr__(self):
"""Gives a string representation of the bounty"""
output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout)
output = output + ", author=" + str(self.data.get('author'))
if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict):
output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
if self.data.get('perms') != {} and isinstance(self.data.get('perms'), dict):
output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
return output + ">"
def __eq__(self, other):
"""Determines whether the bounties are equal"""
try:
return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)
except:
return other is not None
def __ne__(self, other):
"""Determines whether the bounties are unequal"""
try:
return not self.__eq__(other)
except:
return other is None
def __lt__(self, other):
"""Determines whether this bounty has a lower priority"""
try:
if self.reward < other.reward:
return True
elif self.timeout < other.timeout:
return True
else:
return False
except:
return other is not None
def __gt__(self, other):
"""Determines whether this bounty has a higher priority"""
try:
if self.reward > other.reward:
return True
elif self.timeout > other.timeout:
return True
else:
return False
except:
return other is None
def __le__(self, other):
"""Determines whether this bounty has a lower priority or is equal"""
boolean = self.__lt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __ge__(self, other):
"""Determines whether this bounty has a higher or is equal"""
boolean = self.__gt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __hash__(self):
return hash((self.__repr__(), str(self.data)))
def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs):
"""Initialize a Bounty; constructor"""
self.ip = ipAddress
self.btc = btcAddress
self.reward = rewardAmount
self.ident = ''
if kargs.get('timeout') is not None:
self.timeout = kargs.get('timeout')
else:
self.timeout = getUTC() + 86400
self.data = {'author': '',
'reqs': {},
'perms': {}}
if kargs.get('ident') is not None:
self.ident = kargs.get('ident')
if kargs.get('dataDict') is not None:
self.data.update(kargs.get('dataDict'))
if kargs.get('keypair') is not None:
self.sign(kargs.get('keypair'))
def isValid(self):
"""Internal method which checks the Bounty as valid in the most minimal version
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(self.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(self.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if self.reward not in range(1440, 100000001) or (not self.reward and self.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if self.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(self.data.get('reqs')):
return 1
return -1
except:
return False
def isPayable(self, factor):
"""check if address has enough"""
return True # later make this a wrapper for pywallet.balance()
def checkSign(self):
"""check if the signature attatched to the Bounty is valid"""
try:
from rsa import verify, PublicKey
safeprint(keyList)
if self.data.get('cert'): # where key = (PublicKey.n, PublicKey.e)
expected = str(self).encode('utf-8')
data = self.data
n = data.get('key')[0]
e = data.get('key')[1]
if rsa.verify(str((n, e)).encode('utf-8'), data.get('cert'), masterKey):
return verify(expected, data.get('sig'), PublicKey(n, e))
return False
except:
return False
def sign(self, privateKey): # where privateKey is a private key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-256')})
except:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for char in address:
decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
bcbytes = ""
if sys.version_info[0] < 3:
"""long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
else:
bcbytes = decimal.to_bytes(25, 'big')
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def checkIPAddressValid(address):
try:
import socket
socket.getaddrinfo(*address)
a = len(address[0].split(":")) == 1 # Make sure it's not ipv6
b = len(address[0].split(".")) == 4 # Make sure it's not shortened
return a and b and address[1] in range(49152)
except:
return False
def verify(string):
"""External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
test = depickle(string)
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(test.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(test.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if test.reward not in range(1440, 100000001) or (not test.reward and test.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if test.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(test.data.get('reqs')):
return 1
return -1
except:
return False
def getBountyList():
"""Retrieves the bounty list. Temporary method"""
temp = []
with bountyLock:
temp = bountyList[:]
return temp
def saveToFile():
"""Save the current bounty list to a file"""
if not os.path.exists(bounty_path.split(os.sep)[0]):
os.mkdir(bounty_path.split(os.sep)[0])
pickle.dump(getBountyList(), open(bounty_path, "wb"), 0)
return True
def loadFromFile():
"""Load a previous bounty list from a file"""
if os.path.exists(bounty_path):
with bountyLock:
try:
safeprint("Loading bounty list from file", verbosity=2)
templist = pickle.load(open(bounty_path, "rb"))
safeprint(addBounties(templist), verbosity=3)
safeprint("Bounty list loaded and added", verbosity=2)
except:
return False
return True
return False
def depickle(string):
"""Handles the potential errors in unpickling a bounty"""
if isinstance(string, Bounty):
return string
safeprint([sys.version_info[0], sys.version_info[1], sys.version_info[2]])
if sys.version_info[0] == 2 and sys.version_info[1] == 6 and (isinstance(string, str) or isinstance(string, unicode)):
safeprint("Fed as string in 2.6; encoding ascii and ignoring errors")
try:
string = string.encode('ascii', 'ignore')
except:
string = str(string)
elif isinstance(string, str) and sys.version_info[0] >= 3:
safeprint("Fed as string; encoding utf-8")
string = string.encode('utf-8')
try:
return pickle.loads(string)
except:
return None
def addBounty(bounty):
"""Verify a bounty, and add it to the list if it is valid"""
bounty = depickle(bounty)
safeprint("External verify", verbosity=1)
first = verify(bounty)
safeprint("Internal verify")
second = bounty.isValid()
if not second:
rval = -3
elif not first:
rval = -2
elif bounty in getBountyList():
rval = -1
elif second == -1:
rval = 0
else:
rval = 1
addValidBounty(bounty)
return rval
def addValidBounty(bounty):
"""This adds a bounty to the list under the assumption that it's already been validated. Must be of type common.bounty.Bounty"""
with bountyLock:
global bountyList
bountyList.append(bounty)
temp = list(set(bountyList)) # trim it in the simplest way possible. Doesn't protect against malleability
del bountyList[:]
bountyList.extend(temp)
def internalVerify(bounty): # pragma: no cover
"""Proxy for the Bounty.isValid() method, for multiprocessing.Pool"""
return bounty.isValid()
def addBounties(bounties):
"""Add a list of bounties in parallel using multiprocessing.Pool for verification"""
from multiprocessing.pool import ThreadPool
pool = ThreadPool()
safeprint("Mapping verifications", verbosity=3)
async = pool.map_async(verify, bounties) # defer this for possible efficiency boost
internal = pool.map(internalVerify, bounties)
safeprint("Waiting for verifications", verbosity=3)
external = async.get()
safeprint("Received verifications", verbosity=3)
rvals = []
safeprint(internal)
safeprint(external)
for i in range(len(bounties)):
safeprint("Finishing the processing of bounty " + str(i+1) + "/" + str(len(bounties)), verbosity=2)
if not internal[i]:
rvals.append(-3)
elif not external[i]:
rvals.append(-2)
elif bounties[i] in bountyList:
rvals.append(-1)
elif internal[i] == -1:
rvals.append(0)
else:
rvals.append(1)
addValidBounty(bounties[i])
safeprint("Passed first if", verbosity=3)
safeprint("Verifications parsed", verbosity=3)
return rvals
def getBounty(charity, factor):
"""Retrieve the next best bounty from the list"""
global bountyList, bountyLock
best = None
bountyLock.__enter__()
temp = bountyList[:]
safeprint("bountyList = " + str(temp), verbosity=3)
for bounty in temp:
if not bounty.timeout < getUTC():
bountyList.remove(bounty)
continue
elif charity:
best = bounty
break
elif bounty > best:
best = bounty
bountyLock.__exit__()
return best
|
gappleto97/Senior-Project
|
common/bounty.py
|
Python
|
mit
| 14,300
|
/*
* Copyright 2016 Nu-book Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BitWrapperBinarizer.h"
#include "DecodeStatus.h"
#include "BitMatrix.h"
#include "BitArray.h"
namespace ZXing {
BitWrapperBinarizer::BitWrapperBinarizer(const std::shared_ptr<const BitMatrix>& bits, bool pureBarcode) :
BitWrapperBinarizer(bits, 0, 0, bits->width(), bits->height(), pureBarcode)
{
}
BitWrapperBinarizer::BitWrapperBinarizer(std::shared_ptr<const BitMatrix> bits, int left, int top, int width, int height, bool pureBarcode) :
_matrix(std::move(bits)),
_left(left),
_top(top),
_width(width),
_height(height),
_pureBarcode(pureBarcode)
{
}
bool
BitWrapperBinarizer::isPureBarcode() const
{
return _pureBarcode;
}
int
BitWrapperBinarizer::width() const
{
return _width;
}
int
BitWrapperBinarizer::height() const
{
return _height;
}
// Applies simple sharpening to the row data to improve performance of the 1D Readers.
bool
BitWrapperBinarizer::getBlackRow(int y, BitArray& row) const
{
if (y < 0 || y >= _height) {
throw std::out_of_range("Requested row is outside the matrix");
}
if (_width == _matrix->width()) {
_matrix->getRow(_top + y, row);
}
else {
BitArray tmp;
_matrix->getRow(_top + y, tmp);
tmp.getSubArray(_left, _width, row);
}
return true;
}
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
std::shared_ptr<const BitMatrix>
BitWrapperBinarizer::getBlackMatrix() const
{
if (_width == _matrix->width() && _height == _matrix->height()) {
return _matrix;
}
else {
auto matrix = std::make_shared<BitMatrix>(_width, _height);
BitArray tmp;
BitArray row;
for (int y = 0; y < _height; ++y) {
_matrix->getRow(_top + y, tmp);
tmp.getSubArray(_left, _width, row);
matrix->setRow(y, row);
}
return matrix;
}
}
bool
BitWrapperBinarizer::canCrop() const
{
return true;
}
std::shared_ptr<BinaryBitmap>
BitWrapperBinarizer::cropped(int left, int top, int width, int height) const
{
return std::make_shared<BitWrapperBinarizer>(_matrix, left + _left, top + _top, width, height);
}
bool
BitWrapperBinarizer::canRotate() const
{
return false;
}
std::shared_ptr<BinaryBitmap>
BitWrapperBinarizer::rotated(int) const
{
throw std::runtime_error("This binarizer source does not support rotation by 90 degrees.");
}
} // ZXing
|
SLIBIO/SLib
|
external/src/zxing/zxing/BitWrapperBinarizer.cpp
|
C++
|
mit
| 2,834
|
---
title: Kevoree Release 1.1.0 is now available
layout: post
published: true
---
|
dukeboard/dukeboard.github.io
|
_posts/2011-05-12-kevoree-release-1-1-0-is-now-available.html
|
HTML
|
mit
| 85
|
//
// AxcUserInteractionControlVC.h
// AxcUIKit
//
// Created by Axc on 2017/7/25.
// Copyright © 2017年 Axc_5324. All rights reserved.
//
#import "SampleBaseVC.h"
@interface AxcUserInteractionControlVC : SampleBaseVC
@end
|
axclogo/AxcUIKit-Sample
|
AxcUIKit/SampleVC/AxcUserInteractionControlVC.h
|
C
|
mit
| 232
|
<?php
namespace Omnipay\AuthorizeNet\Message;
use Omnipay\Tests\TestCase;
class CIMCreateCardResponseTest extends TestCase
{
/**
* @expectedException Omnipay\Common\Exception\InvalidResponseException
*/
public function testConstructEmpty()
{
new CIMCreateCardResponse($this->getMockRequest(), '');
}
public function testCreateCardSuccess()
{
$httpResponse = $this->getMockHttpResponse('CIMCreateCardSuccess.txt');
$response = new CIMCreateCardResponse($this->getMockRequest(), $httpResponse->getBody());
$this->assertTrue($response->isSuccessful());
$this->assertEquals('I00001', $response->getReasonCode());
$this->assertEquals("1", $response->getResultCode());
$this->assertEquals("Successful.", $response->getMessage());
$this->assertEquals('28972084', $response->getCustomerProfileId());
$this->assertEquals('26317840', $response->getCustomerPaymentProfileId());
}
public function testCreateCardFailure()
{
$httpResponse = $this->getMockHttpResponse('CIMCreateCardFailure.txt');
$response = new CIMCreateCardResponse($this->getMockRequest(), $httpResponse->getBody());
$this->assertFalse($response->isSuccessful());
$this->assertEquals('E00041', $response->getReasonCode());
$this->assertEquals("3", $response->getResultCode());
$this->assertEquals("One or more fields in the profile must contain a value.", $response->getMessage());
$this->assertNull($response->getCustomerProfileId());
$this->assertNull($response->getCustomerPaymentProfileId());
$this->assertNull($response->getCardReference());
}
}
|
cmaciasg/test
|
application/vendor/omnipay/authorizenet/tests/Message/CIMCreateCardResponseTest.php
|
PHP
|
mit
| 1,757
|
/*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using MiningCore.Extensions;
using Contract = MiningCore.Contracts.Contract;
namespace MiningCore.Crypto
{
/// <summary>
/// Merkle tree builder.
/// </summary>
/// <remarks>
/// To get a better understanding of merkle trees check: http://www.youtube.com/watch?v=gUwXCt1qkBU#t=09m09s
/// </remarks>
/// <specification>https://en.bitcoin.it/wiki/Protocol_specification#Merkle_Trees</specification>
/// <example>
/// Python implementation: http://runnable.com/U3HnDaMrJFk3gkGW/bitcoin-block-merkle-root-2-for-python
/// Original implementation: https://code.google.com/p/bitcoinsharp/source/browse/src/Core/Block.cs#330
/// </example>
public class MerkleTree
{
/// <summary>
/// Creates a new merkle-tree instance.
/// </summary>
/// <param name="hashList"></param>
public MerkleTree(IEnumerable<byte[]> hashList)
{
Steps = CalculateSteps(hashList);
}
/// <summary>
/// The steps in tree.
/// </summary>
public IList<byte[]> Steps { get; }
/// <summary>
/// List of hashes, will be used for calculation of merkle root.
/// <remarks>
/// This is not a list of all transactions, it only contains prepared hashes of steps of merkle tree
/// algorithm. Please read some materials (http://en.wikipedia.org/wiki/Hash_tree) for understanding how merkle
/// trees calculation works. (http://mining.bitcoin.cz/stratum-mining)
/// </remarks>
/// <remarks>The coinbase transaction is hashed against the merkle branches to build the final merkle root.</remarks>
/// </summary>
public List<string> Branches
{
get { return Steps.Select(step => step.ToHexString()).ToList(); }
}
/// <summary>
/// </summary>
/// <example>
/// python: http://runnable.com/U3jqtyYUmAUxtsSS/bitcoin-block-merkle-root-python
/// nodejs: https://github.com/zone117x/node-stratum-pool/blob/master/lib/merkleTree.js#L9
/// </example>
/// <param name="hashList"></param>
/// <returns></returns>
private IList<byte[]> CalculateSteps(IEnumerable<byte[]> hashList)
{
Contract.RequiresNonNull(hashList, nameof(hashList));
var steps = new List<byte[]>();
var L = new List<byte[]> {null};
L.AddRange(hashList);
var startL = 2;
var Ll = L.Count;
if (Ll > 1)
while (true)
{
if (Ll == 1)
break;
steps.Add(L[1]);
if (Ll % 2 == 1)
L.Add(L[L.Count - 1]);
var Ld = new List<byte[]>();
//foreach (int i in Range.From(startL).To(Ll).WithStepSize(2))
for (var i = startL; i < Ll; i += 2)
Ld.Add(MerkleJoin(L[i], L[i + 1]));
L = new List<byte[]> {null};
L.AddRange(Ld);
Ll = L.Count;
}
return steps;
}
/// <summary>
/// </summary>
/// <example>
/// nodejs: https://github.com/zone117x/node-stratum-pool/blob/master/lib/merkleTree.js#L11
/// </example>
/// <param name="hash1"></param>
/// <param name="hash2"></param>
/// <returns></returns>
private byte[] MerkleJoin(byte[] hash1, byte[] hash2)
{
var joined = hash1.Concat(hash2);
var dHashed = DoubleDigest(joined).ToArray();
return dHashed;
}
public byte[] WithFirst(byte[] first)
{
Contract.RequiresNonNull(first, nameof(first));
foreach (var step in Steps)
first = DoubleDigest(first.Concat(step)).ToArray();
return first;
}
private static byte[] DoubleDigest(byte[] input)
{
using (var hash = SHA256.Create())
{
var first = hash.ComputeHash(input, 0, input.Length);
return hash.ComputeHash(first);
}
}
private static IEnumerable<byte> DoubleDigest(IEnumerable<byte> input)
{
return DoubleDigest(input.ToArray());
}
}
}
|
shtse8/miningcore
|
src/MiningCore/Crypto/MerkleTree.cs
|
C#
|
mit
| 5,804
|
from collections import Counter
import sys
import numpy as np
import scipy as sp
from lexical_structure import WordEmbeddingDict
import dense_feature_functions as df
def _get_word2vec_ff(embedding_path, projection):
word2vec = df.EmbeddingFeaturizer(embedding_path)
if projection == 'mean_pool':
return word2vec.mean_args
elif projection == 'sum_pool':
return word2vec.additive_args
elif projection == 'max_pool':
return word2vec.max_args
elif projection == 'top':
return word2vec.top_args
else:
raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection)
def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb):
prefix = 'zh_gigaword3'
if cdtb:
file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \
% (prefix, vec_type, num_units)
else:
file_name = '/data/word_embeddings/%s-%s%s.txt' \
% (prefix, vec_type, num_units)
word2vec = df.EmbeddingFeaturizer(file_name)
if projection == 'mean_pool':
return word2vec.mean_args
elif projection == 'sum_pool':
return word2vec.additive_args
elif projection == 'max_pool':
return word2vec.max_args
elif projection == 'top':
return word2vec.top_args
else:
raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection)
def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None):
if alphabet is None:
alphabet = {}
grow_alphabet = True
else:
grow_alphabet = False
feature_vectors = []
print 'Applying feature functions...'
for relation in relation_list:
feature_vector_indices = []
for ff in ff_list:
feature_vector = ff(relation)
for f in feature_vector:
if grow_alphabet and f not in alphabet:
alphabet[f] = len(alphabet)
if f in alphabet:
feature_vector_indices.append(alphabet[f])
feature_vectors.append(feature_vector_indices)
print 'Creating feature sparse matrix...'
feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet)))
for i, fv in enumerate(feature_vectors):
feature_matrix[i, fv] = 1
return feature_matrix.tocsr(), alphabet
def sparse_featurize(relation_list_list, ff_list):
print 'Featurizing...'
data_list = []
alphabet = None
for relation_list in relation_list_list:
data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet)
data_list.append(data)
return (data_list, alphabet)
def convert_seconds_to_hours(num_seconds):
m, s = divmod(num_seconds, 60)
h, m = divmod(m, 60)
return (h, m, s)
def compute_mi(feature_matrix, label_vector):
"""Compute mutual information of each feature
"""
num_labels = np.max(label_vector) + 1
num_features = feature_matrix.shape[1]
num_rows = feature_matrix.shape[0]
total = num_rows + num_labels
c_y = np.zeros(num_labels)
for l in label_vector:
c_y[l] += 1.0
c_y += 1.0
c_x_y = np.zeros((num_features, num_labels))
c_x = np.zeros(num_features)
for i in range(num_rows):
c_x_y[:, label_vector[i]] += feature_matrix[i, :]
c_x += feature_matrix[i, :]
c_x_y += 1.0
c_x += 1.0
c_x_c_y = np.outer(c_x, c_y)
c_not_x_c_y = np.outer((total - c_x), c_y)
c_not_x_y = c_y - c_x_y
inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \
c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y)
mi_x = inner.sum(1)
return mi_x
def prune_feature_matrices(feature_matrices, mi, num_features):
sorted_indices = mi.argsort()[-num_features:]
return [x[:, sorted_indices] for x in feature_matrices]
class BrownDictionary(object):
def __init__(self):
self.word_to_brown_mapping = {}
self.num_clusters = 0
brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt'
#brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt'
#brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt'
self._load_brown_clusters('resources/%s' % brown_cluster_file_name)
def _load_brown_clusters(self, path):
try:
lexicon_file = open(path)
except:
print 'fail to load brown cluster data'
cluster_set = set()
for line in lexicon_file:
cluster_assn, word, _ = line.split('\t')
if cluster_assn not in cluster_set:
cluster_set.add(cluster_assn)
self.word_to_brown_mapping[word] = len(cluster_set) - 1
self.num_clusters = len(cluster_set)
def _get_brown_cluster_bag(self, tokens):
bag = set()
for token in tokens:
if token in self.word_to_brown_mapping:
cluster_assn = self.word_to_brown_mapping[token]
if cluster_assn not in bag:
bag.add(cluster_assn)
return bag
def get_brown_sparse_matrices_relations(self, relations):
X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float)
X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float)
for i, relation in enumerate(relations):
bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1))
for cluster in bag1:
X1[i, cluster] = 1.0
bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2))
for cluster in bag2:
X2[i, cluster] = 1.0
return (X1, X2)
def get_brown_matrices_data(self, relation_list_list, use_sparse):
"""Extract sparse
For each directory, returns
(X1, X2, Y)
X1 and X2 are sparse matrices from arg1 and arg2 respectively.
Y is an integer vector of type int32
"""
data = []
alphabet = None
# load the data
for relation_list in relation_list_list:
# turn them into a data matrix
print 'Making matrices'
X1, X2 = self.get_brown_sparse_matrices_relations(relation_list)
if not use_sparse:
X1 = X1.toarray()
X2 = X2.toarray()
Y, alphabet = level2_labels(relation_list, alphabet)
data.append((X1, X2, Y))
return (data, alphabet)
def label_vectorize(relation_list_list, lf):
alphabet = {}
for i, valid_label in enumerate(lf.valid_labels()):
alphabet[valid_label] = i
label_vectors = []
for relation_list in relation_list_list:
label_vector = [alphabet[lf.label(x)] for x in relation_list]
label_vectors.append(np.array(label_vector, np.int64))
return label_vectors, alphabet
def compute_baseline_acc(label_vector):
label_counter = Counter()
for label in label_vector:
label_counter[label] += 1.0
_, freq = label_counter.most_common(1)[0]
return round(freq / len(label_vector), 4)
def convert_level2_labels(relations):
# TODO: this is not enough because we have to exclude some tinay classes
new_relation_list = []
for relation in relations:
split_sense = relation.senses[0].split('.')
if len(split_sense) >= 2:
relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])]
new_relation_list.append(relation)
return new_relation_list
def level2_labels(relations, alphabet=None):
if alphabet is None:
alphabet = {}
label_set = set()
for relation in relations:
label_set.add(relation.senses[0])
print label_set
sorted_label = sorted(list(label_set))
for i, label in enumerate(sorted_label):
alphabet[label] = i
label_vector = []
for relation in relations:
if relation.senses[0] not in alphabet:
alphabet[relation.senses[0]] = len(alphabet)
label_vector.append(alphabet[relation.senses[0]])
return np.array(label_vector, np.int64), alphabet
def get_wbm(num_units):
if num_units == 50:
dict_file = '/data/word_embeddings/wsj-skipgram50.npy'
vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt'
elif num_units == 100:
dict_file = '/data/word_embeddings/wsj-skipgram100.npy'
vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt'
elif num_units == 300:
#dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy'
dict_file = \
'/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy'
vocab_file = \
'/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt'
else:
# this will crash the next step and te's too lazy to make it throw an exception.
dict_file = None
vocab_file = None
wbm = WordEmbeddingDict(dict_file, vocab_file)
return wbm
def get_zh_wbm(num_units):
dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units
vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units
return WordEmbeddingDict(dict_file, vocab_file)
def set_logger(file_name, dry_mode=False):
if not dry_mode:
sys.stdout = open('%s.log' % file_name, 'w', 1)
json_file = open('%s.json' % file_name, 'w', 1)
return json_file
import base_label_functions as l
from nets.learning import DataTriplet
from data_reader import extract_implicit_relations
from lstm import prep_serrated_matrix_relations
def get_data_srm(dir_list, wbm, max_length=75):
sense_lf = l.SecondLevelLabel()
relation_list_list = [extract_implicit_relations(dir, sense_lf)
for dir in dir_list]
data_list = []
for relation_list in relation_list_list:
data = prep_serrated_matrix_relations(relation_list, wbm, max_length)
data_list.append(data)
label_vectors, label_alphabet = \
label_vectorize(relation_list_list, sense_lf)
data_triplet = DataTriplet(
data_list, [[x] for x in label_vectors], [label_alphabet])
return data_triplet
def make_givens_srm(givens, input_vec, T_training_data,
output_vec, T_training_data_label, start_idx, end_idx):
"""Make the 'given' dict for SGD training for discourse
the input vecs should be [X1 mask1 X2 mask2]
X1 and X2 are TxNxd serrated matrices.
"""
# first arg embedding and mask
givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :]
givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx]
# second arg embedding and mask
givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :]
givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx]
for i, output_var in enumerate(output_vec):
givens[output_var] = T_training_data_label[i][start_idx:end_idx]
def make_givens(givens, input_vec, T_training_data,
output_vec, T_training_data_label, start_idx, end_idx):
"""Make the 'given' dict for SGD training for discourse
the input vecs should be [X1 X2]
X1 and X2 are Nxd matrices.
"""
# first arg embedding and mask
givens[input_vec[0]] = T_training_data[0][start_idx:end_idx]
givens[input_vec[1]] = T_training_data[1][start_idx:end_idx]
for i, output_var in enumerate(output_vec):
givens[output_var] = T_training_data_label[i][start_idx:end_idx]
if __name__ == '__main__':
fm = np.array([ [1, 0, 1],
[1, 0, 0],
[0, 0, 0],
[0, 1, 1],
[0, 1, 0],
[0, 0, 0]])
lv = np.array([0,0,0,1,1,1])
compute_mi(fm, lv)
|
jimmycallin/master-thesis
|
architectures/nn_discourse_parser/nets/util.py
|
Python
|
mit
| 11,972
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mordecai.Types
{
public class TwoWayExit : Exit
{
public Place Location2 { get; set; }
public Place CurrentLocation { get; set; }
public virtual Place GetDestination(IThing thing)
{
CurrentLocation = thing.Location;
if(CurrentLocation == Location)
{
Destination = Location2;
}
else
{
Destination = Location;
}
return Destination;
}
}
}
|
Vineature/Mordecai
|
Mordecai.Types/TwoWayExit.cs
|
C#
|
mit
| 647
|
module Writefully
module Tools
class Retryer
include Celluloid
attr_accessor :job
def retry(job)
@job = job
if job[:message][:tries] <= 5
after(delay) { queue_retry }
else
mark_as_failed
end
end
def queue_retry
Writefully.add_job job[:worker], job[:message].merge({ run: true })
end
def delay
(job[:message][:tries] * job[:message][:tries]).seconds
end
def mark_as_failed
Writefully.redis.with { |c| c.sadd 'failed', Marshal.dump(job) }
end
end
end
end
|
hellfish2/writefully
|
lib/writefully/tools/retryer.rb
|
Ruby
|
mit
| 608
|
<h1>
{{title}}
</h1>
<p-chart type="line" [data]="data"></p-chart>
<p-dataTable [value]="cars" selectionMode="single" [(selection)]="selectedCar">
<header>Right Click on Rows for ContextMenu</header>
<p-column field="vin" header="Vin"></p-column>
<p-column field="year" header="Year"></p-column>
<p-column field="brand" header="Brand"></p-column>
<p-column field="color" header="Color"></p-column>
</p-dataTable>
|
ypolosov/git-test
|
src/app/app.component.html
|
HTML
|
mit
| 428
|
import numpy as np
import numpy.linalg as la
import collections
import IPython
import tensorflow as tf
from utils import *
import time
from collections import defaultdict
class PolicyGradient(Utils):
"""
Calculates policy gradient
for given input state/actions.
Users should primarily be calling main
PolicyGradient class methods.
"""
def __init__(self, net_dims, filepath=None, q_net_dims=None, output_function=None, seed=0, seed_state=None):
"""
Initializes PolicyGradient class.
Parameters:
net_dims: array-like
1D list corresponding to dimensions
of each layer in the net.
output_function: string
Non-linearity function applied to output of
neural network.
Options are: 'tanh', 'sigmoid', 'relu', 'softmax'.
"""
self.q_dict = defaultdict(lambda: defaultdict(float))
self.prev_weight_grad = self.prev_bias_grad = self.prev_weight_update_vals = \
self.prev_bias_update_vals = self.prev_weight_inverse_hess = self.prev_bias_inverse_hess = \
self.total_weight_grad = self.total_bias_grad = None
self.init_action_neural_net(net_dims, output_function, filepath)
if seed_state is not None:
np.random.set_state(seed_state)
tf.set_random_seed(seed)
def train_agent(self, dynamics_func, reward_func, update_method, initial_state, num_iters, batch_size, traj_len, step_size=0.1, momentum=0.5, normalize=True):
"""
Trains agent using input dynamics and rewards functions.
Parameters:
dynamics_func: function
User-provided function that takes in
a state and action, and returns the next state.
reward_func: function
User-provided function that takes in
a state and action, and returns the associated reward.
initial_state: array-like
Initial state that each trajectory starts at.
Must be 1-dimensional NumPy array.
num_iters: int
Number of iterations to run gradient updates.
batch_size: int
Number of trajectories to run in a single iteration.
traj_len: int
Number of state-action pairs in a trajectory.
Output:
mean_rewards: array-like
Mean ending rewards of all iterations.
"""
mean_rewards = []
ending_states = []
for i in range(num_iters):
traj_states = []
traj_actions = []
rewards = []
for j in range(batch_size):
states = []
actions = []
curr_rewards = []
curr_state = initial_state
# Rolls out single trajectory
for k in range(traj_len):
# Get action from learner
curr_action = self.get_action(curr_state)
# Update values
states.append(curr_state)
curr_rewards.append(reward_func(curr_state, curr_action))
actions.append(curr_action)
# Update state
curr_state = dynamics_func(curr_state, curr_action)
# Append trajectory/rewards
traj_states.append(states)
traj_actions.append(actions)
rewards.append(curr_rewards)
# Apply policy gradient iteration
self.gradient_update(np.array(traj_states), np.array(traj_actions), np.array(rewards), \
update_method, step_size, momentum, normalize)
mean_rewards.append(np.mean([np.sum(reward_list) for reward_list in rewards]))
ending_states.append([traj[-1] for traj in traj_states])
return np.array(mean_rewards), ending_states
def gradient_update(self, traj_states, traj_actions, rewards, update_method='sgd', step_size=1.0, momentum=0.5, normalize=True):
"""
Estimates and applies gradient update according to a policy.
States, actions, rewards must be lists of lists; first dimension indexes
the ith trajectory, second dimension indexes the jth state-action-reward of that
trajectory.
Parameters:
traj_states: array-like
List of list of states.
traj_actions: array-like
List of list of actions.
rewards: array-like
List of list of rewards.
step_size: float
Step size.
momentum: float
Momentum value.
normalize: boolean
Determines whether to normalize gradient update.
Recommended if running into NaN/infinite value errors.
"""
assert update_method in ['sgd', 'momentum', 'lbfgs', 'adagrad', 'rmsprop', 'adam']
# Calculate updates and create update pairs
curr_weight_grad = 0
curr_bias_grad = 0
curr_weight_update_vals = []
curr_bias_update_vals = []
curr_weight_inverse_hess = []
curr_bias_inverse_hess = []
iters = traj_states.shape[0]
q_vals = self.estimate_q(traj_states, traj_actions, rewards)
assert traj_states.shape[0] == traj_actions.shape[0] == rewards.shape[0]
assert q_vals.shape[0] == iters
# Update for each example
for i in range(iters):
# Estimate q-values and extract gradients
curr_traj_states = traj_states[i]
curr_traj_actions = traj_actions[i]
curr_q_val_list = q_vals[i]
curr_traj_states = curr_traj_states.reshape(curr_traj_states.shape[0], curr_traj_states.shape[1] * curr_traj_states.shape[2])
curr_traj_actions = curr_traj_actions.reshape(curr_traj_actions.shape[0], curr_traj_actions.shape[1] * curr_traj_actions.shape[2])
curr_q_val_list = curr_q_val_list.reshape(curr_q_val_list.shape[0], 1)
curr_weight_grad_vals = self.sess.run(self.weight_grads, \
feed_dict={self.input_state: curr_traj_states, self.observed_action: curr_traj_actions, self.q_val: curr_q_val_list})
curr_bias_grad_vals = self.sess.run(self.bias_grads, \
feed_dict={self.input_state: curr_traj_states, self.observed_action: curr_traj_actions, self.q_val: curr_q_val_list})
curr_weight_grad += np.array(curr_weight_grad_vals) / np.float(iters)
curr_bias_grad += np.array(curr_bias_grad_vals) / np.float(iters)
# Update weights
for j in range(len(self.weights)):
if update_method == 'sgd':
update_val = step_size * curr_weight_grad[j]
elif update_method == 'momentum':
if self.prev_weight_grad is None:
update_val = step_size * curr_weight_grad[j]
else:
update_val = momentum * self.prev_weight_grad[j] + step_size * curr_weight_grad[j]
elif update_method == 'lbfgs':
if self.prev_weight_inverse_hess is None:
curr_inverse_hess = np.eye(curr_weight_grad[j].shape[0])
update_val = curr_weight_grad[j]
else:
update_val, curr_inverse_hess = \
self.bfgs_update(self.prev_inverse_hess[j], self.prev_update_val[j], self.prev_weight_grad[j], update_val)
update_val = update_val * step_size
curr_weight_inverse_hess.append(curr_inverse_hess)
elif update_method == 'adagrad':
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
else:
self.total_weight_grad[j] += np.square(curr_weight_grad[j])
update_val = step_size * curr_weight_grad[j] / (np.sqrt(np.abs(self.total_weight_grad[j])) + 1e-8)
elif update_method == 'rmsprop':
decay = 0.99
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
else:
self.total_weight_grad[j] = decay * self.total_weight_grad[j] + (1 - decay) * np.square(curr_weight_grad[j])
update_val = step_size * curr_weight_grad[j] / (np.sqrt(np.abs(self.total_weight_grad[j])) + 1e-8)
elif update_method == 'adam':
beta1, beta2 = 0.9, 0.999
if self.total_weight_grad is None:
self.total_weight_grad = curr_weight_grad
self.total_sq_weight_grad = np.square(curr_weight_grad)
else:
self.total_weight_grad[j] = beta1 * self.total_weight_grad[j] + (1 - beta1) * curr_weight_grad[j]
self.total_sq_weight_grad[j] = beta2 * self.total_sq_weight_grad[j] + (1 - beta2) * np.sqrt(np.abs(self.total_weight_grad[j]))
update_val = np.divide(step_size * self.total_weight_grad[j], (np.sqrt(np.abs(self.total_sq_weight_grad[j])) + 1e-8))
if normalize:
norm = la.norm(update_val)
if norm != 0:
update_val = update_val / norm
curr_weight_update_vals.append(update_val)
update = tf.assign(self.weights[j], self.weights[j] + update_val)
self.sess.run(update)
# Update biases
for j in range(len(self.biases)):
if update_method == 'sgd':
update_val = step_size * curr_bias_grad[j]
elif update_method == 'momentum':
if self.prev_bias_grad is None:
update_val = step_size * curr_bias_grad[j]
else:
update_val = momentum * self.prev_bias_grad[j] + step_size * curr_bias_grad[j]
elif update_method == 'lbfgs':
if self.prev_bias_inverse_hess is None:
curr_inverse_hess = np.eye(curr_bias_grad[j].shape[0])
update_val = curr_bias_grad[j]
else:
update_val, curr_inverse_hess = \
self.bfgs_update(self.prev_inverse_hess[j], self.prev_update_val[j], self.prev_bias_grad[j], update_val)
update_val = update_val * step_size
curr_bias_inverse_hess.append(curr_inverse_hess)
elif update_method == 'adagrad':
if self.total_bias_grad is None:
self.total_bias_grad = curr_bias_grad
else:
self.total_bias_grad[j] += np.square(curr_bias_grad[j])
update_val = step_size * curr_bias_grad[j] / (np.sqrt(np.abs(self.total_bias_grad[j])) + 1e-8)
elif update_method == 'rmsprop':
decay = 0.99
if self.total_bias_grad is None:
self.total_bias_grad = curr_bias_grad
else:
self.total_bias_grad[j] = decay * self.total_bias_grad[j] + (1 - decay) * np.square(curr_bias_grad[j])
update_val = step_size * curr_bias_grad[j] / (np.sqrt(np.abs(self.total_bias_grad[j])) + 1e-8)
elif update_method == 'adam':
beta1, beta2 = 0.9, 0.999
if self.total_bias_grad is None:
self.total_bias_grad = curr_bias_grad
self.total_sq_bias_grad = np.square(curr_bias_grad)
else:
self.total_bias_grad[j] = beta1 * self.total_bias_grad[j] + (1 - beta1) * curr_bias_grad[j]
self.total_sq_bias_grad[j] = beta2 * self.total_sq_bias_grad[j] + (1 - beta2) * np.sqrt(np.abs(self.total_bias_grad[j]))
update_val = np.divide(step_size * self.total_bias_grad[j], (np.sqrt(np.abs(self.total_sq_bias_grad[j])) + 1e-8))
if normalize:
norm = la.norm(update_val)
if norm != 0:
update_val = update_val / norm
curr_bias_update_vals.append(update_val)
update = tf.assign(self.biases[j], self.biases[j] + update_val)
self.sess.run(update)
self.prev_weight_grad = curr_weight_grad
self.prev_bias_grad = curr_bias_grad
self.prev_weight_update_vals = curr_weight_update_vals
self.prev_bias_update_vals = curr_weight_update_vals
def get_action(self, state):
"""
Returns action based on input state.
Input:
state: array-like
Input state.
Output:
action: array-like
Predicted action.
"""
state = state.T
curr_output_mean = self.sess.run(self.output_mean, feed_dict={self.input_state: state})
action = self.meanstd_sample(curr_output_mean)
return action
|
WesleyHsieh/policy_gradient
|
policy_gradient/policy_gradient.py
|
Python
|
mit
| 10,569
|
# mdWebEditor
(idea) Editing Markdown in the Web #likeABoss :)
|
f3r/mdWebEditor
|
README.md
|
Markdown
|
mit
| 63
|
---
layout: page
title: Dragon Cube Financial Executive Retreat
date: 2016-05-24
author: Christian Cowan
tags: weekly links, java
status: published
summary: Proin blandit imperdiet diam, rhoncus scelerisque lacus suscipit.
banner: images/banner/leisure-05.jpg
booking:
startDate: 03/04/2017
endDate: 03/07/2017
ctyhocn: LSEDOHX
groupCode: DCFER
published: true
---
In eget tellus libero. In lectus lacus, aliquet a lacinia sed, rhoncus non sem. Ut molestie convallis lobortis. Etiam ullamcorper dolor ut ipsum volutpat faucibus. Donec accumsan hendrerit rhoncus. Quisque feugiat sapien at euismod tempor. Donec id dolor suscipit, consequat felis quis, tristique magna. Morbi condimentum nibh ac ligula consequat auctor.
* Fusce in dolor quis sem viverra mattis sit amet ut tortor
* Maecenas facilisis nunc eu lorem suscipit, eget mollis lacus ullamcorper
* Pellentesque fringilla augue ac dolor gravida malesuada
* Sed auctor ipsum euismod risus viverra, quis ornare nunc pharetra
* Pellentesque suscipit turpis vel elit aliquam, ut bibendum velit dictum.
Proin in pharetra urna. Cras sit amet euismod ex, ut cursus est. Morbi accumsan, est nec bibendum blandit, sem nisi ultrices turpis, sit amet elementum odio massa vitae tortor. Cras malesuada a ex sed commodo. Sed maximus mi vel velit maximus, sit amet euismod lacus suscipit. Etiam eleifend elit at lectus pretium sodales. Nullam rutrum sapien in elit mattis maximus. Morbi ultricies gravida laoreet. Pellentesque efficitur, metus nec dictum placerat, velit velit rutrum magna, et consequat purus velit quis augue. Aliquam at metus consectetur, viverra eros molestie, rutrum nisl.
|
KlishGroup/prose-pogs
|
pogs/L/LSEDOHX/DCFER/index.md
|
Markdown
|
mit
| 1,648
|
package pl.com.softproject.diabetyk.core.exception;
/**
* Class NoAuthInfoAvailableException
*
* @author Marcin Jasinski {@literal <mkjasinski@gmail.com>}
*/
public class NoAuthInfoAvailableException extends RuntimeException {
public NoAuthInfoAvailableException() {
}
public NoAuthInfoAvailableException(String message) {
super(message);
}
public NoAuthInfoAvailableException(String message, Throwable cause) {
super(message, cause);
}
public NoAuthInfoAvailableException(Throwable cause) {
super(cause);
}
public NoAuthInfoAvailableException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
SoftProject/diabetyk
|
diabetyk-core/src/main/java/pl/com/softproject/diabetyk/core/exception/NoAuthInfoAvailableException.java
|
Java
|
mit
| 827
|
all: clean compile test
clean:
@echo "==> Cleaning up previous builds."
@rm -rf ./bin/godoku
compile:
@echo "==> Compiling source code."
@go build -v -o ./bin/godoku $(go list ./... | grep -v /vendor/)
coverage:
@go test -coverprofile cover.out
@go tool cover -html=cover.out
deps:
@echo "==> Downloading dependencies."
@godep save $(go list ./... | grep -v /vendor/)
fmt:
@echo "==> Formatting source code."
@gofmt -w ./
race_compile:
@echo "==> Compiling source code."
@go build -v -race -o ./bin/godoku $(go list ./... | grep -v /vendor/)
test: fmt vet
@echo "==> Running tests."
@go test -cover $(go list ./... | grep -v /vendor/)
@echo "==> Tests complete."
vet:
@go vet $(go list ./... | grep -v /vendor/)
help:
@echo "clean\t\tremove previous builds"
@echo "compile\t\tbuild the code"
@echo "coverage\tgenerate and view code coverage"
@echo "deps\t\tdownload dependencies"
@echo "fmt\t\tformat the code"
@echo "race_compile\tbuild the code with race detection"
@echo "test\t\ttest the code"
@echo "vet\t\tvet the code"
@echo ""
@echo "default will test, format, and compile the code"
.PNONY: all clean deps fmt help test
|
thomaswhitcomb/godoku
|
Makefile
|
Makefile
|
mit
| 1,164
|
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package band
import (
pb_lorawan "github.com/TheThingsNetwork/ttn/api/protocol/lorawan"
"github.com/TheThingsNetwork/ttn/core/types"
"github.com/TheThingsNetwork/ttn/utils/errors"
"github.com/brocaar/lorawan"
lora "github.com/brocaar/lorawan/band"
)
// FrequencyPlan includes band configuration and CFList
type FrequencyPlan struct {
lora.Band
ADR *ADRConfig
CFList *lorawan.CFList
}
func (f *FrequencyPlan) GetDataRateStringForIndex(drIdx int) (string, error) {
dr, err := types.ConvertDataRate(f.DataRates[drIdx])
if err != nil {
return "", err
}
return dr.String(), nil
}
func (f *FrequencyPlan) GetDataRateIndexFor(dataRate string) (int, error) {
dr, err := types.ParseDataRate(dataRate)
if err != nil {
return 0, err
}
return f.Band.GetDataRate(lora.DataRate{Modulation: lora.LoRaModulation, SpreadFactor: int(dr.SpreadingFactor), Bandwidth: int(dr.Bandwidth)})
}
func (f *FrequencyPlan) GetTxPowerIndexFor(txPower int) (int, error) {
for i, power := range f.TXPower {
if power == txPower {
return i, nil
}
}
return 0, errors.New("core/band: the given tx-power does not exist")
}
// Guess the region based on frequency
func Guess(frequency uint64) string {
// Join frequencies
switch {
case frequency == 923200000 && frequency <= 923400000:
// not considering AS_920_923 and AS_923_925 because we're not sure
return pb_lorawan.FrequencyPlan_AS_923.String()
case frequency == 922100000 || frequency == 922300000 || frequency == 922500000:
return pb_lorawan.FrequencyPlan_KR_920_923.String()
}
// Existing Channels
if region, ok := channels[int(frequency)]; ok {
return region
}
// Everything Else: not allowed
return ""
}
// Get the frequency plan for the given region
func Get(region string) (frequencyPlan FrequencyPlan, err error) {
if fp, ok := frequencyPlans[region]; ok {
return fp, nil
}
switch region {
case pb_lorawan.FrequencyPlan_EU_863_870.String():
frequencyPlan.Band, err = lora.GetConfig(lora.EU_863_870, false, lorawan.DwellTimeNoLimit)
// TTN uses SF9BW125 in RX2
frequencyPlan.RX2DataRate = 3
// TTN frequency plan includes extra channels next to the default channels:
frequencyPlan.UplinkChannels = []lora.Channel{
lora.Channel{Frequency: 868100000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 868300000, DataRates: []int{0, 1, 2, 3, 4, 5, 6}}, // Also SF7BW250
lora.Channel{Frequency: 868500000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 867100000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 867300000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 867500000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 867700000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 867900000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 868800000, DataRates: []int{7}}, // FSK 50kbps
}
frequencyPlan.DownlinkChannels = frequencyPlan.UplinkChannels
frequencyPlan.CFList = &lorawan.CFList{867100000, 867300000, 867500000, 867700000, 867900000}
frequencyPlan.ADR = &ADRConfig{MinDataRate: 0, MaxDataRate: 5, MinTXPower: 2, MaxTXPower: 14}
case pb_lorawan.FrequencyPlan_US_902_928.String():
frequencyPlan.Band, err = lora.GetConfig(lora.US_902_928, false, lorawan.DwellTime400ms)
case pb_lorawan.FrequencyPlan_CN_779_787.String():
frequencyPlan.Band, err = lora.GetConfig(lora.CN_779_787, false, lorawan.DwellTimeNoLimit)
case pb_lorawan.FrequencyPlan_EU_433.String():
frequencyPlan.Band, err = lora.GetConfig(lora.EU_433, false, lorawan.DwellTimeNoLimit)
case pb_lorawan.FrequencyPlan_AU_915_928.String():
frequencyPlan.Band, err = lora.GetConfig(lora.AU_915_928, false, lorawan.DwellTime400ms)
case pb_lorawan.FrequencyPlan_CN_470_510.String():
frequencyPlan.Band, err = lora.GetConfig(lora.CN_470_510, false, lorawan.DwellTimeNoLimit)
case pb_lorawan.FrequencyPlan_AS_923.String():
frequencyPlan.Band, err = lora.GetConfig(lora.AS_923, false, lorawan.DwellTime400ms)
case pb_lorawan.FrequencyPlan_AS_920_923.String():
frequencyPlan.Band, err = lora.GetConfig(lora.AS_923, false, lorawan.DwellTime400ms)
frequencyPlan.UplinkChannels = []lora.Channel{
lora.Channel{Frequency: 923200000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923400000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922200000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922400000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922600000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922800000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923000000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922000000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922100000, DataRates: []int{6}},
lora.Channel{Frequency: 921800000, DataRates: []int{7}},
}
frequencyPlan.DownlinkChannels = frequencyPlan.UplinkChannels
frequencyPlan.CFList = &lorawan.CFList{922200000, 922400000, 922600000, 922800000, 923000000}
case pb_lorawan.FrequencyPlan_AS_923_925.String():
frequencyPlan.Band, err = lora.GetConfig(lora.AS_923, false, lorawan.DwellTime400ms)
frequencyPlan.UplinkChannels = []lora.Channel{
lora.Channel{Frequency: 923200000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923400000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923600000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923800000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 924000000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 924200000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 924400000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 924600000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 924500000, DataRates: []int{6}},
lora.Channel{Frequency: 924800000, DataRates: []int{7}},
}
frequencyPlan.DownlinkChannels = frequencyPlan.UplinkChannels
frequencyPlan.CFList = &lorawan.CFList{923600000, 923800000, 924000000, 924200000, 924400000}
case pb_lorawan.FrequencyPlan_KR_920_923.String():
frequencyPlan.Band, err = lora.GetConfig(lora.KR_920_923, false, lorawan.DwellTimeNoLimit)
// TTN frequency plan includes extra channels next to the default channels:
frequencyPlan.UplinkChannels = []lora.Channel{
lora.Channel{Frequency: 922100000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922300000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922500000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922700000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 922900000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923100000, DataRates: []int{0, 1, 2, 3, 4, 5}},
lora.Channel{Frequency: 923300000, DataRates: []int{0, 1, 2, 3, 4, 5}},
}
frequencyPlan.DownlinkChannels = frequencyPlan.UplinkChannels
frequencyPlan.CFList = &lorawan.CFList{922700000, 922900000, 923100000, 923300000, 0}
default:
err = errors.NewErrInvalidArgument("Frequency Band", "unknown")
}
return
}
var frequencyPlans map[string]FrequencyPlan
var channels map[int]string
func init() {
frequencyPlans = make(map[string]FrequencyPlan)
channels = make(map[int]string)
for _, r := range []pb_lorawan.FrequencyPlan{ // ordering is important here
pb_lorawan.FrequencyPlan_EU_863_870,
pb_lorawan.FrequencyPlan_US_902_928,
pb_lorawan.FrequencyPlan_CN_779_787,
pb_lorawan.FrequencyPlan_EU_433,
pb_lorawan.FrequencyPlan_AS_923,
pb_lorawan.FrequencyPlan_AS_920_923,
pb_lorawan.FrequencyPlan_AS_923_925,
pb_lorawan.FrequencyPlan_KR_920_923,
pb_lorawan.FrequencyPlan_AU_915_928,
pb_lorawan.FrequencyPlan_CN_470_510,
} {
region := r.String()
frequencyPlans[region], _ = Get(region)
for _, ch := range frequencyPlans[region].UplinkChannels {
if len(ch.DataRates) > 1 { // ignore FSK channels
if _, ok := channels[ch.Frequency]; !ok { // ordering indicates priority
channels[ch.Frequency] = region
}
}
}
}
}
|
jvanmalder/ttn
|
core/band/band.go
|
GO
|
mit
| 8,287
|
Advanced Vue for SEO and Drupal: prerender and server side rendering
============
* Introduction
* What you will learn in this presentation
|
hoter/js-seo-presentation
|
README.md
|
Markdown
|
mit
| 141
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W28888_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page19.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 1338px; margin-top: 318px;">
<p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DAILY LOG OF OPERATIONS 6:00 AM depth </p>
</div>
<div style="position: absolute; margin-left: 106px; margin-top: 467px;">
<p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DATE DEPTH FOOTAGE DAY FORMATION OPERATIONS <br/> <br/>20-Aug-2014 ‘ 188 0 1 Surface Drill actual from 188-558, trip HWDP out of hole, hold safety meeting and pick up DC, Drill </p>
</div>
<div style="position: absolute; margin-left: 1381px; margin-top: 595px;">
<p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">actual from 558—1387. Drill actual from 1387 to 2036, circulate bottoms up, drop gyro, tr1p out of hole with gyro, strap pipe out of hole, inspect bit and lay down gyro, trip in hole and wash last 2 stands to bottom, drill actual from 2036 to 2078 TD, circulate while building <br/>weighted sweep. </p>
</div>
<div style="position: absolute; margin-left: 127px; margin-top: 935px;">
<p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">21-Aug—20 1 4 </p>
</div>
<div style="position: absolute; margin-left: 421px; margin-top: 935px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2078 </p>
</div>
<div style="position: absolute; margin-left: 127px; margin-top: 1593px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">22-Aug-2014 </p>
</div>
<div style="position: absolute; margin-left: 1020px; margin-top: 2125px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 1615px; margin-top: 2358px;">
<p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 595px; margin-top: 913px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">.1890 </p>
</div>
<div style="position: absolute; margin-left: 425px; margin-top: 1593px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2078 </p>
</div>
<div style="position: absolute; margin-left: 1997px; margin-top: 2125px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 871px; margin-top: 913px;">
<p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 595px; margin-top: 1572px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 1020px; margin-top: 913px;">
<p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Pierre </p>
</div>
<div style="position: absolute; margin-left: 871px; margin-top: 1572px;">
<p class="styleSans3.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 1360px; margin-top: 913px;">
<p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"> <br/> <br/>Circulate while working drill string, monitor well, wiper trip, build sweep, circulate out, pump slug, trip out of hole, lay down 8" DC, break bell sub, bit, bit sub, organize floor, rig up franks casing. Hold safety meeting with franks and make up float equipment, run 9 5/8 casing to 830ft, break circulation and circulate bottoms up, run 9 5/8 casing from 830 to 2003, wash from 2003 to bottom, circulate, wait on schlumberger bulk truck, rig up bulk truck and iron to rig floor, hold safety meeting with schlumberger, make up cement head, pressure test lines (SOO-low 3000—high), lObbl fresh water, l42bbl lead, slurry, 46bbl tail slurry, drop plug, 154be displacement, hold safety meeting and rig down schlumberger, flush cement from flow line with jet lines, drain conductor and fluch with water. </p>
</div>
<div style="position: absolute; margin-left: 1020px; margin-top: 1572px;">
<p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Pierre </p>
</div>
<div style="position: absolute; margin-left: 1381px; margin-top: 1572px;">
<p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Rig down flow line, snub lines to conductor, clean mud tanks, rig down casing bushings, slips, elevators, bails, assist welder on cutting conductor and casing, spot well head, pressure test to lOSOpsi-good, hold safety meeting, nipple up spacer spool, BOP, rotating head, HCR line, choke line. Finish nippling up BOP, choke lines, turn buckles on stack, accumulator lines, function test BOP, hold safety meeting with greenes, pressure test pipe rams, blind rams, choke and kill lines, IBOP, and dart valve (250-low SOOO-high), annular (250-low 2500high), casing (1500 for 30min), replace gasket on union in choke house, tighten clamp on saver sub, install orbit valve. </p>
</div>
</body>
</html>
|
datamade/elpc_bakken
|
ocr_extracted/W28888_text/page20.html
|
HTML
|
mit
| 6,375
|
import Emitter, { Handler } from "../emmett";
const emitterNames = new Map();
const handler1: Handler = function(event) {
console.log("Received event:", event.type);
console.log(" - Data:", event.data);
console.log(" - Target:", emitterNames.get(event.target));
console.log("");
};
const handler2: Handler = function(event) {
console.log("(handler2 here)");
handler1(event);
};
const handler3: Handler = function(e) {
console.log("(handler3 here)");
};
const symbolE = Symbol("eventE");
const symbolF = Symbol("eventF");
// #on
const emitter1 = new Emitter();
emitterNames.set(emitter1, "Emitter 1");
emitter1.on("eventA", handler1);
emitter1.on(["eventB", "eventC"], handler1);
emitter1.on(/eventD/, handler2);
emitter1.on(symbolE, handler1);
emitter1.on([symbolF], handler2);
emitter1.on(handler3);
// #emit
console.log("Everybody should emit twice:");
console.log("");
[..."ABCD"].forEach(c => emitter1.emit("event" + c, { payload1: c }));
emitter1.emit([symbolE, symbolF], { payload: "common payload" });
emitter1.emit({
...[..."ABCD"].reduce(
(events, c) => ({
...events,
["event" + c]: { payload2: c }
}),
{}
),
[symbolE]: { payload2: symbolE },
[symbolF]: { payload2: symbolF }
});
// #off
emitter1.off("eventA");
emitter1.off("eventB", handler1);
emitter1.off(["eventC"], handler1);
emitter1.off({ eventD: handler1 });
emitter1.off(symbolE);
emitter1.off(handler2).off(handler3);
console.log("Nobody should emit:");
console.log("");
[..."ABCD"].forEach(c => emitter1.emit("event" + c, { payload1: c }));
emitter1.emit([symbolE, symbolF], { payload: "common payload" });
// #listeners
emitter1.listeners(symbolE);
// #unbindAll
emitter1.unbindAll();
// #once
const emitter2 = new Emitter();
emitterNames.set(emitter2, "Emitter 2");
console.log("Everybody should emit once:");
console.log("");
emitter2.once("eventA", handler1);
emitter2.once(["eventB", "eventC"], handler1);
emitter2.once(/eventD/, handler2);
emitter2.once(symbolE, handler1);
emitter2.once([symbolF], handler2);
emitter2.once(handler3);
[..."AABBCCDD"].forEach(c => emitter2.emit("event" + c, { payload: c }));
emitter2.emit([symbolE, symbolE, symbolF, symbolF], {
payload: "common payload"
});
// other methods and properties
let emitter3: Emitter = new Emitter();
emitter3 = emitter3.disable();
emitter3 = emitter3.enable();
const value: void = emitter3.kill();
const version: string = Emitter.version;
|
jacomyal/emmett
|
test/types.ts
|
TypeScript
|
mit
| 2,443
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>lens: 16 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.1 / lens - 1.0.1+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
lens
<small>
1.0.1+8.12
<span class="label label-success">16 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-11-05 05:36:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-05 05:36:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "Generation of lenses for record datatypes"
maintainer: "gregory@bedrocksystems.com"
authors: [
"Gregory Malecha <gregory@bedrocksystems.com>"
]
homepage: "https://github.com/bedrocksystems/coq-lens"
dev-repo: "git://github.com/bedrocksystems/coq-lens.git"
bug-reports: "https://github.com/bedrocksystems/coq-lens/issues"
license: "LGPL2.1+BedRock"
build: [
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"coq" {>= "8.12" & < "8.13~"}
"coq-metacoq-template" { = "1.0~beta1+8.12" }
]
tags: [
"logpath:Lens"
"date: 2020-11-18"
]
url {
src: "https://github.com/bedrocksystems/coq-lens/archive/v1.0.1.tar.gz"
checksum: "sha256=c1092aa89e885dd4abe1abc0605474440e8a763569be0accbbf6af4b129b3a91"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-lens.1.0.1+8.12 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-lens.1.0.1+8.12 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>4 m 16 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-lens.1.0.1+8.12 coq.8.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>16 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 111 K</p>
<ul>
<li>86 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/TC/TC.vo</code></li>
<li>13 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/TC/TC.glob</code></li>
<li>5 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/Lens.vo</code></li>
<li>4 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/TC/TC.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/Lens.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.07.1/lib/coq/user-contrib/Lens/Lens.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-lens.1.0.1+8.12</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.07.1-2.0.6/released/8.12.1/lens/1.0.1+8.12.html
|
HTML
|
mit
| 6,992
|
namespace P07InfernoInfinity.Core
{
using P07InfernoInfinity.Contracts;
using System;
using System.Linq;
using System.Reflection;
public class CommandInterpreter : ICommandInterpreter
{
public CommandInterpreter(IRepository weaponRepository, IWeaponFactory weaponFactory, IGemFactory gemFactory)
{
WeaponRepository = weaponRepository;
WeaponFactory = weaponFactory;
GemFactory = gemFactory;
}
public IRepository WeaponRepository { get; private set; }
public IWeaponFactory WeaponFactory { get; private set; }
public IGemFactory GemFactory { get; private set; }
public string InterpretCommand(string[] commandArgs)
{
string commandName = commandArgs[0].ToLower();
Assembly assembly = Assembly.GetCallingAssembly();
Type command = assembly.GetTypes().FirstOrDefault(t => t.Name.ToLower() == commandName+"command");
MethodInfo method = typeof(IExecutable).GetMethods().First();
object[] constrArgs = new object[] { commandArgs, WeaponRepository, WeaponFactory, GemFactory };
object instance = Activator.CreateInstance(command, constrArgs);
try
{
string result = (string)method.Invoke(instance, null);
return result;
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
}
}
|
MihailDobrev/SoftUni
|
C# Fundamentals/C# OOP Advanced/07. Reflection and Attributes - Exercise/P07InfernoInfinity/Core/CommandInterpreter.cs
|
C#
|
mit
| 1,521
|
<?php /* Template Name: CUSTOM Template */ get_header(); ?>
<main id="custom" role="main">
<!-- section -->
<section class="custom-banner">
<div class="custom-title">
<h4><?php echo the_title(); ?></h4>
</div>
<div class="section-sub-nav">
<?php echo get_field('sub_navigation_list');?>
</div>
</section>
<section class="custom-main">
<?php echo get_field('custom_content'); ?>
</section>
<aside class="custom-test-sidebar">
<?php echo get_field('testimonial_shortcode', 4); ?>
</aside>
</main>
<?php get_template_part('sub', 'footer'); ?>
<script>
jQuery(function($){
$(document).ready(function(){
$('.section-sub-nav a').not(':last').append('\xA0\xA0\xA0/\xA0\xA0\xA0');
if ($(window).width() > 641) {
var customMain = $('.custom-main').height();
$('.custom-test-sidebar').css('min-height', customMain + 50 + 'px');
}
})
});
</script>
<?php get_footer(); ?>
|
team3cord/Maid-Services-Northwest
|
custom.php
|
PHP
|
mit
| 1,126
|
<!doctype html>
<html lang="en">
<head>
<%- include ../components/header-common.html %>
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">success</h4>
</div>
<div class="modal-body">
please wait for the HR to contact you,good luck!
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Leave</button>
<button type="button" class="btn btn-primary">Download our app</button>
</div>
</div>
</div>
</div>
<!-- Button trigger modal -->
<button id="launchmodalbtn" type="button" class="btn btn-primary btn-lg hidden" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="jumbotron masthead">
<div class="container">
<a class="text-center">note!you should be careful to take a clear photo resume,otherwise the HR would ignore your resume!</a>
<p class="masthead-button-links">
<a id="addPic" class="btn btn-lg btn-primary btn-shadow" target="_blank" role="button" onclick="_hmt.push(['_trackEvent', 'masthead', 'click', 'CartBoarder 手机客户端'])">take a photo of your resume</a>
<a id="uploadPic" class="btn btn-lg btn-primary btn-shadow hidden" target="_blank" role="button" onclick="_hmt.push(['_trackEvent', 'masthead', 'click', 'CartBoarder 手机客户端'])">upload</a>
</p>
</div>
</div>
<div class="container">
<ul id="picList" class="list-unstyled"></ul>
</div>
<!-- jQuery -->
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="/bootstrap/cust-js/socket.io.js"></script>
<script src="/bootstrap/cust-js/uploadpic-ws-client.js"></script>
<script>
var localIds;
$.ajax({
url: 'http://smartcreate.net:3000/wechatsigserver/0/'// 此处url请求地址需要替换成你自己实际项目中服务器数字签名服务地址
,type: 'post'
,data: {
url: location.href.split('#')[0] // 将当前URL地址上传至服务器用于产生数字签名
}
}).done(function(r){
// 返回了数字签名对象
console.log(r);
console.log(r.appid);
console.log(r.timestamp);
console.log(r.nonceStr);
console.log(r.signature);
// 开始配置微信JS-SDK
wx.config({
debug: false,
appId: r.appid,
timestamp: r.timestamp,
nonceStr: r.nonceStr,
signature: r.signature,
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'hideMenuItems',
'chooseImage',
'uploadImage'
]
});
// 调用微信API
wx.ready(function(){
var sdata = {
title: 'arrdu|测试微信分享及相关API',
desc: 'arrdu|测试微信分享及相关API',
link: 'http://smartcreate.net:3000',
imgUrl: 'http://smartcreate.net:3000/images/20080121174220593.jpg',
success: function () {
alert('用户确认分享后执行的回调函数');
},
cancel: function () {
alert('用户取消分享后执行的回调函数');
}
};
wx.onMenuShareTimeline(sdata);
wx.onMenuShareAppMessage(sdata);
// upload pics
$('#uploadPic').on('click', function(){
localIds.forEach(function(v, i){
wx.uploadImage({
localId: v, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
informServerToRecv(res.serverId);
}
});
});
});
// 添加图片
$('#addPic').on('click', function(){
wx.chooseImage({
success: function (res) {
localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
// var imgs = localIds.split(',');
localIds.forEach(function(v, i){
//alert(v);
$('#picList').append('<li><img src="'+ v +'" alt="" width="auto"></li><hr>');
});
if(localIds.length > 0){
count = localIds.length;
$('#uploadPic').show();
}
}
});
});
});
});
</script>
</body>
</html>
|
Ranpop/future
|
views/renderpages/sendphtoresume.html
|
HTML
|
mit
| 4,931
|
"use strict"
// Keep in length order
module.exports = {
object: {},
objectModule: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
file: 'object.routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
listModule: {
dir: 'list',
templates: [{
name: 'list.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'list.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'list-resolve.service.ts',
file: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list.component.pug',
},{
name: 'list.component.css',
},{
name: 'list.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
detailModule: {
dir: 'detail',
templates: [{
name: 'detail.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'detail.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'detail-resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail.component.pug',
},{
name: 'detail.component.css',
file: 'component.css',
},{
name: 'detail.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
resolveService: {
dir: false,
templates: [{
name: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
canActivateService: {
dir: false,
templates: [{
name: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
commonModule: {
dir: true,
templates: [{
name: 'module.ts',
file: 'common.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
}],
},
service: {
dir: false,
templates: [{
name: 'service.ts',
imports: ['module.ts'],
listItems: ['providers'],
}],
},
component: {
dir: true,
templates: [{
name: 'component.ts',
imports: ['module.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
},{
name: 'component.css',
}],
},
module: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
}
|
tro3/ng2-seed-cli
|
tools/templating/src/types.js
|
JavaScript
|
mit
| 3,588
|
package alternating;
public class AlternatingMainJava
{
public static void main(String[] args_)
{
AlternatingMain.main(args_);
}
}
|
hpclab/cracker
|
src/alternating/AlternatingMainJava.java
|
Java
|
mit
| 138
|
require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "action_mailer/railtie"
Bundler.require
require "jam"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
|
Arhont/jam
|
test/dummy/config/application.rb
|
Ruby
|
mit
| 1,904
|
package com.bramblellc.myapplication.services;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.stevex86.napper.http.connection.ConnectionHandler;
import com.stevex86.napper.http.elements.content.JsonBodyContent;
import com.stevex86.napper.http.elements.method.Post;
import com.stevex86.napper.http.elements.route.Route;
import com.stevex86.napper.request.Request;
import com.stevex86.napper.response.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class LogoutService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public LogoutService(String name) {
super(name);
}
public LogoutService() {
this("LogoutService");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Route route = new Route("http://guarddog.stevex86.com/log_out");
Request request = new Request(route, new Post());
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", intent.getStringExtra("token"));
JsonBodyContent content = new JsonBodyContent(jsonObject.toString());
request.setBodyContent(content);
ConnectionHandler connectionHandler = new ConnectionHandler(request);
Response response = connectionHandler.getResponse();
}
catch (JSONException e) {
Log.d("Guard-Dog", "Ayy lmao, JSON Exception thrown");
}
catch (IOException e) {
Log.d("Guard-Dog", "Ayy lmao, IOException thrown");
}
}
}
|
BrambleLLC/HackAZ-2016
|
android/app/src/main/java/com/bramblellc/myapplication/services/LogoutService.java
|
Java
|
mit
| 1,836
|
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using Nuke.Common.Tooling;
namespace Nuke.Common.Tools.Kubernetes
{
public partial class KubernetesCommonSettings
{
internal Arguments CreateArguments()
{
return ConfigureProcessArguments(new Arguments());
}
public override Action<OutputType, string> ProcessCustomLogger { get; }
}
}
|
nuke-build/nuke
|
source/Nuke.Common/Tools/Kubernetes/KubernetesCommonSettings.cs
|
C#
|
mit
| 514
|
namespace AgileObjects.AgileMapper.UnitTests.Orms.EfCore2.Infrastructure
{
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;
using Orms.Infrastructure;
using TestClasses;
public class EfCore2TestDbContext : DbContext, ITestDbContext
{
private static readonly DbContextOptions _inMemoryOptions =
new DbContextOptionsBuilder<EfCore2TestDbContext>()
.UseLoggerFactory(new LoggerFactory(new[] { new DebugLoggerProvider() }))
.UseInMemoryDatabase(databaseName: "EfCore2TestDb")
.Options;
public EfCore2TestDbContext()
: this(_inMemoryOptions)
{
}
protected EfCore2TestDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Animal> Animals { get; set; }
public DbSet<Shape> Shapes { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Account> Accounts { get; set; }
public DbSet<Person> Persons { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Rota> Rotas { get; set; }
public DbSet<RotaEntry> RotaEntries { get; set; }
public DbSet<OrderUk> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<PublicBool> BoolItems { get; set; }
public DbSet<PublicByte> ByteItems { get; set; }
public DbSet<PublicShort> ShortItems { get; set; }
public DbSet<PublicInt> IntItems { get; set; }
public DbSet<PublicNullableInt> NullableIntItems { get; set; }
public DbSet<PublicLong> LongItems { get; set; }
public DbSet<PublicDecimal> DecimalItems { get; set; }
public DbSet<PublicDouble> DoubleItems { get; set; }
public DbSet<PublicDateTime> DateTimeItems { get; set; }
public DbSet<PublicNullableDateTime> NullableDateTimeItems { get; set; }
public DbSet<PublicString> StringItems { get; set; }
public DbSet<PublicStringNames> StringNameItems { get; set; }
public DbSet<PublicTitle> TitleItems { get; set; }
public DbSet<PublicNullableTitle> NullableTitleItems { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Company>()
.HasOne(c => c.Ceo)
.WithOne(e => e.Company)
.HasForeignKey<Employee>(e => e.CompanyId);
modelBuilder
.Entity<Category>()
.HasOne(c => c.ParentCategory)
.WithMany(c => c.SubCategories)
.HasForeignKey(c => c.ParentCategoryId);
modelBuilder.Entity<Square>();
modelBuilder.Entity<Circle>();
modelBuilder.Entity<AccountAddress>()
.HasKey(aa => new { aa.AccountId, aa.AddressId });
modelBuilder.Entity<AccountAddress>()
.HasOne(aa => aa.Account)
.WithMany(a => a.DeliveryAddresses)
.HasForeignKey(aa => aa.AccountId);
base.OnModelCreating(modelBuilder);
}
#region ITestDbContext Members
IDbSetWrapper<Animal> ITestDbContext.Animals => new EfCore2DbSetWrapper<Animal>(this);
IDbSetWrapper<Shape> ITestDbContext.Shapes => new EfCore2DbSetWrapper<Shape>(this);
IDbSetWrapper<Company> ITestDbContext.Companies => new EfCore2DbSetWrapper<Company>(this);
IDbSetWrapper<Employee> ITestDbContext.Employees => new EfCore2DbSetWrapper<Employee>(this);
IDbSetWrapper<Category> ITestDbContext.Categories => new EfCore2DbSetWrapper<Category>(this);
IDbSetWrapper<Product> ITestDbContext.Products => new EfCore2DbSetWrapper<Product>(this);
IDbSetWrapper<Account> ITestDbContext.Accounts => new EfCore2DbSetWrapper<Account>(this);
IDbSetWrapper<Person> ITestDbContext.Persons => new EfCore2DbSetWrapper<Person>(this);
IDbSetWrapper<Address> ITestDbContext.Addresses => new EfCore2DbSetWrapper<Address>(this);
IDbSetWrapper<Rota> ITestDbContext.Rotas => new EfCore2DbSetWrapper<Rota>(this);
IDbSetWrapper<RotaEntry> ITestDbContext.RotaEntries => new EfCore2DbSetWrapper<RotaEntry>(this);
IDbSetWrapper<OrderUk> ITestDbContext.Orders => new EfCore2DbSetWrapper<OrderUk>(this);
IDbSetWrapper<OrderItem> ITestDbContext.OrderItems => new EfCore2DbSetWrapper<OrderItem>(this);
IDbSetWrapper<PublicBool> ITestDbContext.BoolItems => new EfCore2DbSetWrapper<PublicBool>(this);
IDbSetWrapper<PublicByte> ITestDbContext.ByteItems => new EfCore2DbSetWrapper<PublicByte>(this);
IDbSetWrapper<PublicShort> ITestDbContext.ShortItems => new EfCore2DbSetWrapper<PublicShort>(this);
IDbSetWrapper<PublicInt> ITestDbContext.IntItems => new EfCore2DbSetWrapper<PublicInt>(this);
IDbSetWrapper<PublicNullableInt> ITestDbContext.NullableIntItems => new EfCore2DbSetWrapper<PublicNullableInt>(this);
IDbSetWrapper<PublicLong> ITestDbContext.LongItems => new EfCore2DbSetWrapper<PublicLong>(this);
IDbSetWrapper<PublicDecimal> ITestDbContext.DecimalItems => new EfCore2DbSetWrapper<PublicDecimal>(this);
IDbSetWrapper<PublicDouble> ITestDbContext.DoubleItems => new EfCore2DbSetWrapper<PublicDouble>(this);
IDbSetWrapper<PublicDateTime> ITestDbContext.DateTimeItems => new EfCore2DbSetWrapper<PublicDateTime>(this);
IDbSetWrapper<PublicNullableDateTime> ITestDbContext.NullableDateTimeItems => new EfCore2DbSetWrapper<PublicNullableDateTime>(this);
IDbSetWrapper<PublicString> ITestDbContext.StringItems => new EfCore2DbSetWrapper<PublicString>(this);
IDbSetWrapper<PublicTitle> ITestDbContext.TitleItems => new EfCore2DbSetWrapper<PublicTitle>(this);
IDbSetWrapper<PublicNullableTitle> ITestDbContext.NullableTitleItems => new EfCore2DbSetWrapper<PublicNullableTitle>(this);
Task ITestDbContext.SaveChanges()
{
StringNameItems.RemoveRange(StringNameItems);
return SaveChangesAsync();
}
#endregion
}
}
|
agileobjects/AgileMapper
|
AgileMapper.UnitTests.Orms.EfCore2/Infrastructure/EfCore2TestDbContext.cs
|
C#
|
mit
| 6,469
|
IPython 2.2 containerized and configured to run IPython Notebook server on Cloud Foundry.
|
parente/dockerfiles
|
ipython-cf/README.md
|
Markdown
|
mit
| 89
|
<?php
/**
*
* PHP versions 4 and 5
*
* kml : Kamila Software
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Jesus Baizabal
* @link http://baizabal.xyz
* @mail baizabal.jesus@gmail.com
* @package cake
* @subpackage cake.cake.console.libs.templates.views
* @since CakePHP(tm) v 1.2.0.5234
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php
class PerformanceTripsController extends AppController {
var $name = 'PerformanceTrips';
function index() {
$this->PerformanceTrip->recursive = 0;
$this->set('performanceTrips', $this->paginate());
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid performance trip', true));
$this->redirect(array('action' => 'index'));
}
$this->set('performanceTrip', $this->PerformanceTrip->read(null, $id));
}
function add() {
if (!empty($this->data)) {
$this->PerformanceTrip->create();
if ($this->PerformanceTrip->save($this->data)) {
$this->Session->setFlash(__('The performance trip has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The performance trip could not be saved. Please, try again.', true));
}
}
}
function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid performance trip', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->PerformanceTrip->save($this->data)) {
$this->Session->setFlash(__('The performance trip has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The performance trip could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->PerformanceTrip->read(null, $id);
}
}
function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for performance trip', true));
$this->redirect(array('action'=>'index'));
}
if ($this->PerformanceTrip->delete($id)) {
$this->Session->setFlash(__('Performance trip deleted', true));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Performance trip was not deleted', true));
$this->redirect(array('action' => 'index'));
}
}
|
ambagasdowa/kml
|
cake/console/controllers/performance_trips_controller.php
|
PHP
|
mit
| 2,456
|
version https://git-lfs.github.com/spec/v1
oid sha256:ed3c069c3fb213c279f09fea7c7fe53e4340d9da1e27b560b4ffcb4009dd23e0
size 9790
|
yogeshsaroya/new-cdnjs
|
ajax/libs/buzz/1.1.1/buzz.min.js
|
JavaScript
|
mit
| 129
|
---
layout: page
header: Posts By Tags
group: navigation
---
<div class="list-container">
<ul class="nav nav-tabs-horizontal">
{% assign tags_list = site.tags %}
{% if tags_list.first[0] == null %}
{% for tag in tags_list %}
<li>
<a href="{{ site.BASE_PATH }}/{{ site.tags_path }}#{{ tag[0] }}-ref" data-toggle="tab">
{{ tag | capitalize }} <span class="badge pull-right">({{ site.tags[tag].size }})</span>
</a>
</li>
{% endfor %}
{% else %}
{% for tag in tags_list %}
<li>
<a href="{{ site.BASE_PATH }}/{{ site.tags_path }}#{{ tag[0] }}-ref" data-toggle="tab">
{{ tag[0] | capitalize }} <span class="badge pull-right">({{ tag[1].size }})</span>
</a>
</li>
{% endfor %}
{% endif %}
{% assign tags_list = nil %}
</ul>
</div>
<!-- Tab panes -->
<div class="tab-content list-container">
{% for tag in site.tags %}
<div class="tab-pane" id="{{ tag[0] | replace:' ','-' }}-ref">
<h2 style="margin-top: 0px">{{ tag[0] | capitalize }}</h2>
<ul class="list-unstyled">
{% assign pages_list = tag[1] %}
{% for node in pages_list %}
{% if node.title != null %}
{% if group == null or group == node.group %}
<li style="line-height: 35px;"><span class="text-muted">{{ node.date | date: "%Y-%m-%d" }} </span><a href="{{ site.BASE_PATH }}{{node.url}}">{{node.title}}</a></li>
{% endif %}
{% endif %}
{% endfor %}
{% assign pages_list = nil %}
</ul>
</div>
{% endfor %}
</div>
<div class="clearfix"></div>
|
imgavinwang/imgavinwang.github.com
|
ctags.html
|
HTML
|
mit
| 1,748
|
#!/bin/bash
# Upgrade databases
python application.py db upgrade
|
mtekel/digitalmarketplace-api
|
scripts/build.sh
|
Shell
|
mit
| 66
|
# -*- coding: utf8 -*-
"""
The ``queue` utils
==================
Some operation will require a queue. This utils file
"""
__author__ = 'Salas'
__copyright__ = 'Copyright 2014 LTL'
__credits__ = ['Salas']
__license__ = 'MIT'
__version__ = '0.2.0'
__maintainer__ = 'Salas'
__email__ = 'Salas.106.212@gmail.com'
__status__ = 'Pre-Alpha'
|
salas106/irc-ltl-framework
|
utils/queue.py
|
Python
|
mit
| 352
|
REBAR = $(CURDIR)/rebar3
REBAR_URL := https://github.com/emqx/rebar3/releases/download/3.14.3-emqx-7/rebar3
.PHONY: all
all: compile
compile: $(REBAR) unlock
$(REBAR) compile
.PHONY: unlock
unlock:
$(REBAR) unlock
.PHONY: clean
clean: distclean
.PHONY: distclean
distclean:
@rm -rf _build erl_crash.dump rebar3.crashdump rebar.lock emqtt_bench
.PHONY: xref
xref: compile
$(REBAR) xref
.PHONY: docker
docker:
@docker build --no-cache -t emqtt_bench:$$(git describe --tags --always) .
$(REBAR):
ifneq ($(wildcard rebar3),rebar3)
@curl -Lo rebar3 $(REBAR_URL) || wget $(REBAR_URL)
endif
@chmod a+x rebar3
|
emqtt/emqttd_benchmark
|
Makefile
|
Makefile
|
mit
| 619
|
# encoding: utf-8
module JSON
module Generator
class StringAttribute < BasicAttribute
DEFAULT_VALUE = "bar"
end
end
end
|
tmattia/json-generator
|
lib/json/generator/string_attribute.rb
|
Ruby
|
mit
| 139
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Mono.Nat.Pmp;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Mono.Nat
{
internal class PmpSearcher : ISearcher
{
static PmpSearcher instance = new PmpSearcher();
public static List<UdpClient> sockets;
static Dictionary<UdpClient, List<IPEndPoint>> gatewayLists;
public static PmpSearcher Instance
{
get { return instance; }
}
private int timeout;
private DateTime nextSearch;
public event EventHandler<DeviceEventArgs> DeviceFound;
static PmpSearcher()
{
CreateSocketsAndAddGateways();
}
PmpSearcher()
{
timeout = 250;
}
private static void CreateSocketsAndAddGateways()
{
sockets = new List<UdpClient>();
gatewayLists = new Dictionary<UdpClient,List<IPEndPoint>>();
try
{
foreach (var n in NetworkInterface.GetAllNetworkInterfaces())
{
var properties = n.GetIPProperties();
var gatewayList = new List<IPEndPoint>();
foreach (var gateway in properties.GatewayAddresses)
{
if (gateway.Address.AddressFamily == AddressFamily.InterNetwork)
{
gatewayList.Add(new IPEndPoint(gateway.Address, PmpConstants.ServerPort));
}
}
if (gatewayList.Count > 0)
{
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
{
UdpClient client;
try
{
client = new UdpClient(new IPEndPoint(address.Address, 0));
}
catch (SocketException)
{
continue; // Move on to the next address.
}
gatewayLists.Add(client, gatewayList); sockets.Add(client);
}
}
}
}
}
catch (Exception)
{
// NAT-PMP does not use multicast, so there isn't really a good fallback.
}
}
public void Search()
{
foreach (var s in sockets)
{
try
{
Search(s);
}
catch
{
// Ignore any search errors
}
}
}
void Search (UdpClient client)
{
// Sort out the time for the next search first. The spec says the
// timeout should double after each attempt. Once it reaches 64 seconds
// (and that attempt fails), assume no devices available
nextSearch = DateTime.Now.AddMilliseconds(timeout);
timeout *= 2;
// We've tried 9 times as per spec, try searching again in 5 minutes
if (timeout == 128 * 1000)
{
timeout = 250;
nextSearch = DateTime.Now.AddMinutes(10);
return;
}
// The nat-pmp search message. Must be sent to GatewayIP:53531
var buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
foreach (var gatewayEndpoint in gatewayLists[client])
client.Send(buffer, buffer.Length, gatewayEndpoint);
}
bool IsSearchAddress(IPAddress address)
{
foreach (var gatewayList in gatewayLists.Values)
foreach (var gatewayEndpoint in gatewayList)
if (gatewayEndpoint.Address.Equals(address))
return true;
return false;
}
public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
{
if (!IsSearchAddress(endpoint.Address))
return;
if (response.Length != 12)
return;
if (response[0] != PmpConstants.Version)
return;
if (response[1] != PmpConstants.ServerNoop)
return;
int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
if (errorcode != 0)
NatUtility.Log("Non zero error: {0}", errorcode);
var publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
nextSearch = DateTime.Now.AddMinutes(5);
timeout = 250;
OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(endpoint.Address, publicIp)));
}
public DateTime NextSearch
{
get { return nextSearch; }
}
private void OnDeviceFound(DeviceEventArgs args)
{
if (DeviceFound != null)
DeviceFound(this, args);
}
}
}
|
assinnata/ChainUtils
|
Mono.Nat/PmpSearcher.cs
|
C#
|
mit
| 5,295
|
require 'spec_helper'
describe FannyPack::Request do
describe "::VALID_ACTIONS" do
it { FannyPack::Request::VALID_ACTIONS.should be_frozen }
end
before :each do
@req = FannyPack::Request.new
end
describe "#initialize" do
%w[response params].each do |test|
it "sets @#{test} to a hash" do
@req.instance_variable_get("@#{test}").should be_a Hash
end
end
end
%w[response params].each do |test|
describe "##{test}" do
it "returns @#{test}" do
@req.instance_variable_get("@#{test}").should == @req.send(test)
end
end
end
describe "#commit" do
it "raises exception unless action is valid" do
expect { @req.commit :HammerTime }.to raise_error
end
end
end
|
site5/fanny_pack
|
spec/fanny_pack/request_spec.rb
|
Ruby
|
mit
| 752
|
/* See LICENSE for license details. */
/*
Module: snck_list.h
Description:
Generic linked list to be used for all lists in snck project.
Comments:
The list is a circular doubly linked list. A fake element is used
to point to first and last elements. The same structure is used for
each element including the fake element. However, the fake element
does not have the same derived type as the other elements.
The caller is reponsible of casting the element to the derived type.
Before casting, it is important to make sure that the element is
not the fake element. If the list is not the first member of the
derived type, then it may be useful to use the offsetof() macro to
get a pointer to the start of the derived type.
The circular feature ensures that each element is part of a list.
Operations may be done on a single element or on groups of elements.
The same method is used to insert elements or to remove elements.
See the examples section for more details.
Examples:
- create an empty list
snck_list_init(&o_list);
- insert a first list before a second
snck_list_join(&o_first, &o_second);
- insert a first list after a second
snck_list_join(&o_second, &o_first);
- remove a single element from a list
snck_list_join(&o_element, &o_element);
- remove a group of elements from a list
snck_list_join(&o_last, &o_first);
Notes:
To insert all elements of a list into another, you first need to
detach the elements from the fake or else the final list may end up
with two fake elements.
p_first = o_fake.p_next;
snck_list_join(&o_fake, &o_fake);
snck_list_join(p_first, &o_other);
*/
/* Header file dependencies */
#if !defined(INC_SNCK_OS_H)
#error include snck_os.h first
#endif /* #if !defined(INC_SNCK_OS_H) */
/* Reverse include guard */
#if defined(INC_SNCK_LIST_H)
#error include snck_list.h once
#endif /* #if defined(INC_SNCK_LIST_H) */
#define INC_SNCK_LIST_H
/*
Structure: snck_list
Description:
*/
struct snck_list
{
struct snck_list *
p_next;
struct snck_list *
p_prev;
}; /* struct snck_list */
/* Public functions ... */
#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
snck_list_init(
struct snck_list * const
p_node);
#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
snck_list_join(
struct snck_list * const
p_before,
struct snck_list * const
p_after);
#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
snck_list_iterate(
struct snck_list * const
p_node,
void (* const p_callback)(
void * const
p_context,
struct snck_list * const
p_list),
void * const
p_context);
/* end-of-file: snck_list.h */
|
fboucher9/snck
|
snck_list.h
|
C
|
mit
| 2,956
|
module Scouter
class Github < Scouter::Base::SingleUrlApi
END_POINT = 'https://api.github.com'.freeze
private
def self.check_and_trans_url(urls)
urls = to_array(urls)
github_urls = urls.map do |u|
uri = URI.parse(u)
uri.host == 'github.com' ? u : nil
end.compact
raise ArgumentError, "#{github_urls} is not String and Array" unless github_urls.class == Array
return github_urls
end
# Build GitHub API URL
# @param [String] url
# @return [String] API url
def self.api_url(url)
uri = URI.parse(url)
if uri.path =~ /^\/([^\/]+)\/([^\/]+)/
"#{END_POINT}/repos/#{$1}/#{$2}"
else
raise ArgumentError, "#{url} is not valid GitHub URL"
end
end
# Parse json data for response
# @param [String] json
# @return [Hash] url & count
def self.parse_response(json, url)
res = JSON.parse(json)
{ url => { self.service_name => res['stargazers_count'] } }
end
end
end
|
morizyun/scouter
|
lib/scouter/github.rb
|
Ruby
|
mit
| 1,013
|
module Sunspot::Resque
class Worker
@queue = :sunspot
def self.before_enqueue(sunspot_method = nil, *args)
raise ArgumentError, 'No sunspot method given' unless sunspot_method
end
def self.perform(sunspot_method, object = nil)
sunspot_method = sunspot_method.to_sym
if object.is_a? Hash
object = object.with_indifferent_access
end
Sunspot.without_proxy do
case sunspot_method
when :index, :index!
self.index object[:class].constantize.find(object[:id])
when :remove, :remove!
self.remove_by_id object[:class], object[:id]
when :remove_all
self.remove_all object
when :commit, :optimize
self.send sunspot_method
else
raise "Undefined protocol for #{self.name}: #{sunspot_method} (#{object or 'n/a'})"
end
end
end
def self.index(object)
Sunspot.index object
end
def self.remove_by_id(klass, id)
Sunspot.remove_by_id klass, id
end
def self.remove_all(classes)
classes.map! { |klass| klass.constantize }
Sunspot.remove_all classes
end
def self.commit
# on production, use autocommit in solrconfig.xml
# or commitWithin whenever sunspot supports it
Sunspot.commit unless ::Rails.env.production?
end
def self.optimize
Sunspot.optimize
end
end
end
|
Sija/sunspot_resque
|
lib/sunspot_resque/resque/worker.rb
|
Ruby
|
mit
| 1,410
|
# react-weui-snippets
react-weui snippets for the Sublime Text
|
lincmin/react-weui-snippets
|
README.md
|
Markdown
|
mit
| 64
|
'use strict';
var assert = require('assert');
var x = [1, 2, 3];
var sum = 0;
for (var value of x) {
sum += value;
}
assert(sum === 6);
|
ForbesLindesay/acorn-es6
|
test/examples/for-of.js
|
JavaScript
|
mit
| 140
|
body {
font-family: helvetica;
position: relative;
}
h2 ~ h2 {
border-top: 1px solid #ddd;
padding-top: 35px;
margin-top: 30px;
}
h3 {
padding-top: 15px;
}
#nav-menu {
top: 10px;
}
.nav>li a {
border-left: 3px solid #fff;
padding: 6px 15px;
}
.nav>li.active>a {
border-left: 3px solid #ccc;
}
.nav>li .nav {
transition: all 0.2s;
max-height: 0;
overflow: hidden;
}
.nav>li.active .nav {
max-height: 300px;
}
.nav .nav a {
padding: 0px 15px 0px 30px;
margin: 4px 0;
}
dl.dl-horizontal > * {
padding: 3px 0;
}
#binding-demo > pre {
padding: 20px;
}
#binding-demo * {
text-align: center;
padding: 3px 12px;
}
#qunit-testrunner-toolbar, #qunit-header, #qunit-banner {
display: none;
}
#demo-area input {
margin: 3px;
}
#demo-area input:not([type]) {
width: 47%;
display: inline;
}
|
theninj4/Pajama-JS
|
website/css/screen.css
|
CSS
|
mit
| 835
|
--
-- Reemplazar por la ruta correcta del archivo
--
LOAD DATA LOCAL INFILE 'C:/Users/ALAN7/Documents/GitHub/ViajesTransparentes/DOCUMENTACION BD/Catalogos con datos/cargos_catalogo.csv'
INTO TABLE cargo_catalogo
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(idCargo,CARGO);
|
equipoviajestransparentes/ViajesTransparentes
|
DOCUMENTACION BD/Scripts de consultas y carga/carga masiva de cargos.sql
|
SQL
|
mit
| 294
|
'''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length = conf.ner_step_length
pos_length = conf.ner_pos_length
chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.txt'%folder_path, 'w')
def convert(chunktags):
# convert BIOES to BIO
for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
elif q.startswith("B-"):
if p==0:
chunktags[p] = "I-" + q[2:]
else:
if q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
return chunktags
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)])
prob = model.predict_on_batch([embed_index, hash_index, pos, chunk])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
chunktags = [IOB[j] for j in predict_label][:l]
word_pos_chunk = list(zip(*each))
# convert
word_pos_chunk = list(zip(*word_pos_chunk))
word_pos_chunk = [list(x) for x in word_pos_chunk]
# if data == "test":
# word_pos_chunk[3] = convert(word_pos_chunk[3])
word_pos_chunk = list(zip(*word_pos_chunk))
#convert
# if data == "test":
# chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n')
result.close()
print('epoch %s predict over !'%best_epoch)
os.system('../tools/conlleval < %s/predict.txt'%folder_path)
|
danche354/Sequence-Labeling
|
ner_BIOES/evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py
|
Python
|
mit
| 3,163
|
import numpy as np
import cvxopt as co
def load_mnist_dataset():
import torchvision.datasets as datasets
mnist_train = datasets.MNIST(root='../data/mnist', train=True, download=True, transform=None)
mnist_test = datasets.MNIST(root='../data/mnist', train=False, download=True, transform=None)
test_labels = np.array([mnist_test[i][1].numpy() for i in range(len(mnist_test))], dtype=np.int)
train_labels = np.array([mnist_train[i][1].numpy() for i in range(len(mnist_train))], dtype=np.int)
test = np.array([np.asarray(mnist_test[i][0]).reshape(28*28) for i in range(len(mnist_test))], dtype=np.float)
train = np.array([np.asarray(mnist_train[i][0]).reshape(28*28) for i in range(len(mnist_train))], dtype=np.float)
train /= 255. # normalize data to be in range [0,1]
test /= 255.
return train, train_labels, test, test_labels, [28, 28]
def load_fashion_mnist_dataset():
import torchvision.datasets as datasets
mnist_train = datasets.FashionMNIST(root='../data/fashion-mnist', train=True, download=True, transform=None)
mnist_test = datasets.FashionMNIST(root='../data/fashion-mnist', train=False, download=True, transform=None)
test_labels = np.array([mnist_test[i][1].numpy() for i in range(len(mnist_test))], dtype=np.int)
train_labels = np.array([mnist_train[i][1].numpy() for i in range(len(mnist_train))], dtype=np.int)
test = np.array([np.asarray(mnist_test[i][0]).reshape(28*28) for i in range(len(mnist_test))], dtype=np.float)
train = np.array([np.asarray(mnist_train[i][0]).reshape(28*28) for i in range(len(mnist_train))], dtype=np.float)
train /= 255. # normalize data to be in range [0,1]
test /= 255.
return train, train_labels, test, test_labels, [28, 28]
def load_emnist_dataset():
import torchvision.datasets as datasets
mnist_train = datasets.EMNIST(root='../data/emnist', split='balanced', train=True, download=True, transform=None)
mnist_test = datasets.EMNIST(root='../data/emnist', split='balanced', train=False, download=True, transform=None)
test_labels = np.array([mnist_test[i][1].numpy() for i in range(len(mnist_test))], dtype=np.int)
train_labels = np.array([mnist_train[i][1].numpy() for i in range(len(mnist_train))], dtype=np.int)
test = np.array([np.asarray(mnist_test[i][0]).reshape(28*28) for i in range(len(mnist_test))], dtype=np.float)
train = np.array([np.asarray(mnist_train[i][0]).reshape(28*28) for i in range(len(mnist_train))], dtype=np.float)
train /= 255. # normalize data to be in range [0,1]
test /= 255.
return train, train_labels, test, test_labels, [28, 28]
def load_cifar10_dataset():
import torchvision.datasets as datasets
cifar_train = datasets.CIFAR10(root='../data/cifar10', train=True, download=True, transform=None)
cifar_test = datasets.CIFAR10(root='../data/cifar10', train=False, download=True, transform=None)
test_labels = np.array([cifar_test[i][1] for i in range(len(cifar_test))], dtype=np.int)
train_labels = np.array([cifar_train[i][1] for i in range(len(cifar_train))], dtype=np.int)
test = np.array([np.asarray(cifar_test[i][0].convert('F')).reshape(32*32) for i in range(len(cifar_test))], dtype=np.float)
train = np.array([np.asarray(cifar_train[i][0].convert('F')).reshape(32*32) for i in range(len(cifar_train))], dtype=np.float)
train /= 255. # normalize data to be in range [0,1]
test /= 255.
return train, train_labels, test, test_labels, [32, 32]
def get_gaussian(num, dims=2, means=[0,0], vars=[1,1]):
data = np.random.multivariate_normal(means, np.eye(dims), num)
return data
def get_2state_gaussian_seq(lens,dims=2,means1=[2,2,2,2],means2=[5,5,5,5],vars1=[1,1,1,1],vars2=[1,1,1,1],anom_prob=1.0):
seqs = np.zeros((dims, lens))
lbls = np.zeros((1, lens), dtype=np.int8)
marker = 0
# generate first state sequence
for d in range(dims):
seqs[d, :] = np.random.randn(lens)*vars1[d] + means1[d]
prob = np.random.uniform()
if prob < anom_prob:
# add second state blocks
while True:
max_block_len = 0.6*lens
min_block_len = 0.1*lens
block_len = np.int(max_block_len*np.random.uniform()+3)
block_start = np.int(lens*np.random.uniform())
if block_len - (block_start+block_len-lens)-3 > min_block_len:
break
block_len = min( [block_len, block_len - (block_start+block_len-lens)-3] )
lbls[block_start:block_start+block_len-1] = 1
marker = 1
for d in range(dims):
seqs[d,block_start:block_start+block_len-1] = np.random.randn(1,block_len-1)*vars2[d] + means2[d]
return seqs, lbls, marker
def get_2state_anom_seq(lens, comb_block_len, anom_prob=1.0, num_blocks=1):
seqs = co.matrix(0.0, (1, lens))
lbls = co.matrix(0, (1, lens))
marker = 0
# generate first state sequence, gaussian noise 0=mean, 1=variance
seqs = np.zeros((1, lens))
lbls = np.zeros((1, lens))
bak = seqs.copy()
prob = np.random.uniform()
if prob < anom_prob:
# add second state blocks
block_len = np.int(np.floor(comb_block_len / float(num_blocks)))
marker = 1
# add a single block
blen = 0
for b in range(np.int(num_blocks)):
if (b==num_blocks-1 and b>1):
block_len = np.round(comb_block_len-blen)
isDone = False
while isDone == False:
start = np.int(np.random.uniform()*float(lens-block_len+1))
if np.sum(lbls[0,start:start+block_len]) == 0:
lbls[0, start:start+block_len] = 1
seqs[0, start:start+block_len] = bak[0, start:start+block_len]+4.0
isDone = True
break
blen += block_len
return seqs, lbls, marker
|
nicococo/tilitools
|
tilitools/utils_data.py
|
Python
|
mit
| 5,881
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_XmlRpc
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 10020 2009-08-18 14:34:09Z j.fischer@metaways.de $
*/
/**
* Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_XmlRpc
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_XmlRpc_Exception extends Zend_Exception
{}
|
jodier/tmpdddf
|
web/private/tine20/library/Zend/XmlRpc/Exception.php
|
PHP
|
mit
| 1,104
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 10:43:53 2019
@author: Heathro
Description: Reduces a vcf file to meta section and
one line for each chromosome number for testing and
debugging purposes.
"""
# Open files to read from and write to
vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU")
testvcf = open("REDUCED_ali.vcf", "w")
# Keep track of chromosome number so we can get one of each
temp_chrom = 0
counter = 0
for line_index, line in enumerate(vcfpath):
# Found a chromosome line
if line[0:8] == "sNNffold":
column = line.split('\t')
first_col = column[0].split('_')
current_chrom = first_col[1]
# Write up to 1000 lines of each chromosome
if current_chrom == temp_chrom:
counter = counter + 1
if counter < 1000:
testvcf.write(line)
# If a new chromosome, write a line, start counter at 0
elif current_chrom != temp_chrom:
counter = 0
temp_chrom = current_chrom
testvcf.write(line)
# Include the meta lines and header line
else:
testvcf.write(line)
testvcf.close()
vcfpath.close()
|
davidfarr/mg-gap
|
mg-gap/mg-gap-py/mg-gap/test_files/reduceVCF.py
|
Python
|
mit
| 1,210
|
/**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.test.framework.datafactory.commerce.catalog.admin.products;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import com.mozu.api.ApiException;
import com.mozu.api.ApiContext;
import com.mozu.test.framework.core.TestFailException;
import com.mozu.api.resources.commerce.catalog.admin.products.ProductExtraResource;
/** <summary>
* Use the Extras resource to configure an extra product attribute for products associated with the product type that uses the extra attribute.
* </summary>
*/
public class ProductExtraFactory
{
public static List<com.mozu.api.contracts.productadmin.ProductExtra> getExtras(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, int expectedCode) throws Exception
{
List<com.mozu.api.contracts.productadmin.ProductExtra> returnObj = new ArrayList<com.mozu.api.contracts.productadmin.ProductExtra>();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.getExtras( productCode);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static List<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice> getExtraValueLocalizedDeltaPrices(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, String value, int expectedCode) throws Exception
{
List<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice> returnObj = new ArrayList<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice>();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.getExtraValueLocalizedDeltaPrices( productCode, attributeFQN, value);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice getExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, String value, String currencyCode, int expectedCode) throws Exception
{
return getExtraValueLocalizedDeltaPrice(apiContext, dataViewMode, productCode, attributeFQN, value, currencyCode, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice getExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, String value, String currencyCode, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice returnObj = new com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.getExtraValueLocalizedDeltaPrice( productCode, attributeFQN, value, currencyCode, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtra getExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, int expectedCode) throws Exception
{
return getExtra(apiContext, dataViewMode, productCode, attributeFQN, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtra getExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtra returnObj = new com.mozu.api.contracts.productadmin.ProductExtra();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.getExtra( productCode, attributeFQN, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice addExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice localizedDeltaPrice, String productCode, String attributeFQN, String value, int expectedCode) throws Exception
{
return addExtraValueLocalizedDeltaPrice(apiContext, dataViewMode, localizedDeltaPrice, productCode, attributeFQN, value, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice addExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice localizedDeltaPrice, String productCode, String attributeFQN, String value, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice returnObj = new com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.addExtraValueLocalizedDeltaPrice( localizedDeltaPrice, productCode, attributeFQN, value, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtra addExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtra productExtra, String productCode, int expectedCode) throws Exception
{
return addExtra(apiContext, dataViewMode, productExtra, productCode, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtra addExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtra productExtra, String productCode, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtra returnObj = new com.mozu.api.contracts.productadmin.ProductExtra();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.addExtra( productExtra, productCode, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static List<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice> updateExtraValueLocalizedDeltaPrices(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, List<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice> localizedDeltaPrice, String productCode, String attributeFQN, String value, int expectedCode) throws Exception
{
List<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice> returnObj = new ArrayList<com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice>();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.updateExtraValueLocalizedDeltaPrices( localizedDeltaPrice, productCode, attributeFQN, value);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice updateExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice localizedDeltaPrice, String productCode, String attributeFQN, String value, String currencyCode, int expectedCode) throws Exception
{
return updateExtraValueLocalizedDeltaPrice(apiContext, dataViewMode, localizedDeltaPrice, productCode, attributeFQN, value, currencyCode, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice updateExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice localizedDeltaPrice, String productCode, String attributeFQN, String value, String currencyCode, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice returnObj = new com.mozu.api.contracts.productadmin.ProductExtraValueDeltaPrice();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.updateExtraValueLocalizedDeltaPrice( localizedDeltaPrice, productCode, attributeFQN, value, currencyCode, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.productadmin.ProductExtra updateExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtra productExtra, String productCode, String attributeFQN, int expectedCode) throws Exception
{
return updateExtra(apiContext, dataViewMode, productExtra, productCode, attributeFQN, null, expectedCode);
}
public static com.mozu.api.contracts.productadmin.ProductExtra updateExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.productadmin.ProductExtra productExtra, String productCode, String attributeFQN, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.productadmin.ProductExtra returnObj = new com.mozu.api.contracts.productadmin.ProductExtra();
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
returnObj = resource.updateExtra( productExtra, productCode, attributeFQN, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static void deleteExtra(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, int expectedCode) throws Exception
{
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
resource.deleteExtra( productCode, attributeFQN);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
}
public static void deleteExtraValueLocalizedDeltaPrice(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String productCode, String attributeFQN, String value, String currencyCode, int expectedCode) throws Exception
{
ProductExtraResource resource = new ProductExtraResource(apiContext, dataViewMode);
try
{
resource.deleteExtraValueLocalizedDeltaPrice( productCode, attributeFQN, value, currencyCode);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
}
}
|
Mozu/mozu-java
|
mozu-java-test/src/main/java/com/mozu/test/framework/datafactory/commerce/catalog/admin/products/ProductExtraFactory.java
|
Java
|
mit
| 16,205
|
# Firebase Fruit Detector
An Arduino / Raspberry Pi fruit detector that uses Firebase to power web, Google Glass and Android displays.
v0.1 supports apples and oranges.
## What's here
This project contains 4 directories:
- `/detector` - The node.js code for the fruit detector
- `/android` - An android app to read the detected fruit
- `/web` - A tiny web app to read the detected fruit
- `/google-glass` - A Google Glass app to read the detected fruit
## The Fruit Detector
This probably works with other boards, but it was written with two things you probably have lying around somewhere. Go dig them up and blow the dust off of them.
- Raspberry pi
- Arduino Uno
- Jumper wires, and a resistor
- Something copper, something zinc (A crew and a piece of wire work great)
### Soft dependencies
- [Firebase](https://www.firebase.com/) - realtime platform; the Internet part of this example
- [Johnny Five](https://github.com/rwaldron/johnny-five#user-content-setup-and-assemble-arduino) - open source JavaScript Arduino programming framework
### Running it
0. Add a pull down resistor to A3. Ground the zinc probe. Connect the copper probe to the A3.
0. Install the `StandardFirmata` sketch to your Arduino per the [Johnny Five documentation](https://github.com/rwaldron/johnny-five#user-content-setup-and-assemble-arduino).
0. Install [node.js](http://nodejs.org/), [Johnny Five](https://github.com/rwaldron/johnny-five#user-content-hey-you-heres-johnny) and [Firebase's node.js client](https://www.firebase.com/docs/web/quickstart.html) onto your Raspberry Pi.
0. Create a new [Firebase](https://www.firebase.com/) to store/synchronize your state. Replace `test-firebase-please-ignore` in the code with the subdomain for your Firebase.
0. Copy the JavaScript code on to your Raspberry Pi.
0. Run it:
$ node device/fruit-detector.js
0. Stab the probes into your fruit.
|
mimming/firebase-fruit-detector
|
README.md
|
Markdown
|
mit
| 1,892
|
'use strict';
var compiler = require('gss-compiler');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
module.exports = function() {
function transform (file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file);
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-gss', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
var ast = compiler.compile(str);
file.contents = new Buffer(JSON.stringify(ast, null, 2) + "\n");
file.path = gutil.replaceExtension(file.path, '.json');
self.push(file);
return next();
};
return through2.obj(transform);
};
|
johnetrent/gulp-gss
|
index.js
|
JavaScript
|
mit
| 764
|
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/sourcelair/xterm.js/2.1.0/dist/xterm.css">
<script src="https://cdn.rawgit.com/sourcelair/xterm.js/2.1.0/dist/xterm.js"></script>
<script src="https://cdn.rawgit.com/euank/snailescape.js/master/lib/parser.js"></script>
<script src="https://unpkg.com/browserfs@1.1.0"></script>
<script src="https://unpkg.com/github-api/dist/GitHub.bundle.min.js"></script>
<script src="ansi.js"></script>
<script src="argsparse.js"></script>
</head>
<body>
<div id="terminal"></div>
<script>
var term = new Terminal();
term.open(document.getElementById('#terminal'));
var shellprompt = '$ ';
var curline = '';
var commands = {};
var cwd = '/';
function c(color, str){
return ansi.color(color) + str + ansi.color('reset');
}
var colors = ["white", "black", "blue", "cyan", "green", "magenta", "red", "yellow", "bgWhite", "bgBlack", "bgBlue", "bgCyan", "bgGreen", "bgMagenta", "bgRed", "bgYellow", "grey", "brightBlack", "brightRed", "brightGreen", "brightYellow", "brightBlue", "brightMagenta", "brightCyan", "brightWhite", "bgGrey", "bgBrightBlack", "bgBrightRed", "bgBrightGreen", "bgBrightYellow", "bgBrightBlue", "bgBrightMagenta", "bgBrightCyan", "bgBrightWhite"];
var color = {};
var currentCmd = null;
colors.forEach(function (col) {
color[col] = c.bind(null, col);
});
function runCmd(cmd, args, cb) {
currentCmd = {cmd, args};
function handle(err, res) {
if (err) {
term.write(ansi.color('red') + "Error" + ansi.color('reset') + ": " + err.message || err);
} else {
term.write(res);
}
cb();
currentCmd = null;
}
if (!commands[cmd]) {
term.write(ansi.color('red') + "Command not recognized" + ansi.color('reset') + ": " + cmd);
cb();
} else {
if (commands[cmd].async) {
commands[cmd](args, handle);
} else {
var err, res;
try {res = commands[cmd](args);} catch(e){err = e}
handle(err, res);
}
}
}
term.prompt = function () {
term.write('\r\n' + color.green('guest') + '@' + color.yellow(cwd)+ ' $ ');
};
term.writeln('Welcome to xterm.js');
term.writeln('This is a local terminal emulation, without a real terminal in the back-end.');
term.writeln('Type some keys and commands to play around.');
term.writeln('');
term.prompt();
term.on('key', function (key, ev) {
var printable = (
!ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey
);
if (ev.keyCode == 13) {
term.writeln('');
if (currentCmd) {
if (currentCmd.enter) {
currentCmd.enter(curline);
}
curline = '';
return;
}
var parser = new SnailEscape();
var result = parser.parse(curline);
curline = '';
if(result.error) {
term.write(ansi.color('red') + "Could not parse input" + ansi.color('reset') + ": ", result.error);
finish();
} else {
var cmd = result.parts.shift();
runCmd(cmd, result.parts, finish);
}
function finish() {
// term.writeln('');
term.prompt();
}
} else if (ev.keyCode == 8) {
if (term.x > 10 + cwd.length) {
curline = curline.slice(0, -1);
term.write('\b \b');
}
} else if (printable) {
if (!(currentCmd && currentCmd.doNotEcho)) {
term.write(key);
}
curline += key;
}
});
term.on('paste', function (data, ev) {
term.write(data);
});
var node = (function(){
var obj = {};
BrowserFS.install(obj);
// Constructs an instance of the LocalStorage-backed file system.
var lsfs = new BrowserFS.FileSystem.LocalStorage();
// Initialize it as the root file system.
BrowserFS.initialize(lsfs);
return {fs:obj.require('fs'), process: obj.process, Buffer: obj.Buffer};
})();
var fs = node.fs;
commands.ls = function(args, cb){
fs.readdir(cwd,function(err, res){
cb(err, res && res.join('\r\n'));
});
};
commands.ls.async = true;
commands.pwd = function(){return cwd;}
commands.echo = function(args){return args.join('\r\n');}
commands.cat = function (args, cb) {
fs.readFile(cwd + args[0], 'utf-8', function (err, res) {
cb(err, res);
});
}
commands.cat.async = true;
commands.cd = function(args, cb){
var file = (args[0] === '..' ? file = cwd.split('/').slice(0,-2).join('/') : cwd + args[0]);
if (!file) {
file = '/';
}
fs.exists(file, function (res) {
if (!res) {
cb(new Error('ENOTENT: No such file or directory, ' + file));
} else {
cwd = file;
if (!cwd.endsWith('/')) {
cwd += '/';
}
cb(null, '');
}
});
}
commands.cd.async = true;
commands.mkdir = function(args, cb) {
fs.mkdir(cwd + args[0], function (err) {
cb(err, color.green('Created'));
});
}
commands.mkdir.async = true;
commands.rt = function(args, cb) {
fs.writeFile(cwd + args[0], args[1], function (err) {
cb(err, color.green('Written with') + ': ' + args[1]);
});
}
commands.rt.async = true;
commands.rm = function(args, cb) {
fs.unlink(cwd + args[0], function (err) {
cb(err, color.green('Deleted!'));
});
};
commands.rm.async = true;
commands.rmdir = function(args, cb) {
fs.rmdir(cwd + args[0], function (err) {
cb(err, color.green('Deleted!'));
});
};
commands.rimraf = function(args, cb_) {
var amount = 0;
function cb(err) {
if (amount === 0) {
cb_(err);
} else {
amount--;
}
}
fs.readdir(cwd + args[0], function(err, data) {
if(err)return cb_(err);
data.forEach(function (v){
amount++;
fs.stat(cwd + args[0] + v, function (err, stat) {
if (err)return cb(err);
if (stat.isFile()) {
commands.rm([args[0] + v], cb);
} else {
commands.rimraf([args[0] + v], cb);
}
});
});
});
}
commands.rimraf.async = true;
var gh = null;
commands.rmdir.async = true;
commands.git = function(args, cb) {
if (!gh) {
var username, password;
term.write('Enter your github username: ');
currentCmd.enter = function (line) {
username = line;
term.write('Enter your password: ');
currentCmd.doNotEcho = true;
currentCmd.enter = function (line) {
currentCmd.doNotEcho = false;
password = line;
gh = new GitHub({username, password});
parse(commands.git, argsparse(args), cb);
}
}
} else {
parse(commands.git, argsparse(args), cb);
}
}
commands.git.async = true;
function parse(cmd, args, cb) {
if (args.length === 0) {
cb(null, color.green('Authed'));
} else if (cmd[args[0]]){
cmd[args.shift()](argsparse(args), cb);
} else {
cb("Unknown subcommands: " + args[0]);
}
}
commands.git.clone = function (args, cb) {
var repo = gh.getRepo(args._[0].split('/')[0],args._[0].split('/')[1]);
var branch = args._[1] || 'master';
clone(repo, branch, '.', args._[0].split('/')[1]).then(function (res){cb(null, res);},cb);
}
function clone(repo, branch, path, name) {
return repo.getContents(branch, path, true).then(function(res){
if (typeof res.data === 'object') {
return new Promise(function (resolve, reject) {
commands.mkdir([path === '.' ? name : path], function (err) {
if (err) {reject(err);}else{resolve()}
});
}).then(function () {
return Promise.all(res.data.map(function (v) {
return clone(repo, branch, v.path, name);
}));
});
}
return new Promise(function (resolve, reject) {
commands.rt([name + '/' + path, res.data], function (err) {
if (err) {reject(err);}else{resolve()}
});
});
})
}
</script>
</body>
</html>
|
legodude17/github-edit
|
index.html
|
HTML
|
mit
| 9,608
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Jobs.Data.Action;
using Jobs.Data.Root;
using Jobs.Data.Root.Includes;
using jobs.web.ViewModel.Contact;
using vlko.core.Base;
using vlko.core.Components;
using vlko.core.InversionOfControl;
using vlko.core.Repository;
using vlko.core.Services;
using vlko.core.ValidationAtribute;
namespace jobs.web.Controllers
{
public class ProjectController : BaseController
{
/// <summary>
/// URL: /Project/Index
/// </summary>
/// <returns>Action result.</returns>
public ActionResult Index(PagedModel<Job> pageModel)
{
pageModel.LoadData(RepositoryFactory.Action<JobAction>()
.GetProjects()
.OrderByDescending(item => item.CreateDate));
return ViewWithAjax(pageModel);
}
/// <summary>
/// URL: /Project/Details
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Action result.</returns>
public ActionResult Details(string id)
{
var offer = RepositoryFactory.Action<JobAction>().Load("jobs/" + id);
return ViewWithAjax(offer);
}
/// <summary>
/// URL: /Project/Confirm
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Action result.</returns>
public ActionResult Confirm(string id)
{
bool confirmed = false;
using (var tran = RepositoryFactory.StartTransaction())
{
confirmed = RepositoryFactory.Action<JobAction>().Confirm(id);
tran.Commit();
}
if (confirmed)
{
return View("Confirmed");
}
return new HttpNotFoundResult();
}
/// <summary>
/// URL: /People/Close
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Action result.</returns>
public ActionResult Close(string id)
{
var job = RepositoryFactory.Action<JobAction>().GetJobByCloseToken(id);
if (job != null)
{
return View(job);
}
return new HttpNotFoundResult();
}
/// <summary>
/// URL: /People/Close [post]
/// </summary>
/// <param name="job">The job.</param>
/// <returns>Action result.</returns>
[HttpPost]
public ActionResult Close(Job job)
{
bool closed = false;
using (var tran = RepositoryFactory.StartTransaction())
{
closed = RepositoryFactory.Action<JobAction>().CloseJob(job.Id);
tran.Commit();
}
if (closed)
{
return View("CloseOk");
}
return new HttpNotFoundResult();
}
/// <summary>
/// URL: /Project/Contact
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Action result.</returns>
public ActionResult Contact(string id)
{
var job = RepositoryFactory.Action<JobAction>().Load("jobs/" + id);
if (job != null)
{
return ViewWithAjax(new ContactModel { JobId = job.SimpleId });
}
return new HttpNotFoundResult();
}
/// <summary>
/// URL: /Project/Contact
/// </summary>
/// <param name="contact">The contact.</param>
/// <returns>Action result.</returns>
[HttpPost]
[AntiXss]
public ActionResult Contact(ContactModel contact)
{
if (ModelState.IsValid)
{
var job = RepositoryFactory.Action<JobAction>().Load("jobs/" + contact.JobId);
if (job == null)
{
return new HttpNotFoundResult();
}
if (SendContactEmail(contact, job))
{
return ViewWithAjax("ContactOk");
}
return ViewWithAjax("ContactFail");
}
return ViewWithAjax(contact);
}
/// <summary>
/// URL: /Project/Create
/// </summary>
/// <returns>Action result.</returns>
public ActionResult Create()
{
var job = new Job
{
Properties = new PropertyInfo[] {}
};
return ViewWithAjax(job);
}
/// <summary>
/// URL: /Project/Create
/// </summary>
/// <param name="job">The job.</param>
/// <returns>Action result.</returns>
[HttpPost]
[AntiXss]
public ActionResult Create(Job job)
{
if (job.Properties == null)
{
job.Properties = new PropertyInfo[] {};
}
if (Request.Form["AddProperty"] != null)
{
var propertyList = job.Properties.ToList();
propertyList.Add(new PropertyInfo());
job.Properties = propertyList.ToArray();
}
else if (GetRemoveItemIndex() >= 0)
{
var removeItemIndex = GetRemoveItemIndex();
var propertyList = job.Properties.ToList();
RemoveFromModelState(removeItemIndex, propertyList.Count);
propertyList.RemoveAt(removeItemIndex);
job.Properties = propertyList.ToArray();
}
else if (ModelState.IsValid)
{
using (var tran = RepositoryFactory.StartTransaction())
{
job.JobType = JobTypeEnum.Project;
RepositoryFactory.Action<JobAction>().Create(job);
tran.Commit();
}
if (SendNotificationEmail(job))
{
return ViewWithAjax("SendOk");
}
return ViewWithAjax("SendFail");
}
return ViewWithAjax(job);
}
/// <summary>
/// Sends the contact email.
/// </summary>
/// <param name="contact">The contact.</param>
/// <param name="job">The job.</param>
private bool SendContactEmail(ContactModel contact, Job job)
{
string mailTemplate = RenderPartialViewToString("ContactMail", contact);
var match = Regex.Match(mailTemplate, "<email>(.*)</email>", RegexOptions.Singleline);
var mailText = match.Groups[1].Value;
// send email to creator
return SendEmail(job.Email, "[jobs.preweb.sk] Odpoved od " + contact.Email, mailText);
}
/// <summary>
/// Sends the notification email.
/// </summary>
/// <param name="job">The job.</param>
private bool SendNotificationEmail(Job job)
{
string mailTemplate = RenderPartialViewToString("SendMail", job);
var match = Regex.Match(mailTemplate, "<email>(.*)</email>", RegexOptions.Singleline);
var mailText = match.Groups[1].Value;
// send email to creator
return SendEmail(job.Email, "[jobs.preweb.sk] Potvrdenie registracie", mailText);
}
/// <summary>Sends the email.</summary>
/// <param name="recipient">The recipient.</param>
/// <param name="subject">The subject.</param>
/// <param name="mailText">The mail text.</param>
/// <returns>True if success; otherwise false.</returns>
private bool SendEmail(string recipient, string subject, string mailText)
{
var mailService = IoC.Resolve<IEmailService>();
return mailService.Send(recipient, subject, mailText, true);
}
/// <summary>
/// Renders the partial view to string.
/// </summary>
/// <param name="viewName">Name of the view.</param>
/// <param name="model">The model.</param>
/// <returns>Partial view as text.</returns>
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
/// <summary>
/// Removes the ModelState.
/// </summary>
/// <param name="removeItemIndex">Index of the remove item.</param>
/// <param name="count">The count.</param>
private void RemoveFromModelState(int removeItemIndex, int count)
{
for (int i = removeItemIndex; i < count; i++)
{
ModelState["Properties[" + i + "].Key"] = ModelState["Properties[" + (i + 1) + "].Key"];
ModelState["Properties[" + i + "].Value"] = ModelState["Properties[" + (i + 1) + "].Value"];
}
ModelState.Remove("Properties[" + (count - 1) + "].Key");
ModelState.Remove("Properties[" + (count - 1) + "].Value");
}
/// <summary>
/// Gets the index of the remove item.
/// </summary>
/// <returns>Index of remove item or -1 if not found.</returns>
private int GetRemoveItemIndex()
{
foreach (var formKey in Request.Form.AllKeys)
{
if (formKey.StartsWith("RemoveProperty_"))
{
return int.Parse(formKey.Replace("RemoveProperty_", string.Empty));
}
}
return -1;
}
}
}
|
vlko/jobs
|
jobs.web/Controllers/ProjectController.cs
|
C#
|
mit
| 8,158
|
class DeviseCreateStudents < ActiveRecord::Migration
def change
create_table(:students) do |t|
## Database authenticatable
t.string :name, null: false
t.string :email, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.string :current_sign_in_ip
# t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model.
t.timestamps null: false
t.string :code, null: false, default: ""
end
add_index :students, :reset_password_token, unique: true
add_index :students, :code, unique: true
# add_index :students, :confirmation_token, unique: true
# add_index :students, :unlock_token, unique: true
end
end
|
10suns/forum
|
db/migrate/20160128064701_devise_create_students.rb
|
Ruby
|
mit
| 1,547
|
/* --------------------------------------------------------------------------
*
* File MainScene.h
* Description
* Ported By Young-Hwan Mun
* Created By giginet - 11/05/27
* Contact xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft.
* Copyright (c) 2011-2013 Kawaz. All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#ifndef __MainScene_h__
#define __MainScene_h__
class MainScene : public KWScene
{
public :
SCENE_FUNC ( MainScene );
public :
MainScene ( KDvoid );
virtual ~MainScene ( KDvoid );
protected :
virtual KDbool init ( KDvoid );
virtual KDbool ccTouchBegan ( CCTouch* pTouch, CCEvent* pEvent );
virtual KDvoid update ( KDfloat fDelta );
KDvoid playMusic ( KDvoid );
KDvoid startGame ( KDvoid );
KDvoid hurryUp ( KDvoid );
KDvoid endGame ( KDvoid );
KDvoid showResult ( KDvoid );
KDvoid popTarget ( KDvoid );
KDvoid shakeScreen ( KDvoid );
KDvoid getScore ( KDint nScore );
KDvoid pressRetryButton ( CCObject* pSender );
KDvoid pressReturnButton ( CCObject* pSender );
private :
KDvoid onGameOver ( KDvoid );
KDvoid onShowResult ( KDfloat fDelta );
private :
KDint m_nScore;
KDint m_nHighScore;
KDbool m_bActive;
KDbool m_bHurryUp;
CCArray* m_pTargets;
CCLabelTTF* m_pScoreLabel;
CCLabelTTF* m_pHighScoreLabel;
KWTimerLabel* m_pTimerLabel;
};
#endif // __MainScene_h__
|
mcodegeeks/OpenKODE-Framework
|
04_Sample/KawazBuster/Source/MainScene.h
|
C
|
mit
| 2,594
|
---
uid: SolidEdgePart.WeldmentModel.RollToFeature(System.Object,System.Boolean)
summary:
remarks:
syntax:
parameters:
- id: DisplayPart
description: Specifies whether or not the rolled-back model is to be redisplayed.
- id: Feature
description: Specifies the feature object to which the model is to be rolled back.
---
|
SolidEdgeCommunity/docs
|
docfx_project/apidoc/SolidEdgePart.WeldmentModel.RollToFeature.md
|
Markdown
|
mit
| 349
|
package soottocfg.ast.Absyn; // Java Package generated by the BNF Converter.
public class NamedTpl extends TupleEntry {
public final String ident_;
public final Type type_;
public NamedTpl(String p1, Type p2) { ident_ = p1; type_ = p2; }
public <R,A> R accept(soottocfg.ast.Absyn.TupleEntry.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof soottocfg.ast.Absyn.NamedTpl) {
soottocfg.ast.Absyn.NamedTpl x = (soottocfg.ast.Absyn.NamedTpl)o;
return this.ident_.equals(x.ident_) && this.type_.equals(x.type_);
}
return false;
}
public int hashCode() {
return 37*(this.ident_.hashCode())+this.type_.hashCode();
}
}
|
jayhorn/jayhorn
|
soottocfg/src/main/java/soottocfg/ast/Absyn/NamedTpl.java
|
Java
|
mit
| 747
|
/*
* Copyright (C) 2018-2020 Jakob Nixdorf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.shadowice.flocke.andotp.Activities;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.heinrichreimersoftware.materialintro.app.IntroActivity;
import com.heinrichreimersoftware.materialintro.app.SlideFragment;
import com.heinrichreimersoftware.materialintro.slide.FragmentSlide;
import com.heinrichreimersoftware.materialintro.slide.SimpleSlide;
import org.shadowice.flocke.andotp.R;
import org.shadowice.flocke.andotp.Tasks.FinishIntroTask;
import org.shadowice.flocke.andotp.Utilities.ConfirmedPasswordTransformationHelper;
import org.shadowice.flocke.andotp.Utilities.Constants;
import org.shadowice.flocke.andotp.Utilities.EditorActionHelper;
import org.shadowice.flocke.andotp.Utilities.UIHelper;
public class IntroScreenActivity extends IntroActivity {
private EncryptionFragment encryptionFragment;
private AuthenticationFragment authenticationFragment;
private AndroidSyncFragment androidSyncFragment;
private IntroFinishedFragment introFinishedFragment;
private boolean setupFinished = false;
private byte[] encryptionKey = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
encryptionFragment = new EncryptionFragment();
authenticationFragment = new AuthenticationFragment();
androidSyncFragment = new AndroidSyncFragment(encryptionFragment);
introFinishedFragment = new IntroFinishedFragment(this, (success, encryptionKey) -> {
this.setupFinished = success;
this.encryptionKey = encryptionKey;
});
encryptionFragment.setEncryptionChangedCallback(newEncryptionType -> authenticationFragment.updateEncryptionType(newEncryptionType));
setButtonBackFunction(BUTTON_BACK_FUNCTION_BACK);
addSlide(new SimpleSlide.Builder()
.title(R.string.intro_slide1_title)
.description(R.string.intro_slide1_desc)
.background(R.color.colorPrimary)
.backgroundDark(R.color.colorPrimaryDark)
.canGoBackward(false)
.scrollable(false)
.build()
);
addSlide(new FragmentSlide.Builder()
.background(R.color.colorPrimary)
.backgroundDark(R.color.colorPrimaryDark)
.fragment(encryptionFragment)
.build()
);
// Tell the fragment where it is located
authenticationFragment.setSlidePos(getSlides().size());
addSlide(new FragmentSlide.Builder()
.background(R.color.colorPrimary)
.backgroundDark(R.color.colorPrimaryDark)
.fragment(authenticationFragment)
.build()
);
addSlide(new FragmentSlide.Builder()
.background(R.color.colorPrimary)
.backgroundDark(R.color.colorPrimaryDark)
.fragment(androidSyncFragment)
.build()
);
addSlide(new FragmentSlide.Builder()
.background(R.color.colorPrimary)
.backgroundDark(R.color.colorPrimaryDark)
.fragment(introFinishedFragment)
.build()
);
addOnNavigationBlockedListener((position, direction) -> {
if (position == 2)
authenticationFragment.flashWarning();
});
addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// The second part is needed to prevent the function from being triggered a second
// time when clicking the finish button in the last slide
if (position == getCount() - 1 && getCurrentSlidePosition() < getCount())
introFinishedFragment.saveSettings(encryptionFragment.getEncryptionType(), authenticationFragment.getAuthMethod(), authenticationFragment.getPassword(), androidSyncFragment.getSyncEnabled());
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public Intent onSendActivityResult(int result) {
Intent data = new Intent();
data.putExtra(Constants.EXTRA_INTRO_FINISHED, setupFinished);
data.putExtra(Constants.EXTRA_INTRO_ENCRYPTION_KEY, encryptionKey);
return data;
}
@Override
public void onBackPressed() {
// We don't want users to quit the intro screen and end up in an uninitialized state
}
public static class EncryptionFragment extends SlideFragment {
private EncryptionChangedCallback encryptionChangedCallback = null;
private Spinner selection;
private TextView desc;
private SparseArray<Constants.EncryptionType> selectionMapping;
public EncryptionFragment() {
}
public void setEncryptionChangedCallback(EncryptionChangedCallback cb) {
encryptionChangedCallback = cb;
}
private void generateSelectionMapping() {
String[] encValues = getResources().getStringArray(R.array.settings_values_encryption);
selectionMapping = new SparseArray<>();
for (int i = 0; i < encValues.length; i++)
selectionMapping.put(i, Constants.EncryptionType.valueOf(encValues[i].toUpperCase()));
}
public Constants.EncryptionType getEncryptionType() {
return selectionMapping.get(selection.getSelectedItemPosition());
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.component_intro_encryption, container, false);
selection = root.findViewById(R.id.introEncryptionSelection);
desc = root.findViewById(R.id.introEncryptionDesc);
generateSelectionMapping();
selection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Constants.EncryptionType encryptionType = selectionMapping.get(i);
if (encryptionType == Constants.EncryptionType.PASSWORD)
desc.setText(R.string.intro_slide2_desc_password);
else if (encryptionType == Constants.EncryptionType.KEYSTORE)
desc.setText(R.string.intro_slide2_desc_keystore);
if (encryptionChangedCallback != null)
encryptionChangedCallback.onEncryptionChanged(encryptionType);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
selection.setSelection(selectionMapping.indexOfValue(Constants.EncryptionType.PASSWORD));
return root;
}
public interface EncryptionChangedCallback {
void onEncryptionChanged(Constants.EncryptionType newEncryptionType);
}
}
public static class IntroFinishedFragment extends SlideFragment {
private TextView title;
private TextView message;
private ProgressBar progress;
private final Context context;
private final SaveSettingsCallback callback;
private boolean canGoForward = false;
public IntroFinishedFragment(Context context, SaveSettingsCallback callback) {
this.context = context;
this.callback = callback;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.component_intro_finished, container, false);
title = root.findViewById(R.id.introFinishedTitle);
message = root.findViewById(R.id.introFinishedMessage);
progress = root.findViewById(R.id.introFinishedProgress);
return root;
}
private void saveSettings(Constants.EncryptionType encryptionType, Constants.AuthMethod authMethod, String password, boolean androidSyncEnabled) {
if ((authMethod == Constants.AuthMethod.PASSWORD || authMethod == Constants.AuthMethod.PIN) && (password == null || password.isEmpty())) {
title.setText(R.string.intro_slide4_title_failed);
message.setText(R.string.intro_slide4_desc_failed);
canGoForward = false;
if (callback != null)
callback.onAfterSaveSettings(false, null);
}
FinishIntroTask task = new FinishIntroTask(context, encryptionType, authMethod, password, androidSyncEnabled);
task.setCallback(this::handleTaskResult);
progress.setVisibility(View.VISIBLE);
task.execute();
}
private void handleTaskResult(FinishIntroTask.Result result) {
if (result.saveSuccessful) {
title.setText(R.string.intro_slide4_title);
message.setText(R.string.intro_slide4_desc);
canGoForward = true;
} else {
title.setText(R.string.intro_slide4_title_failed);
message.setText(R.string.intro_slide4_desc_failed);
canGoForward = false;
}
progress.setVisibility(View.INVISIBLE);
if (callback != null)
callback.onAfterSaveSettings(result.saveSuccessful, result.encryptionKey);
}
@Override
public boolean canGoForward() {
return canGoForward;
}
public interface SaveSettingsCallback {
void onAfterSaveSettings(boolean success, byte[] encryptionKey);
}
}
public static class AndroidSyncFragment extends SlideFragment {
private SwitchCompat introAndroidSync;
private final EncryptionFragment encryptionFragment;
public AndroidSyncFragment(EncryptionFragment encryptionFragment) {
this.encryptionFragment = encryptionFragment;
}
public boolean getSyncEnabled()
{
return introAndroidSync.isChecked();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.component_intro_android_sync, container, false);
introAndroidSync = root.findViewById(R.id.introAndroidSync);
introAndroidSync.setOnCheckedChangeListener((compoundButton, b) -> compoundButton.setText( b ?
R.string.settings_toast_android_sync_enabled :
R.string.settings_toast_android_sync_disabled
));
introAndroidSync.setChecked(encryptionFragment.getEncryptionType() != Constants.EncryptionType.KEYSTORE);
introAndroidSync.setEnabled(encryptionFragment.getEncryptionType() != Constants.EncryptionType.KEYSTORE);
return root;
}
}
public static class AuthenticationFragment extends SlideFragment implements TextView.OnEditorActionListener {
private Constants.EncryptionType encryptionType = Constants.EncryptionType.KEYSTORE;
private int slidePos = -1;
private int minLength = Constants.AUTH_MIN_PASSWORD_LENGTH;
private String lengthWarning = "";
private String noPasswordWarning = "";
private String confirmPasswordWarning = "";
private String passwordMismatchWarning = "";
private TextView desc = null;
private Spinner selection = null;
private TextView authWarnings = null;
private LinearLayout credentialsLayout = null;
private TextInputLayout passwordLayout = null;
private TextInputEditText passwordInput = null;
private EditText passwordConfirm = null;
private SparseArray<Constants.AuthMethod> selectionMapping;
public AuthenticationFragment() {
}
public void setSlidePos(int pos) {
slidePos = pos;
}
public void updateEncryptionType(Constants.EncryptionType encryptionType) {
this.encryptionType = encryptionType;
if (desc != null) {
if (encryptionType == Constants.EncryptionType.KEYSTORE) {
desc.setText(R.string.intro_slide3_desc_keystore);
selection.setSelection(selectionMapping.indexOfValue(Constants.AuthMethod.NONE));
} else if (encryptionType == Constants.EncryptionType.PASSWORD) {
desc.setText(R.string.intro_slide3_desc_password);
Constants.AuthMethod selectedMethod = selectionMapping.get(selection.getSelectedItemPosition());
if (selectedMethod != Constants.AuthMethod.PASSWORD && selectedMethod != Constants.AuthMethod.PIN )
selection.setSelection(selectionMapping.indexOfValue(Constants.AuthMethod.PASSWORD));
}
}
}
private void generateSelectionMapping() {
Constants.AuthMethod[] authValues = Constants.AuthMethod.values();
selectionMapping = new SparseArray<>();
for (int i = 0; i < authValues.length; i++)
selectionMapping.put(i, authValues[i]);
}
@SuppressWarnings("SameParameterValue")
private void updateWarning(int resId) {
updateWarning(getString(resId));
}
private void updateWarning(String warning) {
authWarnings.setText(warning);
}
private void hideWarning() {
authWarnings.setVisibility(View.GONE);
authWarnings.setText(null);
}
public void flashWarning() {
if (authWarnings.getText().toString().isEmpty()) {
authWarnings.setVisibility(View.GONE);
} else {
authWarnings.setVisibility(View.VISIBLE);
ObjectAnimator animator = ObjectAnimator.ofInt(authWarnings, "backgroundColor",
Color.TRANSPARENT, getResources().getColor(R.color.colorAccent), Color.TRANSPARENT);
animator.setDuration(500);
animator.setRepeatCount(0);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setEvaluator(new ArgbEvaluator());
animator.start();
}
}
public Constants.AuthMethod getAuthMethod() {
return selectionMapping.get(selection.getSelectedItemPosition());
}
public String getPassword() {
if (passwordInput.getText() != null)
return passwordInput.getText().toString();
else
return null;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.component_intro_authentication, container, false);
desc = root.findViewById(R.id.introAuthDesc);
selection = root.findViewById(R.id.introAuthSelection);
authWarnings = root.findViewById(R.id.introAuthWarnings);
credentialsLayout = root.findViewById(R.id.introCredentialsLayout);
passwordLayout = root.findViewById(R.id.introPasswordLayout);
passwordInput = root.findViewById(R.id.introPasswordEdit);
passwordConfirm = root.findViewById(R.id.introPasswordConfirm);
generateSelectionMapping();
final String[] authEntries = getResources().getStringArray(R.array.settings_entries_auth);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getIntroActivity(), android.R.layout.simple_spinner_item, authEntries) {
@Override
public boolean isEnabled(int position){
return encryptionType != Constants.EncryptionType.PASSWORD ||
position == selectionMapping.indexOfValue(Constants.AuthMethod.PASSWORD) ||
position == selectionMapping.indexOfValue(Constants.AuthMethod.PIN);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
tv.setEnabled(encryptionType != Constants.EncryptionType.PASSWORD ||
position == selectionMapping.indexOfValue(Constants.AuthMethod.PASSWORD) ||
position == selectionMapping.indexOfValue(Constants.AuthMethod.PIN));
return view;
}
};
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selection.setAdapter(spinnerArrayAdapter);
selection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Constants.AuthMethod authMethod = selectionMapping.get(i);
if (authMethod == Constants.AuthMethod.PASSWORD) {
setupForPasswordInput();
} else if (authMethod == Constants.AuthMethod.PIN) {
setupForPinInput();
} else {
credentialsLayout.setVisibility(View.INVISIBLE);
UIHelper.hideKeyboard(getIntroActivity(), root);
}
passwordInput.setText(null);
passwordConfirm.setText(null);
authWarnings.setVisibility(View.GONE);
updateNavigation();
}
private void setupForPasswordInput() {
credentialsLayout.setVisibility(View.VISIBLE);
passwordLayout.setHint(getString(R.string.settings_hint_password));
passwordConfirm.setHint(R.string.settings_hint_password_confirm);
passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
passwordConfirm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
ConfirmedPasswordTransformationHelper.setup(passwordLayout, passwordInput, passwordConfirm);
minLength = Constants.AUTH_MIN_PASSWORD_LENGTH;
lengthWarning = getString(R.string.settings_label_short_password, minLength);
noPasswordWarning = getString(R.string.intro_slide3_warn_no_password);
confirmPasswordWarning = getString(R.string.intro_slide3_warn_confirm_password);
passwordMismatchWarning = getString(R.string.intro_slide3_warn_password_mismatch);
focusOnPasswordInput();
}
private void focusOnPasswordInput() {
if (getIntroActivity().getCurrentSlidePosition() == slidePos) {
passwordInput.requestFocus();
UIHelper.showKeyboard(getContext(), passwordInput);
}
}
private void setupForPinInput() {
credentialsLayout.setVisibility(View.VISIBLE);
passwordLayout.setHint(getString(R.string.settings_hint_pin));
passwordConfirm.setHint(R.string.settings_hint_pin_confirm);
passwordInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
passwordConfirm.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
ConfirmedPasswordTransformationHelper.setup(passwordLayout, passwordInput, passwordConfirm);
minLength = Constants.AUTH_MIN_PIN_LENGTH;
lengthWarning = getString(R.string.settings_label_short_pin, minLength);
noPasswordWarning = getString(R.string.intro_slide3_warn_no_pin);
confirmPasswordWarning = getString(R.string.intro_slide3_warn_confirm_pin);
passwordMismatchWarning = getString(R.string.intro_slide3_warn_pin_mismatch);
focusOnPasswordInput();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
updateNavigation();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
};
passwordInput.addTextChangedListener(textWatcher);
passwordConfirm.addTextChangedListener(textWatcher);
passwordConfirm.setOnEditorActionListener(this);
selection.setSelection(selectionMapping.indexOfValue(Constants.AuthMethod.PASSWORD));
return root;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorActionHelper.isActionDoneOrKeyboardEnter(actionId, event)) {
nextSlide();
return true;
} else {
// Ignore action up after keyboard enter. Otherwise the go-back button would be selected
// after pressing enter with an invalid password.
return EditorActionHelper.isActionUpKeyboardEnter(event);
}
}
@Override
public boolean canGoForward() {
Constants.AuthMethod authMethod = selectionMapping.get(selection.getSelectedItemPosition());
if (authMethod == Constants.AuthMethod.PIN || authMethod == Constants.AuthMethod.PASSWORD) {
String password = null;
if (passwordInput.getText() != null)
password = passwordInput.getText().toString();
String confirm = passwordConfirm.getText().toString();
if (password != null && !password.isEmpty()) {
if (password.length() < minLength) {
updateWarning(lengthWarning);
return false;
} else {
if (!confirm.isEmpty()) {
if (confirm.equals(password)) {
hideWarning();
return true;
} else {
updateWarning(passwordMismatchWarning);
return false;
}
} else {
updateWarning(confirmPasswordWarning);
return false;
}
}
} else {
updateWarning(noPasswordWarning);
return false;
}
} else if (authMethod == Constants.AuthMethod.DEVICE) {
Context context = getContext();
if (context == null)
return false;
KeyguardManager km = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);
assert km != null; // The KEYGUARD_SERVICE should always be available
if (!km.isKeyguardSecure()) {
updateWarning(R.string.settings_toast_auth_device_not_secure);
return false;
}
hideWarning();
return true;
} else {
hideWarning();
return true;
}
}
}
}
|
flocke/andOTP
|
app/src/main/java/org/shadowice/flocke/andotp/Activities/IntroScreenActivity.java
|
Java
|
mit
| 26,912
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array(APPPATH.'third_party/caboose');
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array('parser', 'database', 'parsedown','session','caboose');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('formfields', 'url');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array('flags', 'groups', 'priorities', 'sizes', 'statuses', 'tasks');
|
Comp4711Lab5View/lab7
|
application/config/autoload.php
|
PHP
|
mit
| 4,400
|
Imports YamlDotNet.Serialization
Imports System.IO
Public Class YAMLskins
Inherits YAMLFilesBase
Public Const skinsFile As String = "skins.yaml"
Public Sub New(ByVal YAMLFileName As String, ByVal YAMLFilePath As String, ByRef DatabaseRef As Object, ByRef TranslationRef As YAMLTranslations)
MyBase.New(YAMLFileName, YAMLFilePath, DatabaseRef, TranslationRef)
End Sub
''' <summary>
''' Imports the yaml file into the database set in the constructor
''' </summary>
''' <param name="Params">What the row location is and whether to insert the data or not (for bulk import)</param>
Public Sub ImportFile(ByVal Params As ImportParameters)
Dim DSB = New DeserializerBuilder()
If Not TestForSDEChanges Then
DSB.IgnoreUnmatchedProperties()
End If
DSB = DSB.WithNamingConvention(New NamingConventions.NullNamingConvention)
Dim DS As New Deserializer
DS = DSB.Build
Dim YAMLRecords As New Dictionary(Of Long, skin)
Dim DataFields As List(Of DBField)
Dim IndexFields As List(Of String)
Dim SQL As String = ""
Dim Count As Long = 0
Dim TotalRecords As Long = 0
' Build table
Dim Table As New List(Of DBTableField)
Table.Add(New DBTableField("skinID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("skinDescription", FieldType.text_type, MaxFieldLen, True))
Table.Add(New DBTableField("internalName", FieldType.varchar_type, 100, True))
Table.Add(New DBTableField("skinMaterialID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("isStructureSkin", FieldType.int_type, 0, True))
Table.Add(New DBTableField("typeID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("allowCCPDevs", FieldType.bit_type, 0, True))
Table.Add(New DBTableField("visibleSerenity", FieldType.bit_type, 0, True))
Table.Add(New DBTableField("visibleTranquility", FieldType.bit_type, 0, True))
Call UpdateDB.CreateTable(TableName, Table)
' Create indexes
IndexFields = New List(Of String)
IndexFields.Add("skinID")
Call UpdateDB.CreateIndex(TableName, "IDX_" & TableName & "_SID", IndexFields)
' See if we only want to build the table and indexes
If Not Params.InsertRecords Then
Exit Sub
End If
' Start processing
Call InitGridRow(Params.RowLocation)
Try
' Parse the input text
YAMLRecords = DS.Deserialize(Of Dictionary(Of Long, skin))(New StringReader(File.ReadAllText(YAMLFile)))
Catch ex As Exception
Call ShowErrorMessage(ex)
End Try
TotalRecords = YAMLRecords.Count
' Process Data
For Each DataField In YAMLRecords
For Each DF In DataField.Value.types
DataFields = New List(Of DBField)
With DataField.Value
' Build the insert list
DataFields.Add(UpdateDB.BuildDatabaseField("skinID", .skinID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("skinDescription", .skinDescription, FieldType.text_type))
DataFields.Add(UpdateDB.BuildDatabaseField("internalName", .internalName, FieldType.varchar_type))
DataFields.Add(UpdateDB.BuildDatabaseField("skinMaterialID", .skinMaterialID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("isStructureSkin", .isStructureSkin, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("typeID", DF, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("allowCCPDevs", .allowCCPDevs, FieldType.bit_type))
DataFields.Add(UpdateDB.BuildDatabaseField("visibleSerenity", .visibleSerenity, FieldType.bit_type))
DataFields.Add(UpdateDB.BuildDatabaseField("visibleTranquility", .visibleTranquility, FieldType.bit_type))
End With
Call UpdateDB.InsertRecord(TableName, DataFields)
Next
' Update grid progress
Call UpdateGridRowProgress(Params.RowLocation, Count, TotalRecords)
Count += 1
Next
Call FinalizeGridRow(Params.RowLocation)
End Sub
End Class
Public Class skin
Public Property skinID As Object
Public Property skinDescription As Object
Public Property allowCCPDevs As Object
Public Property internalName As Object
Public Property skinMaterialID As Object
Public Property isStructureSkin As Object
Public Property types As List(Of Object)
Public Property visibleSerenity As Object
Public Property visibleTranquility As Object
End Class
|
EVEIPH/EVE-SDE-Database-Builder
|
EVE SDE Database Builder/SDE YAML Classses/YAMLskins.vb
|
Visual Basic
|
mit
| 4,831
|
<div>
<h4>{{vm.title}} <span class="small">自定义模版</span></h4>
<div>
<p>{{vm.content}}</p>
</div>
<p ng-if="vm.closing"> <strong class="text-danger">{{ vm.time }}</strong>秒后关闭</p>
<button class='jm-btn jm-btn-danger' ng-click='vm.ok($event)'>删除?</button>
</div>
|
jm-team/ng-seed
|
src/page/components/tooltip/tooltip.tpl.html
|
HTML
|
mit
| 298
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.