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
|
|---|---|---|---|---|---|
<?php
$conn = mysqli_connect("localhost", "root", "root", "linkify");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
|
vicols92/linkify
|
resources/includes/dbh.php
|
PHP
|
mit
| 141
|
#
#
#March 2014
#Adam Breznicky - TxDOT TPP - Mapping Group
#
#This is an independent script which requires a single parameter designating a directory.
#The script will walk through each subfolder and file within the designated directory, identifying the MXD files
#and re-sourcing the Comanche database connections to utilize the new 'Admin' prefix
#
#
#
#
#import modules
import arcpy, os
#variables
directory = ""
def re_source_admin():
#issue list
issues = []
#walk through each directory
for root, dirs, files in os.walk(directory):
#ignore file and personal geodatabases
specDir = root.split("\\")[-1]
dbsuffix = specDir.split(".")[-1]
if dbsuffix == "gdb" or dbsuffix == "mdb" or dbsuffix == "tbx":
pass
else:
for n in files:
#identify the mxds
if str(n).split(".")[-1] == "mxd":
print "working on: " + str(os.path.join(root, n))
map = arcpy.mapping.MapDocument(os.path.join(root, n))
dataframes = arcpy.mapping.ListDataFrames(map)
for df in dataframes:
layers = arcpy.mapping.ListLayers(map, "", df)
for lyr in layers:
try:
if "TPP_GIS.MCHAMB1." in lyr.dataSource:
print "lyr source: " + lyr.dataSource
newsource = lyr.dataSource.replace("TPP_GIS.MCHAMB1.", "TPP_GIS.APP_TPP_GIS_ADMIN.")
location = newsource.split("\\")[:-2]
locationFixed = "\\".join(location)
print locationFixed
newname = newsource.split("\\")[-1]
print newname
lyr.replaceDataSource(locationFixed, "SDE_WORKSPACE", newname)
print "lyr replaced: " + newsource
except:
if os.path.join(root, n) not in issues:
issues.append(os.path.join(root, n))
print lyr.name + " is not a feature layer"
tables = arcpy.mapping.ListTableViews(map, "", df)
for tbl in tables:
try:
if "TPP_GIS.MCHAMB1." in tbl.dataSource:
print "tbl source: " + tbl.dataSource
newsource = tbl.dataSource.replace("TPP_GIS.MCHAMB1.", "TPP_GIS.APP_TPP_GIS_ADMIN.")
location = newsource.split("\\")[:-2]
locationFixed = "\\".join(location)
print locationFixed
newname = newsource.split("\\")[-1]
print newname
tbl.replaceDataSource(locationFixed, "SDE_WORKSPACE", newname)
print "tbl replaced: " + newsource
except:
if os.path.join(root, n) not in issues:
issues.append(os.path.join(root, n))
print tbl.name + " is not a feature layer"
map.save()
re_source_admin()
print "success!"
print "the following MXDs contained issues with a layer having not a dataSource (e.g. a non-feature layer):"
for i in issues:
print str(i)
|
TxDOT/python
|
standalone/AdminPrefix_Resourcer_v1.py
|
Python
|
mit
| 3,702
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Bit.CSharpClientSample.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bit.CSharpClientSample.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
|
bit-foundation/bit-framework
|
src/Client/Xamarin/Sample/Bit.CSharpClientSample.UWP/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,033
|
var db = require('../models');
function index(req, res) {
db.User.find({}, function(err, allUsers) {
//TODO: handle the errors.
// TODO: Send this array as a json object
res.json(allUsers);
});
}
function create(req, res) {
// TODO: Consider creating an obect literal then passing in that object rather than just the req.body
db.User.create(req.body, function(err, user) {
if (err) {
console.log('error', err);
}
// remove console logs from production
console.log(user);
res.json(user);
});
}
function destroy(req, res) {
db.User.findOneAndRemove({
_id: req.params.userId
}, function(err, foundUser) {
//TODO: Handle ERR
res.json(foundUser);
});
}
function update(req, res) {
// remove console logs from production
console.log('Updating user', req.body);
var updateUser = {
userName: req.body.userName,
email: req.body.email,
passwordDigest: req.body.passwordDigest,
}
db.User.findOneAndUpdate({_id: req.params.userId}, updateUser, function(err, foundUser) {
if (err) {console.log('usersController.update.error', err);}
res.json(foundUser);
});
}
module.exports = {
index: index,
create: create,
destroy: destroy,
update: update
};
|
namelessprofit/project-1
|
controllers/userController.js
|
JavaScript
|
mit
| 1,342
|
using System;
using System.Net;
namespace Manatee.Trello.Rest
{
/// <summary>
/// Defines properties required for objects returned by RESTful calls.
/// </summary>
public interface IRestResponse
{
/// <summary>
/// The JSON content returned by the call.
/// </summary>
string Content { get; }
/// <summary>
/// Gets any exception that was thrown during the call.
/// </summary>
Exception Exception { get; set; }
/// <summary>
/// Gets the status code.
/// </summary>
HttpStatusCode StatusCode { get; }
}
/// <summary>
/// Defines required properties returned by RESTful calls.
/// </summary>
/// <typeparam name="T">The type expected to be returned by the call.</typeparam>
public interface IRestResponse<out T> : IRestResponse
{
/// <summary>
/// The deserialized data.
/// </summary>
T Data { get; }
}
}
|
gregsdennis/Manatee.Trello
|
Manatee.Trello/Rest/IRestResponse.cs
|
C#
|
mit
| 888
|
---
layout: post
title: "ES6 Promise API, Promise Pattern, Asynchronous Codes"
date: 2015-12-17 15:59:00 +08:00
categories: Web IT
tags: JavaScript ES6 AJAX
---
* content
{:toc}
### Notes about ES6 Promise API
* JavaScript execution model
- single thread, each website
- main thread maintains a queue, which has asynchronous tasks
- HTML5 introduced web workers, which are the actual threads
* Asynchronous code
- Event pattern. e.g. AJAX codes using ECMA script
- Callback pattern. e.g. jQuery AJAX
- Promise pattern - new in ES6
* Promise pattern pattern removes the common code issues that the event and callback pattern had below.
- It is difficult to catch the exceptions, as we have to use multiple try and catch statements.
- The code is harder to read, as it's difficult to follow the code flow due to the nested function calls.
- It's difficult to maintain the state of the asynchronous operation.
### Examples
* [Promise API, resolve(), then()](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_resolve_then.html)
* [Combine one or more promises into new promises, Promise.all()](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_all.html)
* [Promise.race() - race between Promises and see which one finishes first](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_race.html)
* Project sample, using Promise API to wrap an AJAX REST request.
```javascript
/**
* wrapper function for AJAX REST request.
* @param params - The parameter object contains REST request parameters.
* Including: type (method), url, contentType, accept, data.
* @returns {Promise} - The promise object produced by an AJAX call.
*/
function ajaxRestReq(params) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status == 200) {
resolve(xhr.responseText);
} else {
reject("Server Error: " + xhr.status);
}
}
xhr.onerror = () => {
reject("XMLHttpRequest Error:" + xhr.status);
}
xhr.open(params.type, params.url, true);
xhr.setRequestHeader("Content-type", params.contentType);
xhr.setRequestHeader("Accept", params.accept);
xhr.send(params.data);
});
}
/**
* Add a comment and store the data to the REST service.
*/
function addDelightalkComment() {
let user = document.querySelector("#delightalkUserName").value;
let userName = (user == "") ? "Anonymous" : user;
let commentContent = document.querySelector("#delightalkCommentInput").value;
if (commentContent == "") {
document.querySelector("#delightalkCommentInput").focus();
return;
}
let btnAddComment = document.querySelector("#addDelightalkCommentBtn")
btnAddComment.innerText = "Publishing";
btnAddComment.disabled = true;
let commentItem = {
pageURL: delightParams.pageUrlId,
user: userName,
comment: commentContent
};
ajaxRestReq({
url: delightParams.restServiceUrl + delightParams.siteName + '/addComment/', //remote server test
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(commentItem),
accept: 'application/json',
}).then(doneAddDelightalkComment, logErr);
}
/**
* Get recent comments from REST service
*/
function getDelightalkRecentComments() {
let requestData = {
pageURL: delightParams.pageUrlId,
lastN: delightParams.previousComments
};
ajaxRestReq({
url: delightParams.restServiceUrl + delightParams.siteName + '/getRecentComments', //remote server test
type: 'PUT',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(requestData),
accept: 'application/json',
}).then(renderRecentComments, logErr);
}
/**
* Callback function after a new comment is added successfully.
*/
function doneAddDelightalkComment() {
let btnAddComment = document.querySelector("#addDelightalkCommentBtn")
btnAddComment.innerText = "Published";
document.querySelector("#delightalkCommentInput").value = "";
setTimeout(function () {
btnAddComment.innerText = " Publish ";
btnAddComment.disabled = false;
}, 1500);
getDelightalkRecentComments();
}
/**
* Render the REST returned json string into the recent comment section of the page.
* @param jsonString the json format string contains the recent comment data.
*/
function renderRecentComments(jsonString) {
let data = JSON.parse(jsonString);
let htmlTxt = '';
for (i = data.recentComments.length - 1; i >= 0; i--) {
htmlTxt += '<div class="a-delightalk-comment">'
+ '<header id="recentCmtHeader">'
+ '<span id="delightalkCommentUser">'
+ '<i class="fa fa-user comment-icon" aria-hidden="true"></i>'
+ escapeHtml(data.recentComments[i].user + ' ')
+ '</span>'
+ '<span id="delightalkCommentDate">'
+ '<i class="fa fa-clock-o comment-icon" aria-hidden="true"></i>'
+ (new Date(data.recentComments[i].timestamp)).Format("yyyy-MM-dd hh:mm:ss")
+ '</span>'
+ '</header>'
+ '<article id="delightalkCommentContent">'
+ escapeHtml(data.recentComments[i].comment)
+ '</article>'
+ '</div>';
}
document.querySelector("#recentDelightalkComments").innerHTML = htmlTxt;
}
/**
* Callback function in case ajax request error.
* @param reason - the error reason
*/
function logErr(reason) {
console.log(reason);
}
```
|
EastmanJian/blog
|
_posts/2015-12-17-es6-promise-api.markdown
|
Markdown
|
mit
| 5,840
|
**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)*
- [Techland C++ Build Profiler](#top)
- [Getting started](#gettingstarted)
- [Metrics](#metrics)
- [root metrics](#root)
- [top-level metrics](#toplevel)
- [dependency metrics](#dependency)
- [The cppbuildprofiler script](#script)
- [Command-line tool](#cli)
- [Third-party dependencies](#thirdparty)
<a name="top"></a>Techland C++ Build Profiler
=============================================
A tool that attempts to facilitate profiling C++ builds.
For the moment it only supports Visual C++ builds, but other platforms could be easily added.
<a name="gettingstarted"></a>Getting started
--------------------------------------------
A typical workflow in a Visual Studio project could look like this.
0. Install cpp-build-profiler using PIP `pip install cppbuildprofiler`
0. Add `/Bt+ /showIncludes /nologo- /FC` to your compiler options in `C/C++ -> Command Line ->
Additional Options`
0. Rebuild the project, copy the build output to a file, put that file in a directory, say `profile/log.txt`.
0. Open up the command prompt and run
`cppbuildprofiler PROFILE_DIR --log-file LOG_FILE_NAME --codebase-dir ABSOLUTE/PATH/TO/SOURCE/DIR`.
You can add the `--column-separator` option, depending on the spreadsheet tool you use. For Google Spreadsheet
use `--column-separator '\t'`. `--codebase-dir` is important to identify third-party dependencies. See
[remove_thirdparty_dependencies](#thirdparty) for more information.
0. Your profile directory will now (hopefully) contain a number of files (for an explanation of metrics see
the "[Metrics](#metrics)" section):
* *root.csv* - summary of the whole build
* *top_level.csv* - information of build times of specific c++ files
* *dependency.csv* - information about `#include`d files
* *graph.gml* - the project's dependency graph
0. You can now copy the *.csv* file contents into a spreadsheet programme and try to identify the heavy-hitters
in your build. I personally found that the most useful metrics to start with are *aggregated build time deviation
from avg* and *total build time of dependants* in the *dependency* file.
0. After identifying dependencies that have the biggest impact on build times it can be useful to take a look
at the dependency graph using a tool such as [Cytoscape](http://www.cytoscape.org/download.php). If your build
contains a lot of files you can generate a subgraph to see only files related to the inspected file. This can be
done using the `cppbuildprofiler-cli` command-line tool. See the "[Command-line tool](#cli)" section for instructions.
0. Improve and repeat!
<a name="metrics"></a>Metrics
-----------------------------
### <a name="root"></a>*root* metrics
The root node is connected to all top-level nodes and aggregates the information there to provide a summary of
the whole build.
* *total build time [s]* - sum of build times of all top-level files. In parallell builds this value will therefore
be much larger than the actual project building time.
* *total translation units* - speaks for itself
* *total size [B]* - sum of *total size [B]* values of top-level files. This is the total number of bytes of code
compiled.
### <a name="toplevel"></a>*top-level* metrics
* *label* - useful when working with the dependency graph. Use this name to identify nodes. This is normally the
filename, but duplicated files are suffixed with *_NUMBER*
* *project* - name of the project containing the *.cpp* file.
* *absolute path* - make a guess!
* *build time [s]* - total time it took to compile this file
* *file size [B]* - size of the *.cpp* file (without dependencies)
* *total size [B]* - total size of the translation unit. This is the aggregated size of all files in this file's
subtree. Files included through precompiled-headers are excluded from this metric, so this is the actual size
of the compiled code. Headers are assumed to be included only once, so if for some reason you have a file
without an include guard and it should be included twice in the subtree, it will be counted only once.
### <a name="dependency"></a>*dependency* metrics
* *label* - useful when working with the dependency graph. Use this name to identify nodes. This is normally the
filename, but duplicated files are suffixed with *_NUMBER*
* *project* - name of the project containing the dependency file. This is guessed based on the file's location.
The closest parent directory containing a *.cpp* file is found and this file's project name is assumed to be the
dependency project.
* *absolute path* - well...
* *number of dependent translation units* - number of top-level files including this dependency. Inclusions through
precompiled-headers are not counted.
* *file size [B]* - size of the *.cpp* file (without dependencies)
* *aggregated total size [B]* - the aggregated size of the dependency's subtree, calculated independently for each
translation unit. Files included through precompiled-headers are not counted. For example let's consider the following
structure (indentation means inclusion).
* *a.cpp*
* *a.hpp* (10 Bytes)
* *aa.hpp* (15 Bytes)
* *b.hpp* (2 Bytes)
* *bb.hpp* (2 Bytes)
* *c.hpp*
* *b.hpp* (2 Bytes)
* *bb.hpp* (2 Bytes)
* *b.cpp*
* *b.hpp* (2 Bytes)
* *bb.hpp* (2 Bytes)
*b.hpp* will have an aggregated total size of 6 Bytes - once counted through *a.cpp*, once through *b.cpp*, both times
counted with *bb.hpp*. *a.hpp* may report to have an aggregated total size of either 29 Bytes or 25 Bytes. This depends
on the order of graph traversal - either *b.hpp* will be considered as included through *a.hpp* or through *c.hpp*.
* *total build time of dependants [s]* - total time spent on compiling files including this dependency
* *aggregated build time deviation from avg [s]* - this is the sum of signed difference of dependant translation unit's
build time from the average build time. If for example the average build time of a translation unit is 1 second and a
dependency is included in 3 files building 2s, 3s and 0.5s, the value of this metric will be 2.5s. This metric should
essentially tell you the impact a file has on the total build time. A possible way to identify actual culprits of long
build times is to order a spreadsheet by the *aggregated build time deviation from avg* column and look at files with
large *aggregated total size*. Removing dependencies from such files often gives good results.
<a name="script"></a>The cppbuildprofiler script
------------------------------------------------
The `cppbuildprofiler` script loads a compilation log, builds a dependency graph, analyses it and outputs a number of files:
* *root.csv* - summary of the whole build
* *top_level.csv* - information of build times of specific c++ files
* *dependency.csv* - information about `#include`d files
* *graph.gml* - the project's dependency graph
The switches available may be printed out by running `cppbuildprofiler --help`. For information on the meaning of the
CODEBASE-DIR in `--codebase-dir` see the [thirdparty dependencies](#thirdparty) section.
<a name="cli"></a>Command-line tool
-----------------------------------
The command-line tool, executed by running `cppbuildprofiler-cli` may be used to perform more tailor-made analyses than
these done by default using `cppbuildprofiler`. Bear in mind that when working with the tool all commands apply changes
to the current dependency graph in memory. If you generate a subgraph containing only the dependencies of some file, all
its predecessors will be removed and to access them again you'll have to re-load the graph.
Available commands are:
* `help` - displays a list of available commands.
* `help COMMAND` or `COMMAND -h` - displays help on the usage of COMMAND.
* `parse_vs_log LOG_FILE` - parses a VisualC++ build log and creates a bare dependency graph.
* `analyse` - runs a full analysis of the dependency graph (calculates all the metrics).
* `remove_thirdparty_dependencies CODEBASE_ROOT` - removes [thirdparty dependencies](#thirdparty) from the graph. Note that this won't update the metrics.
* `store GML_FILE` - stores the current dependency graph to a .gml file.
* `load GML_FILE` - replaces the dependency graph in memory with the one loaded from the .gml file.
* `get_project_dependency_graph FILE` - creates a dependency graph of projects and stores it in the .gml file specified. Note that this will not modify the dependency graph in any way.
* `subgraph -o LABEL [--dependants] [--dependencies]` - the dependency graph in memory is replaced by its subgraph. The subgraph contains the node denoted by LABEL and
* if `--dependants` is specified: all the nodes that depend on that node
* if `--dependencies` is specified: all the nodes that the node depends on
* `print` - prints the dependency graph nodes in csv format. Run with `-h` to see the available options.
* `set_verbosity DEBUG|INFO` - changes the amount of logs the programme prints.
* `shell COMMAND` - will execute COMMAND in the underlying shell.
<a name="thirdparty"></a>Third-party dependencies
-------------------------------------------------
Usually, we are not interested in dependencies introduced by headers included from third-party code.
E.g. if we `#include <vector>` this dependency suffices in the graph, we don't need to see that it also includes
`xmemory`, `yvals.h` and whatnot. `cppbuildprofiler` removes these automatically if provided with the `--codebase-dir`
switch and `cppbuildprofiler-cli` removes them with the `remove_thirdparty_dependencies` command. Removing third-party
dependencies should be done *after* running `analyse` as otherwise the *total size* and *aggregated total size* metrics
will be incorrect.
A dependency is considered to be third-party if it lays outside the provided *CODEBASE-DIR*. Let's consider the following
scenario:
0. our code lays in 'd:/code/profiled-project',
0. it includes 'utility-lib.h' from 'd:/code/utility-lib',
0. 'utility-lib.h' includes 'detail.h' from the same directory. This file is *NOT* `#include`d by any of our source files,
0. 'utility-lib.h' also includes 'utility-lib-fwd.h' which *IS* `#include`d by our source files,
0. we run `cppbuildprofiler ... --codebase-dir d:/code/profiled-project`.
The resulting analysis will contain information about *utility-lib.h* and *utility-lib-fwd.h* as they are both immediate
dependencies of our code, but it won't contain *detail.h* as it is a purely third-party dependency.
|
techland-games/cpp-build-profiler
|
README.md
|
Markdown
|
mit
| 10,508
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace WebApplication3
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//
}
}
}
|
ratestHub/PostPublishTestRepo
|
WebApplication3/WebApplication3/Global.asax.cs
|
C#
|
mit
| 591
|
using Moq;
using Ocelot.Infrastructure;
using Ocelot.Logging;
using Ocelot.Provider.Kubernetes;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Shouldly;
using System;
using System.Collections.Generic;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class PollingKubeServiceDiscoveryProviderTests
{
private readonly int _delay;
private PollKube _provider;
private readonly List<Service> _services;
private readonly Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IOcelotLogger> _logger;
private readonly Mock<IServiceDiscoveryProvider> _kubeServiceDiscoveryProvider;
private List<Service> _result;
public PollingKubeServiceDiscoveryProviderTests()
{
_services = new List<Service>();
_delay = 1;
_factory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_factory.Setup(x => x.CreateLogger<PollKube>()).Returns(_logger.Object);
_kubeServiceDiscoveryProvider = new Mock<IServiceDiscoveryProvider>();
}
[Fact]
public void should_return_service_from_kube()
{
var service = new Service("", new ServiceHostAndPort("", 0), "", "", new List<string>());
this.Given(x => GivenKubeReturns(service))
.When(x => WhenIGetTheServices(1))
.Then(x => ThenTheCountIs(1))
.BDDfy();
}
private void GivenKubeReturns(Service service)
{
_services.Add(service);
_kubeServiceDiscoveryProvider.Setup(x => x.Get()).ReturnsAsync(_services);
}
private void ThenTheCountIs(int count)
{
_result.Count.ShouldBe(count);
}
private void WhenIGetTheServices(int expected)
{
_provider = new PollKube(_delay, _factory.Object, _kubeServiceDiscoveryProvider.Object);
var result = Wait.WaitFor(3000).Until(() =>
{
try
{
_result = _provider.Get().GetAwaiter().GetResult();
if (_result.Count == expected)
{
return true;
}
return false;
}
catch (Exception)
{
return false;
}
});
result.ShouldBeTrue();
}
}
}
|
geffzhang/Ocelot
|
test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs
|
C#
|
mit
| 2,542
|
// WebHelp 5.10.001
var garrSortChar=new Array();
var gaFtsStop=new Array();
var gaFtsStem=new Array();
var gbWhLang=false;
garrSortChar[0] = 0;
garrSortChar[1] = 1;
garrSortChar[2] = 2;
garrSortChar[3] = 3;
garrSortChar[4] = 4;
garrSortChar[5] = 5;
garrSortChar[6] = 6;
garrSortChar[7] = 7;
garrSortChar[8] = 8;
garrSortChar[9] = 40;
garrSortChar[10] = 41;
garrSortChar[11] = 42;
garrSortChar[12] = 43;
garrSortChar[13] = 44;
garrSortChar[14] = 9;
garrSortChar[15] = 10;
garrSortChar[16] = 11;
garrSortChar[17] = 12;
garrSortChar[18] = 13;
garrSortChar[19] = 14;
garrSortChar[20] = 15;
garrSortChar[21] = 16;
garrSortChar[22] = 17;
garrSortChar[23] = 18;
garrSortChar[24] = 19;
garrSortChar[25] = 20;
garrSortChar[26] = 21;
garrSortChar[27] = 22;
garrSortChar[28] = 23;
garrSortChar[29] = 24;
garrSortChar[30] = 25;
garrSortChar[31] = 26;
garrSortChar[32] = 38;
garrSortChar[33] = 45;
garrSortChar[34] = 46;
garrSortChar[35] = 47;
garrSortChar[36] = 48;
garrSortChar[37] = 49;
garrSortChar[38] = 50;
garrSortChar[39] = 33;
garrSortChar[40] = 51;
garrSortChar[41] = 52;
garrSortChar[42] = 53;
garrSortChar[43] = 88;
garrSortChar[44] = 54;
garrSortChar[45] = 34;
garrSortChar[46] = 55;
garrSortChar[47] = 56;
garrSortChar[48] = 115;
garrSortChar[49] = 119;
garrSortChar[50] = 121;
garrSortChar[51] = 123;
garrSortChar[52] = 125;
garrSortChar[53] = 126;
garrSortChar[54] = 127;
garrSortChar[55] = 128;
garrSortChar[56] = 129;
garrSortChar[57] = 130;
garrSortChar[58] = 57;
garrSortChar[59] = 58;
garrSortChar[60] = 89;
garrSortChar[61] = 90;
garrSortChar[62] = 91;
garrSortChar[63] = 59;
garrSortChar[64] = 60;
garrSortChar[65] = 131;
garrSortChar[66] = 148;
garrSortChar[67] = 150;
garrSortChar[68] = 154;
garrSortChar[69] = 158;
garrSortChar[70] = 168;
garrSortChar[71] = 171;
garrSortChar[72] = 173;
garrSortChar[73] = 175;
garrSortChar[74] = 185;
garrSortChar[75] = 187;
garrSortChar[76] = 189;
garrSortChar[77] = 191;
garrSortChar[78] = 193;
garrSortChar[79] = 197;
garrSortChar[80] = 214;
garrSortChar[81] = 216;
garrSortChar[82] = 218;
garrSortChar[83] = 220;
garrSortChar[84] = 225;
garrSortChar[85] = 230;
garrSortChar[86] = 240;
garrSortChar[87] = 242;
garrSortChar[88] = 244;
garrSortChar[89] = 246;
garrSortChar[90] = 252;
garrSortChar[91] = 61;
garrSortChar[92] = 62;
garrSortChar[93] = 63;
garrSortChar[94] = 64;
garrSortChar[95] = 66;
garrSortChar[96] = 67;
garrSortChar[97] = 131;
garrSortChar[98] = 148;
garrSortChar[99] = 150;
garrSortChar[100] = 154;
garrSortChar[101] = 158;
garrSortChar[102] = 168;
garrSortChar[103] = 171;
garrSortChar[104] = 173;
garrSortChar[105] = 175;
garrSortChar[106] = 185;
garrSortChar[107] = 187;
garrSortChar[108] = 189;
garrSortChar[109] = 191;
garrSortChar[110] = 193;
garrSortChar[111] = 197;
garrSortChar[112] = 214;
garrSortChar[113] = 216;
garrSortChar[114] = 218;
garrSortChar[115] = 220;
garrSortChar[116] = 225;
garrSortChar[117] = 230;
garrSortChar[118] = 240;
garrSortChar[119] = 242;
garrSortChar[120] = 244;
garrSortChar[121] = 246;
garrSortChar[122] = 252;
garrSortChar[123] = 68;
garrSortChar[124] = 69;
garrSortChar[125] = 70;
garrSortChar[126] = 71;
garrSortChar[127] = 27;
garrSortChar[128] = 114;
garrSortChar[129] = 28;
garrSortChar[130] = 82;
garrSortChar[131] = 170;
garrSortChar[132] = 85;
garrSortChar[133] = 112;
garrSortChar[134] = 109;
garrSortChar[135] = 110;
garrSortChar[136] = 65;
garrSortChar[137] = 113;
garrSortChar[138] = 223;
garrSortChar[139] = 86;
garrSortChar[140] = 213;
garrSortChar[141] = 29;
garrSortChar[142] = 255;
garrSortChar[143] = 30;
garrSortChar[144] = 31;
garrSortChar[145] = 80;
garrSortChar[146] = 81;
garrSortChar[147] = 83;
garrSortChar[148] = 84;
garrSortChar[149] = 111;
garrSortChar[150] = 36;
garrSortChar[151] = 37;
garrSortChar[152] = 79;
garrSortChar[153] = 229;
garrSortChar[154] = 222;
garrSortChar[155] = 87;
garrSortChar[156] = 212;
garrSortChar[157] = 32;
garrSortChar[158] = 254;
garrSortChar[159] = 251;
garrSortChar[160] = 39;
garrSortChar[161] = 72;
garrSortChar[162] = 97;
garrSortChar[163] = 98;
garrSortChar[164] = 99;
garrSortChar[165] = 100;
garrSortChar[166] = 73;
garrSortChar[167] = 101;
garrSortChar[168] = 74;
garrSortChar[169] = 102;
garrSortChar[170] = 133;
garrSortChar[171] = 93;
garrSortChar[172] = 103;
garrSortChar[173] = 35;
garrSortChar[174] = 104;
garrSortChar[175] = 75;
garrSortChar[176] = 105;
garrSortChar[177] = 92;
garrSortChar[178] = 122;
garrSortChar[179] = 124;
garrSortChar[180] = 76;
garrSortChar[181] = 106;
garrSortChar[182] = 107;
garrSortChar[183] = 108;
garrSortChar[184] = 77;
garrSortChar[185] = 120;
garrSortChar[186] = 199;
garrSortChar[187] = 94;
garrSortChar[188] = 116;
garrSortChar[189] = 117;
garrSortChar[190] = 118;
garrSortChar[191] = 78;
garrSortChar[192] = 131;
garrSortChar[193] = 131;
garrSortChar[194] = 131;
garrSortChar[195] = 131;
garrSortChar[196] = 131;
garrSortChar[197] = 131;
garrSortChar[198] = 131;
garrSortChar[199] = 150;
garrSortChar[200] = 158;
garrSortChar[201] = 158;
garrSortChar[202] = 158;
garrSortChar[203] = 158;
garrSortChar[204] = 175;
garrSortChar[205] = 175;
garrSortChar[206] = 175;
garrSortChar[207] = 175;
garrSortChar[208] = 154;
garrSortChar[209] = 193;
garrSortChar[210] = 197;
garrSortChar[211] = 197;
garrSortChar[212] = 197;
garrSortChar[213] = 197;
garrSortChar[214] = 197;
garrSortChar[215] = 95;
garrSortChar[216] = 197;
garrSortChar[217] = 230;
garrSortChar[218] = 230;
garrSortChar[219] = 230;
garrSortChar[220] = 230;
garrSortChar[221] = 246;
garrSortChar[222] = 227;
garrSortChar[223] = 224;
garrSortChar[224] = 131;
garrSortChar[225] = 131;
garrSortChar[226] = 131;
garrSortChar[227] = 131;
garrSortChar[228] = 131;
garrSortChar[229] = 131;
garrSortChar[230] = 131;
garrSortChar[231] = 150;
garrSortChar[232] = 158;
garrSortChar[233] = 158;
garrSortChar[234] = 158;
garrSortChar[235] = 158;
garrSortChar[236] = 175;
garrSortChar[237] = 175;
garrSortChar[238] = 175;
garrSortChar[239] = 175;
garrSortChar[240] = 154;
garrSortChar[241] = 193;
garrSortChar[242] = 197;
garrSortChar[243] = 197;
garrSortChar[244] = 197;
garrSortChar[245] = 197;
garrSortChar[246] = 197;
garrSortChar[247] = 96;
garrSortChar[248] = 197;
garrSortChar[249] = 230;
garrSortChar[250] = 230;
garrSortChar[251] = 230;
garrSortChar[252] = 230;
garrSortChar[253] = 246;
garrSortChar[254] = 227;
garrSortChar[255] = 250;
gaFtsStop[0] = "a";
gaFtsStop[1] = "about";
gaFtsStop[2] = "after";
gaFtsStop[3] = "against";
gaFtsStop[4] = "all";
gaFtsStop[5] = "also";
gaFtsStop[6] = "among";
gaFtsStop[7] = "an";
gaFtsStop[8] = "and";
gaFtsStop[9] = "are";
gaFtsStop[10] = "as";
gaFtsStop[11] = "at";
gaFtsStop[12] = "be";
gaFtsStop[13] = "became";
gaFtsStop[14] = "because";
gaFtsStop[15] = "been";
gaFtsStop[16] = "between";
gaFtsStop[17] = "but";
gaFtsStop[18] = "by";
gaFtsStop[19] = "can";
gaFtsStop[20] = "come";
gaFtsStop[21] = "do";
gaFtsStop[22] = "during";
gaFtsStop[23] = "each";
gaFtsStop[24] = "early";
gaFtsStop[25] = "for";
gaFtsStop[26] = "form";
gaFtsStop[27] = "found";
gaFtsStop[28] = "from";
gaFtsStop[29] = "had";
gaFtsStop[30] = "has";
gaFtsStop[31] = "have";
gaFtsStop[32] = "he";
gaFtsStop[33] = "her";
gaFtsStop[34] = "his";
gaFtsStop[35] = "however";
gaFtsStop[36] = "in";
gaFtsStop[37] = "include";
gaFtsStop[38] = "into";
gaFtsStop[39] = "is";
gaFtsStop[40] = "it";
gaFtsStop[41] = "its";
gaFtsStop[42] = "late";
gaFtsStop[43] = "later";
gaFtsStop[44] = "made";
gaFtsStop[45] = "many";
gaFtsStop[46] = "may";
gaFtsStop[47] = "me";
gaFtsStop[48] = "med";
gaFtsStop[49] = "more";
gaFtsStop[50] = "most";
gaFtsStop[51] = "near";
gaFtsStop[52] = "no";
gaFtsStop[53] = "non";
gaFtsStop[54] = "not";
gaFtsStop[55] = "of";
gaFtsStop[56] = "on";
gaFtsStop[57] = "only";
gaFtsStop[58] = "or";
gaFtsStop[59] = "other";
gaFtsStop[60] = "over";
gaFtsStop[61] = "several";
gaFtsStop[62] = "she";
gaFtsStop[63] = "some";
gaFtsStop[64] = "such";
gaFtsStop[65] = "than";
gaFtsStop[66] = "that";
gaFtsStop[67] = "the";
gaFtsStop[68] = "their";
gaFtsStop[69] = "then";
gaFtsStop[70] = "there";
gaFtsStop[71] = "these";
gaFtsStop[72] = "they";
gaFtsStop[73] = "this";
gaFtsStop[74] = "through";
gaFtsStop[75] = "to";
gaFtsStop[76] = "under";
gaFtsStop[77] = "until";
gaFtsStop[78] = "use";
gaFtsStop[79] = "was";
gaFtsStop[80] = "we";
gaFtsStop[81] = "were";
gaFtsStop[82] = "when";
gaFtsStop[83] = "where";
gaFtsStop[84] = "which";
gaFtsStop[85] = "who";
gaFtsStop[86] = "with";
gaFtsStop[87] = "you";
gaFtsStem[0] = "ed";
gaFtsStem[1] = "es";
gaFtsStem[2] = "er";
gaFtsStem[3] = "e";
gaFtsStem[4] = "s";
gaFtsStem[5] = "ingly";
gaFtsStem[6] = "ing";
gaFtsStem[7] = "ly";
// as javascript 1.3 support unicode instead of ISO-Latin-1
// need to transfer come code back to ISO-Latin-1 for compare purpose
// Note: Different Language(Code page) maybe need different array:
var gaUToC=new Array();
gaUToC[8364]=128;
gaUToC[8218]=130;
gaUToC[402]=131;
gaUToC[8222]=132;
gaUToC[8230]=133;
gaUToC[8224]=134;
gaUToC[8225]=135;
gaUToC[710]=136;
gaUToC[8240]=137;
gaUToC[352]=138;
gaUToC[8249]=139;
gaUToC[338]=140;
gaUToC[381]=142;
gaUToC[8216]=145;
gaUToC[8217]=146;
gaUToC[8220]=147;
gaUToC[8221]=148;
gaUToC[8226]=149;
gaUToC[8211]=150;
gaUToC[8212]=151;
gaUToC[732]=152;
gaUToC[8482]=153;
gaUToC[353]=154;
gaUToC[8250]=155;
gaUToC[339]=156;
gaUToC[382]=158;
gaUToC[376]=159;
var gsBiggestChar="";
function getBiggestChar()
{
if(gsBiggestChar.length==0)
{
if(garrSortChar.length<256)
gsBiggestChar=String.fromCharCode(255);
else
{
var nBiggest=0;
var nBigChar=0;
for(var i=0;i<=255;i++)
{
if(garrSortChar[i]>nBiggest)
{
nBiggest=garrSortChar[i];
nBigChar=i;
}
}
gsBiggestChar=String.fromCharCode(nBigChar);
}
}
return gsBiggestChar;
}
function getCharCode(str,i)
{
var code=str.charCodeAt(i)
return code;
}
function compare(strText1,strText2)
{
var strt1=strText1.toLowerCase();
var strt2=strText2.toLowerCase();
if(strt1<strt2) return -1;
if(strt1>strt2) return 1;
return 0;
}
gbWhLang=true;
|
DiptoDas8/Biponi
|
images/Test Credit Card Account Numbers_files/whlang.js
|
JavaScript
|
mit
| 9,945
|
package com.codeborne.selenide.webdriver;
import com.codeborne.selenide.Browser;
import com.codeborne.selenide.Config;
import com.codeborne.selenide.SelenideConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.remote.DesiredCapabilities;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
final class TransferBrowserCapabilitiesFromConfigurationTest {
private static final String SOME_CAP = "some.cap";
private final AbstractDriverFactory driverFactory = new ChromeDriverFactory();
private final Proxy proxy = mock(Proxy.class);
private final SelenideConfig config = new SelenideConfig();
private final Browser browser = new Browser(config.browser(), config.headless());
@AfterEach
void clearConfiguration() {
System.clearProperty(SOME_CAP);
}
@BeforeEach
void createFactory() {
config.browserCapabilities().setCapability(SOME_CAP, "SOME_VALUE_FROM_CONFIGURATION");
}
@Test
void transferCapabilitiesFromConfiguration() {
DesiredCapabilities someCapabilities = new DesiredCapabilities();
someCapabilities.setCapability(SOME_CAP, "SOME_VALUE");
DesiredCapabilities mergedCapabilities = someCapabilities.merge(((Config) config).browserCapabilities());
assertThat(mergedCapabilities.getCapability(SOME_CAP))
.isEqualTo("SOME_VALUE_FROM_CONFIGURATION");
}
@Test
void overrideCapabilitiesFromConfiguration() {
System.setProperty(SOME_CAP, "SOME_VALUE_FROM_ENV_VARIABLE");
assertThat(driverFactory.createCommonCapabilities(config, browser, proxy).getCapability(SOME_CAP))
.isEqualTo("SOME_VALUE_FROM_CONFIGURATION");
}
}
|
codeborne/selenide
|
src/test/java/com/codeborne/selenide/webdriver/TransferBrowserCapabilitiesFromConfigurationTest.java
|
Java
|
mit
| 1,779
|
//-----------------------------------------------------------------------
// <copyright file="Registry.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Globalization;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Win32;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckEmpty</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView <b>Output: </b>Empty)</para>
/// <para><i>CheckValueExists</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView <b>Output: </b>Empty (true iff the value does not exist))</para>
/// <para><i>CreateKey</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView)</para>
/// <para><i>DeleteKey</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView)</para>
/// <para><i>DeleteKeyTree</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView )</para>
/// <para><i>DeleteValue</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView<b>Output: </b>Empty (true iff the Delete was redundant))</para>
/// <para><i>Get</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView <b>Output: </b>Data)</para>
/// <para><i>Set</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> DataType, RegistryView)</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Create a key -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CreateKey" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp"/>
/// <!-- Check if a key is empty -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckEmpty" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp">
/// <Output PropertyName="REmpty" TaskParameter="Empty"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp is empty: $(REmpty)"/>
/// <!-- Set a value -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Set" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting" Data="21"/>
/// <!-- Check if the value exists -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckValueExists" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting">
/// <Output PropertyName="RExists" TaskParameter="Exists"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp\@MySetting exists: $(RExists)"/>
/// <!-- Get the value out -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Get" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting">
/// <Output PropertyName="RData" TaskParameter="Data"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="Registry Value: $(RData)"/>
/// <!-- Check if a key is empty again -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckEmpty" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp">
/// <Output PropertyName="REmpty" TaskParameter="Empty"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp is empty: $(REmpty)"/>
/// <!-- Set some Binary Data -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Set" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" DataType="Binary" Value="binval" Data="10, 43, 44, 45, 14, 255" />
/// <!--Get some Binary Data-->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Get" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="binval">
/// <Output PropertyName="RData" TaskParameter="Data"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="Registry Value: $(RData)"/>
/// <!-- Delete a value -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="DeleteValue" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting" />
/// <!-- Delete a key -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="DeleteKey" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Registry : BaseTask
{
private const string CheckEmptyTaskAction = "CheckEmpty";
private const string CheckValueExistsTaskAction = "CheckValueExists";
private const string CreateKeyTaskAction = "CreateKey";
private const string DeleteKeyTaskAction = "DeleteKey";
private const string DeleteKeyTreeTaskAction = "DeleteKeyTree";
private const string DeleteValueTaskAction = "DeleteValue";
private const string GetTaskAction = "Get";
private const string SetTaskAction = "Set";
private RegistryKey registryKey;
private RegistryHive hive;
private RegistryView view = Microsoft.Win32.RegistryView.Default;
/// <summary>
/// Sets the type of the data. RegistryValueKind Enumeration. Support for Binary, DWord, MultiString, QWord, ExpandString
/// </summary>
public string DataType { get; set; }
/// <summary>
/// Gets the data.
/// </summary>
[Output]
public string Data { get; set; }
/// <summary>
/// Sets the value. If Value is not provided, an attempt will be made to read the Default Value.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Sets the Registry Hive. Supports ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
/// </summary>
[Required]
public string RegistryHive
{
get
{
return this.hive.ToString();
}
set
{
this.hive = (RegistryHive)Enum.Parse(typeof(RegistryHive), value);
}
}
/// <summary>
/// Sets the Registry View. Supports Registry32, Registry64 and Default. Defaults to Default
/// </summary>
public string RegistryView
{
get
{
return this.view.ToString();
}
set
{
this.view = (RegistryView)Enum.Parse(typeof(RegistryView), value);
}
}
/// <summary>
/// Sets the key.
/// </summary>
[Required]
public string Key { get; set; }
/// <summary>
/// Indicates whether the Registry Key is empty or not
/// </summary>
[Output]
public bool Empty { get; set; }
/// <summary>
/// Indicates whether the Registry value exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
try
{
this.registryKey = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view);
}
catch (System.ArgumentException)
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Registry Hive provided is not valid: {0}", this.RegistryHive));
return;
}
switch (this.TaskAction)
{
case CreateKeyTaskAction:
this.CreateKey();
break;
case DeleteKeyTaskAction:
this.DeleteKey();
break;
case DeleteKeyTreeTaskAction:
this.DeleteKeyTree();
break;
case GetTaskAction:
this.Get();
break;
case SetTaskAction:
this.Set();
break;
case CheckEmptyTaskAction:
this.CheckEmpty();
break;
case DeleteValueTaskAction:
this.DeleteValue();
break;
case CheckValueExistsTaskAction:
this.CheckValueExists();
break;
default:
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private static string GetRegistryKeyValue(RegistryKey subkey, string value)
{
var v = subkey.GetValue(value);
if (v == null)
{
return null;
}
RegistryValueKind valueKind = subkey.GetValueKind(value);
if (valueKind == RegistryValueKind.Binary && v is byte[])
{
byte[] valueBytes = (byte[])v;
StringBuilder bytes = new StringBuilder(valueBytes.Length * 2);
foreach (byte b in valueBytes)
{
bytes.Append(b.ToString(CultureInfo.InvariantCulture));
bytes.Append(',');
}
return bytes.ToString(0, bytes.Length - 1);
}
if (valueKind == RegistryValueKind.MultiString && v is string[])
{
var itemList = new StringBuilder();
foreach (string item in (string[])v)
{
itemList.Append(item);
itemList.Append(',');
}
return itemList.ToString(0, itemList.Length - 1);
}
return v.ToString();
}
/// <summary>
/// Checks if a Registry Key contains values or subkeys.
/// </summary>
private void CheckEmpty()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if Registry Key: {0} is empty in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
if (subKey.SubKeyCount <= 0)
{
this.Empty = subKey.ValueCount <= 0;
}
else
{
this.Empty = false;
}
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Registry Key: {0} not found in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
}
}
private void Set()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Registry Value: {0} for Key: {1} in Hive: {2}, View: {3} on: {4}", this.Value, this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
bool changed = false;
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
string oldData = GetRegistryKeyValue(subKey, this.Value);
if (oldData == null || oldData != this.Data)
{
if (string.IsNullOrEmpty(this.DataType))
{
subKey.SetValue(this.Value, this.Data);
}
else
{
// assumption that ',' is separator for binary and multistring value types.
char[] separator = { ',' };
object registryValue;
RegistryValueKind valueKind = (Microsoft.Win32.RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), this.DataType, true);
switch (valueKind)
{
case RegistryValueKind.Binary:
string[] parts = this.Data.Split(separator);
byte[] val = new byte[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
val[i] = byte.Parse(parts[i], CultureInfo.CurrentCulture);
}
registryValue = val;
break;
case RegistryValueKind.DWord:
registryValue = uint.Parse(this.Data, CultureInfo.CurrentCulture);
break;
case RegistryValueKind.MultiString:
string[] parts1 = this.Data.Split(separator);
registryValue = parts1;
break;
case RegistryValueKind.QWord:
registryValue = ulong.Parse(this.Data, CultureInfo.CurrentCulture);
break;
default:
registryValue = this.Data;
break;
}
subKey.SetValue(this.Value, registryValue, valueKind);
}
changed = true;
}
subKey.Close();
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Registry Key: {0} not found in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
}
if (changed)
{
// Broadcast config change
if (0 == NativeMethods.SendMessageTimeout(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, 0, "Environment", NativeMethods.SMTO_ABORTIFHUNG, NativeMethods.SENDMESSAGE_TIMEOUT, 0))
{
this.LogTaskWarning("NativeMethods.SendMessageTimeout returned 0");
}
}
this.registryKey.Close();
}
private void Get()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Registry value: {0} from Key: {1} in Hive: {2}, View: {3} on: {4}", this.Value, this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, false);
if (subKey == null)
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Registry Key provided is not valid: {0}", this.Key));
return;
}
if (subKey.GetValue(this.Value) == null)
{
this.LogTaskMessage(string.IsNullOrEmpty(this.Value) ? string.Format(CultureInfo.CurrentCulture, "A Default value was not found for the Registry Key: {0}", this.Key) : string.Format(CultureInfo.CurrentCulture, "The Registry value provided is not valid: {0}", this.Value));
return;
}
this.Data = GetRegistryKeyValue(subKey, this.Value);
subKey.Close();
this.registryKey.Close();
}
private void DeleteKeyTree()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Key Tree: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
{
r.DeleteSubKeyTree(this.Key);
}
}
private void DeleteKey()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Registry Key: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
{
r.DeleteSubKey(this.Key, false);
}
}
private void CreateKey()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Registry Key: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
using (RegistryKey r2 = r.CreateSubKey(this.Key))
{
}
}
private void DeleteValue()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Registry value: {0} from Key: {1} in Hive: {2} on: {3}", this.Value, this.Key, this.RegistryHive, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
var val = subKey.GetValue(this.Value);
if (val != null)
{
subKey.DeleteValue(this.Value);
}
}
}
private void CheckValueExists()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if Registry Value: {0} for Key {1} exists in Hive: {2} on: {3}", this.Value, this.Key, this.RegistryHive, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, false);
this.Exists = !((subKey == null) || (subKey.GetValue(this.Value) == null));
}
}
}
|
mikefourie/MSBuildExtensionPack
|
Releases/4.0.9.0/Main/Framework/Computer/Registry.cs
|
C#
|
mit
| 19,180
|
import { buildUrl, contentUrl, profileUrl } from 'shared/util/url_factory';
import gql from 'graphql-tag';
import { memo } from 'react';
import { useQuery } from '@apollo/client';
const CONTENT_AND_USER_QUERY = gql`
query ContentAndUserQuery($username: String!, $name: String!) {
fetchContentHead(username: $username, name: $name) {
username
section
album
name
thumb
title
createdAt
updatedAt
comments_count
comments_updated
}
fetchPublicUserDataHead(username: $username) {
description
favicon
google_analytics
logo
name
theme
title
username
viewport
}
}
`;
// NOTE: Keep in sync with index.html for service workers!
export default function HTMLHead(props) {
const { appName, assetPathsByType, nonce, publicUrl, req } = props;
// The username is either the first part of the path (e.g. hostname.com/mime/section/album/name)
// or if we're on a user that has a `hostname` defined then it's implicit in the url
// (e.g. hostname.com/section/album/name) and we figure it out in the user resolver.
const splitPath = req.path.split('/');
const probableContentUsername = splitPath[1];
const probableContentName = splitPath[splitPath.length - 1];
const { loading, data } = useQuery(CONTENT_AND_USER_QUERY, {
variables: {
username: decodeURIComponent(probableContentUsername),
name: decodeURIComponent(probableContentName),
},
});
if (loading) {
return null;
}
// XXX(mime): terrible hack until i figure out what's going on.
// seems that having the same query twice in a tree while doing SSR will prevent rendering of the first
// component. in this case, HTMLHead's data will be missing.
const contentOwner = data.fetchPublicUserDataHead;
const content = data.fetchContentHead;
let description, favicon, rss, theme, title, username, webmentionUrl;
const repliesUrl =
content && buildUrl({ pathname: '/api/social/comments', searchParams: { resource: contentUrl(content) } });
const repliesAttribs = content && {
'thr:count': content.comments_count,
'thr:updated': new Date(content.comments_updated).toISOString(),
};
let viewport = 'width=device-width, initial-scale=1';
if (contentOwner) {
username = contentOwner.username;
const resource = profileUrl(username, req);
description = <meta name="description" content={contentOwner.description || 'Hello, world.'} />;
favicon = contentOwner.favicon;
const feedUrl = buildUrl({ pathname: '/api/social/feed', searchParams: { resource } });
rss = <link rel="alternate" type="application/atom+xml" title={title} href={feedUrl} />;
theme = contentOwner.theme && <link rel="stylesheet" href={contentOwner.theme} />;
title = contentOwner.title;
viewport = contentOwner.viewport || viewport;
webmentionUrl = buildUrl({ req, pathname: '/api/social/webmention', searchParams: { resource } });
}
if (!theme) {
theme = <link rel="stylesheet" href="/css/themes/pixel.css" />;
}
if (!title) {
title = appName;
}
return (
<head>
<meta charSet="utf-8" />
<link rel="author" href={`${publicUrl}humans.txt`} />
{contentOwner ? <link rel="author" href={contentUrl({ username, section: 'main', name: 'about' })} /> : null}
<link rel="icon" href={favicon || `${publicUrl}favicon.ico`} />
<link rel="apple-touch-icon" href={favicon || `${publicUrl}favicon.ico`} />
{assetPathsByType['css'].map((path) => (
<link nonce={nonce} rel="stylesheet" key={path} href={path} />
))}
{theme}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<link
rel="search"
href={buildUrl({ pathname: '/api/opensearch', searchParams: { username } })}
type="application/opensearchdescription+xml"
title={title}
/>
<link rel="canonical" href={content && contentUrl(content, req)} />
{rss}
{!content && <meta name="robots" content="noindex" />}
<meta name="viewport" content={viewport} />
<meta name="theme-color" content="#000000" />
<meta name="generator" content="Hello, world. https://github.com/mimecuvalo/helloworld" />
<meta property="csp-nonce" content={nonce} />
<script
nonce={nonce}
dangerouslySetInnerHTML={{
__html: `__webpack_nonce__ = '${nonce}'`,
}}
/>
{description}
<OpenGraphMetadata contentOwner={contentOwner} content={content} title={title} req={req} />
<StructuredMetaData contentOwner={contentOwner} content={content} nonce={nonce} title={title} req={req} />
<link
rel="alternate"
type="application/json+oembed"
href={buildUrl({
pathname: '/api/social/oembed',
searchParams: { resource: content && contentUrl(content) },
})}
title={content?.title}
/>
{content && webmentionUrl ? <link rel="webmention" href={webmentionUrl} /> : null}
{content?.comments_count ? (
<link rel="replies" type="application/atom+xml" href={repliesUrl} {...repliesAttribs} />
) : null}
{/*
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
*/}
<link rel="manifest" href={`${publicUrl}manifest.json`} />
{/*
Notice the use of publicUrl in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "${publicUrl}favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
*/}
<title>{(content?.title ? content.title + ' – ' : '') + title}</title>
{/*
XXX(mime): Material UI's server-side rendering for CSS doesn't allow for inserting CSS the same way we do
Apollo's data (see apolloStateFn in HTMLBase). So for now, we just do a string replace, sigh.
See related hacky code in server/app/app.js
*/}
<style id="jss-ssr" nonce={nonce} dangerouslySetInnerHTML={{ __html: `<!--CSS-SSR-REPLACE-->` }} />
{contentOwner ? <GoogleAnalytics nonce={nonce} contentOwner={contentOwner} /> : null}
</head>
);
}
// This needs to be filled out by the developer to provide content for the site.
// Learn more here: http://ogp.me/
const OpenGraphMetadata = memo(function OpenGraphMetadata({ contentOwner, content, title, req }) {
const thumb = buildThumb(contentOwner, content, req);
return (
<>
<meta property="og:title" content={content?.title} />
<meta property="og:description" content={contentOwner?.description} />
<meta property="og:type" content="website" />
<meta property="og:url" content={content && contentUrl(content, req)} />
<meta property="og:site_name" content={title} />
<meta property="og:image" content={thumb} />
</>
);
});
function buildThumb(contentOwner, content, req) {
let thumb;
if (content?.thumb) {
thumb = content.thumb;
if (!/^https?:/.test(thumb)) {
thumb = buildUrl({ req, pathname: thumb });
}
}
if (!thumb) {
thumb = buildUrl({ req, pathname: contentOwner?.logo || contentOwner?.favicon });
}
return thumb;
}
// This needs to be filled out by the developer to provide content for the site.
// Learn more here: https://developers.google.com/search/docs/guides/intro-structured-data
function StructuredMetaData({ contentOwner, content, title, req, nonce }) {
const url = buildUrl({ req, pathname: '/' });
const thumb = buildThumb(contentOwner, content, req);
return (
<script
nonce={nonce}
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: `
{
"@context": "http://schema.org",
"@type": "NewsArticle",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "${contentUrl(content, req)}"
},
"headline": "${content?.title}",
"image": [
"${thumb}"
],
"datePublished": "${new Date(content?.createdAt || new Date()).toISOString()}",
"dateModified": "${new Date(content?.updatedAt || new Date()).toISOString()}",
"author": {
"@type": "Person",
"name": "${content?.username}"
},
"publisher": {
"@type": "Organization",
"name": "${title}",
"logo": {
"@type": "ImageObject",
"url": "${url}favicon.ico"
}
},
"description": "${contentOwner?.description}"
}
`,
}}
/>
);
}
// TODO(mime): meh, lame that this is in the <head> but I don't feel like moving this to HTMLBase where we don't have
// contentOwner currently.
function GoogleAnalytics({ nonce, contentOwner }) {
return (
<script
nonce={nonce}
async
dangerouslySetInnerHTML={{
__html: `
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '${contentOwner.google_analytics}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
`,
}}
/>
);
}
|
mimecuvalo/helloworld
|
server/app/HTMLHead.js
|
JavaScript
|
mit
| 9,836
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using CorePoker.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace CorePoker.Controllers
{
[Route("api/[controller]")]
public class TableController : Controller
{
private readonly CorePokerContext db;
public TableController(CorePokerContext db)
{
this.db = db;
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var table = await db.Tables.FirstOrDefaultAsync(_ => _.PublicId == id);
if (table == null)
{
return NotFound();
}
return Json(table);
}
// POST api/values
[HttpPost]
public async Task<IActionResult> Post([FromBody]TablePayload table)
{
var player = await db.Players.FirstOrDefaultAsync(_ => _.Nickname == table.PlayerName);
if (player == null)
{
return NotFound("Player not found");
}
var tableEntity = new Table
{
CreatedAt = DateTime.UtcNow,
Name = table.TableName,
PublicId = Guid.NewGuid().ToString(),
Owner = player
};
tableEntity.TablePlayers.Add(new TablePlayer {Player = player});
db.Tables.Add(tableEntity);
db.SaveChanges();
return Ok(new {tableId = tableEntity.PublicId});
}
public sealed class TablePayload
{
[Required]
[MaxLength(60)]
public string TableName { get; set; }
[Required]
[MaxLength(60)]
public string PlayerName { get; set; }
}
}
}
|
mareklinka/CorePoker
|
src/CorePoker.Web/Controllers/TableController.cs
|
C#
|
mit
| 2,036
|
/*
* <auto-generated>
* This code was generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
* </auto-generated>
*/
#import <Foundation/Foundation.h>
#import "MOZUClient.h"
#import "MOZUFraudScreenRequest.h"
#import "MOZUFraudScreen.h"
@interface MOZUFraudScreenClient : NSObject
//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//
//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//
/**
payments-fraudscreen Post Screen description DOCUMENT_HERE
@param body Mozu.PaymentService.Contracts.Request.FraudScreenRequest ApiType DOCUMENT_HERE
*/
+ (MOZUClient *)clientForScreenOperationWithBody:(MOZUFraudScreenRequest *)body;
//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//
//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//
@end
|
Mozu/mozu-ios-sdk
|
MozuApi/Clients/Commerce/Payments/MOZUFraudScreenClient.h
|
C
|
mit
| 938
|
## Mapping Tools
>**_This documentation is for a preview version of the Azure DevOps Migration Tools._ If you are not using the preview version then please head over to the main [documentation](https://nkdagility.github.io/azure-devops-migration-tools).**
[Overview](.././index.md) > [Reference](../index.md) > *Mapping Tools*
Azure DevOps Migration Tools provides a number of _mapping tools_ that can be used to solve the
diferences between the source and the target Endpoints.
Mapping Tool | Description
----------|-----------
FieldMapping | TBA
GitRepoMapping | TBA
WorkItemTypeMapping | TBA
ChangeSetMapping | TBA
|
nkdAgility/vsts-sync-migration
|
docs/Reference/MappingTools/index.md
|
Markdown
|
mit
| 626
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import <DTGraphKit/DTGraph.h>
@interface DTBarGraph : DTGraph
{
BOOL _hasWidthOrSpacingAttribute;
long long _maxX;
long long _minX;
long long _maxY;
long long _calculatedYAxisLabelHeight;
long long _lastMaximumYValue;
}
+ (id)sortEntries:(id)arg1 keyPath:(id)arg2;
@property long long lastMaximumYValue; // @synthesize lastMaximumYValue=_lastMaximumYValue;
- (BOOL)validateModel:(id)arg1;
- (id)_divisionsForContentMagnitude:(double)arg1 start:(double)arg2 min:(long long)arg3 max:(long long)arg4 spacing:(double)arg5 keypath:(id)arg6 onlyStartAndEnd:(BOOL)arg7;
- (id)_entries:(id)arg1 fittingIntoRect:(struct CGRect)arg2;
- (id)sortedEntries:(id)arg1 fittingIntoRect:(struct CGRect)arg2;
- (id)visibleEntries:(id)arg1;
- (unsigned long long)numberOfBars;
- (unsigned long long)numberOfEntriesThatFitRect:(struct CGRect)arg1;
- (long long)maximumYValue;
- (long long)_maximumValueOfSeries:(id)arg1;
- (long long)minimumXValue;
- (long long)maximumXValue;
- (BOOL)hasBarSpacing;
@property(readonly) double barSpacing;
@property(readonly) double barWidth;
- (struct CGRect)contentFrame;
- (void)clearCache;
- (id)initWithFrame:(struct CGRect)arg1;
- (id)textAttributesForAxisLabels;
- (double)widthToFill:(struct CGRect)arg1 numberOfEntries:(unsigned long long)arg2;
- (id)divisionPositionsYAxis;
- (id)divisionPositionsXAxis;
@property(readonly) double yAxisSpacing;
@property(readonly) double xAxisSpacing;
- (void)getXAxisRect:(struct CGRect *)arg1 yAxisRect:(struct CGRect *)arg2;
- (double)calculateVerticalBorderBuffer;
- (double)calculateHorizontalBorderBuffer;
- (struct CGRect)calculateXAxisBoundsWithinBounds:(struct CGRect)arg1;
- (struct CGRect)calculateYAxisBoundsWithinBounds:(struct CGRect)arg1;
- (void)drawXAxis:(struct CGRect)arg1;
- (void)drawYAxis:(struct CGRect)arg1;
- (void)drawBorder:(struct CGRect)arg1;
- (BOOL)canDrawBeyondContentRect;
- (void)drawContent:(struct CGRect)arg1;
- (void)drawBackground:(struct CGRect)arg1;
- (void)drawRect:(struct CGRect)arg1;
@end
|
wczekalski/Distraction-Free-Xcode-plugin
|
Archived/v1/WCDistractionFreeXcodePlugin/Headers/SharedFrameworks/DTGraphKit/DTBarGraph.h
|
C
|
mit
| 2,158
|
/**
* Copyright 2011 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.multibit.ApplicationDataDirectoryLocator;
import org.multibit.file.FileHandler;
import java.util.Properties;
import java.io.OutputStream;
import org.multibit.model.core.CoreModel;
import org.multibit.utils.FilePermissionUtils;
/**
* Main MultiBitInExecutableJar entry class for when running in an executable jar - put console
* output to a file
*/
public final class MultiMonaInExecutableJar {
public static final String OUTPUT_DIRECTORY = "log";
public static final String CONSOLE_OUTPUT_FILENAME = "multimona.log";
private static Logger log = LoggerFactory.getLogger(MultiMonaInExecutableJar.class);
/**
* Utility class should not have a public constructor
*/
private MultiMonaInExecutableJar() {
}
/**
* Start multibit user interface when running in a jar.
* This will adjust the logging framework output to ensure that console output is sent
* to a file appender in the client.
* @param args The optional command line arguments ([0] can be a Bitcoin URI
*/
public static void main(String args[]) {
// Redirect the console output to a file.
PrintStream fileStream;
try {
if(useLogFile()){
// Get the current data directory
ApplicationDataDirectoryLocator applicationDataDirectoryLocator = new ApplicationDataDirectoryLocator();
String outputDirectory;
String consoleOutputFilename;
if ("".equals(applicationDataDirectoryLocator.getApplicationDataDirectory())) {
// Use defaults
outputDirectory = OUTPUT_DIRECTORY;
consoleOutputFilename = OUTPUT_DIRECTORY + File.separator + CONSOLE_OUTPUT_FILENAME;
} else {
// Use defined data directory as the root
outputDirectory = applicationDataDirectoryLocator.getApplicationDataDirectory() + File.separator
+ OUTPUT_DIRECTORY;
consoleOutputFilename = applicationDataDirectoryLocator.getApplicationDataDirectory() + File.separator
+ OUTPUT_DIRECTORY + File.separator + CONSOLE_OUTPUT_FILENAME;
}
log = LoggerFactory.getLogger(MultiMonaInExecutableJar.class);
// create output directory
(new File(outputDirectory)).mkdir();
// create output console log
File consoleOutputFile = new File(consoleOutputFilename);
consoleOutputFile.createNewFile();
FilePermissionUtils.setWalletPermission(consoleOutputFile);
fileStream = new PrintStream(new FileOutputStream(consoleOutputFilename, true));
} else {
fileStream = new PrintStream(new OutputStream() {
public void write(int b) {
}
});
} // useLogFile
if (fileStream != null) {
// Redirecting console output to file
System.setOut(fileStream);
// Redirecting runtime exceptions to file
System.setErr(fileStream);
}
} catch (FileNotFoundException e) {
if (log != null) {
log.error("Error in IO Redirection", e);
}
} catch (Exception e) {
// Gets printed in the file.
if (log != null) {
log.debug("Error in redirecting output & exceptions to file", e);
}
} finally {
// call the main MultiMonaInExecutableJar code
MultiBit.main(args);
}
}
public static boolean useLogFile(){
ApplicationDataDirectoryLocator adl = new ApplicationDataDirectoryLocator();
Properties pref = FileHandler.loadUserPreferences(adl);
String logging = pref.getProperty( CoreModel.LOGGING );
if( logging != null && logging.equals("true") ){
return true;
}else{
return false;
}
}
}
|
monapu/multimona
|
src/main/java/org/multibit/MultiMonaInExecutableJar.java
|
Java
|
mit
| 5,027
|
/// <reference path="../../d.ts/DefinitelyTyped/jasmine/jasmine.d.ts"/>
import basilisk = require('../basilisk');
import Hash = basilisk.HashMap;
var freeze = (obj:any):any => { return (Object.freeze) ? Object.freeze(obj) : obj; };
// given a map of strings -> numbers, return a
function fixedStringHash(values:any):(key:string) => number {
var safe = {};
for (var key in values) {
if (values.hasOwnProperty(key)) {
if (typeof values[key] !== 'number') {
throw "Must only provide numbers as hashcodes";
}
safe[key] = values[key];
}
}
safe = freeze(safe);
return function (key:string):number {
if (!safe.hasOwnProperty(key)) {
throw "Must only check for keys which are in the provided set.";
}
return safe[key];
}
}
describe('PersistentHashMap', function () {
describe('.from', function () {
it("Should require a function as first parameter.", function () {
var fn = fixedStringHash({ 'a': 0, 'b': 1, 'c': 2 }),
map = Hash.from(fn);
expect(() => { Hash.from(null) }).toThrow();
});
});
// These tests check that the *internal* behaviour is correct: the external contract is tested above.
describe('Internal behaviour', function () {
it("Should still be possible to retrieve correct values, even if all keys map to the same value.", function () {
var map = Hash.from<string, string>((k:any) => { return 0; }),
map = map.set('a', 'a').set('b', 'b').set('c', 'c');
expect(map.get('a')).toBe('a');
expect(map.get('b')).toBe('b');
expect(map.get('c')).toBe('c');
});
it("Collisions one deep should function correctly.", function () {
// 97 is one deep, and the top bit is 1. This should thus generate a nested tree, with an interior node
// in the middle and a collision node further down.
var map = Hash.from<string, string>(fixedStringHash({'a': 1, 'b': 97, 'c': 97 }));
map = map.set('a', 'a');
expect(map['root'] instanceof basilisk.hamt.Leaf).toBe(true);
map = map.set('b', 'b');
expect(map['root'] instanceof basilisk.hamt.Interior).toBe(true);
expect(map['root']['contents'][1] instanceof basilisk.hamt.Interior).toBe(true);
var nested = map['root']['contents'][1];
expect(nested['contents'][0] instanceof basilisk.hamt.Leaf).toBe(true);
expect(nested['contents'][3] instanceof basilisk.hamt.Leaf).toBe(true);
map = map.set('c', 'c');
expect(map['root'] instanceof basilisk.hamt.Interior).toBe(true);
expect(map['root']['contents'][1] instanceof basilisk.hamt.Interior).toBe(true);
nested = map['root']['contents'][1];
expect(nested['contents'][0] instanceof basilisk.hamt.Leaf).toBe(true);
expect(nested['contents'][3] instanceof basilisk.hamt.Collision).toBe(true);
expect(map.get('c')).toBe('c');
expect(map.get('b')).toBe('b');
expect(map.get('a')).toBe('a');
// now unset the items.
map = map.remove('c');
expect(map['root'] instanceof basilisk.hamt.Interior).toBe(true);
expect(map['root']['contents'][1] instanceof basilisk.hamt.Interior).toBe(true);
nested = map['root']['contents'][1];
expect(nested['contents'][0] instanceof basilisk.hamt.Leaf).toBe(true);
expect(nested['contents'][3] instanceof basilisk.hamt.Leaf).toBe(true);
map = map.remove('b');
expect(map['root'] instanceof basilisk.hamt.Leaf).toBe(true);
});
var count:number = 5000;
it("Adding " + count + " elements should not be prohibitive (+- 0.5s).", function () {
var map = Hash.from<number, number>((key:number):number => { return (key >= 0) ? key : -1 * key; });
for (var i=0; i < count; i++) {
map = map.set(i, i);
}
var final = map;
});
});
describe('.size', function () {
var count:number = 76;
it("Should work for different keys.", function () {
var map = Hash.from<number, number>((key:number):number => { return Math.abs(key); }),
correct = true;
for (var i=0; i < count; i++) {
map = map.set(i, i);
correct = correct && (map.size == i + 1);
}
expect(correct).toBe(true);
});
it("Should work for collisions.", function () {
var map = Hash.from<number, number>((key:number):number => { return 0; }),
correct = true;
for (var i=0; i < count; i++) {
map = map.set(i, i);
correct = correct && (map.size == i + 1)
}
expect(correct).toBe(true);
});
});
describe('.keys', function () {
var count:number = 76;
it("Should work for different keys.", function () {
var map = Hash.from<number, number>((key:number):number => { return Math.abs(key); }),
correct = true,
seen = {};
for (var i=0; i < count; i++) {
map = map.set(i * 2, i * 4);
seen['s' + (i * 2)] = false;
}
map.keys().forEach(function (key:number) {
seen['s' + (key)] = true;
});
for (var k in seen) {
if (seen.hasOwnProperty(k)) {
correct = correct && seen[k];
}
}
expect(correct).toBe(true);
});
it("Should work for collisions.", function () {
var map = Hash.from<number, number>((key:number):number => { return 0; }),
correct = true,
seen = {};
for (var i=0; i < count; i++) {
map = map.set(i * 2, i * 4);
seen['s' + (i * 2)] = false;
}
map.keys().forEach(function (key:number) {
seen['s' + (key)] = true;
});
for (var k in seen) {
if (seen.hasOwnProperty(k)) {
correct = correct && seen[k];
}
}
});
});
describe('.values', function () {
var count:number = 76;
it("Should work for different keys.", function () {
var map = Hash.from<number, number>((key:number):number => { return Math.abs(key); }),
correct = true,
seen = {};
for (var i=0; i < count; i++) {
map = map.set(i * 2, i * 4);
seen['s' + (i * 4)] = false;
}
map.values().forEach(function (key:number) {
seen['s' + (key)] = true;
});
for (var k in seen) {
if (seen.hasOwnProperty(k)) {
correct = correct && seen[k];
}
}
});
it("Should work for collisions.", function () {
var map = Hash.from<number, number>((key:number):number => { return 0; }),
correct = true,
seen = {};
for (var i=0; i < count; i++) {
map = map.set(i * 2, i * 4);
seen['s' + (i * 4)] = false;
}
map.values().forEach(function (key:number) {
seen['s' + (key)] = true;
});
for (var k in seen) {
if (seen.hasOwnProperty(k)) {
correct = correct && seen[k];
}
}
});
});
});
|
basiliskjs/basilisk
|
src/tests/persistenthashmap.test.ts
|
TypeScript
|
mit
| 7,837
|
angular.module('VoltronApp.services', []).
factory('voltronAPIservice', function($http)
{
var voltronAPI = {};
function createRequest(requestType, data) {
return {type: "request", request: requestType, data: data}
}
voltronAPI.request = function(request) {
return $http({
method: 'POST',
url: '/api/request',
data: request
});
}
voltronAPI.disassemble_format = function(data) {
res = voltronAPI.request(createRequest('disassemble', {address: address, count: count}))
return $http({
method: 'POST',
url: '/api/request',
data: createRequest('format_disasm', {disassembly: res.data.disassembly})
});
}
voltronAPI.disassemble = function(address, count) {
return voltronAPI.request(createRequest('disassemble', {address: address, count: count}))
}
voltronAPI.command = function(command) {
return voltronAPI.request(createRequest('command', {command: command}))
}
voltronAPI.targets = function() {
return voltronAPI.request(createRequest('targets', {}))
}
voltronAPI.memory = function(address, length) {
return voltronAPI.request(createRequest('memory', {address: address, length: length}))
}
voltronAPI.registers = function() {
return voltronAPI.request(createRequest('registers', {}))
}
voltronAPI.stack = function(length) {
return voltronAPI.request(createRequest('stack', {length: length}))
}
voltronAPI.state = function() {
return voltronAPI.request(createRequest('state', {}))
}
voltronAPI.version = function() {
return voltronAPI.request(createRequest('version', {}))
}
return voltronAPI;
});
|
snare/voltron
|
examples/angularview/static/js/services.js
|
JavaScript
|
mit
| 1,786
|
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#pragma once
#include "PredictionContext.h"
namespace antlr4 {
namespace atn {
class ANTLR4CPP_PUBLIC SingletonPredictionContext : public PredictionContext {
public:
// Usually a parent is linked via a weak ptr. Not so here as we have kinda reverse reference chain.
// There are no child contexts stored here and often the parent context is left dangling when it's
// owning ATNState is released. In order to avoid having this context released as well (leaving all other contexts
// which got this one as parent with a null reference) we use a shared_ptr here instead, to keep those left alone
// parent contexts alive.
const Ref<PredictionContext> parent;
const size_t returnState;
SingletonPredictionContext(Ref<PredictionContext> const& parent, size_t returnState);
virtual ~SingletonPredictionContext() {};
static Ref<SingletonPredictionContext> create(Ref<PredictionContext> const& parent, size_t returnState);
virtual size_t size() const override;
virtual Ref<PredictionContext> getParent(size_t index) const override;
virtual size_t getReturnState(size_t index) const override;
virtual bool operator == (const PredictionContext &o) const override;
virtual std::string toString() const override;
};
} // namespace atn
} // namespace antlr4
|
caicai0/ios_demo
|
antlr_demo/thirdpart/antlr4/antlr4-runtime/atn/SingletonPredictionContext.h
|
C
|
mit
| 1,517
|
define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to:
// - http://documentcloud.github.com/backbone/#Model
// - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.setters
var Util = require('./util');
// 负责 attributes 的初始化
// attributes 是与实例相关的状态信息,可读可写,发生变化时,会自动触发相关事件
exports.initAttrs = function(config) {
// Keep existed attrs.
if (!this.hasOwnProperty('attrs')) {
this.attrs = {};
}
var attrs = this.attrs;
// Only merge all inherited attributes once.
if (!attrs.__defaults) {
attrs.__defaults = Util.getInherited(this, 'attrs', normalize);
Util.merge(attrs, attrs.__defaults);
}
var options = { silent: true };
for (var key in attrs) {
// only merge recognized attributes, and delete it from config
// after merged.
if (config && config.hasOwnProperty(key)) {
this.set(key, config[key], options);
delete config[key];
}
// automatically register `_onChangeX` method as
// 'change:x' handler.
var eventKey = getChangeEventKey(key);
if (this[eventKey]) {
this.on('change:' + key, this[eventKey]);
}
}
};
// Get the value of an attribute.
exports.get = function(key) {
var attr = this.attrs[key] || {};
var val = attr.value;
return attr.getter ? attr.getter.call(this, val, key) : val;
};
// Set a hash of model attributes on the object, firing `"change"` unless
// you choose to silence it.
exports.set = function(key, val, options) {
var attrs = {};
// set("key", val, options)
if (Util.isString(key)) {
attrs[key] = val;
}
// set({ "key": val, "key2": val2 }, options)
else {
attrs = key;
options = val;
}
options || (options = {});
var now = this.attrs;
var silent = options.silent;
for (key in attrs) {
var attr = now[key] || ( now[key] = {} );
val = attrs[key];
// invoke validator
if (attr.validator) {
var ex = attr.validator.call(this, val, key);
if (ex !== true) {
if (options.error) {
options.error.call(this, ex);
}
continue;
}
}
// invoke setter
if (attr.setter) {
val = attr.setter.call(this, val, key);
}
// set finally
var prev = this.get(key);
if (Util.isPlainObject(prev) && Util.isPlainObject(val)) {
val = Util.merge(Util.merge({}, prev), val);
}
now[key].value = val;
// invoke change event
if (!silent && this.trigger && prev !== val) {
this.trigger('change:' + key, val, prev, key);
}
}
};
// Helpers
// -------
var ATTR_SPECIAL_KEYS = ['value', 'getter', 'setter', 'validator'];
// normalize `attrs` to
//
// {
// value: 'xx',
// getter: fn,
// setter: fn,
// validator: fn
// }
//
function normalize(attrs) {
// clone it
attrs = Util.merge({}, attrs);
for (var key in attrs) {
var attr = attrs[key];
if (Util.isPlainObject(attr) &&
hasOwnProperties(attr, ATTR_SPECIAL_KEYS)) {
continue;
}
attrs[key] = {
value: attr
};
}
return attrs;
}
function hasOwnProperties(object, properties) {
for (var i = 0, len = properties.length; i < len; i++) {
if (object.hasOwnProperty(properties[i])) {
return true;
}
}
return false;
}
function getChangeEventKey(key) {
return '_onChange' + key.charAt(0).toUpperCase() + key.substring(1);
}
});
|
leoner/arale
|
dist/base/0.9.2/attrs-debug.js
|
JavaScript
|
mit
| 4,385
|
#!/bin/bash
. ~/.bash_profile
## if [[ $1 ]];
## then;
rootdir=$1;
## else;
## rootdir='django_home'
## fi;
# Create "$rootdir" directory in our home directory
mkdir ~/"$rootdir"
# Change into the newly created ~/"$rootdir" directory
cd ~/"$rootdir"
# Create a place for the Chef cookbooks
mkdir ~/"$rootdir"/cookbooks
# Change into the newly created ~/"$rootdir"/cookbooks directory
cd ~/"$rootdir"/cookbooks
# Clone the Chef cookbooks repositories as needed (we will use the following cookbooks in this guide)
git clone git://github.com/opscode-cookbooks/apache2.git
git clone git://github.com/opscode-cookbooks/apt.git
git clone git://github.com/opscode-cookbooks/build-essential.git
git clone git://github.com/opscode-cookbooks/git.git
git clone git://github.com/opscode-cookbooks/vim.git
git clone git://github.com/opscode-cookbooks/python.git
git clone git://github.com/opscode-cookbooks/pip.git
|
relic7/prodimages
|
python/struct_vagrant.sh
|
Shell
|
mit
| 912
|
<?php
namespace tests\pages;
use tests\pages\mocks\TestController;
use WScore\Pages\Dispatch;
use WScore\Pages\Factory;
require_once( dirname(__DIR__).'/autoload.php' );
require_once( __DIR__ . '/mocks/TestController.php' );
class Dispatch_FunctionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var TestController
*/
var $c;
/**
* @var Dispatch
*/
var $d;
function setup()
{
$this->buildDispatcher();
}
function buildDispatcher()
{
$_REQUEST = array();
$this->c = new TestController();
$this->d = Factory::getDispatch( $this->c );
}
function test0()
{
$this->assertEquals('tests\pages\mocks\TestController', get_class($this->c));
$this->assertEquals('WScore\Pages\Dispatch', get_class($this->d));
$this->assertEquals('WScore\Pages\Request', get_class($this->d->getRequest()));
$this->assertEquals('WScore\Pages\Session', get_class($this->d->getSession()));
$this->assertEquals('WScore\Pages\PageView', get_class($this->d->getView()));
}
// +----------------------------------------------------------------------+
// test correct method is executed.
// +----------------------------------------------------------------------+
/**
* @test
*/
function dispatches_onExecute_method_from_argument()
{
$view = $this->d->execute('execute');
$this->assertEquals('executed', $view['execute']);
}
/**
* @test
*/
function dispatches_onExecute_from_httpMethod()
{
$this->d->getRequest()->setRequest(['_method'=>'execute']);
$view = $this->d->execute();
$this->assertEquals('executed', $view['execute']);
}
/**
* @test
*/
function dispatches_onExecute_by_specifying_method_variable_name()
{
$this->d->getRequest()->setMethodName('action');
$this->d->getRequest()->setRequest(['action'=>'execute']);
$view = $this->d->execute();
$this->assertEquals('executed', $view['execute']);
}
/**
* @test
*/
function executing_non_existence_method_returns_critical_error()
{
$view = $this->d->execute('noSuch');
$this->assertTrue($view->isCritical());
$this->assertEquals('no method: noSuch', $view->getMessage());
}
// +----------------------------------------------------------------------+
// test argument is passed to the execute method.
// +----------------------------------------------------------------------+
/**
* @test
*/
function onArgument_argument_is_populated()
{
$this->d->getRequest()->setRequest(['arg'=>'arg-tested']);
$view = $this->d->execute('argument');
$this->assertEquals('arg-tested', $view['argument']);
}
/**
* @test
*/
function onArgument_without_argument_returns_critical_error()
{
$view = $this->d->execute('argument');
$this->assertTrue($view->isCritical());
$this->assertEquals('please specify the argument', $view->getMessage());
}
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
/**
* @test
*/
function savePost_sets_compact_data_to_view_and_loadPost_to_use_the_data()
{
$this->d->getRequest()->setRequest(['post1'=>'tested', 'post2'=>'more']);
$view = $this->d->execute('savePost');
$this->assertTrue(isset( $view['_savedPost']));
$this->assertEquals('tested:more', $view['posted']);
// check on what is saved.
$saved = $view->get();
$saved = $this->d->getRequest()->unpack($saved['_savedPost']);
$this->assertTrue( is_array($saved));
$this->assertEquals( 'tested', $saved['post1']);
$this->assertEquals( 'more', $saved['post2']);
// let's call it again. this should create no posted...
$this->buildDispatcher();
$view = $this->d->execute('savePost');
$this->assertTrue(isset( $view['_savedPost']));
$this->assertEquals(':', $view['posted']);
// let's call it again with the savedPost.
$this->buildDispatcher();
$this->d->getRequest()->setRequest($saved);
$view = $this->d->execute('savePost');
$this->assertTrue(isset( $view['_savedPost']));
$this->assertEquals('tested:more', $view['posted']);
}
/**
* @test
*/
function currView_sets_views_automatically()
{
$view = $this->d->execute('currView');
$this->assertEquals('nextView', $view['_method']);
$this->assertEquals('view is tested', $view['test']);
}
// +----------------------------------------------------------------------+
}
|
asaokamei/WScore.Pages
|
tests/pages/Dispatch_FunctionTest.php
|
PHP
|
mit
| 4,875
|
<?php
mb_internal_encoding('UTF-8');
define('SQL_HOST', 'localhost');
define('SQL_USER', 'root');
define('SQL_PASS', '');
define('SQL_DB', 'books');
session_start();
$DBconnection = mysqli_connect(SQL_HOST, SQL_USER, SQL_PASS, SQL_DB);
if (!$DBconnection) {
echo 'Няма връзка с базата данни';
exit;
}
mysqli_set_charset($DBconnection, 'utf8');
function render($data,$name){
include $name;
}
function getAuthors($DBconnection) {
$q = mysqli_query($DBconnection, 'SELECT * FROM authors');
if (mysqli_error($DBconnection)) {
return false;
}
$ret = [];
while ($row = mysqli_fetch_assoc($q)) {
$ret[$row['author_id']] = $row;
}
return $ret;
}
function isAuthorIdExists($DBconnection, $ids) {
if (!is_array($ids)) {
return false;
}
$q = mysqli_query($DBconnection, 'SELECT * FROM authors WHERE
author_id IN(' . implode(',', $ids) . ')');
if (mysqli_error($DBconnection)) {
return false;
}
if (mysqli_num_rows($q) == count($ids)) {
return true;
}
return false;
}
|
Steffkn/TelerikAcademy
|
PHP/06.Views/include/functions.php
|
PHP
|
mit
| 1,131
|
var MNote = (function() {
function MNote(label) {
if (label == '' || label == null) {
label = 'Note';
}
var uiElement = document.createElement('span');
$(uiElement).addClass('MNote').css({
'transform' : MNumber.random(-8, 8)
}).html(label);
return uiElement;
};
return MNote;
})();
|
MogulMVC/MogulJS
|
src/ui/MNote.js
|
JavaScript
|
mit
| 311
|
{% extends "layout.html" %}
{% block propositionHeader %}
{% include "includes/propositional_navigation.html" %}
{% endblock %}
{% block content %}
<main id="content" role="main">
{% include "includes/main_nav.html" %}
<div class="main-content">
<h1 class="heading-large">Settings - Maintain record</h1>
{% set currentSettingsPage = 'maintainRecord' %}
{% include "includes/settings_menu.html" %}
<div class="grid-row">
<div class="column-half delete_record">
{% if data.reopenSuccessful %}
<div class="panel panel-border-wide alert-success">
Claim successfully reopened
</div>
{% endif %}
{% if data.deleteSuccessful %}
<div class="panel panel-border-wide alert-success">
Claimant successfully deleted
</div>
{% endif %}
<div class="search-box-container">
<form action="delete_record_view" method="get" class="form" id="search-form">
<label class="form-hint" for="nino">Enter a National Insurance or 12-digit reference number</label>
<input id="nino" type="search" autocomplete="off" name="nino" autofocus="autofocus" class="js-search-focus">
<input id="search-submit" type="submit" class="search-submit" value="Search"/>
</form>
</div>
</div>
</div>
</main>
{% endblock %}
|
dwpdigitaltech/ejs-prototype
|
app/views/latest/delete_record.html
|
HTML
|
mit
| 1,478
|
##[demo](http://www.gaococ.com/2048/)
|
naseeihity/LearnReact
|
Projects/Hello_JS/2048/README.md
|
Markdown
|
mit
| 37
|
/**
* @author mrdoob / http://mrdoob.com/
* @author ryg / http://farbrausch.de/~fg
* @author mraleph / http://mrale.ph/
* @author daoshengmu / http://dsmu.me/
*/
THREE.SoftwareRenderer = function ( parameters ) {
console.log( 'THREE.SoftwareRenderer', THREE.REVISION );
parameters = parameters || {};
var canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' );
var context = canvas.getContext( '2d', {
alpha: parameters.alpha === true
} );
var shaders = {};
var textures = {};
var canvasWidth, canvasHeight;
var canvasWBlocks, canvasHBlocks;
var viewportXScale, viewportYScale, viewportZScale;
var viewportXOffs, viewportYOffs, viewportZOffs;
var clearColor = new THREE.Color( 0x000000 );
var imagedata, data, zbuffer;
var numBlocks, blockMaxZ, blockFlags;
var BLOCK_ISCLEAR = (1 << 0);
var BLOCK_NEEDCLEAR = (1 << 1);
var subpixelBits = 4;
var subpixelBias = (1 << subpixelBits) - 1;
var blockShift = 3;
var blockSize = 1 << blockShift;
var maxZVal = (1 << 24); // Note: You want to size this so you don't get overflows.
var rectx1 = Infinity, recty1 = Infinity;
var rectx2 = 0, recty2 = 0;
var prevrectx1 = Infinity, prevrecty1 = Infinity;
var prevrectx2 = 0, prevrecty2 = 0;
var projector = new THREE.Projector();
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var texCoord1 = new THREE.Vector2();
var texCoord2 = new THREE.Vector2();
var texCoord3 = new THREE.Vector2();
this.domElement = canvas;
this.autoClear = true;
// WebGLRenderer compatibility
this.supportsVertexTextures = function () {};
this.setFaceCulling = function () {};
this.setClearColor = function ( color, alpha ) {
clearColor.set( color );
cleanColorBuffer();
};
this.setPixelRatio = function () {};
this.setSize = function ( width, height ) {
canvasWBlocks = Math.floor( width / blockSize );
canvasHBlocks = Math.floor( height / blockSize );
canvasWidth = canvasWBlocks * blockSize;
canvasHeight = canvasHBlocks * blockSize;
var fixScale = 1 << subpixelBits;
viewportXScale = fixScale * canvasWidth / 2;
viewportYScale = -fixScale * canvasHeight / 2;
viewportZScale = maxZVal / 2;
viewportXOffs = fixScale * canvasWidth / 2 + 0.5;
viewportYOffs = fixScale * canvasHeight / 2 + 0.5;
viewportZOffs = maxZVal / 2 + 0.5;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context.fillStyle = clearColor.getStyle();
context.fillRect( 0, 0, canvasWidth, canvasHeight );
imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight );
data = imagedata.data;
zbuffer = new Int32Array( data.length / 4 );
numBlocks = canvasWBlocks * canvasHBlocks;
blockMaxZ = new Int32Array( numBlocks );
blockFlags = new Uint8Array( numBlocks );
for ( var i = 0, l = zbuffer.length; i < l; i ++ ) {
zbuffer[ i ] = maxZVal;
}
for ( var i = 0; i < numBlocks; i ++ ) {
blockFlags[ i ] = BLOCK_ISCLEAR;
}
cleanColorBuffer();
};
this.setSize( canvas.width, canvas.height );
this.clear = function () {
rectx1 = Infinity;
recty1 = Infinity;
rectx2 = 0;
recty2 = 0;
for ( var i = 0; i < numBlocks; i ++ ) {
blockMaxZ[ i ] = maxZVal;
blockFlags[ i ] = (blockFlags[ i ] & BLOCK_ISCLEAR) ? BLOCK_ISCLEAR : BLOCK_NEEDCLEAR;
}
};
this.render = function ( scene, camera ) {
if ( this.autoClear === true ) this.clear();
var renderData = projector.projectScene( scene, camera, false, false );
var elements = renderData.elements;
for ( var e = 0, el = elements.length; e < el; e ++ ) {
var element = elements[ e ];
var material = element.material;
var shader = getMaterialShader( material );
if ( element instanceof THREE.RenderableFace ) {
if ( !element.uvs ) {
drawTriangle(
element.v1.positionScreen,
element.v2.positionScreen,
element.v3.positionScreen,
null, null, null,
shader, element, material
);
} else {
drawTriangle(
element.v1.positionScreen,
element.v2.positionScreen,
element.v3.positionScreen,
element.uvs[0], element.uvs[1], element.uvs[2],
shader, element, material
);
}
} else if ( element instanceof THREE.RenderableSprite ) {
var scaleX = element.scale.x * 0.5;
var scaleY = element.scale.y * 0.5;
vector1.copy( element );
vector1.x -= scaleX;
vector1.y += scaleY;
vector2.copy( element );
vector2.x -= scaleX;
vector2.y -= scaleY;
vector3.copy( element );
vector3.x += scaleX;
vector3.y += scaleY;
if ( material.map ) {
texCoord1.set( 0, 1 );
texCoord2.set( 0, 0 );
texCoord3.set( 1, 1 );
drawTriangle(
vector1, vector2, vector3,
texCoord1, texCoord2, texCoord3,
shader, element, material
);
} else {
drawTriangle(
vector1, vector2, vector3,
null, null, null,
shader, element, material
);
}
vector1.copy( element );
vector1.x += scaleX;
vector1.y += scaleY;
vector2.copy( element );
vector2.x -= scaleX;
vector2.y -= scaleY;
vector3.copy( element );
vector3.x += scaleX;
vector3.y -= scaleY;
if ( material.map ) {
texCoord1.set( 1, 1 );
texCoord2.set( 0, 0 );
texCoord3.set( 1, 0 );
drawTriangle(
vector1, vector2, vector3,
texCoord1, texCoord2, texCoord3,
shader, element, material
);
} else {
drawTriangle(
vector1, vector2, vector3,
null, null, null,
shader, element, material
);
}
}
}
finishClear();
var x = Math.min( rectx1, prevrectx1 );
var y = Math.min( recty1, prevrecty1 );
var width = Math.max( rectx2, prevrectx2 ) - x;
var height = Math.max( recty2, prevrecty2 ) - y;
/*
// debug; draw zbuffer
for ( var i = 0, l = zbuffer.length; i < l; i++ ) {
var o = i * 4;
var v = (65535 - zbuffer[ i ]) >> 3;
data[ o + 0 ] = v;
data[ o + 1 ] = v;
data[ o + 2 ] = v;
data[ o + 3 ] = 255;
}
*/
if ( x !== Infinity ) {
context.putImageData( imagedata, 0, 0, x, y, width, height );
}
prevrectx1 = rectx1; prevrecty1 = recty1;
prevrectx2 = rectx2; prevrecty2 = recty2;
};
function cleanColorBuffer() {
var size = canvasWidth * canvasHeight * 4;
for ( var i = 0; i < size; i+=4 ) {
data[ i ] = clearColor.r * 255 | 0;
data[ i+1 ] = clearColor.g * 255 | 0;
data[ i+2 ] = clearColor.b * 255 | 0;
data[ i+3 ] = 255;
}
context.fillStyle = clearColor.getStyle();
context.fillRect( 0, 0, canvasWidth, canvasHeight );
}
function getPalette( material, bSimulateSpecular ) {
var i = 0, j = 0;
var diffuseR = material.color.r * 255;
var diffuseG = material.color.g * 255;
var diffuseB = material.color.b * 255;
var palette = new Uint8Array(256*3);
if ( bSimulateSpecular ) {
while(i < 204) {
palette[j++] = Math.min( i * diffuseR / 204, 255 );
palette[j++] = Math.min( i * diffuseG / 204, 255 );
palette[j++] = Math.min( i * diffuseB / 204, 255 );
++i;
}
while(i < 256) { // plus specular highlight
palette[j++] = Math.min( diffuseR + (i - 204) * (255 - diffuseR) / 82, 255 );
palette[j++] = Math.min( diffuseG + (i - 204) * (255 - diffuseG) / 82, 255 );
palette[j++] = Math.min( diffuseB + (i - 204) * (255 - diffuseB) / 82, 255 );
++i;
}
} else {
while(i < 256) {
palette[j++] = Math.min( i * diffuseR / 255, 255 );
palette[j++] = Math.min( i * diffuseG / 255, 255 );
palette[j++] = Math.min( i * diffuseB / 255, 255 );
++i;
}
}
return palette;
}
function basicMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) {
var colorOffset = offset * 4;
var texture = textures[ material.map.id ];
if ( !texture.data )
return;
var tdim = texture.width;
var isTransparent = material.transparent;
var tbound = tdim - 1;
var tdata = texture.data;
var tIndex = (((v * tdim) & tbound) * tdim + ((u * tdim) & tbound)) * 4;
if ( !isTransparent ) {
buffer[ colorOffset ] = tdata[tIndex];
buffer[ colorOffset + 1 ] = tdata[tIndex+1];
buffer[ colorOffset + 2 ] = tdata[tIndex+2];
buffer[ colorOffset + 3 ] = material.opacity * 255;
depthBuf[ offset ] = depth;
}
else {
var opaci = tdata[tIndex+3] * material.opacity;
var texel = (tdata[tIndex] << 16) + (tdata[tIndex+1] << 8) + tdata[tIndex+2];
if(opaci < 250) {
var backColor = (buffer[colorOffset] << 16) + (buffer[colorOffset + 1] << 8) + buffer[colorOffset + 2];
texel = texel * opaci + backColor * (1-opaci);
}
buffer[ colorOffset ] = (texel & 0xff0000) >> 16;
buffer[ colorOffset + 1 ] = (texel & 0xff00) >> 8;
buffer[ colorOffset + 2 ] = texel & 0xff;
buffer[ colorOffset + 3 ] = material.opacity * 255;
}
}
function lightingMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) {
var colorOffset = offset * 4;
var texture = textures[ material.map.id ];
if ( !texture.data )
return;
var tdim = texture.width;
var isTransparent = material.transparent;
var cIndex = (n > 0 ? (~~n) : 0) * 3;
var tbound = tdim - 1;
var tdata = texture.data;
var tIndex = (((v * tdim) & tbound) * tdim + ((u * tdim) & tbound)) * 4;
if ( !isTransparent ) {
buffer[ colorOffset ] = (material.palette[cIndex] * tdata[tIndex]) >> 8;
buffer[ colorOffset + 1 ] = (material.palette[cIndex+1] * tdata[tIndex+1]) >> 8;
buffer[ colorOffset + 2 ] = (material.palette[cIndex+2] * tdata[tIndex+2]) >> 8;
buffer[ colorOffset + 3 ] = material.opacity * 255;
depthBuf[ offset ] = depth;
} else {
var opaci = tdata[tIndex+3] * material.opacity;
var foreColor = ((material.palette[cIndex] * tdata[tIndex]) << 16)
+ ((material.palette[cIndex+1] * tdata[tIndex+1]) << 8 )
+ (material.palette[cIndex+2] * tdata[tIndex+2]);
if(opaci < 250) {
var backColor = buffer[ colorOffset ] << 24 + buffer[ colorOffset + 1 ] << 16 + buffer[ colorOffset + 2 ] << 8;
foreColor = foreColor * opaci + backColor * (1-opaci);
}
buffer[ colorOffset ] = (foreColor & 0xff0000) >> 16;
buffer[ colorOffset + 1 ] = (foreColor & 0xff00) >> 8;
buffer[ colorOffset + 2 ] = (foreColor & 0xff);
buffer[ colorOffset + 3 ] = material.opacity * 255;
}
}
function onMaterialUpdate ( event ) {
var material = event.target;
material.removeEventListener( 'update', onMaterialUpdate );
delete shaders[ material.id ];
}
function getMaterialShader( material ) {
var id = material.id;
var shader = shaders[ id ];
if ( shaders[ id ] === undefined ) {
material.addEventListener( 'update', onMaterialUpdate );
if ( material instanceof THREE.MeshBasicMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.SpriteMaterial ) {
if ( material instanceof THREE.MeshLambertMaterial ) {
// Generate color palette
if ( !material.palette ) {
material.palette = getPalette( material, false );
}
} else if ( material instanceof THREE.MeshPhongMaterial ) {
// Generate color palette
if ( !material.palette ) {
material.palette = getPalette( material, true );
}
}
var string;
if ( material.map ) {
var texture = new THREE.SoftwareRenderer.Texture();
texture.fromImage( material.map.image );
material.map.addEventListener( 'update', function ( event ) {
texture.fromImage( event.target.image );
} );
textures[ material.map.id ] = texture;
if ( material instanceof THREE.MeshBasicMaterial
|| material instanceof THREE.SpriteMaterial ) {
shader = basicMaterialShader;
} else {
shader = lightingMaterialShader;
}
} else {
if ( material.vertexColors === THREE.FaceColors ) {
string = [
'var colorOffset = offset * 4;',
'buffer[ colorOffset ] = face.color.r * 255;',
'buffer[ colorOffset + 1 ] = face.color.g * 255;',
'buffer[ colorOffset + 2 ] = face.color.b * 255;',
'buffer[ colorOffset + 3 ] = material.opacity * 255;',
'depthBuf[ offset ] = depth;'
].join('\n');
} else {
string = [
'var colorOffset = offset * 4;',
'buffer[ colorOffset ] = material.color.r * 255;',
'buffer[ colorOffset + 1 ] = material.color.g * 255;',
'buffer[ colorOffset + 2 ] = material.color.b * 255;',
'buffer[ colorOffset + 3 ] = material.opacity * 255;',
'depthBuf[ offset ] = depth;'
].join('\n');
}
shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string );
}
} else {
var string = [
'var colorOffset = offset * 4;',
'buffer[ colorOffset ] = u * 255;',
'buffer[ colorOffset + 1 ] = v * 255;',
'buffer[ colorOffset + 2 ] = 0;',
'buffer[ colorOffset + 3 ] = 255;',
'depthBuf[ offset ] = depth;'
].join('\n');
shader = new Function( 'buffer, depthBuf, offset, depth, u, v', string );
}
shaders[ id ] = shader;
}
return shader;
}
function clearRectangle( x1, y1, x2, y2 ) {
var xmin = Math.max( Math.min( x1, x2 ), 0 );
var xmax = Math.min( Math.max( x1, x2 ), canvasWidth );
var ymin = Math.max( Math.min( y1, y2 ), 0 );
var ymax = Math.min( Math.max( y1, y2 ), canvasHeight );
var offset = ( xmin + ymin * canvasWidth ) * 4 + 3;
var linestep = ( canvasWidth - ( xmax - xmin ) ) * 4;
for ( var y = ymin; y < ymax; y ++ ) {
for ( var x = xmin; x < xmax; x ++ ) {
data[ offset += 4 ] = 0;
}
offset += linestep;
}
}
function drawTriangle( v1, v2, v3, uv1, uv2, uv3, shader, face, material ) {
// TODO: Implement per-pixel z-clipping
if ( v1.z < -1 || v1.z > 1 || v2.z < -1 || v2.z > 1 || v3.z < -1 || v3.z > 1 ) return;
// https://gist.github.com/2486101
// explanation: http://pouet.net/topic.php?which=8760&page=1
// 28.4 fixed-point coordinates
var x1 = (v1.x * viewportXScale + viewportXOffs) | 0;
var x2 = (v2.x * viewportXScale + viewportXOffs) | 0;
var x3 = (v3.x * viewportXScale + viewportXOffs) | 0;
var y1 = (v1.y * viewportYScale + viewportYOffs) | 0;
var y2 = (v2.y * viewportYScale + viewportYOffs) | 0;
var y3 = (v3.y * viewportYScale + viewportYOffs) | 0;
// Z values (.28 fixed-point)
var z1 = (v1.z * viewportZScale + viewportZOffs) | 0;
var z2 = (v2.z * viewportZScale + viewportZOffs) | 0;
var z3 = (v3.z * viewportZScale + viewportZOffs) | 0;
// UV values
var bHasUV = false;
var tu1, tv1, tu2, tv2, tu3, tv3;
if ( uv1 && uv2 && uv3 ) {
bHasUV = true;
tu1 = uv1.x;
tv1 = 1-uv1.y;
tu2 = uv2.x;
tv2 = 1-uv2.y;
tu3 = uv3.x;
tv3 = 1-uv3.y;
}
// Normal values
var bHasNormal = false;
var n1, n2, n3, nz1, nz2, nz3;
if ( face.vertexNormalsModel ) {
bHasNormal = true;
n1 = face.vertexNormalsModel[0];
n2 = face.vertexNormalsModel[1];
n3 = face.vertexNormalsModel[2];
nz1 = n1.z * 255;
nz2 = n2.z * 255;
nz3 = n3.z * 255;
}
// Deltas
var dx12 = x1 - x2, dy12 = y2 - y1;
var dx23 = x2 - x3, dy23 = y3 - y2;
var dx31 = x3 - x1, dy31 = y1 - y3;
// Bounding rectangle
var minx = Math.max( ( Math.min( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, 0 );
var maxx = Math.min( ( Math.max( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, canvasWidth );
var miny = Math.max( ( Math.min( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, 0 );
var maxy = Math.min( ( Math.max( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, canvasHeight );
rectx1 = Math.min( minx, rectx1 );
rectx2 = Math.max( maxx, rectx2 );
recty1 = Math.min( miny, recty1 );
recty2 = Math.max( maxy, recty2 );
// Block size, standard 8x8 (must be power of two)
var q = blockSize;
// Start in corner of 8x8 block
minx &= ~(q - 1);
miny &= ~(q - 1);
// Constant part of half-edge functions
var minXfixscale = (minx << subpixelBits);
var minYfixscale = (miny << subpixelBits);
var c1 = dy12 * ((minXfixscale) - x1) + dx12 * ((minYfixscale) - y1);
var c2 = dy23 * ((minXfixscale) - x2) + dx23 * ((minYfixscale) - y2);
var c3 = dy31 * ((minXfixscale) - x3) + dx31 * ((minYfixscale) - y3);
// Correct for fill convention
if ( dy12 > 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++;
if ( dy23 > 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++;
if ( dy31 > 0 || ( dy31 == 0 && dx31 > 0 ) ) c3 ++;
// Note this doesn't kill subpixel precision, but only because we test for >=0 (not >0).
// It's a bit subtle. :)
c1 = (c1 - 1) >> subpixelBits;
c2 = (c2 - 1) >> subpixelBits;
c3 = (c3 - 1) >> subpixelBits;
// Z interpolation setup
var dz12 = z1 - z2, dz31 = z3 - z1;
var invDet = 1.0 / (dx12*dy31 - dx31*dy12);
var dzdx = (invDet * (dz12*dy31 - dz31*dy12)); // dz per one subpixel step in x
var dzdy = (invDet * (dz12*dx31 - dx12*dz31)); // dz per one subpixel step in y
// Z at top/left corner of rast area
var cz = ( z1 + ((minXfixscale) - x1) * dzdx + ((minYfixscale) - y1) * dzdy ) | 0;
// Z pixel steps
var fixscale = (1 << subpixelBits);
dzdx = (dzdx * fixscale) | 0;
dzdy = (dzdy * fixscale) | 0;
var dtvdx, dtvdy, cbtu, cbtv;
if ( bHasUV ) {
// UV interpolation setup
var dtu12 = tu1 - tu2, dtu31 = tu3 - tu1;
var dtudx = (invDet * (dtu12*dy31 - dtu31*dy12)); // dtu per one subpixel step in x
var dtudy = (invDet * (dtu12*dx31 - dx12*dtu31)); // dtu per one subpixel step in y
var dtv12 = tv1 - tv2, dtv31 = tv3 - tv1;
dtvdx = (invDet * (dtv12*dy31 - dtv31*dy12)); // dtv per one subpixel step in x
dtvdy = (invDet * (dtv12*dx31 - dx12*dtv31)); // dtv per one subpixel step in y
// UV at top/left corner of rast area
cbtu = ( tu1 + (minXfixscale - x1) * dtudx + (minYfixscale - y1) * dtudy );
cbtv = ( tv1 + (minXfixscale - x1) * dtvdx + (minYfixscale - y1) * dtvdy );
// UV pixel steps
dtudx = dtudx * fixscale;
dtudy = dtudy * fixscale;
dtvdx = dtvdx * fixscale;
dtvdy = dtvdy * fixscale;
}
var dnxdx, dnzdy, cbnz;
if ( bHasNormal ) {
// Normal interpolation setup
var dnz12 = nz1 - nz2, dnz31 = nz3 - nz1;
var dnzdx = (invDet * (dnz12*dy31 - dnz31*dy12)); // dnz per one subpixel step in x
var dnzdy = (invDet * (dnz12*dx31 - dx12*dnz31)); // dnz per one subpixel step in y
// Normal at top/left corner of rast area
cbnz = ( nz1 + (minXfixscale - x1) * dnzdx + (minYfixscale - y1) * dnzdy );
// Normal pixel steps
dnzdx = (dnzdx * fixscale);
dnzdy = (dnzdy * fixscale);
}
// Set up min/max corners
var qm1 = q - 1; // for convenience
var nmin1 = 0, nmax1 = 0;
var nmin2 = 0, nmax2 = 0;
var nmin3 = 0, nmax3 = 0;
var nminz = 0, nmaxz = 0;
if (dx12 >= 0) nmax1 -= qm1*dx12; else nmin1 -= qm1*dx12;
if (dy12 >= 0) nmax1 -= qm1*dy12; else nmin1 -= qm1*dy12;
if (dx23 >= 0) nmax2 -= qm1*dx23; else nmin2 -= qm1*dx23;
if (dy23 >= 0) nmax2 -= qm1*dy23; else nmin2 -= qm1*dy23;
if (dx31 >= 0) nmax3 -= qm1*dx31; else nmin3 -= qm1*dx31;
if (dy31 >= 0) nmax3 -= qm1*dy31; else nmin3 -= qm1*dy31;
if (dzdx >= 0) nmaxz += qm1*dzdx; else nminz += qm1*dzdx;
if (dzdy >= 0) nmaxz += qm1*dzdy; else nminz += qm1*dzdy;
// Loop through blocks
var linestep = canvasWidth - q;
var scale = 1.0 / (c1 + c2 + c3);
var cb1 = c1;
var cb2 = c2;
var cb3 = c3;
var cbz = cz;
var qstep = -q;
var e1x = qstep * dy12;
var e2x = qstep * dy23;
var e3x = qstep * dy31;
var ezx = qstep * dzdx;
var etux, etvx;
if ( bHasUV ) {
etux = qstep * dtudx;
etvx = qstep * dtvdx;
}
var enzx;
if ( bHasNormal ) {
enzx = qstep * dnzdx;
}
var x0 = minx;
for ( var y0 = miny; y0 < maxy; y0 += q ) {
// New block line - keep hunting for tri outer edge in old block line dir
while ( x0 >= minx && x0 < maxx && cb1 >= nmax1 && cb2 >= nmax2 && cb3 >= nmax3 ) {
x0 += qstep;
cb1 += e1x;
cb2 += e2x;
cb3 += e3x;
cbz += ezx;
if ( bHasUV ) {
cbtu += etux;
cbtv += etvx;
}
if ( bHasNormal ) {
cbnz += enzx;
}
}
// Okay, we're now in a block we know is outside. Reverse direction and go into main loop.
qstep = -qstep;
e1x = -e1x;
e2x = -e2x;
e3x = -e3x;
ezx = -ezx;
if ( bHasUV ) {
etux = -etux;
etvx = -etvx;
}
if ( bHasNormal ) {
enzx = -enzx;
}
while ( 1 ) {
// Step everything
x0 += qstep;
cb1 += e1x;
cb2 += e2x;
cb3 += e3x;
cbz += ezx;
if ( bHasUV ) {
cbtu += etux;
cbtv += etvx;
}
if ( bHasNormal ) {
cbnz += enzx;
}
// We're done with this block line when at least one edge completely out
// If an edge function is too small and decreasing in the current traversal
// dir, we're done with this line.
if (x0 < minx || x0 >= maxx) break;
if (cb1 < nmax1) if (e1x < 0) break; else continue;
if (cb2 < nmax2) if (e2x < 0) break; else continue;
if (cb3 < nmax3) if (e3x < 0) break; else continue;
// We can skip this block if it's already fully covered
var blockX = x0 >> blockShift;
var blockY = y0 >> blockShift;
var blockId = blockX + blockY * canvasWBlocks;
var minz = cbz + nminz;
// farthest point in block closer than closest point in our tri?
if ( blockMaxZ[ blockId ] < minz ) continue;
// Need to do a deferred clear?
var bflags = blockFlags[ blockId ];
if ( bflags & BLOCK_NEEDCLEAR) clearBlock( blockX, blockY );
blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR );
// Offset at top-left corner
var offset = x0 + y0 * canvasWidth;
// Accept whole block when fully covered
if ( cb1 >= nmin1 && cb2 >= nmin2 && cb3 >= nmin3 ) {
var maxz = cbz + nmaxz;
blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz );
var cy1 = cb1;
var cy2 = cb2;
var cyz = cbz;
var cytu, cytv;
if ( bHasUV ) {
cytu = cbtu;
cytv = cbtv;
}
var cynz;
if ( bHasNormal ) {
cynz = cbnz;
}
for ( var iy = 0; iy < q; iy ++ ) {
var cx1 = cy1;
var cx2 = cy2;
var cxz = cyz;
var cxtu;
var cxtv;
if ( bHasUV ) {
cxtu = cytu;
cxtv = cytv;
}
var cxnz;
if ( bHasNormal ) {
cxnz = cynz;
}
for ( var ix = 0; ix < q; ix ++ ) {
var z = cxz;
if ( z < zbuffer[ offset ] ) {
shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material );
}
cx1 += dy12;
cx2 += dy23;
cxz += dzdx;
if ( bHasUV ) {
cxtu += dtudx;
cxtv += dtvdx;
}
if ( bHasNormal ) {
cxnz += dnzdx;
}
offset++;
}
cy1 += dx12;
cy2 += dx23;
cyz += dzdy;
if ( bHasUV ) {
cytu += dtudy;
cytv += dtvdy;
}
if ( bHasNormal ) {
cynz += dnzdy;
}
offset += linestep;
}
} else { // Partially covered block
var cy1 = cb1;
var cy2 = cb2;
var cy3 = cb3;
var cyz = cbz;
var cytu, cytv;
if ( bHasUV ) {
cytu = cbtu;
cytv = cbtv;
}
var cynz;
if ( bHasNormal ) {
cynz = cbnz;
}
for ( var iy = 0; iy < q; iy ++ ) {
var cx1 = cy1;
var cx2 = cy2;
var cx3 = cy3;
var cxz = cyz;
var cxtu;
var cxtv;
if ( bHasUV ) {
cxtu = cytu;
cxtv = cytv;
}
var cxnz;
if ( bHasNormal ) {
cxnz = cynz;
}
for ( var ix = 0; ix < q; ix ++ ) {
if ( ( cx1 | cx2 | cx3 ) >= 0 ) {
var z = cxz;
if ( z < zbuffer[ offset ] ) {
shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material );
}
}
cx1 += dy12;
cx2 += dy23;
cx3 += dy31;
cxz += dzdx;
if ( bHasUV ) {
cxtu += dtudx;
cxtv += dtvdx;
}
if ( bHasNormal ) {
cxnz += dnzdx;
}
offset++;
}
cy1 += dx12;
cy2 += dx23;
cy3 += dx31;
cyz += dzdy;
if ( bHasUV ) {
cytu += dtudy;
cytv += dtvdy;
}
if ( bHasNormal ) {
cynz += dnzdy;
}
offset += linestep;
}
}
}
// Advance to next row of blocks
cb1 += q*dx12;
cb2 += q*dx23;
cb3 += q*dx31;
cbz += q*dzdy;
if ( bHasUV ) {
cbtu += q*dtudy;
cbtv += q*dtvdy;
}
if ( bHasNormal ) {
cbnz += q*dnzdy;
}
}
}
function clearBlock( blockX, blockY ) {
var zoffset = blockX * blockSize + blockY * blockSize * canvasWidth;
var poffset = zoffset * 4;
var zlinestep = canvasWidth - blockSize;
var plinestep = zlinestep * 4;
for ( var y = 0; y < blockSize; y ++ ) {
for ( var x = 0; x < blockSize; x ++ ) {
zbuffer[ zoffset ++ ] = maxZVal;
data[ poffset ++ ] = clearColor.r * 255 | 0;
data[ poffset ++ ] = clearColor.g * 255 | 0;
data[ poffset ++ ] = clearColor.b * 255 | 0;
data[ poffset ++ ] = 255;
}
zoffset += zlinestep;
poffset += plinestep;
}
}
function finishClear( ) {
var block = 0;
for ( var y = 0; y < canvasHBlocks; y ++ ) {
for ( var x = 0; x < canvasWBlocks; x ++ ) {
if ( blockFlags[ block ] & BLOCK_NEEDCLEAR ) {
clearBlock( x, y );
blockFlags[ block ] = BLOCK_ISCLEAR;
}
block ++;
}
}
}
};
THREE.SoftwareRenderer.Texture = function() {
var canvas;
this.fromImage = function( image ) {
if( !image || image.width <= 0 || image.height <= 0 )
return;
if ( canvas === undefined ) {
canvas = document.createElement( 'canvas' );
}
var size = image.width > image.height ? image.width : image.height;
size = THREE.Math.nextPowerOfTwo( size );
if ( canvas.width != size || canvas.height != size) {
canvas.width = size;
canvas.height = size;
}
var ctx = canvas.getContext('2d');
ctx.clearRect( 0, 0, size, size );
ctx.drawImage( image, 0, 0, size, size );
var imgData = ctx.getImageData( 0, 0, size, size );
this.data = imgData.data;
this.width = size;
this.height = size;
this.srcUrl = image.src;
};
};
|
fta2012/three.js
|
examples/js/renderers/SoftwareRenderer.js
|
JavaScript
|
mit
| 26,317
|
class msvidctl_msvidaudiorendererdevices_1 {
constructor() {
// IMSVidAudioRenderer Item (Variant) {get}
this.Parameterized = undefined;
// int Count () {get}
this.Count = undefined;
}
// void Add (IMSVidAudioRenderer)
Add(IMSVidAudioRenderer) {
}
// void Remove (Variant)
Remove(Variant) {
}
}
module.exports = msvidctl_msvidaudiorendererdevices_1;
|
mrpapercut/wscript
|
testfiles/COMobjects/JSclasses/MSVidCtl.MSVidAudioRendererDevices.1.js
|
JavaScript
|
mit
| 423
|
//
// UIColor+SZGradient.h
// SZCategories
//
// Created by 陈圣治 on 16/6/21.
// Copyright © 2016年 陈圣治. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (SZGradient)
//渐变
+ (UIColor *)sz_gradientFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor withHeight:(int)height;
@end
|
chenshengzhi/SZCategories
|
SZCategories/UIKit/UIColor/UIColor+SZGradient.h
|
C
|
mit
| 325
|
/**
* Created by Administrator on 2015/1/6.
*/
var grunt = require("grunt");
var htmlConverter = require("../tasks/lib/text").init(grunt);
describe("Test JSON Converter",function(){
it("should convert JSON to cmd module",function(){
var code = JSON.stringify({test:"test",value:1,number:2.2});
var e = 'define("test",[],"{\\\"test\\\":\\\"test\\\",\\\"value\\\":1,\\\"number\\\":2.2}");';
expect(htmlConverter.html2js(code,"test")).toEqual(e);
});
it("should convert JSON file to cmd module",function(){
var src = "test/fixture/no-modifier.json";
var dest = "test/tmp/no-modifier.json";
var output = htmlConverter.htmlConverter({
src : src,
dest : dest
},{});
expect(grunt.file.read(dest+".js")).toEqual(grunt.file.read("test/expect/no-modifier.json.js"));
})
});
|
chenliangyu/grunt-seajs-converter
|
test/jsonConverterSpec.js
|
JavaScript
|
mit
| 869
|
ConvertFrom-StringData @'
###PSLOC
# Common
NoKeyFound = No Localization key found for ErrorType: '{0}'.
AbsentNotImplemented = Ensure = Absent is not implemented!
TestFailedAfterSet = Test-TargetResource returned false after calling set.
RemoteConnectionFailed = Remote PowerShell connection to Server '{0}' failed.
TODO = ToDo. Work not implemented at this time.
# SQLServer
NoDatabase = Database '{0}' does not exist on SQL server '{1}\{2}'.
SSRSNotFound = SQL Reporting Services instance {0} does not exist!
RoleNotFound = Role '{0}' does not exist on database '{1}' on SQL server '{2}\{3}'."
LoginNotFound = Login '{0}' does not exist on SQL server '{1}\{2}'."
FailedLogin = Creating a login of type 'SqlLogin' requires LoginCredential
'@
|
randorfer/RunbookExample
|
PowerShellModules/xSQLServer/1.4.0.0/en-US/xSQLServer.strings.psd1
|
PowerShell
|
mit
| 765
|
/*global jQuery:true*/
(function($, window){
"use strict";
function MaxlengthInput( el ){
var self = this;
this.el = el;
this.$el = $(el);
// prevent double init
if( this.$el.data( "MaxlengthInput" ) ){
return;
}
this.$el.data( "MaxlengthInput", this);
this.maxlength = this.$el.attr("maxlength");
this.$el
.bind("keydown", function(event){
// prevent extra text entry based on the maxlength
self.onKeydown(event);
})
.bind("paste", function(event){
// prevent extra characters in the form element from pastes
self.onPaste(event);
});
}
MaxlengthInput.allowedKeys = [
9, // Tab
27, // Escape
8, // Backspace
39, // ArrowRight
37, // ArrowLeft
38, // ArrowUp
40 // ArrowDown
];
MaxlengthInput.returnRegex = /\r\n|\n/g;
// TODO shared behavior with NumericInput
MaxlengthInput.prototype.isKeyAllowed = function( event ) {
var isAllowed = false, key = event.keyCode;
// indexOf not supported everywhere for arrays
$.each(MaxlengthInput.allowedKeys, function(i, e){
if( e === key ) {
isAllowed = true;
}
});
return event.altKey || event.ctrlKey || event.metaKey || isAllowed;
};
MaxlengthInput.prototype.onKeydown = function( event ){
var self = this;
if( this.isKeyAllowed( event ) ){
return;
}
// if any character would put us at the
if(this.valueLength() >= this.maxlength){
event.preventDefault();
return;
}
// if the user hits return and that would put the length above
// the max, prevent the return character addition
if(event.keyCode == 13 && this.valueLength() + 2 > this.maxlength){
event.preventDefault();
return;
}
setTimeout(function(){
self.alterValue();
});
};
MaxlengthInput.prototype.alterValue = function(){
var newValue = this.el
.value
.replace(MaxlengthInput.returnRegex, "\r\n")
.slice(0, this.maxlength);
return this.el.value = newValue;
};
MaxlengthInput.prototype.onPaste = function( e ){
var self = this;
// force the text to look right after the paste has applied
setTimeout(function(){
self.alterValue();
});
};
MaxlengthInput.prototype.valueLength = function(check){
return (check || this.el.value)
.replace(MaxlengthInput.returnRegex, "__")
.length;
};
window.MaxlengthInput = MaxlengthInput;
}(jQuery, this));
|
filamentgroup/formcore
|
js/maxlength-input.js
|
JavaScript
|
mit
| 2,335
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SVPMigrator.Old
{
using System;
using System.Collections.Generic;
public partial class group
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public group()
{
this.members = new HashSet<member>();
}
public int id { get; set; }
public string name { get; set; }
public int competition_id { get; set; }
public int participant_id { get; set; }
public virtual competition competition { get; set; }
public virtual participant participant { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<member> members { get; set; }
}
}
|
chschenk/SVP
|
SVPMigrator/Old/group.cs
|
C#
|
mit
| 1,274
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W29086_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="page32.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 0px; margin-top: 0px;">
<img src="images/tmp2u83Lr.png" alt="tmp2u83Lr.png" />
</div>
</body>
</html>
|
datamade/elpc_bakken
|
ocr_extracted/W29086_text/page33.html
|
HTML
|
mit
| 693
|
<p>Home site</p>
|
karin112358/Samples
|
AngularJS/SnapSvgAndHtml5Mode/components/home/home.html
|
HTML
|
mit
| 19
|
namespace Noikoio.RegexBot.ConfigItem
{
enum EntityType { Channel, Role, User }
/// <summary>
/// Used to join together an entity ID and its name when read from configuration.
/// In configuration, entities are fully specified with a prefix (if necessary), an ID, two colons, and a name.
/// An EntityName struct can have either an ID, Name, or both. It cannot have neither.
/// </summary>
struct EntityName
{
private readonly ulong? _id;
private readonly string _name;
private readonly EntityType _type;
public ulong? Id => _id;
public string Name => _name;
public EntityType Type => _type;
/// <summary>
/// Creates a new EntityItem instance
/// </summary>
/// <param name="input">Input text WITHOUT the leading prefix. It must be stripped beforehand.</param>
/// <param name="t">Type of this entity. Should be determined by the input prefix.</param>
public EntityName(string input, EntityType t)
{
_type = t;
// Check if input contains both ID and label
int separator = input.IndexOf("::");
if (separator != -1)
{
_name = input.Substring(separator + 2, input.Length - (separator + 2));
if (ulong.TryParse(input.Substring(0, separator), out var id))
{
_id = id;
}
else
{
// Failed to parse ID. Assuming the actual name includes our separator.
_id = null;
_name = input;
}
}
else
{
// Input is either only an ID or only a name
if (ulong.TryParse(input, out var id))
{
_id = id;
_name = null;
}
else
{
_name = input;
_id = null;
}
}
}
public override string ToString()
{
string prefix;
if (_type == EntityType.Channel) prefix = "#";
else if (_type == EntityType.User) prefix = "@";
else prefix = "";
if (_id.HasValue && _name != null)
{
return $"{prefix}{Id}::{Name}";
}
if (_id.HasValue)
{
return $"{prefix}{Id}";
}
return $"{prefix}{Name}";
}
}
}
|
Noikoio/RegexBot
|
RegexBot/ConfigItem/EntityName.cs
|
C#
|
mit
| 2,592
|
```jsx
const { Button, ButtonGroup } = require('react-bootstrap');
const { SwButton } = require('./button');
class SandboxButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.setSize = this.setSize.bind(this);
this.togglePending = this.togglePending.bind(this);
this.state = {
events: [],
pending: false,
size: undefined,
};
}
render() {
return (
<div>
<ButtonGroup>
{['xs', 'sm', undefined, 'lg'].map(size => (
<Button
bsStyle={this.state.size === size ? 'primary' : 'default'}
key={String(size)}
onClick={this.setSize(size)}
>
{String(size)}
</Button>
))}
</ButtonGroup>
<Button onClick={this.togglePending} style={{ marginLeft: '20px' }}>
Toggle pending <code>{this.state.pending ? 'true' : 'false'}</code>
</Button>
<hr />
<SwButton
bsSize={this.state.size}
bsStyle="danger"
onClick={this.handleClick}
pending={this.state.pending}
>
click me!
</SwButton>
<hr />
{this.state.events.length > 0 ? <pre>{this.state.events.join('\n')}</pre> : null}
</div>
);
}
handleClick() {
this.setState(({ events }) => ({ events: events.concat('clicked') }));
}
setSize(size) {
return () => {
this.setState({ size });
};
}
togglePending() {
this.setState(({ pending }) => ({ pending: !pending }));
}
}
<SandboxButton />
```
|
samwise-tech/components
|
src/input/button/example.md
|
Markdown
|
mit
| 1,643
|
{{/*
{{% button href="https://getgrav.org/" %}}Get Grav{{% /button %}}
{{% button href="https://getgrav.org/" icon="fa-play" %}}Get Grav with awesome icon{{% /button %}}
*/}}
<a {{ with .Get "href"}} href="{{.}}" target="_blank" {{ end }}
class="button {{ with.Get "icon"}}icon {{.}}{{end}}">
{{ .Inner }}
</a>
|
tattwamasi/hugo-guild-theme
|
layouts/shortcodes/button.html
|
HTML
|
mit
| 315
|
<?php
/**
* Part of the kurobuta.jp.
*
* Copyright (c) 2015 Maemori Fumihiro
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*
* @version 1.0
* @author Maemori Fumihiro
* @link https://kurobuta.jp
*/
namespace Accon;
/**
* Class Library_Utility
*/
class Library_Utility
{
/**
* 文字列を区切り文字で配列化
*
* @param string $str
* @return array
*/
public static function replace($str = ''){
$delimiter = array(" ", ",", ".", "'", "\"", "|", "\\", "/", ";", ":");
$replace = str_replace($delimiter, $delimiter[0], $str);
$array = array_values(array_filter(explode($delimiter[0], $replace)));
foreach ($array as $key => $value) {
$array[$key] = trim($value);
}
return $array;
}
/**
* 文字列を区切り文字で分割しシリアライズする
*
* @param string $var
* @param bool $reverse true:keyとvalを反転
* @return string
*/
public static function serialize($var = '', $reverse = false)
{
if (empty($var)) return $var;
$serialize_data = self::replace($var);
if ($reverse) $serialize_data = array_flip($serialize_data);
return serialize($serialize_data);
}
/**
* シリアライズされた文字列をカンマ区切りの文字列に変換
*
* @param string $var
* @param bool $reverse true:keyとvalを反転
* @return string
*/
public static function un_serialize($var = '', $reverse = false)
{
if (empty($var)) return $var;
$un_serialize_data = unserialize(htmlspecialchars_decode($var));
if ($reverse) $un_serialize_data = array_flip($un_serialize_data);
foreach ($un_serialize_data as $key => $value) {
$un_serialize_data[$key] = trim($value);
}
if (isset($un_serialize_data)) $var = implode(', ', $un_serialize_data);
return $var;
}
/**
* 指定された文字数で文字列を後方から、その文字数だけ表示する
*
* @param $str
* @param $width
* @return string
*/
public static function omit_character_behind($str, $width, $trim_marker = '...')
{
if (strlen($str) >= $width){
return $trim_marker.substr($str, (-1)*$width);
}
return $str;
}
}
|
maemori/accon
|
fuel/app/modules/accon/classes/library/utility.php
|
PHP
|
mit
| 2,179
|
#ifndef GL_HELPER_H
#define GL_HELPER_H
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "SOIL.h"
#include <map>
#include <string>
#include <iostream>
using namespace std;
class gl_helper
{
private:
/****************************************************************
public
****************************************************************/
public:
gl_helper()
{
}
~gl_helper()
{
}
// Draws a texture onto a simple square by using 2 triangles.
// Inputs:
// texture: Given texture.
// tx: Translation in x.
// ty: Translation in y.
// x:
// y:
// xw:
// yh:
static void draw_texture(GLuint texture, double tx, double ty, int x, int y, int xw, int yh)
{
glPushMatrix();
glTranslatef(tx,ty,0.f);
glBindTexture(GL_TEXTURE_2D,texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glBegin(GL_TRIANGLES);
glTexCoord2f(0.0f, 0.0f); glVertex2i(x,y);
glTexCoord2f(1.0f, 0.0f); glVertex2i(xw,y);
glTexCoord2f(1.0f, 1.0f); glVertex2i(xw,yh);
glTexCoord2f(0.0f, 0.0f); glVertex2i(x,y);
glTexCoord2f(0.0f, 1.0f); glVertex2i(x,yh);
glTexCoord2f(1.0f, 1.0f); glVertex2i(xw,yh);
glEnd();
glPopMatrix();
}
// Draws a quad.
// Inputs:
// tx: Translation in x.
// ty: Translation in y.
// x:
// y:
// xw:
// yh:
// color: Static array of 3 specifying the color.
static void draw_quad(double tx, double ty, int x, int y, int xw, int yh, float color[3])
{
glPushMatrix();
glBindTexture(GL_TEXTURE_2D,0);
glTranslatef(tx,ty,0.f);
glLineWidth(1.f);
glColor3f(color[0],color[1],color[2]);
glBegin(GL_QUADS);
glVertex2i(xw,yh);
glVertex2i(xw,y);
glVertex2i(x,y);
glVertex2i(x,yh);
glEnd();
glPopMatrix();
}
};
#endif /* GL_HELPER_H */
|
xforns/kitxen-wars
|
x86_64/src/gl_helper.h
|
C
|
mit
| 1,890
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
namespace ForEvolve.DynamicInternalServerError.TestWebServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// Add DynamicInternalServerError
services.AddDynamicInternalServerError();
// Add framework services.
services.AddMvc(options =>
{
options.ConfigureDynamicInternalServerError();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
|
ForEvolve/DynamicInternalServerError
|
test/ForEvolve.DynamicInternalServerError.TestWebServer/Startup.cs
|
C#
|
mit
| 1,519
|
<?php
/**
* Template part for top bar menu
*
* @package WordPress
* @subpackage FoundationPress
* @since FoundationPress 1.0.0
*/
?>
<br>
<div class="top-bar-container contain-to-grid show-for-medium-up">
<div class="title-area row show-for-large-up">
<div class="name large-6 large-centered columns">
<div class="row show-for-large-up" style="height: 20px;"></div>
<h1 class="large-10 large-centered columns">
<a href="<?php echo home_url(); ?>">
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="<?php bloginfo( 'name' ); ?>" /> </a>
</h1>
</div>
</div>
<div class="sticky">
<nav class="top-bar row" data-topbar role="navigation">
<section class="top-bar-section medium-12 columns">
<?php foundationpress_top_bar_c(); ?>
</section>
</nav>
</div>
</div>
|
esm-erika/eSchoolNews
|
wp-content/themes/ecampusnews/parts/top-bar.php
|
PHP
|
mit
| 1,106
|
module RoxClient
class Project
# TODO: remove project name once API v0 is dead
attr_accessor :name, :version, :api_id, :category, :tags, :tickets
def initialize options = {}
update options
end
def update options = {}
%w(name version api_id category).each do |k|
instance_variable_set "@#{k}", options[k.to_sym] ? options[k.to_sym].to_s : nil if options.key? k.to_sym
end
@tags = wrap(options[:tags]).compact if options.key? :tags
@tickets = wrap(options[:tickets]).compact if options.key? :tickets
end
def validate!
required = { "version" => @version, "API identifier" => @api_id }
missing = required.inject([]){ |memo,(k,v)| v.to_s.strip.length <= 0 ? memo << k : memo }
raise PayloadError.new("Missing project options: #{missing.join ', '}") if missing.any?
end
private
def wrap a
a.kind_of?(Array) ? a : [ a ]
end
end
end
|
lotaris/rox-client-ruby
|
lib/rox-client-ruby/project.rb
|
Ruby
|
mit
| 941
|
/*
* SeriouslyConstants.h
* Seriously
*
* Created by Corey Johnson on 7/6/10.
* Copyright 2010 Probably Interactive. All rights reserved.
*
*/
@class SeriouslyOperation;
@class SeriouslyOAuthOperation;
typedef void(^SeriouslyHandler)(id data, NSHTTPURLResponse *response, NSError *error);
typedef void(^SeriouslyProgressHandler)(float progress, double downloadSpeed, NSTimeInterval secondsRemaining, NSData *data);
extern const NSString *kSeriouslyMethod;
extern const NSString *kSeriouslyTimeout;
extern const NSString *kSeriouslyHeaders;
extern const NSString *kSeriouslyBody;
extern const NSString *kSeriouslyProgressHandler;
extern const NSString *kSeriouslyCachePolicy;
extern const NSString *kSeriouslyPostDictionary;
|
probablycorey/seriously
|
src/SeriouslyConstants.h
|
C
|
mit
| 738
|
'use strict';
// This file is auto-generated using scripts/doc-sync.js
/**
* Visible page viewport
*
* @param {number} scrollX X scroll offset in CSS pixels.
* @param {number} scrollY Y scroll offset in CSS pixels.
* @param {number} contentsWidth Contents width in CSS pixels.
* @param {number} contentsHeight Contents height in CSS pixels.
* @param {number} pageScaleFactor Page scale factor.
* @param {number} minimumPageScaleFactor Minimum page scale factor.
* @param {number} maximumPageScaleFactor Maximum page scale factor.
*/
exports.Viewport =
function Viewport(props) {
this.scrollX = props.scrollX;
this.scrollY = props.scrollY;
this.contentsWidth = props.contentsWidth;
this.contentsHeight = props.contentsHeight;
this.pageScaleFactor = props.pageScaleFactor;
this.minimumPageScaleFactor = props.minimumPageScaleFactor;
this.maximumPageScaleFactor = props.maximumPageScaleFactor;
};
|
buggerjs/bugger
|
lib/agents/emulation/types.js
|
JavaScript
|
mit
| 941
|
require 'autoprefixer-rails'
require 'weui-rails/version'
require 'weui-rails/helpers/weui_message_box'
module Weui
module Rails
class Engine < ::Rails::Engine
end
# Make Weui helpers available in Rails applications.
class Railtie < ::Rails::Railtie
initializer 'weui.add_helpers' do
ActionView::Base.send :include, Weui::Helpers
end
end
end
end
|
Eric-Guo/weui-rails
|
lib/weui-rails.rb
|
Ruby
|
mit
| 392
|
version https://git-lfs.github.com/spec/v1
oid sha256:3027fc57c3d0f37949a71c0e7f6cecae9198b13aa8ac666d1a752323b776547f
size 97712
|
yogeshsaroya/new-cdnjs
|
ajax/libs/angular.js/1.2.0rc3/angular.min.js
|
JavaScript
|
mit
| 130
|
---
layout: default
title: Case Sensitivity
categories: docs
# parent: Docs
nav_order: 4
---
# Case Sensitivity
The spell checker supports case sensitive checking. By default it is turned off.
Because the spell checker was originally case insensitive, making it case aware takes care so as to not break things. CSpell `5.x` introduced the `caseSensitive` setting to allow checking case.
**Note:** Not all dictionaries are currently case aware, so in those cases, lower case words are allowed.
## Always Enable Case Sensitive Checking
**Note:** this might create a lot of false issues in code files.
**Global Enable: `cspell.json`**
```js
{
"caseSensitive": true
}
```
## By File Type
It can be enabled per file type.
The following configuration will turn on case sensitivity for `markdown` files.
**`cspell.json`**
```js
"languageSettings": [
{
"languageId": "markdown",
"caseSensitive": true
}
]
```
## By Glob Pattern
**`cspell.json`**
```js
"overrides": [
{
// Case sensitive markdown in the docs folder
"filename": "docs/**/*.md",
"caseSensitive": true
}
]
```
|
Jason3S/cspell
|
docs/docs/case-sensitive.md
|
Markdown
|
mit
| 1,111
|
# -*- coding: utf-8 -*-
import sys
import time
from subprocess import call
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class Raspistill(Sensor):
def __init__(self):
super(Raspistill, self).__init__()
# ISO100
iso100MetaData = MetaData('ISO100')
iso100MetaData.setValueCallback(self.getIso100)
iso100MetaData.setUnitCallback(self.getUnit)
self.addMetaData(iso100MetaData)
# ISO200
iso200MetaData = MetaData('ISO200')
iso200MetaData.setValueCallback(self.getIso200)
iso200MetaData.setUnitCallback(self.getUnit)
self.addMetaData(iso200MetaData)
# ISO400'
iso400MetaData = MetaData('ISO400')
iso400MetaData.setValueCallback(self.getIso400)
iso400MetaData.setUnitCallback(self.getUnit)
self.addMetaData(iso400MetaData)
# ISO800'
iso800MetaData = MetaData('ISO800')
iso800MetaData.setValueCallback(self.getIso800)
iso800MetaData.setUnitCallback(self.getUnit)
self.addMetaData(iso800MetaData)
def getIso100(self):
filename = "photos/" + str(time.time()) + "-iso100.jpg"
call(["raspistill", "--ISO", "100", "-o", filename])
return str(filename)
def getIso200(self):
filename = "photos/" + str(time.time()) + "-iso200.jpg"
call(["raspistill", "--ISO", "200", "-o", filename])
return str(filename)
def getIso400(self):
filename = "photos/" + str(time.time()) + "-iso400.jpg"
call(["raspistill", "--ISO", "400", "-o", filename])
return str(filename)
def getIso800(self):
filename = "photos/" + str(time.time()) + "-iso800.jpg"
call(["raspistill", "--ISO", "800", "-o", filename])
return str(filename)
def getUnit(self):
return " Photo"
def getMetaData(self):
return super(Raspistill, self).getMetaData()
|
OpenSpaceProgram/pyOSP
|
library/sensors/Raspistill.py
|
Python
|
mit
| 2,060
|
using System;
using System.Management.Automation;
using System.Net;
using System.Security;
namespace PowerShellExecutionSample
{
class Program
{
static void Main(string[] args)
{
PowerShellExecutor t = new PowerShellExecutor();
t.ExecuteSynchronously();
}
}
class PowerShellExecutor
{
public void ExecuteSynchronously()
{
bool useServicePrincipal = false;
using (PowerShell ps = PowerShell.Create())
{
var aasEnv = "contosoregion.asazure.windows.net";
var aasServer = "contosoaas";
var aasDB = "contosodb";
var role = "contosoRead";
var user2Add = "joe@contoso.com";
var tenantId = "contoso azure ad tenant id"; //only needed for service principal
var adminuser = useServicePrincipal ?
"contoso service principal" :
"admin@contoso.com";
// put password in a secure store in production, for example Azure Key Vault
var adminpwd = System.IO.File.ReadAllText(@"c:\users\admin\secret.txt");
var aasURL = "asazure://" + aasEnv + "/" + aasServer;
SecureString securepwd = new NetworkCredential("", adminpwd).SecurePassword;
PSCredential cred = new PSCredential(adminuser, securepwd);
if (useServicePrincipal)
{
ps.AddScript("Import-Module Azure.AnalysisServices")
.AddStatement()
.AddCommand("Add-AzureAnalysisServicesAccount")
.AddParameter("ServicePrincipal")
.AddParameter("TenantId", tenantId)
.AddParameter("RolloutEnvironment", aasEnv)
.AddParameter("Credential", cred)
.AddStatement()
.AddScript("Import-Module SqlServer")
.AddStatement()
.AddCommand("Add-RoleMember")
.AddParameter("Server", aasURL)
.AddParameter("Database", aasDB)
.AddParameter("RoleName", role)
.AddParameter("MemberName", user2Add)
.Invoke();
}
else
{
ps.AddScript("Import-Module SqlServer")
.AddStatement()
.AddCommand("Add-RoleMember")
.AddParameter("Server", aasURL)
.AddParameter("Database", aasDB)
.AddParameter("RoleName", role)
.AddParameter("MemberName", user2Add)
.AddParameter("Credential", cred)
.Invoke();
}
if (ps.Streams.Error.Count > 0)
{
Console.WriteLine(ps.Streams.Error[0].Exception.InnerException.Message);
}
}
}
}
}
|
liupeirong/Azure
|
DotNetAnalysisService/AASAddRoleMember/Program.cs
|
C#
|
mit
| 3,151
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Axiinput.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UseKeyboard {
get {
return ((bool)(this["UseKeyboard"]));
}
set {
this["UseKeyboard"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UseMouse {
get {
return ((bool)(this["UseMouse"]));
}
set {
this["UseMouse"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8128")]
public ushort DefaultPort {
get {
return ((ushort)(this["DefaultPort"]));
}
set {
this["DefaultPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("14")]
public ushort PoolingInterval {
get {
return ((ushort)(this["PoolingInterval"]));
}
set {
this["PoolingInterval"] = value;
}
}
}
}
|
nejclesek/Axiinput
|
Axiinput/Properties/Settings.Designer.cs
|
C#
|
mit
| 2,786
|
var myWindow = {
screenX: window.screenX,
screenY: window.screenY,
location: window.location.pathname,
screenW: window.screen.width,
screenZ: window.screen.height,
render: function() {
var ele = document.getElementById("location");
ele.value = this.location;
ele = document.getElementById("sx");
ele.value = this.screenX;
ele = document.getElementById("sy");
ele.value = this.screenY;
ele = document.getElementById("sw");
ele.value = this.screenW;
ele = document.getElementById("sz");
ele.value = this.screenZ;
}
};
myWindow.render();
|
smokeylee/ITE220
|
Week3/js/window-example.js
|
JavaScript
|
mit
| 568
|
import { module, test } from 'qunit';
import { setupApplicationTest } from 'travis/tests/helpers/setup-application-test';
import jobPage from 'travis/tests/pages/job';
import topPage from 'travis/tests/pages/top';
import signInUser from 'travis/tests/helpers/sign-in-user';
import { enableFeature } from 'ember-feature-flags/test-support';
import { percySnapshot } from 'ember-percy';
import { setupMirage } from 'ember-cli-mirage/test-support';
module('Acceptance | jobs/debug', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
test('debugging job', async function (assert) {
enableFeature('debugBuilds');
const currentUser = this.server.create('user', { confirmed_at: Date.now() });
this.server.create('allowance', {subscription_type: 1});
this.server.create('user', {login: 'travis-ci'});
this.server.create('allowance', {subscription_type: 1});
signInUser(currentUser);
let repo = this.server.create('repository', { slug: 'travis-ci/travis-web', private: true, owner: { login: 'travis-ci', id: 1 } });
let branch = this.server.create('branch', { name: 'acceptance-tests' });
let gitUser = this.server.create('git-user', { name: 'Mr T' });
let commit = this.server.create('commit', { author: gitUser, committer: gitUser, branch: 'acceptance-tests', message: 'This is a message', branch_is_default: true });
let build = this.server.create('build', { repository: repo, state: 'failed', commit, branch });
let job = this.server.create('job', { number: '1234.1', repository: repo, state: 'failed', commit, build });
commit.job = job;
job.save();
commit.save();
this.server.create('log', { id: job.id });
const requestBodies = [];
this.server.post(`/job/${job.id}/debug`, function (schema, request) {
const parsedRequestBody = JSON.parse(request.requestBody);
requestBodies.push(parsedRequestBody);
});
await jobPage
.visit()
.debugJob();
assert.deepEqual(requestBodies.pop(), { quiet: true });
assert.equal(topPage.flashMessage.text, 'The job was successfully restarted in debug mode but make sure to watch the log for a host to connect to.');
percySnapshot(assert);
});
});
|
travis-ci/travis-web
|
tests/acceptance/job/debug-test.js
|
JavaScript
|
mit
| 2,230
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><defs><style>.b{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:2px;}</style></defs><title>ran</title><path class="b" d="M269.72,618a11,11,0,1,1-15.54,0A11,11,0,0,1,269.72,618Z" transform="translate(-249.97 -613.79)"/><line class="b" x1="19.97" y1="19.94" x2="31" y2="31"/><line class="b" x1="17.01" y1="11.99" x2="7.51" y2="11.99"/><line class="b" x1="12.26" y1="7.24" x2="12.26" y2="16.74"/></svg>
|
baillieo/baillieo.github.io
|
_includes/icons/icon-zoom.html
|
HTML
|
mit
| 489
|
{-# LANGUAGE OverloadedStrings,NoImplicitPrelude #-}
module TypePlay.Infer.HM where
import Prelude hiding (map,concat)
import Data.List (map,concat,nub,union,intersect)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Monoid ((<>),mconcat)
type Id = Text
enumId :: Int -> Id
enumId = ("v" <>) . T.pack . show
data Kind
= Star
| Kfun Kind Kind
deriving (Eq,Show)
data Type
= TVar Tyvar
| TCon Tycon
| TAp Type Type
| TGen Int
deriving (Eq,Show)
data Tyvar = Tyvar Id Kind
deriving (Eq,Show)
data Tycon = Tycon Id Kind
deriving (Eq,Show)
type Subst = [(Tyvar, Type)]
data InferenceErr
= SubstMerge
| Unification Type Type
| DoesNotOccur Tyvar [Tyvar]
| KindsDontMatch Kind Kind
| TypesDontMatch Type Type
| ClassMisMatch Id Id
| NoSuperClassFound Id
| NoInstancesOfClass Id
type Infer a = Either InferenceErr a
instance Show InferenceErr where
show SubstMerge = "Substitution Merge Failed"
show (Unification t1 t2)
= "Unable to unify" <> show t1 <> " with " <> show t2
show (DoesNotOccur tv t)
= show t <> " not found in " <> show tv
show (KindsDontMatch k1 k2)
= mconcat
[ "Incorrect Kind.\n Found ("
, show k1
, ").\nExpected ("
, show k2
]
show (TypesDontMatch t t')
= mconcat
[ "Could not match types:\n"
, show t
, " with "
, show t'
]
show (ClassMisMatch i i')
= mconcat
[ "Type Classes differ.\n Found("
, show i
, "). Expected ("
, show i'
, ")."
]
show (NoSuperClassFound i)
= mconcat
[ "No type class matching: "
, show i
, " found."
]
show (NoInstancesOfClass i)
= mconcat
[ "No instances of "
, show i
, " found in current environment."
]
typeConst :: Text -> Kind -> Type
typeConst i = TCon . Tycon i
tUnit = typeConst "()" Star
tChar = typeConst "Char" Star
tInt = typeConst "Int" Star
tInteger = typeConst "Integer" Star
tFloat = typeConst "Float" Star
tDouble = typeConst "Double" Star
tList = typeConst "[]" $ Kfun Star Star
tArrow = typeConst "(->)" $ Kfun Star $ Kfun Star Star
tTuple2 = typeConst "(,)" $ Kfun Star $ Kfun Star Star
tString :: Type
tString = list tChar
infixr 4 `fn`
fn :: Type -> Type -> Type
a `fn` b = TAp (TAp tArrow a) b
list :: Type -> Type
list = TAp tList
pair :: Type -> Type -> Type
pair a b = TAp (TAp tTuple2 a) b
class HasKind t where
kind :: t -> Kind
instance HasKind Tyvar where
kind (Tyvar v k) = k
instance HasKind Tycon where
kind (Tycon v k) = k
instance HasKind Type where
kind (TCon tc) = kind tc
kind (TVar u) = kind u
kind (TAp t _) = case kind t of
(Kfun _ k) -> k
nullSubst :: Subst
nullSubst = []
(+->) :: Tyvar -> Type -> Subst
u +-> t = [(u,t)]
class Types t where
apply :: Subst -> t -> t
tv :: t -> [Tyvar]
instance Types Type where
apply s (TVar u) = case lookup u s of
Just t -> t
Nothing -> TVar u
apply s (TAp l r) = TAp (apply s l) (apply s r)
apply s t = t
tv (TVar u) = [u]
tv (TAp l r) = tv l `union` tv r
tv t = []
instance Types a => Types [a] where
apply s = fmap (apply s)
tv = nub . concat . fmap tv
infixr 4 @@
(@@) :: Subst -> Subst -> Subst
s1 @@ s2 = [ (u, apply s1 t) | (u,t) <- s2] <> s1
merge :: Subst -> Subst -> Infer Subst
merge s1 s2 = if agree
then Right $ s1 <> s2
else Left SubstMerge
where
agree = all (\v -> apply s1 (TVar v) == apply s2 (TVar v))
(gFst s1 `intersect` gFst s2)
gFst = fmap fst
mgu :: Type -> Type -> Infer Subst
mgu (TAp l r) (TAp l' r') = do
s1 <- mgu l l'
s2 <- mgu (apply s1 r) (apply s1 r')
return $ s2 @@ s1
mgu (TVar u) t = varBind u t
mgu t (TVar u) = varBind u t
mgu (TCon tc1) (TCon tc2)
| tc1 == tc2 = return nullSubst
mgu t1 t2 = Left $ Unification t1 t2
varBind :: Tyvar -> Type -> Infer Subst
varBind u t
| t == TVar u = return nullSubst
| u `elem` tv t = Left $ DoesNotOccur u $ tv t
| kind u /= kind t = Left $ KindsDontMatch (kind u) (kind t)
| otherwise = return $ u +-> t
match :: Type -> Type -> Infer Subst
match (TAp l r) (TAp l' r') = do
sl <- match l l'
sr <- match r r'
merge sl sr
match (TVar u) t
| kind u == kind t = return $ u +-> t
match (TCon tcl) (TCon tcr)
| tcl == tcr = return nullSubst
match t1 t2 = Left $ TypesDontMatch t1 t2
-- Type Classes
data Qual t = [Pred] :=> t
deriving (Show,Eq)
data Pred = IsIn Id Type
deriving (Show,Eq)
-- Example 'Num a => a -> Int'
-- [IsIn "Num" (TVar (Tyvar "a" Star))]
-- :=> (TVar (Tyvar "a" Star) 'fn' tInt)
instance Types t => Types (Qual t) where
apply s (ps :=> t) = apply s ps :=> apply s t
tv (ps :=> t) = tv ps `union` tv t
instance Types Pred where
apply s (IsIn i t) = IsIn i (apply s t)
tv (IsIn i t) = tv t
mguPred :: Pred -> Pred -> Infer Subst
mguPred = lift mgu
matchPred :: Pred -> Pred -> Infer Subst
matchPred = lift match
lift
:: (Type -> Type -> Infer b)
-> Pred
-> Pred
-> Infer b
lift m (IsIn i t) (IsIn i' t')
| i == i' = m t t'
| otherwise = Left $ ClassMisMatch i i'
type Class = ([Id], [Inst])
type Inst = Qual Pred
data ClassEnv = ClassEnv
{ classes :: Id -> Maybe Class
, defaults :: [Type]
}
super :: ClassEnv -> Id -> Infer [Id]
super ce i = case classes ce i of
Just (is, its) -> return is
Nothing -> Left $ NoSuperClassFound i
insts :: ClassEnv -> Id -> Infer [Inst]
insts ce i = case classes ce i of
Just (is, its) -> return its
Nothing -> Left $ NoInstancesOfClass i
modify :: ClassEnv -> Id -> Class -> ClassEnv
modify ce i c = ce { classes = \j -> if i == j
then Just c
else classes ce j
}
initialEnv :: ClassEnv
initialEnv = ClassEnv { classes = \i -> Nothing
, defaults = [tInteger, tDouble]
}
|
mankyKitty/TypePlay
|
src/TypePlay/Infer/HM.hs
|
Haskell
|
mit
| 6,014
|
var net = require('net');
var HOST = '128.197.50.236';
var PORT = 55000;
var n=1;
var client = new net.Socket();
var RollingSpider = new require('rolling-spider');
var quad = new RollingSpider({
logger: console.log
});
var flying = false;
var inFlip = false;
var land = false;
var count=0;
var prevControls;
quad.connect(function(err) {
if (err) console.log(err);
quad.setup(function(err) {
if (err) console.log(err);
quad.flatTrim();
quad.startPing();
quad.flatTrim();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
// client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
if (data == 3 && flying == false){
quad.flatTrim();
quad.takeoff();
console.log('takeoff');
flying = true;
count=0;
}
else if (data == 2 && flying==true && count<3){
count=count+1;
}
else if (data == 2 && flying== true && count >= 3){
quad.land();
flying = false;
console.log('landing');
count=0;
}
else if (data == 6 && flying== true && inFlip == false){
inFlip = true;
quad.frontFlip(flipDone);
console.log('frontflip');
count=0;
}
else if (data == 11 && flying== true && inFlip == false){
inFlip = true;
quad.backFlip(flipDone);
console.log('backflip');
count=0;
}
else quad.hover();
// Close the client socket completely
//client.destroy();
});
});
});
function flipDone() {
inFlip = false;
}
// Add a 'clos joystick.on('data', function(buf) {
/* var controls = parseControls(buf);
if (!prevControls)
prevControls = controls;
if (prevControls.buttons[0] === 0 && controls.buttons[0] === 1) {
if (flying) {
quad.land();
flying = false;
} else {
quad.flatTrim();
quad.takeoff();
flying = true;
}
}
if (prevControls.view === 8 && controls.view !== 8)
switch (controls.view) {
case 0:
inFlip = true;
quad.frontFlip(flipDone);
break;
case 2:
inFlip = true;
quad.rightFlip(flipDone);
break;
case 4:
inFlip = true;
quad.backFlip(flipDone);
break;
case 6:
inFlip = true;
quad.leftFlip(flipDone);
break;
}
prevControls = controls;
if (flying && !inFlip) {
if (controls.buttons[1]) {
quad.driveStepsRemaining = 1;
quad.speeds = {
yaw: 100 * (controls.yaw - 128) / 128,
pitch: -100 * (controls.pitch - 512) / 512,
roll: 100 * (controls.roll - 512) / 512,
altitude: 100 * (controls.throttle - 128) / 128
}
} else quad.hover();
}
// console.log(JSON.stringify(controls));
});
joystick.on('error', function() {
quad.land();
});
});
});
function flipDone() {
inFlip = false;
}
function parseControls(buf) {
var ch = buf.toString('hex').match(/.{1,2}/g).map(function(c) {
return parseInt(c, 16);
});
return {
roll: ((ch[1] & 0x03) << 8) + ch[0],
pitch: ((ch[2] & 0x0f) << 6) + ((ch[1] & 0xfc) >> 2),
yaw: ch[3],
view: (ch[2] & 0xf0) >> 4,
throttle: -ch[5] + 255,
buttons: [
(ch[4] & 0x01) >> 0, (ch[4] & 0x02) >> 1, (ch[4] & 0x04) >> 2, (ch[4] & 0x08) >> 3, (ch[4] & 0x10) >> 4, (ch[4] & 0x20) >> 5, (ch[4] & 0x40) >> 6, (ch[4] & 0x80) >> 7, (ch[6] & 0x01) >> 0, (ch[6] & 0x02) >> 1, (ch[6] & 0x04) >> 2, (ch[6] & 0x08) >> 3
]
}
}e' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
*/
//var hid = require('node-hid');
// console.log(hid.devices());
// Logitech Extreme 3D Pro's vendorID and productID: 1133:49685 (i.e. 046d:c215)
//var joystick = new hid.HID(1133, 49685);
// console.log(joystick);
|
buuav/Myo_gesture_suite
|
rolling-spider-joystick/myocontrol.js
|
JavaScript
|
mit
| 4,843
|
import React from 'react';
import classes from 'classnames';
import Feed from 'src/components/Feed';
import equip from './equip';
const Content = ({ isFetching, posts, postCount, lastUpdated }) => (
<div>
{isFetching && posts.length === 0 &&
<h2>Loading...</h2>
}
{!isFetching && posts.length === 0 &&
<h2>Empty.</h2>
}
{postCount > 0 &&
<div>
{lastUpdated &&
<sub className={classes('pa3', 'top-075', 'grey-text')}>
Last updated at {new Date(lastUpdated).toLocaleTimeString()}
</sub>
}
<Feed style={{ opacity: isFetching ? 0.5 : 1 }} />
</div>
}
</div>
);
export default equip(Content);
|
RayBenefield/halo-forge
|
src/components/Content/index.js
|
JavaScript
|
mit
| 806
|
import path from 'path'
import webpack from 'webpack'
import UglifyJsPlugin from 'uglifyjs-webpack-plugin'
const config = {
mode: process.env.NODE_ENV,
entry: [
'./src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: process.env.NODE_ENV === 'production' ? 'threesixty.min.js' : 'threesixty.js',
library: 'threesixty',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
],
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
ie8: false,
warnings: false,
},
})
]
},
}
export default config
|
rbartoli/threesixty
|
webpack.config.babel.js
|
JavaScript
|
mit
| 950
|
@if ($navbar)
<nav class="typicms-navbar navbar navbar-expand-md navbar-dark bg-dark justify-content-between sticky-top">
@if (Request::segment(1) === 'admin')
<button class="navbar-toggler" type="button" data-toggle="offcanvas" data-target="#navigation" aria-controls="navigation" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
@endif
<a class="typicms-navbar-brand navbar-brand" href="{{ route('admin::dashboard') }}">{{ TypiCMS::title(config('typicms.admin_locale')) }}</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#userMenu" aria-controls="userMenu" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="userMenu">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
@section('otherSideLink')
@if (Request::segment(1) === 'admin')
@include('core::admin._navbar-public-link')
@else
@include('core::public._navbar-admin-link')
@endif
@show
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ auth()->user()->first_name.' '.auth()->user()->last_name }}</a>
<div class="dropdown-menu dropdown-user">
<div class="dropdown-user-wrapper">
<div class="img">
<img src="https://www.gravatar.com/avatar/{{ md5(auth()->user()->email) }}?d=mm" class="pull-left">
</div>
<div class="info">
<div class="mt-1 mb-1">{{ auth()->user()->email }}</div>
@can('update users')
<div class="mb-3">
<a href="{{ route('admin::edit-user', Auth::id()) }}">{{ __('Profile', [], config('typicms.admin_locale')) }}</a>
</div>
@endcan
<div class="mb-2">
<form action="{{ route(TypiCMS::mainLocale().'::logout') }}" method="post">
{{ csrf_field() }}
<button class="btn btn-secondary btn-sm" type="submit">@lang('Logout', [], config('typicms.admin_locale'))</button>
</form>
</div>
</div>
</div>
</div>
</li>
@can('read settings')
<li class="nav-item">
<a class="nav-link" href="{{ route('admin::index-settings') }}">
<svg class="me-2" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M9.405 1.05c-.413-1.4-2.397-1.4-2.81 0l-.1.34a1.464 1.464 0 0 1-2.105.872l-.31-.17c-1.283-.698-2.686.705-1.987 1.987l.169.311c.446.82.023 1.841-.872 2.105l-.34.1c-1.4.413-1.4 2.397 0 2.81l.34.1a1.464 1.464 0 0 1 .872 2.105l-.17.31c-.698 1.283.705 2.686 1.987 1.987l.311-.169a1.464 1.464 0 0 1 2.105.872l.1.34c.413 1.4 2.397 1.4 2.81 0l.1-.34a1.464 1.464 0 0 1 2.105-.872l.31.17c1.283.698 2.686-.705 1.987-1.987l-.169-.311a1.464 1.464 0 0 1 .872-2.105l.34-.1c1.4-.413 1.4-2.397 0-2.81l-.34-.1a1.464 1.464 0 0 1-.872-2.105l.17-.31c.698-1.283-.705-2.686-1.987-1.987l-.311.169a1.464 1.464 0 0 1-2.105-.872l-.1-.34zM8 10.93a2.929 2.929 0 1 0 0-5.86 2.929 2.929 0 0 0 0 5.858z"/>
</svg>
<span class="hidden-sm">{{ __('Settings', [], config('typicms.admin_locale')) }}</span>
</a>
</li>
@endcan
</ul>
</div>
</nav>
@endif
|
TypiCMS/Core
|
resources/views/_navbar.blade.php
|
PHP
|
mit
| 4,351
|
# 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.serialization import Model
class ConnectionMonitorParameters(Model):
"""Parameters that define the operation to create a connection monitor.
All required parameters must be populated in order to send to Azure.
:param source: Required.
:type source:
~azure.mgmt.network.v2018_01_01.models.ConnectionMonitorSource
:param destination: Required.
:type destination:
~azure.mgmt.network.v2018_01_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start
automatically once created. Default value: True .
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
Default value: 60 .
:type monitoring_interval_in_seconds: int
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'},
}
def __init__(self, **kwargs):
super(ConnectionMonitorParameters, self).__init__(**kwargs)
self.source = kwargs.get('source', None)
self.destination = kwargs.get('destination', None)
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
|
lmazuel/azure-sdk-for-python
|
azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connection_monitor_parameters.py
|
Python
|
mit
| 2,077
|
# tim
**tim** 是宙品科技的前端框架。`tim` 的名字来源于 "Time is money"。
特点:
* 尽力做到兼容IE8+。
* 用Scss编写。
* 提供了2列,3列,4列,5列,6列,7列,8列,9列,10列,12列,20列这几种常用网格,基本满足99%的常规布局要求。
* 提供了push,pull,offset。
* 提供了多种列间距模式。
|
zeupin/tim
|
README.md
|
Markdown
|
mit
| 361
|
a11y-what-why-how
=================
Talk for visit to Hyderabad, India, entitled Designing Online Course Content for Universal Access. This presentation will introduce people to the “What?”, “Why?” and “How?” of web content accessibility highlighting the particular relevance and importance to online education. I will discuss international standards such as the WCAG 2.0, and techniques web developers use to meet them. Using real examples and a screen reader, I will demonstrate some of my own team's successes and pitfalls in our journey to make our course content accessible to everyone.
|
terracoda/a11y-what-why-how
|
README.md
|
Markdown
|
mit
| 606
|
import { normalizeToInterval } from './format.js'
import { client } from '../plugins/Platform.js'
export const FOCUSABLE_SELECTOR = [
'a[href]:not([tabindex="-1"]):not(.q-focus__clone)',
'area[href]:not([tabindex="-1"]):not(.q-focus__clone)',
'input:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)',
'select:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)',
'textarea:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)',
'button:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)',
'iframe:not([tabindex="-1"]):not(.q-focus__clone)',
'[tabindex]:not([tabindex="-1"]):not(.q-focus__clone)',
'[contenteditable]:not([tabindex="-1"]):not(.q-focus__clone):not([contenteditable="false"])',
'.q-tab.q-focusable:not(.q-focus__clone)'
].join(',')
export const KEY_SKIP_SELECTOR = [
'input:not([disabled])',
'select:not([disabled])',
'select:not([disabled]) *',
'textarea:not([disabled])',
'[contenteditable]:not([contenteditable="false"])',
'[contenteditable]:not([contenteditable="false"]) *',
'.q-key-group-navigation--ignore-key',
'.q-key-group-navigation--ignore-key *',
'.q-focus__clone'
].join(',')
export const EDITABLE_SELECTOR = [
'input:not(.q-focus__clone):not([disabled]):not([readonly]):not([type="button"]):not([type="checkbox"]):not([type="file"]):not([type="hidden"]):not([type="image"]):not([type="radio"]):not([type="range"]):not([type="reset"]):not([type="submit"])',
'textarea:not(.q-focus__clone):not([disabled]):not([readonly])',
'[contenteditable]:not(.q-focus__clone):not([contenteditable="false"])',
'[contenteditable]:not(.q-focus__clone):not([contenteditable="false"]) *'
].join(',')
let scrollOffset = 0
let managedFocusFn
export function managedFocus (el) {
if (managedFocusFn === void 0) {
const scrollIntoView = typeof el.scrollIntoViewIfNeeded === 'function'
? target => { target.scrollIntoViewIfNeeded(false) }
: target => { target.scrollIntoView() }
managedFocusFn = client.is.ios === true || client.is.nativeMobile === true || window.matchMedia('(display-mode: standalone)').matches === true
? el => {
const elIsEditable = el.matches(EDITABLE_SELECTOR)
if (
el === document.body ||
(elIsEditable !== true && el.tabIndex < 0)
) {
el !== document.activeElement && el.focus({ preventScroll: true })
return
}
const elInPortal = el.matches('.q-dialog *, .q-menu *, .q-tooltip *, .q-stepper__step-content *')
const clone = el.cloneNode(true)
const parent = el.parentNode
const scrollingElement = document.scrollingElement || document.documentElement
const initialScrollTop = scrollingElement.scrollTop
clone.setAttribute('tabindex', -1)
clone.removeAttribute('id')
clone.removeAttribute('autofocus')
clone.removeAttribute('data-autofocus')
clone.classList.add('q-focus__clone')
parent.insertBefore(clone, el)
el !== document.activeElement && el.focus({ preventScroll: true })
setTimeout(() => {
clone.remove()
if (el && el === document.activeElement && elIsEditable === true) {
elInPortal === true && scrollIntoView(el)
const
{ top, bottom } = el.getBoundingClientRect(),
height = window.visualViewport !== void 0
? window.visualViewport.height
: window.innerHeight
let finalScrollTop = scrollingElement.scrollTop
if (top < 0) {
finalScrollTop += top - 32
}
else if (top > 0 && bottom > height) {
finalScrollTop += bottom - height + 64
}
requestAnimationFrame(() => {
scrollingElement.scrollTop = finalScrollTop
})
if (el.qRestoreScrollSet !== true && elInPortal !== true) {
scrollOffset += finalScrollTop - initialScrollTop
const restoreScrollFn = () => {
if (el) {
el.qRestoreScrollSet = void 0
el.removeEventListener('blur', restoreScrollFn)
}
if (scrollingElement.scrollTop !== finalScrollTop) {
scrollOffset = 0
}
else if (scrollOffset !== 0) {
requestAnimationFrame(() => {
const { activeElement } = document
if (
!activeElement ||
(activeElement.matches(EDITABLE_SELECTOR) !== true && activeElement.tabIndex < 0)
) {
scrollingElement.scrollTop -= scrollOffset
scrollOffset = 0
}
})
}
}
el.qRestoreScrollSet = true
el.addEventListener('blur', restoreScrollFn)
}
}
}, 200)
}
: el => {
const elInPortal = el.matches('.q-dialog *, .q-menu *, .q-tooltip *, .q-stepper__step-content *')
const elIsEditable = el.matches(EDITABLE_SELECTOR)
el !== document.activeElement && el.focus({ preventScroll: true })
if (elInPortal === true && elIsEditable === true) {
setTimeout(() => {
el && el === document.activeElement && scrollIntoView(el)
}, 200)
}
}
}
managedFocusFn(el)
}
export function changeFocusedElement (list, to, direction = 1, managed, noWrap, start) {
const lastIndex = list.length - 1
if (noWrap === true && (to > lastIndex || to < 0)) {
return
}
const index = normalizeToInterval(to, 0, lastIndex)
if (index === start || index > lastIndex) {
return
}
const initialEl = document.activeElement
const focusFn = managed === true
? () => { managedFocus(list[index]) }
: () => { list[index].focus() }
if (initialEl !== null) {
initialEl._qKeyNavIgnore = true
focusFn()
initialEl._qKeyNavIgnore = false
}
else {
focusFn()
}
if (document.activeElement !== list[index]) {
changeFocusedElement(list, index + direction, direction, managed, noWrap, start === void 0 ? index : start)
}
}
|
pdanpdan/quasar
|
ui/src/utils/focus-manager.js
|
JavaScript
|
mit
| 6,277
|
FROM python:2.7-alpine
WORKDIR /usr/src/app
RUN pip install requests && apk add --no-cache curl
COPY snipe.py /usr/src/app
ENTRYPOINT ["python", "-u", "snipe.py"]
|
giubil/Pokemongo-bot-scripts
|
pokemongomap-snipe/Dockerfile
|
Dockerfile
|
mit
| 166
|
require "test_helper"
describe RssNewsBrasil::Rss do
before do
url = "http://extra.globo.com/rss.xml"
@rss_feed = RSS::Parser.parse(url, false)
@rss = RssNewsBrasil::Rss.new(@rss_feed)
end
describe "title" do
it "return the name of feeds author" do
@rss.title.must_be_kind_of String
@rss.title.wont_be_empty
@rss.title.must_equal @rss_feed.channel.title
end
end
describe "description" do
it "return the description of feeds author" do
@rss.description.must_be_kind_of String
@rss.description.must_equal @rss_feed.channel.description
end
end
describe "link" do
it "return the link" do
@rss.link.must_be_kind_of String
@rss.link.wont_be_empty
@rss.link.must_equal @rss_feed.channel.link
end
end
describe "image_url" do
it "return the image url of the feed" do
@rss.image_url.must_be_kind_of String
@rss.image_url.must_equal @rss_feed.channel.image.url
end
end
describe "last_build_date" do
it "return the the last build date" do
@rss.last_build_date.must_be_kind_of Time
@rss.last_build_date.must_equal @rss_feed.channel.lastBuildDate
end
end
describe "items" do
it "return feeds items" do
@rss.items.must_be_kind_of Array
@rss.items.wont_be_empty
end
end
end
|
vinicius834/rss_news_brasil
|
test/rss_news_brasil/rss_test.rb
|
Ruby
|
mit
| 1,337
|
var express = require('express');
var router = express.Router();
// use auth_token cookie to secure the angular /app files
//TODO this needs to be reworked since someone could spoof
//a legitimate cookie named auth_token. Need to actually verify
//the cookie
router.use('/', function (req, res, next) {
if (!req.cookies.auth_token) {
return res.redirect('/login?returnUrl=' + encodeURIComponent('/app' + req.path));
}
next();
});
// serve angular app files from the '/app' route
router.use('/', express.static('app'));
module.exports = router;
|
cwkingjr/mean-example
|
controllers/app.controller.js
|
JavaScript
|
mit
| 567
|
#ifndef MERCURY_INI_H
#define MERCURY_INI_H
#include <map>
#include <vector>
#include "MercuryString.h"
#if defined(WIN32)
#define PROPERRETURN "\r\n"
#else
#define PROPERRETURN "\n"
#endif
///Framework for INI files
class MercuryINI
{
public:
MercuryINI( ) { m_bSaveOnExit = false; }
MercuryINI( const MString &sFileName, bool bSaveOnExit );
~MercuryINI( );
///Open a INI from a file; bAddIncludes specifies whether or not to look at [AdditionalFiles], bClearToStart states whether or not all data should be erased when starting
bool Open( const MString &sFileName, bool bAddIncludes = true, bool bClearToStart = false );
///Load an INI from a given c-style string
bool Load( const char * sIniText, long slen );
///Load an INI from a given string
bool Load( const MString &sIniText ) { return Load( sIniText.c_str(), sIniText.length() ); }
///Save the INI file
bool Save( const MString sFileName = "" );
///Dump the file into the incoming MString
void Dump( MString & data );
///Dump the file into then c-style string, this will also allocate ram.
long Dump( char * & toDump );
///Enumerate all keys in this ini file into keys
void EnumerateKeys( std::vector< MString > &keys );
///Enumerate all values in the given key to values.
void EnumerateValues( const MString &key, std::vector< MString > &values );
///Enumerate all values in the given key to a map.
void EnumerateValues( const MString &key, std::map< MString, MString > & values ) { values = m_mDatas[key]; }
///Return string value, blank if non-existant
MString GetValueS( const MString &key, const MString &value, MString sDefaultValue="", bool bMakeValIfNoExist=false );
///Return long value, 0 if non-existant
long GetValueI( const MString &key, const MString &value, long iDefaultValue=0, bool bMakeValIfNoExist=false );
///Return float value, 0 if non-existant
float GetValueF( const MString &key, const MString &value, float fDefaultValue=0, bool bMakeValIfNoExist=false );
///Return bool value, 0 if non-existant
bool GetValueB( const MString &key, const MString &value, bool bDefaultValue=0, bool bMakeValIfNoExist=false );
///Return value through data, false if non-existant
bool GetValue( const MString &key, const MString &value, MString &data );
///Set a value
void SetValue( const MString &key, const MString &value, const MString &data );
///Remove a value
bool RemoveValue( const MString &key, const MString &value );
///Get the last error.
MString GetLastError() { return m_sLastError; }
private:
///[internal] save all of the values when this ini file is destroyed
bool m_bSaveOnExit;
MString m_sLastError;
MString m_sFileName;
std::map< MString, std::map< MString, MString > > m_mDatas;
std::map< MString, bool > m_mLoaded;
};
///Instantiation of mercury.ini
extern MercuryINI * PREFSMAN;
///Check to see if Prefsman was set up.
/** If you are using PREFSMAN in a static time initiation, you should
execute this function first. */
inline void CheckPREFSMANSetup() { if ( PREFSMAN == NULL ) PREFSMAN = new MercuryINI( "Mercury.ini", true ); }
///Dump data into the file filename. bytes specifies the length of data. Returns true if successful, false else.
bool DumpToFile( const MString & filename, const char * data, long bytes );
///Dump data from a file into a char * and return the size of data. If -1 then there was an error opening the file.
long DumpFromFile( const MString & filename, char * & data );
///Bytes until desired terminal
long BytesUntil( const char* strin, const char * termin, long start, long slen, long termlen );
///Bytes until something other than a terminal
long BytesNUntil( const char* strin, const char * termin, long start, long slen, long termlen );
///Convert string containing binary characters to C-style formatted string.
MString ConvertToCFormat( const MString & ncf );
#endif
/*
* Copyright (c) 2005-2006, Charles Lohr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of the Mercury Engine nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
|
freem/SMOnline-v1
|
MercuryINI.h
|
C
|
mit
| 5,426
|
var mongoose = require("../../database/");
var UserSchema = mongoose.Schema({
username: String,
password: String,
lastLoginTime: Date,
createTime: Date,
userType: String, // admin,normal
projectList: [
{
_id: Object,
name: String
}
]
});
module.exports = UserSchema;
|
LaiHuanMin/JDocument
|
WebServer/util/mongoose/schema/user/index.js
|
JavaScript
|
mit
| 301
|
# https://projecteuler.net/problem=81
from projecteuler.FileReader import file_to_2D_array_of_ints
# this problem uses a similar solution to problem 18, "Maximum Path Sum 1."
# this problem uses a diamond instead of a pyramid
matrix = file_to_2D_array_of_ints("p081.txt", ",")
y_max = len(matrix) - 1
x_max = len(matrix[0]) - 1
for y in range(y_max, -1, -1):
for x in range(x_max, -1, -1):
if y == y_max and x == x_max:
continue
elif y == y_max:
matrix[y][x] += matrix[y][x + 1]
elif x == x_max:
matrix[y][x] += matrix[y + 1][x]
else:
matrix[y][x] += min(matrix[y][x + 1], matrix[y + 1][x])
print(matrix[0][0])
|
Peter-Lavigne/Project-Euler
|
p081.py
|
Python
|
mit
| 699
|
define(['angular'], function(angular) {
'use strict';
return angular.module('biomsef.filter', [ ]);
});
|
agjacome/biomsef
|
src/main/assets/js/filter/main.js
|
JavaScript
|
mit
| 112
|
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
def to_s
name
end
end
|
samok13/jumpstart_blogger
|
app/models/tag.rb
|
Ruby
|
mit
| 127
|
# Changelog
## [0.2.1](https://github.com/qgadrian/smokex/releases/tag/0.2.1) (2017-09-18)
* Add JSON output format.
* Bug fixes.
## [0.1.0](https://github.com/qgadrian/smokex/releases/tag/0.1.0) (2017-08-27)
* First release.
|
qgadrian/smokex
|
CHANGELOG.md
|
Markdown
|
mit
| 230
|
<!DOCTYPE html>
<html lang="en">
<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>Facility Editor</title>
<script src="https://use.fontawesome.com/7ae57e4dd9.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-S7YMK1xjUjSpEnF4P8hPUcgjXYLZKK3fQW1j5ObLSl787II9p8RO9XUGehRmKsxd" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="main-container">
<div class="left-container">
<div class="left-top-container">Facility Service Definition</div>
<div class="left-bottom-container"></div>
</div>
<div class="middle-container">
<div>Generator:</div>
<select class="generator-picker" size="8">
<option value="csharp" selected>C#</option>
<option value="javascript" selected>JavaScript</option>
<option value="typescript" selected>TypeScript</option>
<option value="markdown" selected>Markdown</option>
<option value="fsd">FSD</option>
<option value="swagger-yaml">Swagger YAML (OpenAPI 2.0)</option>
<option value="swagger-json">Swagger JSON (OpenAPI 2.0)</option>
<option value="asp-net-web-api">ASP.NET Web API</option>
</select>
<div class="middle-space-above">Output:</div>
<div class="file-list-container">
<select class="file-list" size="100">
</select>
</div>
<form action="https://fsdgenapi.faithlife.com/generate/zip" method="post">
<input type="hidden" name="definitionName" value="">
<input type="hidden" name="definitionText" value="">
<input type="hidden" name="generatorName" value="">
<button type="submit" class="btn btn-link download-button">Download Output</button>
</form>
</div>
<div class="right-container">
<div class="right-top-container"> </div>
<div class="right-bottom-container"></div>
<div class="right-working-overlay">
<i class="right-working fa fa-cog fa-spin fa-3x fa-fw"></i>
<span class="right-working sr-only">Loading...</span>
</div>
</div>
</div>
<script src='vs/loader.js'></script>
<script>
require(['vs/editor/editor.main'], function() {
if (window.onMonacoReady) {
window.onMonacoReady();
}
});
</script>
<script src='bundle.js' type='text/javascript'></script>
</body>
</html>
|
FacilityApi/FacilityApi.github.io
|
editor/index.html
|
HTML
|
mit
| 2,739
|
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'keepHtml', pure: false })
export class EscapeHtmlPipe implements PipeTransform {
constructor(public sanitizer: DomSanitizer) {
}
transform(content) {
return this.sanitizer.bypassSecurityTrustHtml(content);
}
}
|
leChuckles/PeerActivate
|
src/app/shared/pipes/escape-html.pipe.ts
|
TypeScript
|
mit
| 349
|
import unittest
from hamlpy.parser.core import (
ParseException,
Stream,
peek_indentation,
read_line,
read_number,
read_quoted_string,
read_symbol,
read_whitespace,
read_word,
)
from hamlpy.parser.utils import html_escape
class ParserTest(unittest.TestCase):
def test_read_whitespace(self):
stream = Stream(" \t foo \n bar ")
assert read_whitespace(stream) == " \t "
assert stream.text[stream.ptr :] == "foo \n bar "
stream.ptr += 3 # skip over foo
assert read_whitespace(stream) == " "
assert stream.text[stream.ptr :] == "\n bar "
assert read_whitespace(stream, include_newlines=True) == "\n "
assert stream.text[stream.ptr :] == "bar "
stream.ptr += 3 # skip over bar
assert read_whitespace(stream) == " "
assert stream.text[stream.ptr :] == ""
def test_peek_indentation(self):
assert peek_indentation(Stream("content")) == 0
assert peek_indentation(Stream(" content")) == 2
assert peek_indentation(Stream("\n")) is None
assert peek_indentation(Stream(" \n")) is None
def test_quoted_string(self):
stream = Stream("'hello'---")
assert read_quoted_string(stream) == "hello"
assert stream.text[stream.ptr :] == "---"
stream = Stream('"this don\'t \\"x\\" hmm" not in string')
assert read_quoted_string(stream) == 'this don\'t "x" hmm'
assert stream.text[stream.ptr :] == " not in string"
self.assertRaises(ParseException, read_quoted_string, Stream('"no end quote...'))
def test_read_line(self):
stream = Stream("line1\n line2\n\nline4\n\n")
assert read_line(stream) == "line1"
assert read_line(stream) == " line2"
assert read_line(stream) == ""
assert read_line(stream) == "line4"
assert read_line(stream) == ""
assert read_line(stream) is None
assert read_line(Stream("last line ")) == "last line "
def test_read_number(self):
stream = Stream('123"')
assert read_number(stream) == "123"
assert stream.text[stream.ptr :] == '"'
stream = Stream("123.4xx")
assert read_number(stream) == "123.4"
assert stream.text[stream.ptr :] == "xx"
stream = Stream("0.0001 ")
assert read_number(stream) == "0.0001"
assert stream.text[stream.ptr :] == " "
def test_read_symbol(self):
stream = Stream("=> bar")
assert read_symbol(stream, ["=>", ":"]) == "=>"
assert stream.text[stream.ptr :] == " bar"
self.assertRaises(ParseException, read_symbol, Stream("foo"), ["=>"])
def test_read_word(self):
stream = Stream("foo_bar")
assert read_word(stream) == "foo_bar"
assert stream.text[stream.ptr :] == ""
stream = Stream("foo_bar ")
assert read_word(stream) == "foo_bar"
assert stream.text[stream.ptr :] == " "
stream = Stream("ng-repeat(")
assert read_word(stream) == "ng"
assert stream.text[stream.ptr :] == "-repeat("
stream = Stream("ng-repeat(")
assert read_word(stream, ("-",)) == "ng-repeat"
assert stream.text[stream.ptr :] == "("
stream = Stream("これはテストです...")
assert read_word(stream) == "これはテストです"
assert stream.text[stream.ptr :] == "..."
class UtilsTest(unittest.TestCase):
def test_html_escape(self):
assert html_escape("") == ""
assert html_escape("&<>\"'") == "&<>"'"
assert html_escape('{% trans "hello" %}') == '{% trans "hello" %}'
assert html_escape('{{ foo|default:"hello" }}') == '{{ foo|default:"hello" }}'
assert html_escape("{% }} & %}") == "{% }} & %}"
result = html_escape('<>{% trans "hello" %}<>{{ foo|default:"hello" }}<>')
assert result == '<>{% trans "hello" %}<>{{ foo|default:"hello" }}<>'
|
nyaruka/django-hamlpy
|
hamlpy/test/test_parser.py
|
Python
|
mit
| 4,020
|
//
// EXTRuntimeExtensions.h
// extobjc
//
// Created by Justin Spahr-Summers on 2011-03-05.
// Copyright (C) 2012 Justin Spahr-Summers.
// Released under the MIT license.
//
#import <objc/runtime.h>
/**
* Describes the memory management policy of a property.
*/
typedef enum {
/**
* The value is assigned.
*/
wt_propertyMemoryManagementPolicyAssign = 0,
/**
* The value is retained.
*/
wt_propertyMemoryManagementPolicyRetain,
/**
* The value is copied.
*/
wt_propertyMemoryManagementPolicyCopy
} wt_propertyMemoryManagementPolicy;
/**
* Describes the attributes and type information of a property.
*/
typedef struct {
/**
* Whether this property was declared with the \c readonly attribute.
*/
BOOL readonly;
/**
* Whether this property was declared with the \c nonatomic attribute.
*/
BOOL nonatomic;
/**
* Whether the property is a weak reference.
*/
BOOL weak;
/**
* Whether the property is eligible for garbage collection.
*/
BOOL canBeCollected;
/**
* Whether this property is defined with \c \@dynamic.
*/
BOOL dynamic;
/**
* The memory management policy for this property. This will always be
* #wt_propertyMemoryManagementPolicyAssign if #readonly is \c YES.
*/
wt_propertyMemoryManagementPolicy memoryManagementPolicy;
/**
* The selector for the getter of this property. This will reflect any
* custom \c getter= attribute provided in the property declaration, or the
* inferred getter name otherwise.
*/
SEL getter;
/**
* The selector for the setter of this property. This will reflect any
* custom \c setter= attribute provided in the property declaration, or the
* inferred setter name otherwise.
*
* @note If #readonly is \c YES, this value will represent what the setter
* \e would be, if the property were writable.
*/
SEL setter;
/**
* The backing instance variable for this property, or \c NULL if \c
* \c @synthesize was not used, and therefore no instance variable exists. This
* would also be the case if the property is implemented dynamically.
*/
const char *ivar;
/**
* If this property is defined as being an instance of a specific class,
* this will be the class object representing it.
*
* This will be \c nil if the property was defined as type \c id, if the
* property is not of an object type, or if the class could not be found at
* runtime.
*/
Class objectClass;
/**
* The type encoding for the value of this property. This is the type as it
* would be returned by the \c \@encode() directive.
*/
char type[];
} wt_propertyAttributes;
/**
* Returns a pointer to a structure containing information about \a property.
* You must \c free() the returned pointer. Returns \c NULL if there is an error
* obtaining information from \a property.
*/
wt_propertyAttributes *wt_copyPropertyAttributes(objc_property_t property);
|
JaonFanwt/WtCore
|
WtCore/Classes/GCD/Macros/WtEXTRuntimeExtensions.h
|
C
|
mit
| 3,055
|
<?php
namespace IIA\ApiBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use IIA\ApiBundle\Entity\QCM;
use IIA\ApiBundle\Form\QCMType;
/**
* QCM controller.
*
* @Route("/iia_qcm")
*/
class QCMController extends Controller
{
/**
* Lists all QCM entities.
*
* @Route("/", name="iia_qcm")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('IIAApiBundle:QCM')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new QCM entity.
*
* @Route("/", name="iia_qcm_create")
* @Method("POST")
* @Template("IIAApiBundle:QCM:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new QCM();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('iia_qcm_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a QCM entity.
*
* @param QCM $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(QCM $entity)
{
$form = $this->createForm(new QCMType(), $entity, array(
'action' => $this->generateUrl('iia_qcm_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new QCM entity.
*
* @Route("/new", name="iia_qcm_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new QCM();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a QCM entity.
*
* @Route("/{id}", name="iia_qcm_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('IIAApiBundle:QCM')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find QCM entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing QCM entity.
*
* @Route("/{id}/edit", name="iia_qcm_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('IIAApiBundle:QCM')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find QCM entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a QCM entity.
*
* @param QCM $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(QCM $entity)
{
$form = $this->createForm(new QCMType(), $entity, array(
'action' => $this->generateUrl('iia_qcm_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing QCM entity.
*
* @Route("/{id}", name="iia_qcm_update")
* @Method("PUT")
* @Template("IIAApiBundle:QCM:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('IIAApiBundle:QCM')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find QCM entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('iia_qcm_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a QCM entity.
*
* @Route("/{id}", name="iia_qcm_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('IIAApiBundle:QCM')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find QCM entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('iia_qcm'));
}
/**
* Creates a form to delete a QCM entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('iia_qcm_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
|
elouf/QC-MANAGER
|
src/IIA/ApiBundle/Controller/QCMController.php
|
PHP
|
mit
| 6,511
|
namespace Promact.Trappist.DomainModel.Enum
{
public enum TestStatus
{
AllCandidates = 0,
CompletedTest = 1,
ExpiredTest = 2,
BlockedTest = 3,
UnfinishedTest = 4
}
}
|
Promact/trappist
|
Trappist/src/Promact.Trappist.DomainModel/Enum/TestStatus.cs
|
C#
|
mit
| 221
|
#!/bin/sh
set -e
APPDIR="$(dirname "$(readlink -e "$0")")"
. "$APPDIR"/common.conf
exec "$PYTHON" "$@"
|
fyookball/electrum
|
contrib/build-linux/appimage/scripts/python.sh
|
Shell
|
mit
| 106
|
export const ic_picture_in_picture_alt_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 11h-8v6h8v-6zm-2 4h-4v-2h4v2zm4-12H3c-1.1 0-2 .88-2 1.98V19c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V4.98C23 3.88 22.1 3 21 3zm0 16.02H3V4.97h18v14.05z"},"children":[]}]};
|
wmira/react-icons-kit
|
src/md/ic_picture_in_picture_alt_outline.js
|
JavaScript
|
mit
| 359
|
package com.stuffwithstuff.magpie.intrinsic;
import com.stuffwithstuff.magpie.Def;
import com.stuffwithstuff.magpie.Doc;
import com.stuffwithstuff.magpie.interpreter.Context;
import com.stuffwithstuff.magpie.interpreter.Obj;
public class IntMethods {
/*
@Shared
@Signature("parse(text String -> Int)")
public static class Parse implements BuiltInCallable {
public Obj invoke(Context context, Obj thisObj, Obj arg) {
String text = arg.asString();
try {
int value = Integer.parseInt(text);
return interpreter.createInt(value);
} catch (NumberFormatException ex) {
return interpreter.nothing();
}
}
}
*/
@Def("(left is Int) +(right is Int)")
@Doc("Adds the two numbers.")
public static class Add extends ArithmeticOperator {
protected int perform(int left, int right) { return left + right; }
}
@Def("(left is Int) -(right is Int)")
@Doc("Subtracts the two numbers.")
public static class Subtract extends ArithmeticOperator {
protected int perform(int left, int right) { return left - right; }
}
@Def("(left is Int) *(right is Int)")
@Doc("Multiplies the two numbers.")
public static class Multiply extends ArithmeticOperator {
protected int perform(int left, int right) { return left * right; }
}
@Def("(left is Int) /(right is Int)")
@Doc("Divides the two numbers.")
public static class Divide extends ArithmeticOperator {
protected int perform(int left, int right) { return left / right; }
}
@Def("(left is Int) %(right is Int)")
@Doc("Returns left modulo right.")
public static class Modulo extends ArithmeticOperator {
protected int perform(int left, int right) { return left % right; }
}
private abstract static class ArithmeticOperator implements Intrinsic {
public Obj invoke(Context context, Obj left, Obj right) {
return context.toObj(perform(left.asInt(), right.asInt()));
}
protected abstract int perform(int left, int right);
}
@Def("(left is Int) ==(right is Int)")
@Doc("Returns true if the two numbers are equal.")
public static class Equals implements Intrinsic {
public Obj invoke(Context context, Obj left, Obj right) {
return context.toObj(left.asInt() == right.asInt());
}
}
@Def("(left is Int) compareTo(right is Int)")
@Doc("Returns -1 if left is less than right, 1 if it is greater or 0 if\n" +
"they are the same.")
public static class Compare implements Intrinsic {
public Obj invoke(Context context, Obj left, Obj right) {
return context.toObj(((Integer)left.asInt()).compareTo(right.asInt()));
}
}
@Def("(is Int) toString")
@Doc("Returns a string representation of the number.")
public static class ToString implements Intrinsic {
public Obj invoke(Context context, Obj left, Obj right) {
return context.toObj(Integer.toString(left.asInt()));
}
}
}
|
munificent/magpie
|
src/com/stuffwithstuff/magpie/intrinsic/IntMethods.java
|
Java
|
mit
| 2,936
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddForeignKeysToTracksTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('tracks', function(Blueprint $table)
{
$table->foreign('genre_id')->references('id')->on('genres')->onUpdate('RESTRICT')->onDelete('RESTRICT');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('tracks', function(Blueprint $table)
{
$table->dropForeign('tracks_genre_id_foreign');
});
}
}
|
scrapewww/AutomatedMusicSite
|
database/migrations/2017_08_02_004718_add_foreign_keys_to_tracks_table.php
|
PHP
|
mit
| 613
|
#include "TypeDecoratorTypedefName.h"
#include "TypedefDecorator.h"
#include "ConcreteTableColumn.h"
TypeDecoratorTypedefName::TypeDecoratorTypedefName(DataExtractor *next, ConcreteTableColumn *prototype, TypedefDecorator *condition):DataExtractor(next,prototype,condition) {}
TableColumn* TypeDecoratorTypedefName::handleExtraction(AbstractTree &tree) {
TableColumn *column = prototype->clone();
std::string value;
value = VTP_NAME_STRING(VTP_TreeAtomValue(tree.tree));
column->init(value,false);
return column;
}
|
petrufm/mcc
|
mcc/src/TypeDecoratorTypedefName.cpp
|
C++
|
mit
| 528
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AstrophotographyBlog.Web.Areas.Admin.Controllers
{
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
// GET: Admin/Admin
public ActionResult Index()
{
return View();
}
}
}
|
J-Mitko/AstrophotographyBlog
|
AstrophotographyBlog/AstrophotographyBlog.Web/Areas/Admin/Controllers/AdminController.cs
|
C#
|
mit
| 375
|
/**
* Controller module.
* This is the unique master controller, with tiny controllers for each view.
* Our project is not large scaled, so our controllers can all stay together
* happily like a family.
* @module shell
*/
'use strict';
var helpers = require('./helpers');
var model = require('./model');
// var page = require('page');
var pubSub = require('pubsub-js');
var notie = require('notie');
/* Views */
var views = {};
views.peopleList = require('./views/people-list');
views.chat = require('./views/chat');
views.account = require('./views/account');
var configMap = {
};
var isTesting = true;
var _testing = function() {
// model.people.login('Alfred');
};
///////////////////////////
// VIEWS EVENTS HANDLERS //
///////////////////////////
/* ACCOUNT */
var _onSignClick = function() {
var currentUser = model.people.getCurrentUser();
if(currentUser.getIsAnon()) {
notie.input('Please sign-in with a nickname: ', 'Sign-in', 'Cancel', 'text', 'Nickname', function(userName) {
if( (userName.length < 3) || (userName.length > 12) ) {
notie.alert(3, 'Sorry, username must be between 3 and 12 characters');
} else {
model.people.login(userName);
document.qs('.account .sign').textContent = '... Processing ...';
}
});
} else {
model.people.logout();
}
return false;
};
/* PEOPLE LIST */
var onSetChatee = function(personId) {
model.chat.setChatee(personId);
};
/* CHAT */
var onSubmitMsg = function(msgText) {
if(!model.chat.getChatee()) {
return;
}
model.chat.sendMsg(msgText);
};
////////////////////////////////////
// RENDERING VIEWS WHEN USER LOGS IN //
////////////////////////////////////
var onLogin = function() {
//people-list
views.peopleList.init();
views.peopleList.bind('setChatee', onSetChatee);
//chat
views.chat.init();
views.chat.bind('submitMsg', onSubmitMsg);
};
/**
* PUBLIC FUNCTIONS
*/
var configModule = function(inputMap) {
helpers.configMap(inputMap, configMap);
};
var init = function() {
//Account
views.account.init();
views.account.bind('onSignClick', _onSignClick);
//People list
//When user is logged in
pubSub.subscribe('login', onLogin);
if(isTesting) {
_testing();
}
};
module.exports = {
/** configures the module configMap */
configModule: configModule,
/** init shell module */
init: init
};
|
jiayihu/chattina
|
app/javascripts/controller.js
|
JavaScript
|
mit
| 2,398
|
require "simplecov"
SimpleCov.start
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../test/dummy/config/environment.rb", __FILE__)
ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)]
require "rails/test_help"
# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
ActiveSupport::TestCase.fixtures :all
end
|
nativestranger/cerializable
|
test/test_helper.rb
|
Ruby
|
mit
| 847
|
---
title: Forlife Teapot
date: 2016-06-01 00:00:00 Z
layout: post
---
## A New Post
Enter text in [Markdown](http://daringfireball.net/projects/markdown/). Use the toolbar above, or click the **?** button for formatting help.
|
dtsn/dtsn
|
_drafts/forlife-teapot.md
|
Markdown
|
mit
| 229
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
/// <content>
/// Contains the <see cref="ServiceInfoLevel"/> nested enum.
/// </content>
public static partial class AdvApi32
{
/// <summary>
/// Describes the configuration information to be changed.
/// </summary>
public enum ServiceInfoLevel
{
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceDescription"/> structure.
/// </summary>
SERVICE_CONFIG_DESCRIPTION = 1,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceFailureActions"/> structure.
/// If the service controller handles the <see cref="ServiceControlActionType.SC_ACTION_REBOOT"/> action, the caller must have the SE_SHUTDOWN_NAME privilege.
/// </summary>
SERVICE_CONFIG_FAILURE_ACTIONS = 2,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceDelayedAutoStartInfo"/> struct.
/// Windows Server 2003 and Windows XP: This value is not supported.
/// </summary>
SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceFailureActions"/> structure.
/// Windows Server 2003 and Windows XP: This value is not supported.
/// </summary>
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceSidInfo"/> structure.
/// </summary>
SERVICE_CONFIG_SERVICE_SID_INFO = 5,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServiceRequiredPrivilegesInfo"/> structure.
/// Windows Server 2003 and Windows XP: This value is not supported.
/// </summary>
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 6,
/// <summary>
/// The lpInfo parameter is a pointer to a <see cref="ServicePreshutdownInfo"/> structure.
/// Windows Server 2003 and Windows XP: This value is not supported.
/// </summary>
SERVICE_CONFIG_PRESHUTDOWN_INFO = 7,
/// <summary>
/// The lpInfo parameter is a pointer to a SERVICE_TRIGGER_INFO structure.
/// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported until Windows Server 2008 R2.
/// </summary>
SERVICE_CONFIG_TRIGGER_INFO = 8,
/// <summary>
/// The lpInfo parameter is a pointer to a SERVICE_PREFERRED_NODE_INFO structure.
/// Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This value is not supported.
/// </summary>
SERVICE_CONFIG_PREFERRED_NODE = 9,
/// <summary>
/// The lpInfo parameter is a pointer a <see cref="ServiceLaunchProtected"/> structure.
/// Note This value is supported starting with Windows 8.1.
/// </summary>
SERVICE_CONFIG_LAUNCH_PROTECTED = 12
}
}
}
|
fearthecowboy/pinvoke
|
src/AdvApi32.Shared/AdvApi32+ServiceInfoLevel.cs
|
C#
|
mit
| 3,446
|
Ext.define("Com.GatotKaca.ERP.module.Personal.view.grids.Experience",{extend:"Com.GatotKaca.ERP.module.HumanResources.view.grids.Experience",alias:"widget.gridprexperience",id:"gridprexperience",title:"Experiences",store:"Com.GatotKaca.ERP.module.Personal.store.Experience"});
|
AdenKejawen/erp
|
web/assets/app/module/Personal/view/grids/Experience.js
|
JavaScript
|
mit
| 276
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version184 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE report ADD status_cached TEXT DEFAULT NULL');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE report DROP status_cached');
}
}
|
ministryofjustice/opg-digi-deps-api
|
api/app/DoctrineMigrations/Version184.php
|
PHP
|
mit
| 1,049
|
<?php
namespace Softbox\Support\Tests;
use PHPUnit\Framework\TestCase;
use Softbox\Support\Collection;
use Softbox\Support\CollectionHelper;
use Softbox\Support\Tests\Mocks\JsonSerializableClass;
use Softbox\Support\Tests\Mocks\TraversableClass;
class CollectionTest extends TestCase
{
public function testCreationFromCollection()
{
$data = array(1, 2, 3);
$collectionFromArray = new Collection($data);
$collectionFromCollection = new Collection($collectionFromArray);
$this->assertInstanceOf('Softbox\Support\Collection', $collectionFromCollection);
$this->assertEquals(array(1, 2, 3), $collectionFromCollection->all());
}
public function testCreationFromJsonSerializable()
{
$jsonSerializableData = new JsonSerializableClass(array(1, 2, 3, 4));
$collection = new Collection($jsonSerializableData);
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
$this->assertEquals(array(1, 2, 3, 4), $collection->all());
}
public function testCreationFromTraversable()
{
$traversable = new TraversableClass();
$collection = new Collection($traversable);
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
$this->assertTrue(is_array($collection->all()));
$this->assertArrayHasKey('property1', $collection->all());
$this->assertArrayHasKey('property2', $collection->all());
$this->assertArrayHasKey('property3', $collection->all());
}
public function testCreationFromObject()
{
$collection = new Collection(new \stdClass());
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
}
public function testCreationFromLiteral()
{
$collection = new Collection("william");
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
$this->assertEquals(array("william"), $collection->all());
}
/**
* @test
*/
public function testMap()
{
$data = array(1, 2, 3, 4);
$collection = new Collection($data);
$newCollection = $collection->map(function ($item) {
return $item * 2;
});
$this->assertEquals(array(1, 2, 3, 4), $collection->all());
$this->assertEquals($data, $collection->all());
$this->assertEquals(array(2, 4, 6, 8), $newCollection->all());
$this->assertNotEquals($newCollection, $collection);
$this->assertNotEquals($newCollection->all(), $collection->all());
}
public function testFilter()
{
$data = array(1, 2, 3, 4);
$collection = new Collection($data);
$filteredCollection = $collection->filter(function ($item) {
return $item % 2 == 1;
}, false);
$odds = $filteredCollection->all();
$this->assertTrue(is_array($odds));
$this->assertTrue(!empty($odds));
$this->assertEquals(array(1, 3), $odds);
$this->assertNotEquals(array(1, 3), $collection->all());
$this->assertNotEquals($odds, $data);
}
public function testReduce()
{
$data = array(1, 2, 3, 4, 5, 6);
$collection = new Collection($data);
$reducedData = $collection
->filter(function ($item) {
return $item % 2 == 0;
})
->map(function ($item) {
return $item * 2;
})
->reduce(function ($acc, $other) {
return $acc + $other;
})
;
$this->assertEquals(24, $reducedData);
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
$this->assertEquals(array(1, 2, 3, 4, 5, 6), $collection->all());
}
public function testChunk()
{
$data = array(1, 2, 3, 4, 5);
$collection = new Collection($data);
$chunks = $collection->chunk(3)->all();
$this->assertEquals(2, count($chunks));
$this->assertEquals(array(1, 2, 3), $chunks[0]);
$this->assertEquals(array(4, 5), $chunks[1]);
$this->assertEquals(array(1, 2, 3, 4, 5), $collection->all());
}
public function testCountable()
{
$data = array(
array(1, 2, 3, 4, 5),
array(1, 2, 3),
array(),
(object) array(
'name' => 'William',
'age' => 28,
),
);
/** @var Collection[] $collections */
$collections = array_map(function ($data) {
return new Collection($data);
}, $data);
foreach ($collections as $key => $collection) {
$originalData = (array) $data[$key];
$this->assertInstanceOf('Softbox\Support\Collection', $collection);
$this->assertEquals($originalData, $collection->all());
$this->assertEquals(count($originalData), $collection->count());
$this->assertEquals(count($originalData), count($collection));
}
}
public function testArrayAccess()
{
$data = array(
array(1, 2, 3, 4),
array(
'name' => 'William',
'lastname' => 'Okano',
'anotherArray' => array(10, 9, 8, 7, 6),
),
(object) array(
'name' => 'William',
'weird_property' => 'with weird value',
),
new Collection(array(4, 3, 2, 'hello_moto' => 1)),
);
/** @var Collection[] $collections */
$collections = array_map(function ($data) {
return new Collection($data);
}, $data);
// test get
foreach ($collections as $idx => $collection) {
if ($data[$idx] instanceof Collection) {
$originalData = $data[$idx]->all();
} else {
$originalData = (array) $data[$idx];
}
foreach ($originalData as $key => $value) {
$this->assertEquals($value, $collection[$key], "Failed at idx $idx and key $key");
}
}
// Test unset
unset($collections[3][0]);
$this->assertEquals(array(
1 => 3,
2 => 2,
'hello_moto' => 1
), $collections[3]->all());
// test set
$collections[3][0] = 4;
$this->assertEquals(array(
0 => 4,
1 => 3,
2 => 2,
'hello_moto' => 1
), $collections[3]->all());
}
}
|
SoftboxLab/php-collection-helper
|
tests/CollectionTest.php
|
PHP
|
mit
| 6,623
|
using OpenTK.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeDF
{
interface IDrawable
{
int GetWidth();
int GetHeight();
int GetX();
int GetY();
Color4 GetFG();
Color4 GetBG();
void Draw();
void SetHost(IDrawable host);
void SetForegroundColor(Color4 fg);
void SetBackgroundColor(Color4 bg);
}
abstract class Gadget : IDrawable
{
protected int x, y;
protected IDrawable host;
protected Color4 fgcolor;
protected Color4 bgcolor;
public int GetX()
{
return x;
}
public int GetY()
{
return y;
}
public abstract int GetWidth();
public abstract int GetHeight();
public abstract void Draw();
public virtual void SetHost(IDrawable host)
{
this.host = host;
GUI.Change();
}
public virtual Color4 GetFG()
{
if ((fgcolor == new Color4()) && (host != null)) return host.GetFG();
else return fgcolor;
}
public virtual Color4 GetBG()
{
if ((bgcolor == new Color4()) && (host != null)) return host.GetBG();
else return bgcolor;
}
public virtual void SetForegroundColor(Color4 fg)
{
fgcolor = fg;
GUI.Change();
}
public virtual void SetBackgroundColor(Color4 bg)
{
bgcolor = bg;
GUI.Change();
}
}
class Label : Gadget
{
string text;
public Label(int x, int y, string text, IDrawable host=null)
{
this.text = text;
this.x = x;
this.y = y;
SetHost(host);
}
public override int GetWidth() {
return text.Length;
}
public override int GetHeight()
{
return 1;
}
public override void Draw()
{
ConsoleWindowManager.Write(y + host.GetY(), x + host.GetX(), text, GetFG(), GetBG());
}
}
enum AlignmentType { left, center, right};
class Selector : Gadget, IControllable
{
List<Button> buttons = new List<Button>();
int selectedButton = 0;
public Selector(int x, int y, Dictionary<string, Action> buttons, IDrawable host=null)
{
int i = 0;
foreach(string s in buttons.Keys)
{
int w = buttons.Max((kvp) => kvp.Key.Length);
Button but = new Button(x, y + i, s, w, buttons[s]);
but.SetHost(this);
this.buttons.Add(but);
i += 2;
}
SetHost(host);
InvertActiveLabel();
}
public void SetTextAlignment(AlignmentType align)
{
foreach(Button b in buttons)
{
b.SetTextAlignment(align);
}
}
public override void SetHost(IDrawable host)
{
base.SetHost(host);
InvertActiveLabel();
}
void InvertActiveLabel()
{
buttons[selectedButton].SetBackgroundColor(GetFG());
buttons[selectedButton].SetForegroundColor(GetBG());
}
void NormalizeActiveLabel()
{
buttons[selectedButton].SetBackgroundColor(GetBG());
buttons[selectedButton].SetForegroundColor(GetFG());
}
public override void SetForegroundColor(Color4 fg)
{
base.SetForegroundColor(fg);
InvertActiveLabel();
}
public override void SetBackgroundColor(Color4 bg)
{
base.SetBackgroundColor(bg);
InvertActiveLabel();
}
public override void Draw()
{
foreach (Button b in buttons) b.Draw();
}
public override int GetHeight()
{
return 2 * buttons.Count - 1;
}
public override int GetWidth()
{
return buttons.Max((label) => label.GetWidth());
}
void Back()
{
NormalizeActiveLabel();
selectedButton--;
if (selectedButton < 0) selectedButton += buttons.Count;
InvertActiveLabel();
GUI.Change();
}
void Forward()
{
NormalizeActiveLabel();
selectedButton++;
if (selectedButton >= buttons.Count) selectedButton -= buttons.Count;
InvertActiveLabel();
GUI.Change();
}
public void KeyPress(string key)
{
switch (key)
{
case "enter":
buttons[selectedButton].Act();
break;
case "up":
Back();
break;
case "down":
Forward();
break;
default:
throw new Exception("WTF, don't know what to do with key " + key);
}
}
public bool AcceptsKey(string key)
{
return (key == "enter") || (key == "up") || (key == "down");
}
}
class Button : Gadget
{
string text;
Action action;
AlignmentType textAlign = AlignmentType.left;
int width;
public void SetTextAlignment(AlignmentType align)
{
if (align != textAlign) GUI.Change();
textAlign = align;
}
public Button(int x, int y, string text, int width, Action action, IDrawable host=null)
{
this.text = text;
this.x = x;
this.y = y;
SetHost(host);
this.action = action;
this.width = width;
}
public void Act()
{
action();
}
public override int GetWidth()
{
return width;
}
public override int GetHeight()
{
return 1;
}
public void SetAction(Action action)
{
this.action = action;
}
public override void Draw()
{
switch (textAlign)
{
case AlignmentType.left:
int pos_x = x + host.GetX();
int pos_space = pos_x + text.Length;
ConsoleWindowManager.Write(y + host.GetY(), pos_x, text, GetFG(), GetBG());
ConsoleWindowManager.Write(y + host.GetY(), pos_space, new string(' ', width - text.Length), GetFG(), GetBG());
break;
case AlignmentType.right:
pos_x = x + host.GetX() + GetWidth() - text.Length;
pos_space = x + host.GetX();
ConsoleWindowManager.Write(y + host.GetY(), pos_x, text, GetFG(), GetBG());
ConsoleWindowManager.Write(y + host.GetY(), pos_space, new string(' ', width - text.Length), GetFG(), GetBG());
break;
case AlignmentType.center:
pos_x = x + host.GetX() + (GetWidth() - text.Length) / 2;
pos_space = x + host.GetX();
ConsoleWindowManager.Write(y + host.GetY(), pos_space, new string(' ', width), GetFG(), GetBG());
ConsoleWindowManager.Write(y + host.GetY(), pos_x, text, GetFG(), GetBG());
break;
}
}
}
class SymbolMatrix : Gadget, IControllable
{
int width, height;
char[,] matrix;
Color4[,] foreground;
Color4[,] background;
public override void Draw()
{
for (int i = 0; i< width; i++)
for (int j = 0; j < height; j++)
ConsoleWindowManager.Write(x + i, y + j, matrix[i, j], foreground[i, j], background[i, j]);
}
public SymbolMatrix(int width, int height)
{
this.width = width;
this.height = height;
matrix = new char[width, height];
foreground = new Color4[width, height];
background = new Color4[width, height];
}
public void SetPixel(int x, int y, char c, Color4 fg, Color4 bg)
{
matrix[x, y] = c;
foreground[x, y] = fg;
background[x, y] = bg;
GUI.Change();
}
public void SetRectangle(int x, int y, string[] lines, Color4[,] fgs, Color4[,] bgs)
// NB! Despite the fact that the chars in lines are numbered like [y, x],
// the colors should be numbered like [x, y]
{
for (int i = 0; i < lines.Length; i++)
for (int j = 0; j < lines[i].Length; j++)
{
matrix[j, i] = lines[i][j];
foreground[j, i] = fgs[j, i];
background[j, i] = bgs[j, i];
}
GUI.Change();
}
public void SetRectangle(int x, int y, ColoredSymbolMatrix CSM)
{
SetRectangle(x, y, Misc.ConvertChar2DToString1D(CSM.symbols, CSM.width, CSM.height), CSM.foreground, CSM.background);
}
public void SetRectangle(int x, int y, string[] lines, Color4 fg, Color4 bg)
{
for (int i = 0; i < lines.Length; i++)
for (int j = 0; j < lines[i].Length; j++)
{
matrix[j, i] = lines[i][j];
foreground[j, i] = fg;
background[j, i] = bg;
}
GUI.Change();
}
public override int GetHeight()
{
return height;
}
public override int GetWidth()
{
return width;
}
public virtual void KeyPress(string key)
{
}
public virtual bool AcceptsKey(string key)
{
return false;
}
}
class SymbolMatrixWithCursor : SymbolMatrix
{
public SymbolMatrixWithCursor(int width, int height) : base(width, height)
{
}
int cursorX = 0, cursorY = 0;
public Action upAction = () => { }, leftAction = () => { }, rightAction = () => { }, downAction = () => { };
public Dictionary<string, Action> bindings = new Dictionary<string, Action>();
public int CursorX { get { return cursorX; } }
public int CursorY { get { return cursorY; } }
public override bool AcceptsKey(string key)
{
return bindings.ContainsKey(key);
}
public override void KeyPress(string key)
{
bindings[key]();
}
public Pair<int> GetCursorPosition()
{
return new Pair<int>(cursorX, cursorY);
}
public void On(string key, Action action)
{
if (!bindings.ContainsKey(key)) bindings[key] = () => { };
bindings[key] += action;
}
public override void Draw()
{
base.Draw();
ConsoleWindowManager.Write(host.GetX() + cursorX, host.GetY() + y + cursorY, 'X', Color4.Red, Color4.Black);
}
public void BindDirectionKeysToCursor()
{
On("left", () => { cursorX--; });
On("right", () => { cursorX++; });
On("up", () => { cursorY--; });
On("down", () => { cursorY++; });
}
}
}
|
vestatus/FreeDF
|
FreeDF/GUI/Gadget.cs
|
C#
|
mit
| 11,688
|
#! /usr/bin/env python
# Copyright (c) 2019 Red Hat, Inc.
# Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# 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.
"""Molecule distribution package setuptools installer."""
import setuptools
HAS_DIST_INFO_CMD = False
try:
import setuptools.command.dist_info
HAS_DIST_INFO_CMD = True
except ImportError:
"""Setuptools version is too old."""
ALL_STRING_TYPES = tuple(map(type, ('', b'', u'')))
MIN_NATIVE_SETUPTOOLS_VERSION = 34, 4, 0
"""Minimal setuptools having good read_configuration implementation."""
RUNTIME_SETUPTOOLS_VERSION = tuple(map(int, setuptools.__version__.split('.')))
"""Setuptools imported now."""
READ_CONFIG_SHIM_NEEDED = (
RUNTIME_SETUPTOOLS_VERSION < MIN_NATIVE_SETUPTOOLS_VERSION
)
def str_if_nested_or_str(s):
"""Turn input into a native string if possible."""
if isinstance(s, ALL_STRING_TYPES):
return str(s)
if isinstance(s, (list, tuple)):
return type(s)(map(str_if_nested_or_str, s))
if isinstance(s, (dict, )):
return stringify_dict_contents(s)
return s
def stringify_dict_contents(dct):
"""Turn dict keys and values into native strings."""
return {
str_if_nested_or_str(k): str_if_nested_or_str(v)
for k, v in dct.items()
}
if not READ_CONFIG_SHIM_NEEDED:
from setuptools.config import read_configuration, ConfigOptionsHandler
import setuptools.config
import setuptools.dist
# Set default value for 'use_scm_version'
setattr(setuptools.dist.Distribution, 'use_scm_version', False)
# Attach bool parser to 'use_scm_version' option
class ShimConfigOptionsHandler(ConfigOptionsHandler):
"""Extension class for ConfigOptionsHandler."""
@property
def parsers(self):
"""Return an option mapping with default data type parsers."""
_orig_parsers = super(ShimConfigOptionsHandler, self).parsers
return dict(use_scm_version=self._parse_bool, **_orig_parsers)
def parse_section_packages__find(self, section_options):
find_kwargs = super(
ShimConfigOptionsHandler, self
).parse_section_packages__find(section_options)
return stringify_dict_contents(find_kwargs)
setuptools.config.ConfigOptionsHandler = ShimConfigOptionsHandler
else:
"""This is a shim for setuptools<required."""
import functools
import io
import json
import sys
import warnings
try:
import setuptools.config
def filter_out_unknown_section(i):
def chi(self, *args, **kwargs):
i(self, *args, **kwargs)
self.sections = {
s: v for s, v in self.sections.items()
if s != 'packages.find'
}
return chi
setuptools.config.ConfigHandler.__init__ = filter_out_unknown_section(
setuptools.config.ConfigHandler.__init__,
)
except ImportError:
pass
def ignore_unknown_options(s):
@functools.wraps(s)
def sw(**attrs):
try:
ignore_warning_regex = (
r"Unknown distribution option: "
r"'(license_file|project_urls|python_requires)'"
)
warnings.filterwarnings(
'ignore',
message=ignore_warning_regex,
category=UserWarning,
module='distutils.dist',
)
return s(**attrs)
finally:
warnings.resetwarnings()
return sw
def parse_predicates(python_requires):
import itertools
import operator
sorted_operators_map = tuple(sorted(
{
'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'==': operator.eq,
'!=': operator.ne,
'': operator.eq,
}.items(),
key=lambda i: len(i[0]),
reverse=True,
))
def is_decimal(s):
return type(u'')(s).isdecimal()
conditions = map(str.strip, python_requires.split(','))
for c in conditions:
for op_sign, op_func in sorted_operators_map:
if not c.startswith(op_sign):
continue
raw_ver = itertools.takewhile(
is_decimal,
c[len(op_sign):].strip().split('.'),
)
ver = tuple(map(int, raw_ver))
yield op_func, ver
break
def validate_required_python_or_fail(python_requires=None):
if python_requires is None:
return
python_version = sys.version_info
preds = parse_predicates(python_requires)
for op, v in preds:
py_ver_slug = python_version[:max(len(v), 3)]
condition_matches = op(py_ver_slug, v)
if not condition_matches:
raise RuntimeError(
"requires Python '{}' but the running Python is {}".
format(
python_requires,
'.'.join(map(str, python_version[:3])),
)
)
def verify_required_python_runtime(s):
@functools.wraps(s)
def sw(**attrs):
try:
validate_required_python_or_fail(attrs.get('python_requires'))
except RuntimeError as re:
sys.exit('{} {!s}'.format(attrs['name'], re))
return s(**attrs)
return sw
setuptools.setup = ignore_unknown_options(setuptools.setup)
setuptools.setup = verify_required_python_runtime(setuptools.setup)
try:
from configparser import ConfigParser, NoSectionError
except ImportError:
from ConfigParser import ConfigParser, NoSectionError
ConfigParser.read_file = ConfigParser.readfp
def maybe_read_files(d):
"""Read files if the string starts with `file:` marker."""
FILE_FUNC_MARKER = 'file:'
d = d.strip()
if not d.startswith(FILE_FUNC_MARKER):
return d
descs = []
for fname in map(str.strip, str(d[len(FILE_FUNC_MARKER):]).split(',')):
with io.open(fname, encoding='utf-8') as f:
descs.append(f.read())
return ''.join(descs)
def cfg_val_to_list(v):
"""Turn config val to list and filter out empty lines."""
return list(filter(bool, map(str.strip, str(v).strip().splitlines())))
def cfg_val_to_dict(v):
"""Turn config val to dict and filter out empty lines."""
return dict(
map(lambda l: list(map(str.strip, l.split('=', 1))),
filter(bool, map(str.strip, str(v).strip().splitlines())))
)
def cfg_val_to_primitive(v):
"""Parse primitive config val to appropriate data type."""
return json.loads(v.strip().lower())
def read_configuration(filepath):
"""Read metadata and options from setup.cfg located at filepath."""
cfg = ConfigParser()
with io.open(filepath, encoding='utf-8') as f:
cfg.read_file(f)
md = dict(cfg.items('metadata'))
for list_key in 'classifiers', 'keywords', 'project_urls':
try:
md[list_key] = cfg_val_to_list(md[list_key])
except KeyError:
pass
try:
md['long_description'] = maybe_read_files(md['long_description'])
except KeyError:
pass
opt = dict(cfg.items('options'))
for list_key in 'include_package_data', 'use_scm_version', 'zip_safe':
try:
opt[list_key] = cfg_val_to_primitive(opt[list_key])
except KeyError:
pass
for list_key in 'scripts', 'install_requires', 'setup_requires':
try:
opt[list_key] = cfg_val_to_list(opt[list_key])
except KeyError:
pass
try:
opt['package_dir'] = cfg_val_to_dict(opt['package_dir'])
except KeyError:
pass
try:
opt_package_data = dict(cfg.items('options.package_data'))
if not opt_package_data.get('', '').strip():
opt_package_data[''] = opt_package_data['*']
del opt_package_data['*']
except (KeyError, NoSectionError):
opt_package_data = {}
try:
opt_extras_require = dict(cfg.items('options.extras_require'))
opt['extras_require'] = {}
for k, v in opt_extras_require.items():
opt['extras_require'][k] = cfg_val_to_list(v)
except NoSectionError:
pass
opt['package_data'] = {}
for k, v in opt_package_data.items():
opt['package_data'][k] = cfg_val_to_list(v)
try:
opt_exclude_package_data = dict(
cfg.items('options.exclude_package_data'),
)
if (
not opt_exclude_package_data.get('', '').strip()
and '*' in opt_exclude_package_data
):
opt_exclude_package_data[''] = opt_exclude_package_data['*']
del opt_exclude_package_data['*']
except NoSectionError:
pass
else:
opt['exclude_package_data'] = {}
for k, v in opt_exclude_package_data.items():
opt['exclude_package_data'][k] = cfg_val_to_list(v)
cur_pkgs = opt.get('packages', '').strip()
if '\n' in cur_pkgs:
opt['packages'] = cfg_val_to_list(opt['packages'])
elif cur_pkgs.startswith('find:'):
opt_packages_find = stringify_dict_contents(
dict(cfg.items('options.packages.find'))
)
opt['packages'] = setuptools.find_packages(**opt_packages_find)
return {'metadata': md, 'options': opt}
def cut_local_version_on_upload(version):
"""Generate a PEP440 local version if uploading to PyPI."""
import os
import setuptools_scm.version # only present during setup time
IS_PYPI_UPLOAD = os.getenv('PYPI_UPLOAD') == 'true' # set in tox.ini
return (
'' if IS_PYPI_UPLOAD
else setuptools_scm.version.get_local_node_and_date(version)
)
if HAS_DIST_INFO_CMD:
class patched_dist_info(setuptools.command.dist_info.dist_info):
def run(self):
self.egg_base = str_if_nested_or_str(self.egg_base)
return setuptools.command.dist_info.dist_info.run(self)
declarative_setup_params = read_configuration('setup.cfg')
"""Declarative metadata and options as read by setuptools."""
setup_params = {}
"""Explicit metadata for passing into setuptools.setup() call."""
setup_params = dict(setup_params, **declarative_setup_params['metadata'])
setup_params = dict(setup_params, **declarative_setup_params['options'])
if HAS_DIST_INFO_CMD:
setup_params['cmdclass'] = {
'dist_info': patched_dist_info,
}
setup_params['use_scm_version'] = {
'local_scheme': cut_local_version_on_upload,
}
# Patch incorrectly decoded package_dir option
# ``egg_info`` demands native strings failing with unicode under Python 2
# Ref https://github.com/pypa/setuptools/issues/1136
setup_params = stringify_dict_contents(setup_params)
__name__ == '__main__' and setuptools.setup(**setup_params)
|
metacloud/molecule
|
setup.py
|
Python
|
mit
| 12,584
|
# This SDK is deprecated
Howdy all! 👋 Thanks for checking out this repo. Your 👀 mean a lot to us. 💗
Unfortunately, this project is deprecated, and the code hosted here is woefully out of date. We wouldn't recommend it as anything other than a curiosity.
If you're interested in developing against the Pocket API, please visit our [Developer Documentation](https://getpocket.com/developer/).
Welcome!
========
Thanks for checking out the Pocket SDK. With a few lines of code, your app can quickly add support for saving URLs to users' Pocket lists.
## Installing the Pocket SDK ##
The Pocket SDK is the fastest way to add Pocket integration to any iOS or Mac application. Adding the Pocket SDK to your app is incredibly easy. Follow the steps below and you can be saving urls to Pocket from your app within 15 minutes.
### Step 1: Download the Pocket SDK ###
You can download the SDK at: [http://getpocket.com/api/v3/pocket-objc-sdk.zip](http://getpocket.com/api/v3/pocket-objc-sdk.zip)
You can also watch/checkout the SDK from GitHub at: [http://github.com/Pocket/Pocket-ObjC-SDK](http://github.com/Pocket/Pocket-ObjC-SDK). If you use recommend adding the Pocket SDK as a git submodule of your project by running `git submodule add git://github.com/Pocket/Pocket-ObjC-SDK.git <path>` from the root directory of your repository, replacing the `<path>` with the path you'd like it installed to.
If you use [CocoaPods](http://cocoapods.org/), you can add the `PocketAPI` pod to your Podfile. Then run `pod install`, and the Pocket SDK will be available in your project. See the documentation on the CocoaPods website if you want to set up a new or existing project.
The project download includes the SDK and an example project.
### Step 2: Add the Pocket SDK to your project ###
- Open your existing project.
- Drag the SDK folder from the example project into your Xcode project.
- Make sure the “Copy items into destination group’s folder (if needed)” checkbox is checked.
- Select your Xcode project in the Project Navigator, select your application target, select “Build Phases”, and add Security.framework to your “Link Binary With Libraries” phase.
The SDK includes all necessary source files and does not have any other dependencies.


###Step 3: Obtain a platform consumer key###
When you register your app with Pocket, it will provide you with a platform consumer key. This key identifies your app to Pocket’s API.
If you have not obtained a consumer key yet, you can register one at [http://getpocket.com/api/signup](http://getpocket.com/api/signup)
### Step 4: Add the Pocket URL scheme ###
Once you have the consumer key for the platform you are supporting, the application must register a URL scheme to receive login callbacks. By default, this is "pocketapp" plus your application's ID (which you can find at the beginning of the consumer key before the hyphen). So if your consumer key is 42-abcdef, your app ID is 42, and your URL scheme will be "pocketapp42".
If there are already URL schemes in your app’s Info.plist, you can either add the new URL scheme, or use an existing scheme by calling `[[PocketAPI sharedAPI] setURLScheme:@"YOUR-URL-SCHEME-HERE"]`. To add a URL Scheme, create a block like the one below in your Info.plist, updating it with the app’s scheme:
▾ URL Types (Array)
▾ Item 0 (Dictionary)
URL Identifier (String) com.getpocket.sdk
▾ URL Schemes (Array) (1 item)
Item 0 (String) [YOUR URL SCHEME, like "pocketapp42"]
Or you can copy and paste the following into the XML Source for the Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.readitlater</string>
<key>CFBundleURLSchemes</key>
<array>
<string>pocketapp9553</string>
</array>
</dict>
</array>
### Step 5: Configure your App Delegate ###
The final steps to set up the Pocket SDK requires adding a few lines of code to your main app delegate. This is the class where you include iOS required methods like applicationDidFinishLaunching.
#### Import the PocketAPI Header ####
At the top of your app delegate source file (and anywhere you call the PocketAPI object), you'll need to include the PocketAPI header. At the top of your class you'll probably see other imports already. Simply add this line:
#import "PocketAPI.h"
#### Set Your Platform Consumer Key ####
The Pocket SDK requires your consumer key in order to make any requests to the API. Call this method with your registered consumer key when launching your app:
[[PocketAPI sharedAPI] setConsumerKey:@"Your Consumer Key Here"];
#### Add a method for the Pocket url-scheme ####
The final step is to give the SDK an opportunity to handle incoming URLs. If you do not already implement this method on your app delegate, simply add the following method:
-(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation{
if([[PocketAPI sharedAPI] handleOpenURL:url]){
return YES;
}else{
// if you handle your own custom url-schemes, do it here
return NO;
}
}
### Step 6: Start Saving to Pocket! ###
At this point you’ve properly installed the SDK and can now start making requests and saving urls to Pocket. Here is a two line example:
NSURL *url = [NSURL URLWithString:@"http://google.com"];
[[PocketAPI sharedAPI] saveURL:url handler: ^(PocketAPI *API, NSURL *URL, NSError *error){
if(error){
// there was an issue connecting to Pocket
// present some UI to notify if necessary
}else{
// the URL was saved successfully
}
}];
The example above uses blocks which requires iOS 4.0 or greater. If you have a need to support iOS 3.0, you can use the delegate or operation based methods.
## Managing Accounts / Handling User Logins ##
Following Pocket’s API best practices, you’ll want to provide a way for the user to manage what account they are logged into. This is most commonly handled by adding a setting in your app’s option screen that lets the user configure their Pocket account. When the user taps this, you can simply call one line of code which will handle the entire authorization process:
[[PocketAPI sharedAPI] loginWithHandler: ^(PocketAPI *API, NSError *error){
if (error != nil)
{
// There was an error when authorizing the user. The most common error is that the user denied access to your application.
// The error object will contain a human readable error message that you should display to the user
// Ex: Show an UIAlertView with the message from error.localizedDescription
}
else
{
// The user logged in successfully, your app can now make requests.
// [API username] will return the logged-in user’s username and API.loggedIn will == YES
}
}];
It is also recommended to observe changes to the PocketAPI's username and loggedIn properties to determine when the logged-in user changes. If iOS terminates your application while it is in the background (e.g. due to memory constraints), any pending login attempts are automatically saved and restored at launch if needed. Therefore, your delegate/block responses may not get called. If you need to update UI when the logged in user changes, register for observers on PocketAPI at application launch.
### Calling Other Pocket APIs ###
To call other arbitrary APIs, pass the API's method name, the HTTP method name, and an NSDictionary of arguments. An NSDictionary with the response from the API will be passed to the handler.
NSString *apiMethod = ...;
PocketAPIHTTPmethod httpMethod = ...; // usually PocketAPIHTTPMethodPOST
NSDictionary *arguments = ...;
[[PocketAPI sharedAPI] callAPIMethod:apiMethod
withHTTPMethod:httpMethod
arguments:arguments
handler: ^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
// handle the response here
}];
## Enabling Extension Support ##
The first step is to "Enable Keychain Sharing" in both your app and extension capabilities in Xcode.

See [Configuring Keychain Sharing](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW15) for more information.
Final step is to add the following before you initialize the PocketAPI in your main app and extension:
[[PocketAPI sharedAPI] enableKeychainSharingWithKeychainAccessGroup:@"Your Keychain Access Group"];
[[PocketAPI sharedAPI] setConsumerKey:@"Your Consumer Key Here"];
After enabling keychain sharing, the app and extensions can access data that is securely stored in the keychain. From now on you can use the default methods of the PocketAPI class to save links from within extensions. See [Step 6: Start Saving to Pocket!](#step-6-start-saving-to-pocket) for more details.
Acknowledgements
================
The Pocket SDK uses the following open source software:
- [SFHFKeychainUtils](https://github.com/ldandersen/scifihifi-iphone/tree/master/security) for saving user credentials securely to the keychain.
- [UIDevice-Hardware](https://github.com/erica/uidevice-extension) for creating a user agent
License
=======
Copyright (c) 2015 Read It Later, Inc.
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.
|
Pocket/Pocket-ObjC-SDK
|
README.md
|
Markdown
|
mit
| 10,841
|
from django.contrib import admin
from xbee_module.models import xbee_module
# Register your models here.
admin.site.register(xbee_module);
|
EricJones89/SmartHome
|
SmartHome/xbee_module/admin.py
|
Python
|
mit
| 139
|
# banshee
Banshee is a Python script that tails your access log and ban abusive IP addresses from accessing your Django applications.
## Installation
Place the 'ip' directory into your Django project directory.
Update your project settings.py by adding 'ip' into your INSTALLED_APPS.
Run 'python manage.py syncdb', you should see this:
Creating table ip_bannedip
Update at least the following 3 entries in banshee.config:
# API to add newly banned IP address
'ban_ip_url': 'http://localhost/ip/ban_ip'
# Magic key is required for all HTTP POST requests sent to the API above
'magic_key': 'iLzmJkPe8JbzMmt30Frz',
# List of strings that may appear in request URL; these are the monitored requests
'watchlist': [
'/app1',
'/app2',
],
Add a cronjob entry to ensure banshee.py is always running, example:
* * * * * python BANSHEE_PY --access_log=ACCESS_LOG >> banshee.log 2>&1
* Replace BANSHEE_PY with the absolute path to banshee.py
* Replace ACCESS_LOG with the absolute path to your web server access log
* Piping the STDOUT and STDERR to banshee.log is optional
## Usage
Use `ip.is_allowed_ip` view function to check if an IP address has been banned.
The default max. requests that a particular IP address can make within 60 minutes period is set to 30.
Change `banshee.config['max_requests']` if you wish to increase or decrease this value.
Certain user agents are never banned by banshee.
You may want to change the list of these user agents in `banshee.config['passthrough_user_agents']`
Instead of whitelisting user agents, a better alternative would be to always allow requests from a trusted network.
You may update the list of networks that you trust in `banshee.config['trusted_networks']`
Banshee recognizes web server access log that uses the following log format:
LogFormat "%{X-Forwarded-For}i %l %u %t %T \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
|
ayeowch/banshee
|
README.md
|
Markdown
|
mit
| 1,953
|
export default function singleOrDefault<TSource>(this: Iterable<TSource>): TSource | null;
export default function singleOrDefault<TSource>(this: Iterable<TSource>, predicate: (element: TSource) => boolean): TSource | null;
export default function singleOrDefault<TSource>(this: Iterable<TSource>, predicate: ((element: TSource) => boolean) | null, defaultValue: TSource): TSource;
export default function singleOrDefault<TSource>(this: Iterable<TSource>, predicate?: ((element: TSource) => boolean) | null, defaultValue: TSource | null = null): TSource | null {
if (predicate) {
let value: TSource | undefined;
let hasValue = false;
for (const element of this) {
if (predicate(element)) {
if (hasValue) {
return defaultValue;
}
value = element;
hasValue = true;
}
}
if (hasValue) {
return value as TSource;
}
} else {
if (Array.isArray(this)) {
switch ((this as any).length) {
case 1:
return (this as any)[0];
default:
return defaultValue;
}
} else {
let value: TSource | undefined;
let hasValue = false;
for (const element of this) {
if (hasValue) {
return defaultValue;
}
value = element;
hasValue = true;
}
if (hasValue) {
return value as TSource;
}
}
}
return defaultValue;
}
|
emonkak/js-enumerable
|
src/singleOrDefault.ts
|
TypeScript
|
mit
| 1,645
|
require "spec_helper"
describe Moneybird::Service::SalesInvoice do
let(:client) { Moneybird::Client.new('bearer token') }
let(:service) { Moneybird::Service::SalesInvoice.new(client, '123') }
describe "#all" do
before do
stub_request(:get, 'https://moneybird.com/api/v2/123/sales_invoices')
.to_return(status: 200, body: fixture_response(:sales_invoices))
end
it "returns list of sales_invoices" do
sales_invoices = service.all
_(sales_invoices.length).must_equal 3
_(sales_invoices.first.id).must_equal "194733567493801235"
end
end
describe "#save" do
let(:id) { '1' }
let(:attributes) { { id: id, reference: 'FooBar' } }
it "creates when not persisted" do
stub_request(:post, "https://moneybird.com/api/v2/123/sales_invoices")
.to_return(status: 201, body: fixture_response(:sales_invoice))
attributes.delete(:id)
resource = service.build(attributes)
_(service.save(resource)).must_equal resource
end
it "updates when persisted" do
stub_request(:patch, "https://moneybird.com/api/v2/123/sales_invoices/#{id}")
.to_return(status: 200, body: fixture_response(:sales_invoice))
resource = service.build(attributes)
_(service.save(resource)).must_equal resource
end
end
describe "#send_invoice" do
before do
stub_request(:patch, 'https://moneybird.com/api/v2/123/sales_invoices/456/send_invoice')
.to_return(status: 200, body: fixture_response(:sales_invoice))
end
let(:sales_invoice) { Moneybird::Resource::SalesInvoice.new(client: client, id: '456') }
it "will send the invoice" do
_(service.send_invoice(sales_invoice)).must_equal sales_invoice
end
end
describe "#download_pdf" do
before do
stub_request(:get, 'https://moneybird.com/api/v2/123/sales_invoices/456/download_pdf')
.to_return(
status: 302,
body: 'This resource has been moved temporarily.',
headers: {
'Location' => 'https://storage.moneybird.dev/036ce3bd95c725c04aa5b81ee9419f9b49246a4b91483c2ad913e31a99204fa6/36cabf4c517ca62001f1bd3c9e014b0cacb2f77e9c24ab432c72ca6dc1820b6e/download'
})
end
it "will return download url" do
_(service.download_pdf(456)).must_equal 'https://storage.moneybird.dev/036ce3bd95c725c04aa5b81ee9419f9b49246a4b91483c2ad913e31a99204fa6/36cabf4c517ca62001f1bd3c9e014b0cacb2f77e9c24ab432c72ca6dc1820b6e/download'
end
end
describe "#mark_as_uncollectible" do
before do
stub_request(:patch, 'https://moneybird.com/api/v2/123/sales_invoices/456/mark_as_uncollectible')
.to_return(status: 200, body: fixture_response(:sales_invoice))
end
let(:sales_invoice) { Moneybird::Resource::SalesInvoice.new(client: client, id: '456') }
it "will mark the invoice as uncollectible" do
_(service.mark_as_uncollectible(sales_invoice)).must_equal sales_invoice
end
end
end
|
maartenvanvliet/moneybird
|
spec/lib/moneybird/service/sales_invoice_spec.rb
|
Ruby
|
mit
| 2,977
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.