answer
stringlengths 15
1.25M
|
|---|
// Ecma International makes this code available under the terms and conditions set
function testcase() {
function callbackfn(prevVal, curVal, idx, obj) {
return (obj.length === 2);
}
try {
var oldLen = fnGlobalObject().length;
fnGlobalObject()[0] = 12;
fnGlobalObject()[1] = 11;
fnGlobalObject()[2] = 9;
fnGlobalObject().length = 2;
return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true;
} finally {
delete fnGlobalObject()[0];
delete fnGlobalObject()[1];
delete fnGlobalObject()[2];
fnGlobalObject().length = oldLen;
}
}
runTestCase(testcase);
|
import builder = require('botbuilder');
export module Helpers {
export class API {
public static async DownloadJson(url:string, post:boolean=false, options:any=undefined): Promise<string>{
return new Promise<string>(resolve => {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.onload = function (){
try {
resolve(xhr.responseText);
}
catch(e){
console.log("Error while calling api: " + e.message);
}
};
xhr.open(options ? "POST" : "GET", url, true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(options));
});
}
}
export enum SearchType { "code", "documentation" };
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WingtipToys.Models;
namespace WingtipToys.Logic
{
public class AddProducts
{
public bool AddProduct(string ProductName, string ProductDesc, string ProductPrice, string ProductCategory, string ProductImagePath)
{
var myProduct = new Product();
myProduct.ProductName = ProductName;
myProduct.Description = ProductDesc;
myProduct.UnitPrice = Convert.ToDouble(ProductPrice);
myProduct.ImagePath = ProductImagePath;
myProduct.CategoryID = Convert.ToInt32(ProductCategory);
using (ProductContext _db = new ProductContext())
{
// Add product to DB.
_db.Products.Add(myProduct);
_db.SaveChanges();
}
// Success.
return true;
}
}
}
|
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.security.fluent.models.<API key>;
/** An instance of this class provides access to all the operations defined in <API key>. */
public interface <API key> {
/**
* List the available security controls, their assessments, and the max score.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<<API key>> list();
/**
* List the available security controls, their assessments, and the max score.
*
* @param context The context to associate with this operation.
* @throws <API key> thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<<API key>> list(Context context);
/**
* For a specified subscription, list the available security controls, their assessments, and the max score.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<<API key>> listBySubscription();
/**
* For a specified subscription, list the available security controls, their assessments, and the max score.
*
* @param context The context to associate with this operation.
* @throws <API key> thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<<API key>> listBySubscription(Context context);
}
|
<?php
namespace Seahinet\Catalog\Indexer;
use Seahinet\Catalog\Model\Collection\Product;
use Seahinet\Catalog\Model\Product as ProductModel;
use Seahinet\Catalog\Model\Collection\Category;
use Seahinet\Lib\Db\Sql\Ddl\Column\UnsignedInteger;
use Seahinet\Lib\Indexer\Handler\AbstractHandler;
use Seahinet\Lib\Indexer\Handler\Database;
use Seahinet\Lib\Indexer\Provider;
use Seahinet\Lib\Model\Collection\Language;
use Zend\Db\Sql\Ddl;
class Url implements Provider
{
use \Seahinet\Lib\Traits\Container;
protected $path = [];
public function provideStructure(AbstractHandler $handler)
{
if ($handler instanceof Database) {
$adapter = $this->getContainer()->get('dbAdapter');
$platform = $adapter->getPlatform();
$languages = new Language;
$languages->columns(['id']);
foreach ($languages as $language) {
$table = 'catalog_url_' . $language['id'] . '_index';
$adapter->query(
'DROP TABLE IF EXISTS ' . $table, $adapter::QUERY_MODE_EXECUTE
);
$ddl = new Ddl\CreateTable($table);
$ddl->addColumn(new UnsignedInteger('product_id', true, 0))
->addColumn(new UnsignedInteger('category_id', false, 0))
->addColumn(new Ddl\Column\Varchar('path', 512, false))
->addConstraint(new Ddl\Constraint\UniqueKey(['category_id', 'product_id'], 'UNQ_' . strtoupper($table) . '<API key>'))
->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '<API key>', 'product_id', 'product_entity', 'id', 'CASCADE', 'CASCADE'))
->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '<API key>', 'category_id', 'category_entity', 'id', 'CASCADE', 'CASCADE'))
->addConstraint(new Ddl\Index\Index('path', 'IDX_' . strtoupper($table) . '_PATH'));
$adapter->query(
$ddl->getSqlString($platform), $adapter::QUERY_MODE_EXECUTE
);
}
} else {
$handler->buildStructure([['attr' => 'path', 'is_unique' => 1]]);
}
return true;
}
public function provideData(AbstractHandler $handler)
{
$languages = new Language;
$languages->columns(['id']);
foreach ($languages as $language) {
$categories = new Category($language['id']);
$categories->where(['status' => 1]);
$categories->load(false);
$data = [$language['id'] => []];
$tree = [];
foreach ($categories as $category) {
$tree[$category['id']] = [
'object' => $category,
'pid' => (int) $category['parent_id']
];
}
foreach ($categories as $category) {
if ($path = $this->getPath($category, $tree)) {
$data[$language['id']][$category['id']] = [
'product_id' => null,
'category_id' => $category['id'],
'path' => $path
];
}
}
$handler->buildData($data);
$products = new Product($language['id']);
$products->where(['status' => 1])->limit(50);
$init = $data;
for ($i = 0;; $i++) {
$data = [$language['id'] => []];
$products->reset('offset')->offset(50 * $i);
$products->load(false, true);
if (!$products->count()) {
break;
}
foreach ($products as $product) {
$product = new ProductModel($language['id'], $product);
$categories = $product->getCategories();
foreach ($categories as $category) {
$data[$language['id']][] = [
'product_id' => $product['id'],
'category_id' => $category['id'],
'path' => (isset($init[$language['id']][$category['id']]['path']) ?
($init[$language['id']][$category['id']]['path'] . '/') : '') .
$product['uri_key']
];
}
}
$data[$language['id']] = array_values($data[$language['id']]);
$handler->buildData($data);
}
}
return true;
}
private function getPath($category, $tree)
{
if (isset($this->path[$category['id'] . '#' . $category['uri_key']])) {
return $this->path[$category['id'] . '#' . $category['uri_key']];
}
if (!isset($category['uri_key'])) {
return '';
}
$path = $category['uri_key'];
$pid = (int) $category['parent_id'];
if ($pid && isset($tree[$pid])) {
$path = trim($this->getPath($tree[$pid]['object'], $tree) . '/' . $path, '/');
}
$this->path[$category['id'] . '#' . $category['uri_key']] = $path;
return $path;
}
}
|
package org.superboot.service;
import com.querydsl.core.types.Predicate;
import org.springframework.data.domain.Pageable;
import org.superboot.base.BaseException;
import org.superboot.base.BaseResponse;
/**
* <b> </b>
* <p>
* :
* </p>
*/
public interface ErrorLogService {
/**
*
*
* @return
* @throws BaseException
*/
BaseResponse <API key>() throws BaseException;
/**
*
*
* @param pageable
* @param predicate
* @return
* @throws BaseException
*/
BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException;
/**
*
*
* @return
* @throws BaseException
*/
BaseResponse getErrorLogCount(Predicate predicate) throws BaseException;
/**
*
*
* @param id
* @return
* @throws BaseException
*/
BaseResponse getErrorLogItem(String id) throws BaseException;
}
|
$(function () {
var $container = $('#container');
var certificatesInfo = $container.data('certinfo');
var runDate = $container.data('rundate');
$('#created_date').html(runDate);
var sorted_certificates = Object.keys(certificatesInfo)
.sort(function( a, b ) {
return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left;
}).map(function(sortedKey) {
return certificatesInfo[sortedKey];
});
var card_html = String()
+'<div class="col-xs-12 col-md-6 col-xl-4">'
+' <div class="card text-xs-center" style="border-color:#333;">'
+' <div class="card-header" style="overflow:hidden;">'
+' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>'
+' </div>'
+' <div class="card-block {{background}}">'
+' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>'
+' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>'
+' </div>'
+' <div class="card-footer">'
+' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>'
+' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>'
+' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>'
+' </div>'
+' </div>'
+'</div>';
function insert_card(json) {
var card_template = Handlebars.compile(card_html),
html = card_template(json);
$('#panel').append(html);
};
sorted_certificates.forEach(function(element, index, array){
var json = {
'server': element.server,
'days_left': element.info.days_left,
'issuer': element.issuer.org,
'common_name': element.subject.common_name,
'issuer_cn': element.issuer.common_name
}
if (element.info.days_left <= 30 ){
json.background = 'card-inverse card-danger';
} else if (element.info.days_left > 30 && element.info.days_left <= 60 ) {
json.background = 'card-inverse card-warning';
} else if (element.info.days_left === "??") {
json.background = 'card-inverse card-info';
} else {
json.background = 'card-inverse card-success';
}
insert_card(json);
});
});
|
title: "Configuring the Terminal on a New Macbook"
date: 2016-06-01 21:12:00
category: post
tags: [efficiency, osx, shell, sublime]
I bought a new Macbook Pro Retina today for personal use, and spent most of the day re-configuring the terminal and development environment to match my old machine. This post is both a reference for my future self (to save some time with future environment configuration) and a set of recommendations for anyone looking for some time saving tricks.
## [Changing `ls` Colors][ls]{:target="_blank"}
The default colors displayed in the output of the `ls` command in the terminal don't make any differentiation between folders or file types. The guide above highlights a few environment variables to set in your `~/.bash_profile` that allow for customization of the colors of `ls` output. This is exceedingly helpful when trying to navigate foreign folder structures, or trying to find that one executable in a sea of non executables.
The variables are as follows:
{% highlight shell %}
export CLICOLOR=1 # tells the shell to apply coloring to command output (just needs to be set)
export LSCOLORS=<API key> # configuration of colors for particular file types
# NOTE: see the article linked above for detail on LSCOLORS values
{% endhighlight %}
## [Sublime Text Symlink][subl]{:target="_blank"}
My text editor of preference is Sublime, so the article linked above is applicable for creating a symlink for its CLI and adding it to your path. This is convenient since it allows you to open a file (or folder) in your text editor of choice ***from the command line***, instead of having to open files manually from the editor itself. Once you create the symlink, make sure you add the location of the link to your path and put it in your `~/.bash_profile`.
{% highlight shell %}
export PATH=$PATH:~/.bin # augments PATH with location of sublime symlink
{% endhighlight %}
## Additional Sublime Configuration
On the topic of Sublime, I recommend enabling the following options in `Preferences > Settings - User`:
{%highlight json%}
{
"<API key>": true,
"<API key>": true,
"scroll_past_end": true
}
{%endhighlight%}
`<API key>` will do just that, making your diffs in github easier to parse through.
`<API key>` is also self explanatory, and keeps your files consistent with the expectation of many unix based text editing utilities that non-empty files have a newline `\n` at the end. Github also tracks this in files, so having it enabled ensures all of your files remain consistent and do not show up in diffs because newlines were removed.
`scroll_past_end` lets the editor scroll further down than the last line of the file. This is useful to bring text at the end of a file higher up in the editor, without needing to add a bunch of unnecessary blank lines.
## [Current Git Branch in Your PS1][gbps1]{:target="_blank"}
This one blew my mind when I enabled it, and also taught me how to configure the "Prompt String 1" (PS1) that displays by default in the terminal. Just follow the instructions in the post above, which involves adding a shell function to your `~/.bash_profile` that checks for the presence of a git repository and parses the text of the current branch. If a branch was found, the name of the branch will be added to your `PS1`, right before your cursor! Knowing what branch you're on is critical when working on a complex project with multiple branches, preventing inadvertent work in / commits to the wrong branch.
## [Tab Completion of Git Branches][tab]{:target="_blank"}
Another trick that saves me a lot of time is tab completion of git branches. Without this, you are forced to type out the full branch name to which you are switching, which slows you down. See the SO post linked above for details on enabling this. It involves downloading a script that performs the tab completion logic (credit to Shawn O. Pearce <spearce@spearce.org>) and sourcing it in your `~/.bash_profile`. In all honestly I haven't looked through the script in much detail... but works like a charm!
Let me know in the comments if you have any additional time saving tricks that you think I've missed. I'm always interested in improving my personal development process.
[ls]: http://osxdaily.com/2012/02/21/<API key>/
[subl]: http://stackoverflow.com/questions/16199581/<API key>#answer-16495202
[gbps1]: https://coderwall.com/p/fasnya/<API key>
[tab]: http://apple.stackexchange.com/a/55886
|
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1')
fig1 = plt.figure(1)
img1.seek(0)
# for i in range(250):
# pixA11 = img1.getpixel((1,i))
# print(pixA11)
f1 = list(img1.getdata())
print(f1[1000])
plt.imshow(img1)
fig1.show()
input()
# Plots eleventh frame
# print('Frame 11')
# fig2 = plt.figure(2)
# img1.seek(10)
# # for i in range(250):
# # pixB11 = img1.getpixel((1,i))
# # print(pixB11)
# f2 = list(img1.getdata())
# print(f2[10000])
# plt.imshow(img1)
# fig2.show()
# input()
# Create a new image
fig3 = plt.figure(3)
imgAvg = Image.new(img1.mode, img1.size)
print(img1.mode)
print(img1.size)
fAvg = list()
pix = imgAvg.load()
for i in range(512):
for j in range(512):
pixVal = (f1[i*512+j] + f1[i*512+j]) / 2
# fAvg.append(pixVal)
fAvg.insert(i*512+j,pixVal)
imgAvg.putdata(fAvg)
imgAvg.save('avg.tiff')
plt.imshow(imgAvg)
fig3.show()
print('Average')
# The following is necessary to keep the above figures 'alive'
input()
# data = random.random((256, 256))
# img1 = Image.fromarray(data)
# img1.save('test.tiff')
|
FROM nginx
MAINTAINER Konstantin Volodin, volodin.konstantin@gmail.com
COPY nginx.conf /etc/nginx
EXPOSE 80
EXPOSE 5500
ENTRYPOINT nginx -g "daemon off;"
|
FROM golang:alpine as build
WORKDIR /go/src
COPY main.go .
RUN go build -o /go/bin/memhogger .
FROM alpine
LABEL maintainer="Michael Gasch <embano1@live.com>"
COPY --from=build /go/bin/memhogger /bin/memhogger
ENTRYPOINT ["memhogger"]
|
-- phpMyAdmin SQL Dump
-- version 4.0.9
-- http:
-- Host: 127.0.0.1
-- Generation Time: May 11, 2014 at 07:52 AM
SET SQL_MODE = "<API key>";
SET time_zone = "+00:00";
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET NAMES utf8 */;
-- Database: `apdb`
-- Table structure for table `bm2`
CREATE TABLE IF NOT EXISTS `bm2` (
`date` int(11) NOT NULL,
`att` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `bm2`
INSERT INTO `bm2` (`date`, `att`) VALUES
(1, 90),
(2, 88),
(3, 0),
(4, 88),
(5, 90),
(6, 92),
(7, 88),
(8, 90),
(9, 86),
(10, 0),
(11, 86),
(12, 0),
(13, 85),
(14, 90),
(15, 92),
(16, 88),
(17, 0),
(18, 86),
(19, 92),
(20, 93),
(21, 90),
(22, 90),
(23, 92),
(24, 0),
(25, 93),
(26, 93),
(27, 93),
(28, 93),
(29, 93),
(30, 0),
(31, 0);
-- Table structure for table `fan`
CREATE TABLE IF NOT EXISTS `fan` (
`date` date NOT NULL,
`ta` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Table structure for table `school_name`
CREATE TABLE IF NOT EXISTS `school_name` (
`sid` varchar(5) NOT NULL,
`sname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `school_name`
INSERT INTO `school_name` (`sid`, `sname`) VALUES
('s1', 'GLPS- NELGULI'),
('', ''),
('s2', 'GLPS SEETHARAMAM PALYA '),
('s3', 'RBANMS - HPS - DICKENSON ROAD '),
('s4', 'GHPS - BASAVANNA NAGARA'),
('s5', 'GLPS - SADANA PALYA');
-- Table structure for table `superv`
CREATE TABLE IF NOT EXISTS `superv` (
`date` date NOT NULL,
`te` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Table structure for table `superv2`
CREATE TABLE IF NOT EXISTS `superv2` (
`date` int(11) NOT NULL,
`te` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `superv2`
INSERT INTO `superv2` (`date`, `te`, `fb`) VALUES
(1, 90, ''),
(2, 84, ''),
(3, 0, ''),
(4, 86, ''),
(5, 91, ''),
(6, 92, ''),
(7, 89, ''),
(8, 88, ''),
(9, 87, ''),
(10, 0, ''),
(11, 88, ''),
(12, 0, ''),
(13, 86, ''),
(14, 92, ''),
(15, 92, ''),
(16, 90, ''),
(17, 0, ''),
(18, 88, ''),
(19, 92, ''),
(20, 94, ''),
(21, 90, ''),
(22, 91, ''),
(23, 92, ''),
(24, 0, ''),
(25, 92, ''),
(26, 92, ''),
(27, 92, ''),
(28, 90, ''),
(29, 92, ''),
(30, 0, ''),
(31, 0, '');
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */;
|
package com.InfinityRaider.AgriCraft.utility;
import com.InfinityRaider.AgriCraft.items.ItemAgricraft;
import com.InfinityRaider.AgriCraft.items.ItemNugget;
import com.InfinityRaider.AgriCraft.reference.Data;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class OreDictHelper {
private static final Map<String, Block> oreBlocks = new HashMap<String, Block>();
private static final Map<String, Integer> oreBlockMeta = new HashMap<String, Integer>();
private static final Map<String, Item> nuggets = new HashMap<String, Item>();
private static final Map<String, Integer> nuggetMeta = new HashMap<String, Integer>();
public static Block getOreBlockForName(String name) {
return oreBlocks.get(name);
}
public static int getOreMetaForName(String name) {
return oreBlockMeta.get(name);
}
public static Item getNuggetForName(String name) {
return nuggets.get(name);
}
public static int <API key>(String name) {
return nuggetMeta.get(name);
}
//checks if an itemstack has this ore dictionary entry
public static boolean hasOreId(ItemStack stack, String tag) {
if(stack==null || stack.getItem()==null) {
return false;
}
int[] ids = OreDictionary.getOreIDs(stack);
for(int id:ids) {
if(OreDictionary.getOreName(id).equals(tag)) {
return true;
}
}
return false;
}
public static boolean hasOreId(Block block, String tag) {
return block != null && hasOreId(new ItemStack(block), tag);
}
//checks if two blocks have the same ore dictionary entry
public static boolean isSameOre(Block block1, int meta1, Block block2, int meta2) {
if(block1==block2 && meta1==meta2) {
return true;
}
if(block1==null || block2==null) {
return false;
}
int[] ids1 = OreDictionary.getOreIDs(new ItemStack(block1, 1, meta1));
int[] ids2 = OreDictionary.getOreIDs(new ItemStack(block2, 1, meta2));
for (int id1:ids1) {
for (int id2:ids2) {
if (id1==id2) {
return true;
}
}
}
return false;
}
//finds the ingot for a nugget ore dictionary entry
public static ItemStack getIngot(String ore) {
ItemStack ingot = null;
ArrayList<ItemStack> entries = OreDictionary.getOres("ingot" + ore);
if (entries.size() > 0 && entries.get(0).getItem() != null) {
ingot = entries.get(0);
}
return ingot;
}
//finds what ores and nuggets are already registered in the ore dictionary
public static void getRegisteredOres() {
//Vanilla
for (String oreName : Data.vanillaNuggets) {
getOreBlock(oreName);
if(oreBlocks.get(oreName)!=null) {
getNugget(oreName);
}
}
//Modded
for (String[] data : Data.modResources) {
String oreName = data[0];
getOreBlock(oreName);
if(oreBlocks.get(oreName)!=null) {
getNugget(oreName);
}
}
}
private static void getOreBlock(String oreName) {
for (ItemStack itemStack : OreDictionary.getOres("ore"+oreName)) {
if (itemStack.getItem() instanceof ItemBlock) {
ItemBlock block = (ItemBlock) itemStack.getItem();
oreBlocks.put(oreName, block.field_150939_a);
oreBlockMeta.put(oreName, itemStack.getItemDamage());
break;
}
}
}
private static void getNugget(String oreName) {
List<ItemStack> nuggets = OreDictionary.getOres("nugget" + oreName);
if (!nuggets.isEmpty()) {
Item nugget = nuggets.get(0).getItem();
OreDictHelper.nuggets.put(oreName, nugget);
nuggetMeta.put(oreName, nuggets.get(0).getItemDamage());
} else {
ItemAgricraft nugget = new ItemNugget(oreName);
OreDictionary.registerOre("nugget"+oreName, nugget);
OreDictHelper.nuggets.put(oreName, nugget);
nuggetMeta.put(oreName, 0);
}
}
public static ArrayList<ItemStack> <API key>(ItemStack seed) {
return <API key>(seed, true);
}
public static ArrayList<ItemStack> <API key>(ItemStack seed, boolean sameMod) {
String seedModId = IOHelper.getModId(seed);
ArrayList<ItemStack> fruits = new ArrayList<ItemStack>();
for(int id:OreDictionary.getOreIDs(seed)) {
if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) {
String name = OreDictionary.getOreName(id).substring(4);
ArrayList<ItemStack> fromOredict = OreDictionary.getOres("crop"+name);
for(ItemStack stack:fromOredict) {
if(stack==null || stack.getItem()==null) {
continue;
}
String stackModId = IOHelper.getModId(stack);
if((!sameMod) || stackModId.equals(seedModId)) {
fruits.add(stack);
}
}
}
}
return fruits;
}
}
|
'use strict';
//Setting up route
angular.module('socketio-area').config(['$stateProvider',
function($stateProvider) {
// Socketio area state routing
$stateProvider.
state('socketio-area', {
url: '/socketio',
templateUrl: 'modules/socketio-area/views/socketio-area.client.view.html'
});
}
]);
|
#include "utlua.h"
#ifdef __linux__
#include <limits.h>
#include <linux/netfilter_ipv4.h>
#endif
#include <net/if.h>
#define <API key> "<tcpd.connect>"
#define <API key> "<tcpd.bind %s %d>"
#define <API key> "<tcpd.accept %s %d>"
#if FAN_HAS_OPENSSL
typedef struct
{
SSL_CTX *ssl_ctx;
char *key;
int retainCount;
} SSLCTX;
#endif
typedef struct
{
struct bufferevent *buf;
#if FAN_HAS_OPENSSL
SSLCTX *sslctx;
int ssl_verifyhost;
int ssl_verifypeer;
const char *ssl_error;
#endif
lua_State *mainthread;
int onReadRef;
int onSendReadyRef;
int onDisconnectedRef;
int onConnectedRef;
char *host;
char *ssl_host;
int port;
int send_buffer_size;
int receive_buffer_size;
int interface;
lua_Number read_timeout;
lua_Number write_timeout;
} Conn;
#if FAN_HAS_OPENSSL
#define VERIFY_DEPTH 5
static int conn_index = 0;
#endif
typedef struct
{
struct evconnlistener *listener;
lua_State *mainthread;
int onAcceptRef;
int onSSLHostNameRef;
char *host;
int port;
int ipv6;
#if FAN_HAS_OPENSSL
int ssl;
SSL_CTX *ctx;
EC_KEY *ecdh;
#endif
int send_buffer_size;
int receive_buffer_size;
} SERVER;
typedef struct
{
struct bufferevent *buf;
lua_State *mainthread;
int onReadRef;
int onSendReadyRef;
int selfRef;
char ip[INET6_ADDRSTRLEN];
int port;
int onDisconnectedRef;
} ACCEPT;
#define TCPD_ACCEPT_UNREF(accept) \
CLEAR_REF(accept->mainthread, accept->onSendReadyRef) \
CLEAR_REF(accept->mainthread, accept->onReadRef) \
CLEAR_REF(accept->mainthread, accept->onDisconnectedRef) \
CLEAR_REF(accept->mainthread, accept->selfRef)
LUA_API int <API key>(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, <API key>);
CLEAR_REF(L, serv->onAcceptRef)
CLEAR_REF(L, serv->onSSLHostNameRef)
if (serv->host)
{
free(serv->host);
serv->host = NULL;
}
if (<API key>() && serv->listener)
{
evconnlistener_free(serv->listener);
serv->listener = NULL;
}
#if FAN_HAS_OPENSSL
if (serv->ctx)
{
SSL_CTX_free(serv->ctx);
EC_KEY_free(serv->ecdh);
serv->ctx = NULL;
serv->ecdh = NULL;
}
#endif
return 0;
}
LUA_API int lua_tcpd_server_gc(lua_State *L)
{
return <API key>(L);
}
LUA_API int <API key>(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
lua_pushfstring(L, <API key>, accept->ip, accept->port);
return 1;
}
LUA_API int <API key>(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, <API key>);
if (serv->listener)
{
char host[INET6_ADDRSTRLEN];
<API key>(<API key>(serv->listener), host);
lua_pushfstring(
L, <API key>, host,
<API key>(<API key>(serv->listener)));
}
else
{
lua_pushfstring(L, <API key>, 0);
}
return 1;
}
static void tcpd_accept_eventcb(struct bufferevent *bev, short events,
void *arg)
{
ACCEPT *accept = (ACCEPT *)arg;
if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF ||
events & BEV_EVENT_TIMEOUT)
{
if (events & BEV_EVENT_ERROR)
{
#if DEBUG
printf("BEV_EVENT_ERROR %s\n",
<API key>(EVUTIL_SOCKET_ERROR()));
#endif
}
bufferevent_free(bev);
accept->buf = NULL;
if (accept->onDisconnectedRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onDisconnectedRef);
if (events & BEV_EVENT_ERROR && EVUTIL_SOCKET_ERROR())
{
lua_pushstring(co,
<API key>(EVUTIL_SOCKET_ERROR()));
}
else if (events & BEV_EVENT_TIMEOUT)
{
lua_pushstring(co, "timeout");
}
else if (events & BEV_EVENT_EOF)
{
lua_pushstring(co, "client disconnected");
}
else
{
lua_pushnil(co);
}
CLEAR_REF(mainthread, accept->onDisconnectedRef)
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
TCPD_ACCEPT_UNREF(accept)
}
else
{
}
}
#define BUFLEN 1024
static void tcpd_accept_readcb(struct bufferevent *bev, void *ctx)
{
ACCEPT *accept = (ACCEPT *)ctx;
char buf[BUFLEN];
int n;
BYTEARRAY ba = {0};
bytearray_alloc(&ba, BUFLEN * 2);
struct evbuffer *input = <API key>(bev);
while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0)
{
<API key>(&ba, buf, n);
}
<API key>(&ba);
if (accept->onReadRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onReadRef);
lua_pushlstring(co, (const char *)ba.buffer, ba.total);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
bytearray_dealloc(&ba);
}
static void tcpd_accept_writecb(struct bufferevent *bev, void *ctx)
{
ACCEPT *accept = (ACCEPT *)ctx;
if (evbuffer_get_length(<API key>(bev)) == 0)
{
if (accept->onSendReadyRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onSendReadyRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
}
void connlistener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *addr, int socklen, void *arg)
{
SERVER *serv = (SERVER *)arg;
if (serv->onAcceptRef != LUA_NOREF)
{
lua_State *mainthread = serv->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onAcceptRef);
ACCEPT *accept = lua_newuserdata(co, sizeof(ACCEPT));
memset(accept, 0, sizeof(ACCEPT));
accept->buf = NULL;
accept->mainthread = mainthread;
accept->selfRef = LUA_NOREF;
accept->onReadRef = LUA_NOREF;
accept->onSendReadyRef = LUA_NOREF;
accept->onDisconnectedRef = LUA_NOREF;
luaL_getmetatable(co, <API key>);
lua_setmetatable(co, -2);
struct event_base *base = <API key>(listener);
struct bufferevent *bev;
#if FAN_HAS_OPENSSL
if (serv->ssl && serv->ctx)
{
bev = <API key>(
base, fd, SSL_new(serv->ctx), <API key>,
<API key> | <API key>);
}
else
{
#endif
bev = <API key>(base, fd, <API key> | <API key>);
#if FAN_HAS_OPENSSL
}
#endif
bufferevent_setcb(bev, tcpd_accept_readcb, tcpd_accept_writecb,
tcpd_accept_eventcb, accept);
bufferevent_enable(bev, EV_READ | EV_WRITE);
if (serv->send_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &serv->send_buffer_size,
sizeof(serv->send_buffer_size));
}
if (serv->receive_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &serv->receive_buffer_size,
sizeof(serv->receive_buffer_size));
}
memset(accept->ip, 0, INET6_ADDRSTRLEN);
if (addr->sa_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), accept->ip,
INET_ADDRSTRLEN);
accept->port = ntohs(addr_in->sin_port);
}
else
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)addr;
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), accept->ip,
INET6_ADDRSTRLEN);
accept->port = ntohs(addr_in->sin6_port);
}
accept->buf = bev;
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
}
LUA_API int tcpd_accept_bind(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
luaL_checktype(L, 2, LUA_TTABLE);
lua_settop(L, 2);
lua_pushvalue(L, 1);
accept->selfRef = luaL_ref(L, LUA_REGISTRYINDEX);
<API key>(L, accept->onReadRef, 2, "onread")
<API key>(L, accept->onSendReadyRef, 2, "onsendready")
<API key>(L, accept->onDisconnectedRef, 2, "ondisconnected")
lua_pushstring(L, accept->ip);
lua_pushinteger(L, accept->port);
return 2;
}
#if FAN_HAS_OPENSSL
static int ssl_servername_cb(SSL *s, int *ad, void *arg)
{
const char *hostname = SSL_get_servername(s, <API key>);
// if (hostname)
// printf("Hostname in TLS extension: \"%s\"\n", hostname);
SERVER *serv = (SERVER *)arg;
if (hostname && serv->onSSLHostNameRef != LUA_NOREF)
{
lua_State *mainthread = serv->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onSSLHostNameRef);
lua_pushstring(co, hostname);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
// if (!p->servername)
// return <API key>;
// if (servername) {
// if (strcasecmp(servername, p->servername))
// return p->extension_error;
return SSL_TLSEXT_ERR_OK;
}
#endif
static void tcpd_server_rebind(lua_State *L, SERVER *serv)
{
if (serv->listener)
{
evconnlistener_free(serv->listener);
serv->listener = NULL;
}
if (serv->host)
{
char portbuf[6];
evutil_snprintf(portbuf, sizeof(portbuf), "%d", serv->port);
struct evutil_addrinfo hints = {0};
struct evutil_addrinfo *answer = NULL;
hints.ai_family = serv->ipv6 ? AF_INET6 : AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = <API key>;
int err = evutil_getaddrinfo(serv->host, portbuf, &hints, &answer);
if (err < 0 || !answer)
{
luaL_error(L, "invaild bind address %s:%d", serv->host, serv->port);
}
serv->listener =
<API key>(event_mgr_base(), connlistener_cb, serv,
<API key> | LEV_OPT_REUSEABLE, -1,
answer->ai_addr, answer->ai_addrlen);
evutil_freeaddrinfo(answer);
}
else
{
struct sockaddr *addr = NULL;
size_t addr_size = 0;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
memset(&sin, 0, sizeof(sin));
memset(&sin6, 0, sizeof(sin6));
if (!serv->ipv6)
{
addr = (struct sockaddr *)&sin;
addr_size = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(0);
sin.sin_port = htons(serv->port);
}
else
{
addr = (struct sockaddr *)&sin6;
addr_size = sizeof(sin6);
sin6.sin6_family = AF_INET6;
// sin6.sin6_addr.s6_addr
sin6.sin6_port = htons(serv->port);
}
serv->listener = <API key>(
event_mgr_base(), connlistener_cb, serv,
<API key> | LEV_OPT_REUSEABLE, -1, addr, addr_size);
}
}
LUA_API int <API key>(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, <API key>);
tcpd_server_rebind(L, serv);
return 0;
}
LUA_API int tcpd_bind(lua_State *L)
{
event_mgr_init();
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1);
SERVER *serv = lua_newuserdata(L, sizeof(SERVER));
memset(serv, 0, sizeof(SERVER));
luaL_getmetatable(L, <API key>);
lua_setmetatable(L, -2);
serv->mainthread = utlua_mainthread(L);
<API key>(L, serv->onAcceptRef, 1, "onaccept")
<API key>(L, serv->onSSLHostNameRef, 1, "onsslhostname")
DUP_STR_FROM_TABLE(L, serv->host, 1, "host")
SET_INT_FROM_TABLE(L, serv->port, 1, "port")
lua_getfield(L, 1, "ssl");
int ssl = lua_toboolean(L, -1);
lua_pop(L, 1);
#if FAN_HAS_OPENSSL
serv->ssl = ssl;
if (serv->ssl)
{
lua_getfield(L, 1, "cert");
const char *cert = lua_tostring(L, -1);
lua_getfield(L, 1, "key");
const char *key = lua_tostring(L, -1);
if (cert && key)
{
SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
<API key>(ctx, ssl_servername_cb);
<API key>(ctx, serv);
serv->ctx = ctx;
SSL_CTX_set_options(ctx,
<API key> | <API key> |
0); // SSL_OP_NO_SSLv2
serv->ecdh = <API key>(<API key>);
if (!serv->ecdh)
{
<API key>("<API key>");
}
if (1 != <API key>(ctx, serv->ecdh))
{
<API key>("<API key>");
}
server_setup_certs(ctx, cert, key);
}
lua_pop(L, 2);
}
#else
if (ssl)
{
luaL_error(L, "ssl is not supported on micro version.");
}
#endif
SET_INT_FROM_TABLE(L, serv->send_buffer_size, 1, "send_buffer_size")
SET_INT_FROM_TABLE(L, serv->receive_buffer_size, 1, "receive_buffer_size")
lua_getfield(L, 1, "ipv6");
serv->ipv6 = lua_toboolean(L, -1);
lua_pop(L, 1);
tcpd_server_rebind(L, serv);
if (!serv->listener)
{
return 0;
}
else
{
if (!serv->port)
{
serv->port = <API key>(<API key>(serv->listener));
}
lua_pushinteger(L, serv->port);
return 2;
}
}
static void tcpd_conn_readcb(struct bufferevent *bev, void *ctx)
{
Conn *conn = (Conn *)ctx;
char buf[BUFLEN];
int n;
BYTEARRAY ba;
bytearray_alloc(&ba, BUFLEN * 2);
struct evbuffer *input = <API key>(bev);
while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0)
{
<API key>(&ba, buf, n);
}
<API key>(&ba);
if (conn->onReadRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_rawgeti(mainthread, LUA_REGISTRYINDEX, conn->onReadRef);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_xmove(mainthread, co, 1);
lua_unlock(mainthread);
lua_pushlstring(co, (const char *)ba.buffer, ba.total);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
bytearray_dealloc(&ba);
}
static void tcpd_conn_writecb(struct bufferevent *bev, void *ctx)
{
Conn *conn = (Conn *)ctx;
if (evbuffer_get_length(<API key>(bev)) == 0)
{
if (conn->onSendReadyRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onSendReadyRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
}
static void tcpd_conn_eventcb(struct bufferevent *bev, short events,
void *arg)
{
Conn *conn = (Conn *)arg;
if (events & BEV_EVENT_CONNECTED)
{
// printf("tcp connected.\n");
if (conn->onConnectedRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onConnectedRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
else if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF ||
events & BEV_EVENT_TIMEOUT)
{
#if FAN_HAS_OPENSSL
SSL *ssl = <API key>(bev);
if (ssl)
{
SSL_set_shutdown(ssl, <API key>);
SSL_shutdown(ssl);
}
#endif
bufferevent_free(bev);
conn->buf = NULL;
if (conn->onDisconnectedRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onDisconnectedRef);
if (events & BEV_EVENT_TIMEOUT)
{
if (events & BEV_EVENT_READING)
{
lua_pushliteral(co, "read timeout");
}
else if (events & BEV_EVENT_WRITING)
{
lua_pushliteral(co, "write timeout");
}
else
{
lua_pushliteral(co, "unknown timeout");
}
}
else if (events & BEV_EVENT_ERROR)
{
#if FAN_HAS_OPENSSL
if (conn->ssl_error)
{
lua_pushfstring(co, "SSLError: %s", conn->ssl_error);
}
else
{
#endif
int err = <API key>(bev);
if (err)
{
lua_pushstring(co, evutil_gai_strerror(err));
}
else if (EVUTIL_SOCKET_ERROR())
{
lua_pushstring(
co, <API key>(EVUTIL_SOCKET_ERROR()));
}
else
{
lua_pushnil(co);
}
#if FAN_HAS_OPENSSL
}
#endif
}
else if (events & BEV_EVENT_EOF)
{
lua_pushliteral(co, "server disconnected");
}
else
{
lua_pushnil(co);
}
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
}
}
#if FAN_HAS_OPENSSL
static int ssl_verifypeer_cb(int preverify_ok, X509_STORE_CTX *ctx)
{
if (!preverify_ok)
{
SSL *ssl = <API key>(ctx, <API key>());
Conn *conn = SSL_get_ex_data(ssl, conn_index);
int err = <API key>(ctx);
conn->ssl_error = strdup(<API key>(err));
}
return preverify_ok;
}
#endif
static void luatcpd_reconnect(Conn *conn)
{
if (conn->buf)
{
bufferevent_free(conn->buf);
conn->buf = NULL;
}
#if FAN_HAS_OPENSSL
conn->ssl_error = 0;
if (conn->sslctx)
{
SSL *ssl = SSL_new(conn->sslctx->ssl_ctx);
SSL_set_ex_data(ssl, conn_index, conn);
if (conn->ssl_verifyhost && (conn->ssl_host ?: conn->host))
{
SSL_set_hostflags(ssl, <API key>);
if (!SSL_set1_host(ssl, conn->ssl_host ?: conn->host))
{
printf("SSL_set1_host '%s' failed!\n", conn->ssl_host ?: conn->host);
}
}
/* Enable peer verification (with a non-null callback if desired) */
if (conn->ssl_verifypeer)
{
SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
}
else
{
SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
}
<API key>(ssl, conn->ssl_host ?: conn->host);
conn->buf = <API key>(
event_mgr_base(), -1, ssl, <API key>,
<API key> | <API key>);
#ifdef <API key>
#if (<API key> >= 0x02010500)
<API key>(conn->buf, 1);
#endif
#endif
}
else
{
#endif
conn->buf = <API key>(
event_mgr_base(), -1, <API key> | <API key>);
#if FAN_HAS_OPENSSL
}
#endif
int rc = <API key>(conn->buf, event_mgr_dnsbase(),
AF_UNSPEC,
conn->host, conn->port);
evutil_socket_t fd = bufferevent_getfd(conn->buf);
if (conn->send_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &conn->send_buffer_size,
sizeof(conn->send_buffer_size));
}
if (conn->receive_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &conn->receive_buffer_size,
sizeof(conn->receive_buffer_size));
}
#ifdef IP_BOUND_IF
if (conn->interface)
{
setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &conn->interface, sizeof(conn->interface));
}
#endif
if (rc < 0)
{
LOGE("could not connect to %s:%d %s", conn->host, conn->port,
<API key>(EVUTIL_SOCKET_ERROR()));
bufferevent_free(conn->buf);
conn->buf = NULL;
return;
}
bufferevent_enable(conn->buf, EV_WRITE | EV_READ);
bufferevent_setcb(conn->buf, tcpd_conn_readcb, tcpd_conn_writecb,
tcpd_conn_eventcb, conn);
}
LUA_API int tcpd_connect(lua_State *L)
{
event_mgr_init();
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1);
Conn *conn = lua_newuserdata(L, sizeof(Conn));
memset(conn, 0, sizeof(Conn));
luaL_getmetatable(L, <API key>);
lua_setmetatable(L, -2);
conn->mainthread = utlua_mainthread(L);
conn->buf = NULL;
#if FAN_HAS_OPENSSL
conn->sslctx = NULL;
conn->ssl_error = 0;
#endif
conn->send_buffer_size = 0;
conn->receive_buffer_size = 0;
<API key>(L, conn->onReadRef, 1, "onread")
<API key>(L, conn->onSendReadyRef, 1, "onsendready")
<API key>(L, conn->onDisconnectedRef, 1, "ondisconnected")
<API key>(L, conn->onConnectedRef, 1, "onconnected")
DUP_STR_FROM_TABLE(L, conn->host, 1, "host")
SET_INT_FROM_TABLE(L, conn->port, 1, "port")
lua_getfield(L, 1, "ssl");
int ssl = lua_toboolean(L, -1);
lua_pop(L, 1);
#if FAN_HAS_OPENSSL
lua_getfield(L, 1, "ssl_verifyhost");
conn->ssl_verifyhost = (int)luaL_optinteger(L, -1, 1);
lua_pop(L, 1);
lua_getfield(L, 1, "ssl_verifypeer");
conn->ssl_verifypeer = (int)luaL_optinteger(L, -1, 1);
lua_pop(L, 1);
DUP_STR_FROM_TABLE(L, conn->ssl_host, 1, "ssl_host")
if (ssl)
{
lua_getfield(L, 1, "cainfo");
const char *cainfo = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "capath");
const char *capath = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "pkcs12.path");
const char *p12path = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "pkcs12.password");
const char *p12password = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
if (!cainfo && !capath)
{
cainfo = "cert.pem";
}
BYTEARRAY ba = {0};
bytearray_alloc(&ba, BUFLEN);
<API key>(&ba, "SSL_CTX:", strlen("SSL_CTX_"));
if (cainfo)
{
<API key>(&ba, cainfo, strlen(cainfo));
}
if (capath)
{
<API key>(&ba, capath, strlen(capath));
}
if (p12path)
{
<API key>(&ba, p12path, strlen(p12path));
}
if (p12password)
{
<API key>(&ba, p12password, strlen(p12password));
}
bytearray_write8(&ba, 0);
<API key>(&ba);
char *cache_key = strdup((const char *)ba.buffer);
bytearray_dealloc(&ba);
lua_getfield(L, LUA_REGISTRYINDEX, cache_key);
if (lua_isnil(L, -1))
{
SSLCTX *sslctx = lua_newuserdata(L, sizeof(SSLCTX));
sslctx->key = strdup(cache_key);
sslctx->ssl_ctx = SSL_CTX_new(TLS_method());
conn->sslctx = sslctx;
sslctx->retainCount = 1;
lua_setfield(L, LUA_REGISTRYINDEX, cache_key);
if (!<API key>(sslctx->ssl_ctx, cainfo, capath))
{
printf("<API key> failed: cainfo=%s capath=%s\n", cainfo, capath);
}
#ifdef <API key>
SSL_CTX_set_mode(sslctx->ssl_ctx, <API key>);
#endif
SSL_CTX_set_options(sslctx->ssl_ctx, <API key>);
SSL_CTX_set_verify(sslctx->ssl_ctx, SSL_VERIFY_PEER, ssl_verifypeer_cb);
while (p12path)
{
FILE *fp = NULL;
EVP_PKEY *pkey = NULL;
X509 *cert = NULL;
STACK_OF(X509) *ca = NULL;
PKCS12 *p12 = NULL;
if ((fp = fopen(p12path, "rb")) == NULL)
{
fprintf(stderr, "Error opening file %s\n", p12path);
break;
}
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (!p12)
{
fprintf(stderr, "Error reading PKCS#12 file\n");
ERR_print_errors_fp(stderr);
break;
}
if (!PKCS12_parse(p12, p12password, &pkey, &cert, &ca))
{
fprintf(stderr, "Error parsing PKCS#12 file\n");
ERR_print_errors_fp(stderr);
}
else
{
<API key>(sslctx->ssl_ctx, cert);
if (ca && sk_X509_num(ca))
{
int i = 0;
for (i = 0; i < sk_X509_num(ca); i++)
{
<API key>(sslctx->ssl_ctx, sk_X509_value(ca, i));
}
}
<API key>(sslctx->ssl_ctx, pkey);
sk_X509_pop_free(ca, X509_free);
X509_free(cert);
EVP_PKEY_free(pkey);
}
PKCS12_free(p12);
p12 = NULL;
break;
}
}
else
{
SSLCTX *sslctx = lua_touserdata(L, -1);
sslctx->retainCount++;
conn->sslctx = sslctx;
}
lua_pop(L, 1);
FREE_STR(cache_key);
}
#else
if (ssl)
{
luaL_error(L, "ssl is not supported on micro version.");
}
#endif
SET_INT_FROM_TABLE(L, conn->send_buffer_size, 1, "send_buffer_size")
SET_INT_FROM_TABLE(L, conn->receive_buffer_size, 1, "receive_buffer_size")
lua_getfield(L, 1, "read_timeout");
lua_Number read_timeout = (int)luaL_optnumber(L, -1, 0);
conn->read_timeout = read_timeout;
lua_pop(L, 1);
lua_getfield(L, 1, "write_timeout");
lua_Number write_timeout = (int)luaL_optnumber(L, -1, 0);
conn->write_timeout = write_timeout;
lua_pop(L, 1);
lua_getfield(L, 1, "interface");
if (lua_type(L, -1) == LUA_TSTRING)
{
const char *interface = lua_tostring(L, -1);
conn->interface = if_nametoindex(interface);
}
lua_pop(L, 1);
luatcpd_reconnect(conn);
return 1;
}
static const luaL_Reg tcpdlib[] = {
{"bind", tcpd_bind}, {"connect", tcpd_connect}, {NULL, NULL}};
LUA_API int tcpd_conn_close(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, <API key>);
if (<API key>() && conn->buf)
{
bufferevent_free(conn->buf);
conn->buf = NULL;
}
CLEAR_REF(L, conn->onReadRef)
CLEAR_REF(L, conn->onSendReadyRef)
CLEAR_REF(L, conn->onDisconnectedRef)
CLEAR_REF(L, conn->onConnectedRef)
FREE_STR(conn->host)
FREE_STR(conn->ssl_host)
#if FAN_HAS_OPENSSL
if (conn->sslctx)
{
conn->sslctx->retainCount
if (conn->sslctx->retainCount <= 0)
{
lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, conn->sslctx->key);
SSL_CTX_free(conn->sslctx->ssl_ctx);
free(conn->sslctx->key);
}
conn->sslctx = NULL;
}
#endif
return 0;
}
LUA_API int tcpd_conn_gc(lua_State *L) { return tcpd_conn_close(L); }
LUA_API int tcpd_accept_remote(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
lua_newtable(L);
lua_pushstring(L, accept->ip);
lua_setfield(L, -2, "ip");
lua_pushinteger(L, accept->port);
lua_setfield(L, -2, "port");
return 1;
}
#ifdef __linux__
LUA_API int <API key>(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
evutil_socket_t fd = bufferevent_getfd(accept->buf);
struct sockaddr_storage ss;
socklen_t len = sizeof(struct sockaddr_storage);
if (getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &ss, &len))
{
lua_pushnil(L);
lua_pushfstring(L, "getsockopt: %s", strerror(errno));
return 2;
}
char host[INET6_ADDRSTRLEN];
int port = 0;
if (ss.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss;
port = ntohs(((struct sockaddr_in *)&ss)->sin_port);
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host,
INET_ADDRSTRLEN);
}
else if (ss.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss;
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host,
INET6_ADDRSTRLEN);
}
lua_pushstring(L, host);
lua_pushinteger(L, port);
return 2;
}
#endif
LUA_API int <API key>(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
evutil_socket_t fd = bufferevent_getfd(accept->buf);
struct sockaddr_storage ss;
socklen_t len = sizeof(struct sockaddr_storage);
if (getsockname(fd, (struct sockaddr *)&ss, &len))
{
lua_pushnil(L);
lua_pushfstring(L, "getsockname: %s", strerror(errno));
return 2;
}
char host[INET6_ADDRSTRLEN];
int port = 0;
if (ss.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss;
port = ntohs(((struct sockaddr_in *)&ss)->sin_port);
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host,
INET_ADDRSTRLEN);
}
else if (ss.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss;
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host,
INET6_ADDRSTRLEN);
}
lua_pushstring(L, host);
lua_pushinteger(L, port);
return 2;
}
LUA_API int tcpd_accept_close(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
if (<API key>() && accept->buf)
{
bufferevent_free(accept->buf);
accept->buf = NULL;
}
TCPD_ACCEPT_UNREF(accept)
return 0;
}
LUA_API int lua_tcpd_accept_gc(lua_State *L) { return tcpd_accept_close(L); }
LUA_API int <API key>(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
if (accept->buf)
{
bufferevent_disable(accept->buf, EV_READ);
}
return 0;
}
LUA_API int <API key>(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
if (accept->buf)
{
bufferevent_enable(accept->buf, EV_READ);
}
return 0;
}
LUA_API int <API key>(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, <API key>);
if (conn->buf)
{
bufferevent_disable(conn->buf, EV_READ);
}
return 0;
}
LUA_API int <API key>(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, <API key>);
if (conn->buf)
{
bufferevent_enable(conn->buf, EV_READ);
}
return 0;
}
LUA_API int tcpd_conn_send(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, <API key>);
size_t len = 0;
const char *data = luaL_checklstring(L, 2, &len);
if (data && len > 0 && conn->buf)
{
if (conn->read_timeout > 0)
{
struct timeval tv1;
d2tv(conn->read_timeout, &tv1);
if (conn->write_timeout > 0)
{
struct timeval tv2;
d2tv(conn->write_timeout, &tv2);
<API key>(conn->buf, &tv1, &tv2);
}
else
{
<API key>(conn->buf, &tv1, NULL);
}
}
else
{
if (conn->write_timeout > 0)
{
struct timeval tv2;
d2tv(conn->write_timeout, &tv2);
<API key>(conn->buf, NULL, &tv2);
}
}
bufferevent_write(conn->buf, data, len);
size_t total = evbuffer_get_length(<API key>(conn->buf));
lua_pushinteger(L, total);
}
else
{
lua_pushinteger(L, -1);
}
return 1;
}
LUA_API int tcpd_conn_reconnect(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, <API key>);
luatcpd_reconnect(conn);
return 0;
}
LUA_API int tcpd_accept_flush(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
int mode = luaL_optinteger(L, 2, BEV_NORMAL);
lua_pushinteger(L, bufferevent_flush(accept->buf, EV_WRITE, mode));
return 1;
}
LUA_API int tcpd_accept_send(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, <API key>);
size_t len = 0;
const char *data = luaL_checklstring(L, 2, &len);
if (data && len > 0 && accept->buf)
{
bufferevent_write(accept->buf, data, len);
size_t total = evbuffer_get_length(<API key>(accept->buf));
lua_pushinteger(L, total);
}
else
{
lua_pushinteger(L, -1);
}
return 1;
}
LUA_API int luaopen_fan_tcpd(lua_State *L)
{
#if FAN_HAS_OPENSSL
conn_index = <API key>(0, "conn_index", NULL, NULL, NULL);
#endif
luaL_newmetatable(L, <API key>);
lua_pushcfunction(L, &tcpd_conn_send);
lua_setfield(L, -2, "send");
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "pause_read");
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "resume_read");
lua_pushcfunction(L, &tcpd_conn_close);
lua_setfield(L, -2, "close");
lua_pushcfunction(L, &tcpd_conn_reconnect);
lua_setfield(L, -2, "reconnect");
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &tcpd_conn_gc);
lua_rawset(L, -3);
lua_pop(L, 1);
luaL_newmetatable(L, <API key>);
lua_pushcfunction(L, &tcpd_accept_send);
lua_setfield(L, -2, "send");
lua_pushcfunction(L, &tcpd_accept_flush);
lua_setfield(L, -2, "flush");
lua_pushcfunction(L, &tcpd_accept_close);
lua_setfield(L, -2, "close");
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "pause_read");
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "resume_read");
lua_pushcfunction(L, &tcpd_accept_bind);
lua_setfield(L, -2, "bind");
lua_pushcfunction(L, &tcpd_accept_remote);
lua_setfield(L, -2, "remoteinfo");
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "getsockname");
#ifdef __linux__
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "original_dst");
#endif
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pushstring(L, "__tostring");
lua_pushcfunction(L, &<API key>);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &lua_tcpd_accept_gc);
lua_rawset(L, -3);
lua_pop(L, 1);
luaL_newmetatable(L, <API key>);
lua_pushstring(L, "close");
lua_pushcfunction(L, &<API key>);
lua_rawset(L, -3);
lua_pushcfunction(L, &<API key>);
lua_setfield(L, -2, "rebind");
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &lua_tcpd_server_gc);
lua_rawset(L, -3);
lua_pushstring(L, "__tostring");
lua_pushcfunction(L, &<API key>);
lua_rawset(L, -3);
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pop(L, 1);
lua_newtable(L);
luaL_register(L, "tcpd", tcpdlib);
return 1;
}
|
/**
* configuration for grunt tasks
* @module Gruntfile
*/
module.exports = function(grunt) {
/** load tasks */
require('load-grunt-tasks')(grunt);
/** config for build paths */
var config = {
dist: {
dir: 'dist/',
StoreFactory: 'dist/StoreFactory.js',
ngStoreFactory: 'dist/ngStore.js'
},
src: {
dir: 'src/'
},
tmp: {
dir: 'tmp/'
}
};
/** paths to files */
var files = {
/** src files */
Factory: [
'StoreFactory.js'
],
/** src files */
Store: [
'Store.js'
],
};
/** config for grunt tasks */
var taskConfig = {
/** concatentation tasks for building the source files */
concat: {
StoreFactory: {
options: {
// stripBanners: true
banner: '',
footer: '',
},
src: (function() {
var
cwd = config.src.dir,
queue = [].concat(files.Factory, files.Store);
return queue.map(function(path) {
return cwd + path;
});
})(),
dest: config.dist.StoreFactory,
},
ngSession: {
options: {
banner: 'angular.module("ngStore", [])\n' +
'.service("ngStore", [\n' +
'function() {\n\n',
footer: '\n\n' +
'return new StoreFactory();\n\n}' +
'\n]);'
},
src: (function() {
return [
config.dist.StoreFactory,
];
})(),
dest: config.dist.ngStoreFactory
}
},
/** uglify (javascript minification) config */
uglify: {
StoreFactory: {
options: {},
files: [
{
src: config.dist.StoreFactory,
dest: (function() {
var split = config.dist.StoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
},
ngStoreFactory: {
options: {},
files: [
{
src: config.dist.ngStoreFactory,
dest: (function() {
var split = config.dist.ngStoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
}
}
};
// register default & custom tasks
grunt.initConfig(taskConfig);
grunt.registerTask('default', [
'build'
]);
grunt.registerTask('build', [
'concat',
'uglify'
]);
};
|
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var seo = require('./lib/seo');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(seo);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
app.get('/<API key>/', function(req, res, next) {
res.send('<API key>');
});
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
var cacheBuster = function(req, res, next){
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
};
// @todo isolate to api routes...
app.use(cacheBuster);
// catch all which sends all urls to index page, thus starting our app
// @note that because Express routes are registered in order, and we already defined our api routes
// this catch all will not effect prior routes.
app.use(function(req, res, next) {
app.get('*', function(req, res, next) {
//return res.ok('catch all');
res.redirect('/#!' + req.url);
});
});
|
# KnockGame
This sketch is responsible for the **Handshake** and **Knock** interfaces.
# External Libraries
## SerialCommand
https://github.com/kroimon/<API key>
|
#include <iostream>
#include <string>
#include <forward_list>
using namespace std;
void insert(forward_list<string>& fst, const string& to_find, const string& to_add);
int main() {
forward_list<string> fst{ "pen", "pineapple", "apple", "pen" };
insert(fst, "pen", "and");
for (auto& i : fst)
cout << i << " ";
cout << endl;
return 0;
}
void insert(forward_list<string>& fst, const string& to_find, const string& to_add) {
auto prev = fst.before_begin();
for (auto iter = fst.begin(); iter != fst.end(); prev = iter++) {
if (*iter == to_find) {
fst.insert_after(iter, to_add);
return;
}
}
fst.insert_after(prev, to_add);
return;
}
|
package mrkoopa.jfbx;
public interface FbxCameraStereo extends FbxCamera {
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToDB.Data
{
using Linq;
using Common;
using SqlProvider;
using SqlQuery;
public partial class DataConnection
{
IQueryRunner IDataContext.GetQueryRunner(Query query, int queryNumber, Expression expression, object[] parameters)
{
<API key>();
return new QueryRunner(query, queryNumber, this, expression, parameters);
}
internal class QueryRunner : QueryRunnerBase
{
public QueryRunner(Query query, int queryNumber, DataConnection dataConnection, Expression expression, object[] parameters)
: base(query, queryNumber, dataConnection, expression, parameters)
{
_dataConnection = dataConnection;
}
readonly DataConnection _dataConnection;
readonly DateTime _startedOn = DateTime.UtcNow;
readonly Stopwatch _stopwatch = Stopwatch.StartNew();
bool _isAsync;
Expression _mapperExpression;
public override Expression MapperExpression
{
get => _mapperExpression;
set
{
_mapperExpression = value;
if (value != null && Common.Configuration.Linq.<API key> &&
TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.MapperCreated)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
IsAsync = _isAsync,
});
}
}
}
public override string GetSqlText()
{
SetCommand(false);
var sqlProvider = _preparedQuery.SqlProvider ?? _dataConnection.DataProvider.CreateSqlBuilder();
var sb = new StringBuilder();
sb.Append("-- ").Append(_dataConnection.ConfigurationString);
if (_dataConnection.ConfigurationString != _dataConnection.DataProvider.Name)
sb.Append(' ').Append(_dataConnection.DataProvider.Name);
if (_dataConnection.DataProvider.Name != sqlProvider.Name)
sb.Append(' ').Append(sqlProvider.Name);
sb.AppendLine();
sqlProvider.PrintParameters(sb, _preparedQuery.Parameters);
var isFirst = true;
foreach (var command in _preparedQuery.Commands)
{
sb.AppendLine(command);
if (isFirst && _preparedQuery.QueryHints != null && _preparedQuery.QueryHints.Count > 0)
{
isFirst = false;
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length
sb.AppendLine();
var sql = sb.ToString();
var sqlBuilder = _dataConnection.DataProvider.CreateSqlBuilder();
sql = sqlBuilder.ApplyQueryHints(sql, _preparedQuery.QueryHints);
sb = new StringBuilder(sql);
}
}
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length
sb.AppendLine();
return sb.ToString();
}
public override void Dispose()
{
if (TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.Completed)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
Command = _dataConnection.Command,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
RecordsAffected = RowsCount,
IsAsync = _isAsync,
});
}
base.Dispose();
}
public class PreparedQuery
{
public string[] Commands;
public List<SqlParameter> SqlParameters;
public IDbDataParameter[] Parameters;
public SqlStatement Statement;
public ISqlBuilder SqlProvider;
public List<string> QueryHints;
}
PreparedQuery _preparedQuery;
static PreparedQuery GetCommand(DataConnection dataConnection, IQueryContext query, int startIndent = 0)
{
if (query.Context != null)
{
return new PreparedQuery
{
Commands = (string[])query.Context,
SqlParameters = query.Statement.Parameters,
Statement = query.Statement,
QueryHints = query.QueryHints,
};
}
var sql = query.Statement.ProcessParameters(dataConnection.MappingSchema);
var newSql = dataConnection.ProcessQuery(sql);
if (!object.ReferenceEquals(sql, newSql))
{
sql = newSql;
sql.<API key> = true;
}
var sqlProvider = dataConnection.DataProvider.CreateSqlBuilder();
var cc = sqlProvider.CommandCount(sql);
var sb = new StringBuilder();
var commands = new string[cc];
for (var i = 0; i < cc; i++)
{
sb.Length = 0;
sqlProvider.BuildSql(i, sql, sb, startIndent);
commands[i] = sb.ToString();
}
if (!sql.<API key>)
query.Context = commands;
return new PreparedQuery
{
Commands = commands,
SqlParameters = sql.Parameters,
Statement = sql,
SqlProvider = sqlProvider,
QueryHints = query.QueryHints,
};
}
static void GetParameters(DataConnection dataConnection, IQueryContext query, PreparedQuery pq)
{
var parameters = query.GetParameters();
if (parameters.Length == 0 && pq.SqlParameters.Count == 0)
return;
var ordered = dataConnection.DataProvider.SqlProviderFlags.<API key>;
var c = ordered ? pq.SqlParameters.Count : parameters.Length;
var parms = new List<IDbDataParameter>(c);
if (ordered)
{
for (var i = 0; i < pq.SqlParameters.Count; i++)
{
var sqlp = pq.SqlParameters[i];
if (sqlp.IsQueryParameter)
{
var parm = parameters.Length > i && object.ReferenceEquals(parameters[i], sqlp) ?
parameters[i] :
parameters.First(p => object.ReferenceEquals(p, sqlp));
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
}
else
{
foreach (var parm in parameters)
{
if (parm.IsQueryParameter && pq.SqlParameters.Contains(parm))
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
pq.Parameters = parms.ToArray();
}
static void AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm)
{
var p = dataConnection.Command.CreateParameter();
var systemType = parm.SystemType;
var dataType = parm.DataType;
var dbType = parm.DbType;
var dbSize = parm.DbSize;
var paramValue = parm.Value;
if (systemType == null)
{
if (paramValue != null)
systemType = paramValue.GetType();
}
if (dataType == DataType.Undefined)
{
dataType = dataConnection.MappingSchema.GetDataType(
parm.SystemType == typeof(object) && paramValue != null ?
paramValue.GetType() :
systemType).DataType;
}
dataConnection.DataProvider.SetParameter(p, name, new DbDataType(systemType, dataType, dbType, dbSize), paramValue);
parms.Add(p);
}
public static PreparedQuery SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent = 0)
{
var preparedQuery = GetCommand(dataConnection, queryContext, startIndent);
GetParameters(dataConnection, queryContext, preparedQuery);
return preparedQuery;
}
protected override void SetQuery()
{
_preparedQuery = SetQuery(_dataConnection, Query.Queries[QueryNumber]);
}
void SetCommand()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
}
#region ExecuteNonQuery
static int ExecuteNonQueryImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
if (preparedQuery.Commands.Length == 1)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteNonQuery();
}
var rowsAffected = -1;
for (var i = 0; i < preparedQuery.Commands.Length; i++)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[i], null, i == 0 ? preparedQuery.QueryHints : null);
if (i == 0 && preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
if (i < preparedQuery.Commands.Length - 1 && preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
dataConnection.ExecuteNonQuery();
}
catch (Exception)
{
}
}
else
{
var n = dataConnection.ExecuteNonQuery();
if (i == 0)
rowsAffected = n;
}
}
return rowsAffected;
}
public override int ExecuteNonQuery()
{
SetCommand(true);
return ExecuteNonQueryImpl(_dataConnection, _preparedQuery);
}
public static int ExecuteNonQuery(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
return ExecuteNonQueryImpl(dataConnection, preparedQuery);
}
#endregion
#region ExecuteScalar
static object ExecuteScalarImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
IDbDataParameter idParam = null;
if (dataConnection.DataProvider.SqlProviderFlags.<API key>)
{
if (preparedQuery.Statement.NeedsIdentity())
{
idParam = dataConnection.Command.CreateParameter();
idParam.ParameterName = "IDENTITY_PARAMETER";
idParam.Direction = ParameterDirection.Output;
idParam.DbType = DbType.Decimal;
dataConnection.Command.Parameters.Add(idParam);
}
}
if (preparedQuery.Commands.Length == 1)
{
if (idParam != null)
{
// This is because the firebird provider does not return any parameters via ExecuteReader
// the rest of the providers must support this mode
dataConnection.ExecuteNonQuery();
return idParam.Value;
}
return dataConnection.ExecuteScalar();
}
dataConnection.ExecuteNonQuery();
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[1], null, null);
return dataConnection.ExecuteScalar();
}
public static object ExecuteScalar(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return ExecuteScalarImpl(dataConnection, preparedQuery);
}
public override object ExecuteScalar()
{
SetCommand();
return ExecuteScalarImpl(_dataConnection, _preparedQuery);
}
#endregion
#region ExecuteReader
public static IDataReader ExecuteReader(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteReader();
}
public override IDataReader ExecuteReader()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return _dataConnection.ExecuteReader();
}
#endregion
class DataReaderAsync : IDataReaderAsync
{
public DataReaderAsync(DbDataReader dataReader)
{
_dataReader = dataReader;
}
readonly DbDataReader _dataReader;
public IDataReader DataReader => _dataReader;
public Task<bool> ReadAsync(Cancellation<API key>)
{
return _dataReader.ReadAsync(cancellationToken);
}
public void Dispose()
{
// call interface method, because at least MySQL provider incorrectly override
// methods for .net core 1x
DataReader.Dispose();
}
}
public override async Task<IDataReaderAsync> ExecuteReaderAsync(Cancellation<API key>)
{
_isAsync = true;
await _dataConnection.<API key>(cancellationToken);
base.SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
var dataReader = await _dataConnection.ExecuteReaderAsync(_dataConnection.GetCommandBehavior(CommandBehavior.Default), cancellationToken);
return new DataReaderAsync(dataReader);
}
public override async Task<int> <API key>(Cancellation<API key>)
{
_isAsync = true;
await _dataConnection.<API key>(cancellationToken);
base.SetCommand(true);
if (_preparedQuery.Commands.Length == 1)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[0], null, _preparedQuery.QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return await _dataConnection.<API key>(cancellationToken);
}
for (var i = 0; i < _preparedQuery.Commands.Length; i++)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[i], null, i == 0 ? _preparedQuery.QueryHints : null);
if (i == 0 && _preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
if (i < _preparedQuery.Commands.Length - 1 && _preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
await _dataConnection.<API key>(cancellationToken);
}
catch
{
}
}
else
{
await _dataConnection.<API key>(cancellationToken);
}
}
return -1;
}
public override async Task<object> ExecuteScalarAsync(Cancellation<API key>)
{
_isAsync = true;
await _dataConnection.<API key>(cancellationToken);
SetCommand();
IDbDataParameter idparam = null;
if (_dataConnection.DataProvider.SqlProviderFlags.<API key>)
{
if (_preparedQuery.Statement.NeedsIdentity())
{
idparam = _dataConnection.Command.CreateParameter();
idparam.ParameterName = "IDENTITY_PARAMETER";
idparam.Direction = ParameterDirection.Output;
idparam.DbType = DbType.Decimal;
_dataConnection.Command.Parameters.Add(idparam);
}
}
if (_preparedQuery.Commands.Length == 1)
{
if (idparam != null)
{
await _dataConnection.<API key>(cancellationToken);
return idparam.Value;
}
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
await _dataConnection.<API key>(cancellationToken);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[1], null, null);
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
}
}
}
|
# Swagger JSON
This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.

|
#include <API key> //original-code:"rtc_base/win32socketserver.h"
#include <ws2tcpip.h> // NOLINT
#include <algorithm>
#include <API key> //original-code:"rtc_base/byteorder.h"
#include <API key> //original-code:"rtc_base/checks.h"
#include <API key> //original-code:"rtc_base/logging.h"
#include <API key> //original-code:"rtc_base/win32window.h"
namespace rtc {
// Win32Socket
// TODO: Enable for production builds also? Use FormatMessage?
#if !defined(NDEBUG)
LPCSTR WSAErrorToString(int error, LPCSTR* description_result) {
LPCSTR string = "Unspecified";
LPCSTR description = "Unspecified description";
switch (error) {
case ERROR_SUCCESS:
string = "SUCCESS";
description = "Operation succeeded";
break;
case WSAEWOULDBLOCK:
string = "WSAEWOULDBLOCK";
description = "Using a non-blocking socket, will notify later";
break;
case WSAEACCES:
string = "WSAEACCES";
description = "Access denied, or sharing violation";
break;
case WSAEADDRNOTAVAIL:
string = "WSAEADDRNOTAVAIL";
description = "Address is not valid in this context";
break;
case WSAENETDOWN:
string = "WSAENETDOWN";
description = "Network is down";
break;
case WSAENETUNREACH:
string = "WSAENETUNREACH";
description = "Network is up, but unreachable";
break;
case WSAENETRESET:
string = "WSANETRESET";
description = "Connection has been reset due to keep-alive activity";
break;
case WSAECONNABORTED:
string = "WSAECONNABORTED";
description = "Aborted by host";
break;
case WSAECONNRESET:
string = "WSAECONNRESET";
description = "Connection reset by host";
break;
case WSAETIMEDOUT:
string = "WSAETIMEDOUT";
description = "Timed out, host failed to respond";
break;
case WSAECONNREFUSED:
string = "WSAECONNREFUSED";
description = "Host actively refused connection";
break;
case WSAEHOSTDOWN:
string = "WSAEHOSTDOWN";
description = "Host is down";
break;
case WSAEHOSTUNREACH:
string = "WSAEHOSTUNREACH";
description = "Host is unreachable";
break;
case WSAHOST_NOT_FOUND:
string = "WSAHOST_NOT_FOUND";
description = "No such host is known";
break;
}
if (description_result) {
*description_result = description;
}
return string;
}
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
LPCSTR description_string;
LPCSTR error_string = WSAErrorToString(error, &description_string);
RTC_LOG(LS_INFO) << context << " = " << error << " (" << error_string << ":"
<< description_string << ") [" << address.ToString() << "]";
}
#else
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
#endif
// Win32Socket::EventSink
#define WM_SOCKETNOTIFY (WM_USER + 50)
#define WM_DNSNOTIFY (WM_USER + 51)
struct Win32Socket::DnsLookup {
HANDLE handle;
uint16_t port;
char buffer[MAXGETHOSTSTRUCT];
};
class Win32Socket::EventSink : public Win32Window {
public:
explicit EventSink(Win32Socket* parent) : parent_(parent) {}
void Dispose();
bool OnMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) override;
void OnNcDestroy() override;
private:
bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
Win32Socket* parent_;
};
void Win32Socket::EventSink::Dispose() {
parent_ = nullptr;
if (::IsWindow(handle())) {
::DestroyWindow(handle());
} else {
delete this;
}
}
bool Win32Socket::EventSink::OnMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
switch (uMsg) {
case WM_SOCKETNOTIFY:
case WM_TIMER:
return OnSocketNotify(uMsg, wParam, lParam, result);
case WM_DNSNOTIFY:
return OnDnsNotify(wParam, lParam, result);
}
return false;
}
bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
result = 0;
int wsa_event = WSAGETSELECTEVENT(lParam);
int wsa_error = WSAGETSELECTERROR(lParam);
// Treat connect timeouts as close notifications
if (uMsg == WM_TIMER) {
wsa_event = FD_CLOSE;
wsa_error = WSAETIMEDOUT;
}
if (parent_)
parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
return true;
}
bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
result = 0;
int error = WSAGETASYNCERROR(lParam);
if (parent_)
parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
return true;
}
void Win32Socket::EventSink::OnNcDestroy() {
if (parent_) {
RTC_LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
" hasn't yet been disposed.";
} else {
delete this;
}
}
// Win32Socket
Win32Socket::Win32Socket()
: socket_(INVALID_SOCKET),
error_(0),
state_(CS_CLOSED),
connect_time_(0),
closing_(false),
close_error_(0),
sink_(nullptr),
dns_(nullptr) {}
Win32Socket::~Win32Socket() {
Close();
}
bool Win32Socket::CreateT(int family, int type) {
Close();
int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0);
if (socket_ == INVALID_SOCKET) {
UpdateLastError();
return false;
}
if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
return false;
}
return true;
}
int Win32Socket::Attach(SOCKET s) {
RTC_DCHECK(socket_ == INVALID_SOCKET);
if (socket_ != INVALID_SOCKET)
return SOCKET_ERROR;
RTC_DCHECK(s != INVALID_SOCKET);
if (s == INVALID_SOCKET)
return SOCKET_ERROR;
socket_ = s;
state_ = CS_CONNECTED;
if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
return SOCKET_ERROR;
return 0;
}
void Win32Socket::SetTimeout(int ms) {
if (sink_)
::SetTimer(sink_->handle(), 1, ms, 0);
}
SocketAddress Win32Socket::GetLocalAddress() const {
sockaddr_storage addr = {0};
socklen_t addrlen = sizeof(addr);
int result =
::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen);
SocketAddress address;
if (result >= 0) {
<API key>(addr, &address);
} else {
RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
<< socket_;
}
return address;
}
SocketAddress Win32Socket::GetRemoteAddress() const {
sockaddr_storage addr = {0};
socklen_t addrlen = sizeof(addr);
int result =
::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen);
SocketAddress address;
if (result >= 0) {
<API key>(addr, &address);
} else {
RTC_LOG(LS_WARNING)
<< "GetRemoteAddress: unable to get remote addr, socket=" << socket_;
}
return address;
}
int Win32Socket::Bind(const SocketAddress& addr) {
RTC_DCHECK(socket_ != INVALID_SOCKET);
if (socket_ == INVALID_SOCKET)
return SOCKET_ERROR;
sockaddr_storage saddr;
size_t len = addr.ToSockAddrStorage(&saddr);
int err = ::bind(socket_, reinterpret_cast<sockaddr*>(&saddr),
static_cast<int>(len));
UpdateLastError();
return err;
}
int Win32Socket::Connect(const SocketAddress& addr) {
if (state_ != CS_CLOSED) {
SetError(EALREADY);
return SOCKET_ERROR;
}
if (!addr.IsUnresolvedIP()) {
return DoConnect(addr);
}
RTC_LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
DnsLookup* dns = new DnsLookup;
if (!sink_) {
// Explicitly create the sink ourselves here; we can't rely on SetAsync
// because we don't have a socket_ yet.
CreateSink();
}
// TODO: Replace with IPv6 compatible lookup.
dns->handle = <API key>(sink_->handle(), WM_DNSNOTIFY,
addr.hostname().c_str(), dns->buffer,
sizeof(dns->buffer));
if (!dns->handle) {
RTC_LOG_F(LS_ERROR) << "<API key> error: " << WSAGetLastError();
delete dns;
UpdateLastError();
Close();
return SOCKET_ERROR;
}
dns->port = addr.port();
dns_ = dns;
state_ = CS_CONNECTING;
return 0;
}
int Win32Socket::DoConnect(const SocketAddress& addr) {
if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
return SOCKET_ERROR;
}
if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
return SOCKET_ERROR;
}
sockaddr_storage saddr = {0};
size_t len = addr.ToSockAddrStorage(&saddr);
connect_time_ = Time();
int result = connect(socket_, reinterpret_cast<SOCKADDR*>(&saddr),
static_cast<int>(len));
if (result != SOCKET_ERROR) {
state_ = CS_CONNECTED;
} else {
int code = WSAGetLastError();
if (code == WSAEWOULDBLOCK) {
state_ = CS_CONNECTING;
} else {
ReportWSAError("WSAAsync:connect", code, addr);
error_ = code;
Close();
return SOCKET_ERROR;
}
}
addr_ = addr;
return 0;
}
int Win32Socket::GetError() const {
return error_;
}
void Win32Socket::SetError(int error) {
error_ = error;
}
Socket::ConnState Win32Socket::GetState() const {
return state_;
}
int Win32Socket::GetOption(Option opt, int* value) {
int slevel;
int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1)
return -1;
char* p = reinterpret_cast<char*>(value);
int optlen = sizeof(value);
return ::getsockopt(socket_, slevel, sopt, p, &optlen);
}
int Win32Socket::SetOption(Option opt, int value) {
int slevel;
int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1)
return -1;
const char* p = reinterpret_cast<const char*>(&value);
return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
}
int Win32Socket::Send(const void* buffer, size_t length) {
int sent = ::send(socket_, reinterpret_cast<const char*>(buffer),
static_cast<int>(length), 0);
UpdateLastError();
return sent;
}
int Win32Socket::SendTo(const void* buffer,
size_t length,
const SocketAddress& addr) {
sockaddr_storage saddr;
size_t addr_len = addr.ToSockAddrStorage(&saddr);
int sent = ::sendto(
socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length),
0, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(addr_len));
UpdateLastError();
return sent;
}
int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) {
if (timestamp) {
*timestamp = -1;
}
int received =
::recv(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0);
UpdateLastError();
if (closing_ && received <= static_cast<int>(length))
PostClosed();
return received;
}
int Win32Socket::RecvFrom(void* buffer,
size_t length,
SocketAddress* out_addr,
int64_t* timestamp) {
if (timestamp) {
*timestamp = -1;
}
sockaddr_storage saddr;
socklen_t addr_len = sizeof(saddr);
int received =
::recvfrom(socket_, static_cast<char*>(buffer), static_cast<int>(length),
0, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
UpdateLastError();
if (received != SOCKET_ERROR)
<API key>(saddr, out_addr);
if (closing_ && received <= static_cast<int>(length))
PostClosed();
return received;
}
int Win32Socket::Listen(int backlog) {
int err = ::listen(socket_, backlog);
if (!SetAsync(FD_ACCEPT))
return SOCKET_ERROR;
UpdateLastError();
if (err == 0)
state_ = CS_CONNECTING;
return err;
}
Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
sockaddr_storage saddr;
socklen_t addr_len = sizeof(saddr);
SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
UpdateLastError();
if (s == INVALID_SOCKET)
return nullptr;
if (out_addr)
<API key>(saddr, out_addr);
Win32Socket* socket = new Win32Socket;
if (0 == socket->Attach(s))
return socket;
delete socket;
return nullptr;
}
int Win32Socket::Close() {
int err = 0;
if (socket_ != INVALID_SOCKET) {
err = ::closesocket(socket_);
socket_ = INVALID_SOCKET;
closing_ = false;
close_error_ = 0;
UpdateLastError();
}
if (dns_) {
<API key>(dns_->handle);
delete dns_;
dns_ = nullptr;
}
if (sink_) {
sink_->Dispose();
sink_ = nullptr;
}
addr_.Clear();
state_ = CS_CLOSED;
return err;
}
void Win32Socket::CreateSink() {
RTC_DCHECK(nullptr == sink_);
// Create window
sink_ = new EventSink(this);
sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10);
}
bool Win32Socket::SetAsync(int events) {
if (nullptr == sink_) {
CreateSink();
RTC_DCHECK(nullptr != sink_);
}
// start the async select
if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events) ==
SOCKET_ERROR) {
UpdateLastError();
Close();
return false;
}
return true;
}
bool Win32Socket::HandleClosed(int close_error) {
// WM_CLOSE will be received before all data has been read, so we need to
// hold on to it until the read buffer has been drained.
char ch;
closing_ = true;
close_error_ = close_error;
return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
}
void Win32Socket::PostClosed() {
// If we see that the buffer is indeed drained, then send the close.
closing_ = false;
::PostMessage(sink_->handle(), WM_SOCKETNOTIFY, socket_,
WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
}
void Win32Socket::UpdateLastError() {
error_ = WSAGetLastError();
}
int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
switch (opt) {
case OPT_DONTFRAGMENT:
*slevel = IPPROTO_IP;
*sopt = IP_DONTFRAGMENT;
break;
case OPT_RCVBUF:
*slevel = SOL_SOCKET;
*sopt = SO_RCVBUF;
break;
case OPT_SNDBUF:
*slevel = SOL_SOCKET;
*sopt = SO_SNDBUF;
break;
case OPT_NODELAY:
*slevel = IPPROTO_TCP;
*sopt = TCP_NODELAY;
break;
case OPT_DSCP:
RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
return -1;
default:
RTC_NOTREACHED();
return -1;
}
return 0;
}
void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
// Ignore events if we're already closed.
if (socket != socket_)
return;
error_ = error;
switch (event) {
case FD_CONNECT:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:connect notify", error, addr_);
#if !defined(NDEBUG)
int64_t duration = TimeSince(connect_time_);
RTC_LOG(LS_INFO) << "WSAAsync:connect error (" << duration
<< " ms), faking close";
#endif
state_ = CS_CLOSED;
// If you get an error connecting, close doesn't really do anything
// and it certainly doesn't send back any close notification, but
// we really only maintain a few states, so it is easiest to get
// back into a known state by pretending that a close happened, even
// though the connect event never did occur.
SignalCloseEvent(this, error);
} else {
#if !defined(NDEBUG)
int64_t duration = TimeSince(connect_time_);
RTC_LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
#endif
state_ = CS_CONNECTED;
SignalConnectEvent(this);
}
break;
case FD_ACCEPT:
case FD_READ:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:read notify", error, addr_);
} else {
SignalReadEvent(this);
}
break;
case FD_WRITE:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:write notify", error, addr_);
} else {
SignalWriteEvent(this);
}
break;
case FD_CLOSE:
if (HandleClosed(error)) {
ReportWSAError("WSAAsync:close notify", error, addr_);
state_ = CS_CLOSED;
SignalCloseEvent(this, error);
}
break;
}
}
void Win32Socket::OnDnsNotify(HANDLE task, int error) {
if (!dns_ || dns_->handle != task)
return;
uint32_t ip = 0;
if (error == 0) {
hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]);
ip = NetworkToHost32(net_ip);
}
RTC_LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString() << ", "
<< error << ")";
if (error == 0) {
SocketAddress address(ip, dns_->port);
error = DoConnect(address);
} else {
Close();
}
if (error) {
error_ = error;
SignalCloseEvent(this, error_);
} else {
delete dns_;
dns_ = nullptr;
}
}
// Win32SocketServer
// Provides cricket base services on top of a win32 gui thread
static UINT s_wm_wakeup_id = 0;
const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
Win32SocketServer::Win32SocketServer()
: wnd_(this), posted_(false), hdlg_(nullptr) {
if (s_wm_wakeup_id == 0)
s_wm_wakeup_id = <API key>(L"WM_WAKEUP");
if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) {
RTC_LOG_GLE(LS_ERROR) << "Failed to create message window.";
}
}
Win32SocketServer::~Win32SocketServer() {
if (wnd_.handle() != nullptr) {
KillTimer(wnd_.handle(), 1);
wnd_.Destroy();
}
}
Socket* Win32SocketServer::CreateSocket(int family, int type) {
return CreateAsyncSocket(family, type);
}
AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
Win32Socket* socket = new Win32Socket;
if (socket->CreateT(family, type)) {
return socket;
}
delete socket;
return nullptr;
}
void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
message_queue_ = queue;
}
bool Win32SocketServer::Wait(int cms, bool process_io) {
BOOL b;
if (process_io) {
// Spin the Win32 message pump at least once, and as long as requested.
// This is the Thread::ProcessMessages case.
uint32_t start = Time();
do {
MSG msg;
SetTimer(wnd_.handle(), 0, cms, nullptr);
// Get the next available message. If we have a modeless dialog, give
// give the message to IsDialogMessage, which will return true if it
// was a message for the dialog that it handled internally.
// Otherwise, dispatch as usual via Translate/DispatchMessage.
b = GetMessage(&msg, nullptr, 0, 0);
if (b == -1) {
RTC_LOG_GLE(LS_ERROR) << "GetMessage failed.";
return false;
} else if (b) {
if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(wnd_.handle(), 0);
} while (b && TimeSince(start) < cms);
} else if (cms != 0) {
// Sit and wait forever for a WakeUp. This is the Thread::Send case.
RTC_DCHECK(cms == -1);
MSG msg;
b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id);
{
CritScope scope(&cs_);
posted_ = false;
}
} else {
// No-op (cms == 0 && !process_io). This is the Pump case.
b = TRUE;
}
return (b != FALSE);
}
void Win32SocketServer::WakeUp() {
if (wnd_.handle()) {
// Set the "message pending" flag, if not already set.
{
CritScope scope(&cs_);
if (posted_)
return;
posted_ = true;
}
PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
}
}
void Win32SocketServer::Pump() {
// Clear the "message pending" flag.
{
CritScope scope(&cs_);
posted_ = false;
}
// Dispatch all the messages that are currently in our queue. If new messages
// are posted during the dispatch, they will be handled in the next Pump.
// We use max(1, ...) to make sure we try to dispatch at least once, since
// this allow us to process "sent" messages, not included in the size() count.
Message msg;
for (size_t <API key> =
std::max<size_t>(1, message_queue_->size());
<API key> > 0 && message_queue_->Get(&msg, 0, false);
--<API key>) {
message_queue_->Dispatch(&msg);
}
// Anything remaining?
int delay = message_queue_->GetDelay();
if (delay == -1) {
KillTimer(wnd_.handle(), 1);
} else {
SetTimer(wnd_.handle(), 1, delay, nullptr);
}
}
bool Win32SocketServer::MessageWindow::OnMessage(UINT wm,
WPARAM wp,
LPARAM lp,
LRESULT& lr) {
bool handled = false;
if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
ss_->Pump();
lr = 0;
handled = true;
}
return handled;
}
Win32Thread::Win32Thread(SocketServer* ss) : Thread(ss), id_(0) {}
Win32Thread::~Win32Thread() {
Stop();
}
void Win32Thread::Run() {
id_ = GetCurrentThreadId();
Thread::Run();
id_ = 0;
}
void Win32Thread::Quit() {
PostThreadMessage(id_, WM_QUIT, 0, 0);
}
} // namespace rtc
|
class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
""":type: list[R]"""
for c in p:
if c == '*':
rs[-1].is_star = True
else:
rs.append(R(c))
lr = len(rs)
ls = len(s)
s += '\0'
dp = [[False] * (ls + 1) for _ in range(lr + 1)]
dp[0][0] = True
for i, r in enumerate(rs):
for j in range(ls + 1):
c = s[j - 1]
if r.is_star:
dp[i + 1][j] = dp[i][j]
if j and r.match(c):
dp[i + 1][j] |= dp[i + 1][j - 1]
else:
if j and r.match(c):
dp[i + 1][j] = dp[i][j - 1]
return dp[-1][-1]
|
# escape=`
FROM mcr.microsoft.com/windows/servercore as msi
SHELL ["powershell", "-Command", "$<API key> = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ENV MONGO_VERSION 3.4.5
ENV MONGO_DOWNLOAD_URL https://downloads.mongodb.com/win32/<API key>-${MONGO_VERSION}-signed.msi
ENV <API key> <SHA256-like>
RUN Write-Host ('Downloading {0} ...' -f $env:MONGO_DOWNLOAD_URL)
RUN Invoke-WebRequest -Uri $env:MONGO_DOWNLOAD_URL -OutFile 'mongodb.msi'
RUN Write-Host ('Verifying sha256 ({0}) ...' -f $env:<API key>)
RUN if ((Get-FileHash mongodb.msi -Algorithm sha256).Hash -ne $env:<API key>) { `
Write-Host 'FAILED!'; `
exit 1; `
}
RUN Start-Process msiexec.exe -ArgumentList '/i', 'mongodb.msi', '/quiet', '/norestart', 'INSTALLLOCATION=C:\mongodb', 'ADDLOCAL=Server,Client,MonitoringTools,ImportExportTools,MiscellaneousTools' -NoNewWindow -Wait
RUN Remove-Item C:\mongodb\bin\*.pdb
FROM mcr.microsoft.com/windows/nanoserver:sac2016
COPY --from=msi C:\mongodb\ C:\mongodb\
COPY --from=msi C:\windows\system32\msvcp140.dll C:\windows\system32
COPY --from=msi C:\windows\system32\vcruntime140.dll C:\windows\system32
COPY --from=msi C:\windows\system32\wininet.dll C:\windows\system32
RUN mkdir C:\data\db & setx /m PATH %PATH%;C:\mongodb\bin
VOLUME C:\data\db
EXPOSE 27017
CMD ["mongod.exe"]
|
public class App {
public static void main(String[] args) {
System.out.println("Old man, look at my life...");
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Thu Jan 05 15:34:48 PST 2017 -->
<title>Uses of Class main.CurrentDateAndTime</title>
<meta name="date" content="2017-01-05">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class main.CurrentDateAndTime";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../main/package-summary.html">Package</a></li>
<li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li>
<li><a href="CurrentDateAndTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class main.CurrentDateAndTime" class="title">Uses of Class<br>main.CurrentDateAndTime</h2>
</div>
<div class="classUseContainer">No usage of main.CurrentDateAndTime</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../main/package-summary.html">Package</a></li>
<li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li>
<li><a href="CurrentDateAndTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html>
|
var score = 0;
var scoreText;
var map_x = 14;
var map_y = 10;
var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update });
function preload() {
// game.scale.maxWidth = 600;
// game.scale.maxHeight = 600;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.setScreenSize();
game.load.image('cat', 'assets/cat.png', 16, 16);
game.load.image('ground', 'assets/darkfloor.png', 16, 16);
game.load.image('l_wall', 'assets/l_wall.png', 16, 16);
game.load.image('r_wall', 'assets/r_wall.png', 16, 16);
game.load.image('t_wall', 'assets/t_wall.png', 16, 16);
game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16);
game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16);
game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16);
game.load.image('br_wall', 'assets/br_wall.png', 16, 16);
game.load.image('stone_door', 'assets/door_stone.png', 16, 16);
game.load.image('star', 'assets/star.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
// the game world
gmap = game.add.tilemap();
gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0);
gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1);
gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2);
gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3);
gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4);
gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5);
gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6);
gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7);
gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8);
ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16);
wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16);
for (var i=0; i<map_x; i++) {
for(var j=0; j<map_y; j++) {
if (i==0 && j==0) {
gmap.putTile(4, i, j, wall_layer);
} else if (i==map_x/2 && j==0) {
gmap.putTile(8, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(5, i, j, wall_layer);
} else if (i==0 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==map_x-1 && j == 0) {
gmap.putTile(3, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==0) {
gmap.putTile(1, i, j, wall_layer);
} else if(i==map_x-1) {
gmap.putTile(2, i, j, wall_layer);
} else if(j==map_y-1) {
gmap.putTile(7, i, j, wall_layer);
} else if(j==0) {
gmap.putTile(7, i, j, wall_layer);
} else {
gmap.putTile(0, i, j, ground_layer);
}
}
}
wall_layer.resizeWorld();
game.physics.arcade.enable(wall_layer);
gmap.setCollision(wall_layer);
// the player
player = game.add.sprite(32, 32, 'cat');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
// gmap.setCollisionBetween(0, 100, true, wall_layer);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collide(player, wall_layer);
player.body.velocity.x = 0;
player.body.velocity.y = 0;
if (cursors.left.isDown) {
player.body.velocity.x = -150;
} else if (cursors.right.isDown) {
player.body.velocity.x = 150;
} else if (cursors.down.isDown) {
player.body.velocity.y = 150;
} else if (cursors.up.isDown) {
player.body.velocity.y = -150;
} else {
}
}
|
package com.thebluealliance.androidclient.gcm.notifications;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.activities.ViewMatchActivity;
import com.thebluealliance.androidclient.datafeed.JSONManager;
import com.thebluealliance.androidclient.helpers.EventHelper;
import com.thebluealliance.androidclient.helpers.MatchHelper;
import com.thebluealliance.androidclient.helpers.MyTBAHelper;
import com.thebluealliance.androidclient.listeners.<API key>;
import com.thebluealliance.androidclient.models.BasicModel;
import com.thebluealliance.androidclient.models.Match;
import com.thebluealliance.androidclient.models.StoredNotification;
import com.thebluealliance.androidclient.views.MatchView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class ScoreNotification extends BaseNotification {
private String eventName, eventKey, matchKey;
private Match match;
public ScoreNotification(String messageData) {
super("score", messageData);
}
@Override
public void parseMessageData() throws JsonParseException {
JsonObject jsonData = JSONManager.getasJsonObject(messageData);
if (!jsonData.has("match")) {
throw new JsonParseException("Notification data does not contain 'match");
}
JsonObject match = jsonData.get("match").getAsJsonObject();
this.match = gson.fromJson(match, Match.class);
try {
this.matchKey = this.match.getKey();
} catch (BasicModel.<API key> e) {
e.printStackTrace();
}
this.eventKey = MatchHelper.<API key>(matchKey);
if (!jsonData.has("event_name")) {
throw new JsonParseException("Notification data does not contain 'event_name");
}
eventName = jsonData.get("event_name").getAsString();
}
@Override
public Notification buildNotification(Context context) {
Resources r = context.getResources();
String matchKey;
try {
matchKey = match.getKey();
this.matchKey = matchKey;
} catch (BasicModel.<API key> e) {
Log.e(getLogTag(), "Incoming Match object does not have a key. Can't post score update");
e.printStackTrace();
return null;
}
String matchTitle = MatchHelper.<API key>(context, matchKey);
String matchAbbrevTitle = MatchHelper.<API key>(context, matchKey);
JsonObject alliances;
try {
alliances = match.getAlliances();
} catch (BasicModel.<API key> e) {
Log.e(getLogTag(), "Incoming match object does not contain alliance data. Can't post score update");
e.printStackTrace();
return null;
}
int redScore = Match.getRedScore(alliances);
ArrayList<String> redTeamKeys = new ArrayList<>();
JsonArray redTeamsJson = Match.getRedTeams(alliances);
for (int i = 0; i < redTeamsJson.size(); i++) {
redTeamKeys.add(redTeamsJson.get(i).getAsString());
}
int blueScore = Match.getBlueScore(alliances);
ArrayList<String> blueTeamKeys = new ArrayList<>();
JsonArray blueTeamsJson = Match.getBlueTeams(alliances);
for (int i = 0; i < blueTeamsJson.size(); i++) {
blueTeamKeys.add(blueTeamsJson.get(i).getAsString());
}
// TODO filter out teams that the user doesn't want notifications about
// These arrays hold the numbers of teams that the user cares about
ArrayList<String> redTeams = new ArrayList<>();
ArrayList<String> blueTeams = new ArrayList<>();
for (String key : redTeamKeys) {
redTeams.add(key.replace("frc", ""));
}
for (String key : blueTeamKeys) {
blueTeams.add(key.replace("frc", ""));
}
// Make sure the score string is formatted properly with the winning score first
String scoreString;
if (redScore > blueScore) {
scoreString = redScore + "-" + blueScore;
} else if (redScore < blueScore) {
scoreString = blueScore + "-" + redScore;
} else {
scoreString = redScore + "-" + redScore;
}
String redTeamString = Utilities.<API key>(context, redTeams);
String blueTeamString = Utilities.<API key>(context, blueTeams);
boolean <API key>;
try {
<API key> = match.getYear() == 2015 && match.getType() != MatchHelper.TYPE.FINAL;
} catch (BasicModel.<API key> e) {
<API key> = false;
Log.w(Constants.LOG_TAG, "Couldn't determine if we should use 2015 score format. Defaulting to no");
}
String eventShortName = EventHelper.shortName(eventName);
String notificationString;
if (redTeams.size() == 0 && blueTeams.size() == 0) {
// We must have gotten this GCM message by mistake
return null;
} else if (<API key>) {
/* Only for 2015 non-finals matches. Ugh */
notificationString = context.getString(R.string.<API key>, eventShortName, matchTitle, redTeamString, redScore, blueTeamString, blueScore);
} else if ((redTeams.size() > 0 && blueTeams.size() == 0)) {
// The user only cares about some teams on the red alliance
if (redScore > blueScore) {
// Red won
notificationString = context.getString(R.string.<API key>, eventShortName, redTeamString, matchTitle, scoreString);
} else if (redScore < blueScore) {
// Red lost
notificationString = context.getString(R.string.<API key>, eventShortName, redTeamString, matchTitle, scoreString);
} else {
// Red tied
notificationString = context.getString(R.string.<API key>, eventShortName, redTeamString, matchTitle, scoreString);
}
} else if ((blueTeams.size() > 0 && redTeams.size() == 0)) {
// The user only cares about some teams on the blue alliance
if (blueScore > redScore) {
// Blue won
notificationString = context.getString(R.string.<API key>, eventShortName, blueTeamString, matchTitle, scoreString);
} else if (blueScore < redScore) {
// Blue lost
notificationString = context.getString(R.string.<API key>, eventShortName, blueTeamString, matchTitle, scoreString);
} else {
// Blue tied
notificationString = context.getString(R.string.<API key>, eventShortName, blueTeamString, matchTitle, scoreString);
}
} else if ((blueTeams.size() > 0 && redTeams.size() > 0)) {
// The user cares about teams on both alliances
if (blueScore > redScore) {
// Blue won
notificationString = context.getString(R.string.<API key>, eventShortName, blueTeamString, redTeamString, matchTitle, scoreString);
} else if (blueScore < redScore) {
// Blue lost
notificationString = context.getString(R.string.<API key>, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString);
} else {
// Blue tied
notificationString = context.getString(R.string.<API key>, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString);
}
} else {
// We should never, ever get here but if we do...
return null;
}
// We can finally build the notification!
Intent instance = getIntent(context);
stored = new StoredNotification();
stored.setType(getNotificationType());
String eventCode = EventHelper.getEventCode(matchKey);
String notificationTitle = r.getString(R.string.<API key>, eventCode, matchAbbrevTitle);
stored.setTitle(notificationTitle);
stored.setBody(notificationString);
stored.setIntent(MyTBAHelper.serializeIntent(instance));
stored.setTime(Calendar.getInstance().getTime());
NotificationCompat.Builder builder = getBaseBuilder(context, instance)
.setContentTitle(notificationTitle)
.setContentText(notificationString)
.setLargeIcon(<API key>(context, R.drawable.<API key>));
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle().bigText(notificationString);
builder.setStyle(style);
return builder.build();
}
@Override
public void updateDataLocally(Context c) {
if (match != null) {
match.write(c);
}
}
@Override
public Intent getIntent(Context c) {
return ViewMatchActivity.newInstance(c, matchKey);
}
@Override
public int getNotificationId() {
return (new Date().getTime() + ":" + getNotificationType() + ":" + matchKey).hashCode();
}
@Override
public View getView(Context c, LayoutInflater inflater, View convertView) {
ViewHolder holder;
if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) {
convertView = inflater.inflate(R.layout.<API key>, null, false);
holder = new ViewHolder();
holder.header = (TextView) convertView.findViewById(R.id.card_header);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.matchView = (MatchView) convertView.findViewById(R.id.match_details);
holder.time = (TextView) convertView.findViewById(R.id.notification_time);
holder.summaryContainer = convertView.findViewById(R.id.summary_container);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.header.setText(c.getString(R.string.<API key>, EventHelper.shortName(eventName), EventHelper.<API key>(eventKey).toUpperCase()));
holder.title.setText(c.getString(R.string.<API key>, MatchHelper.<API key>(c, matchKey)));
holder.time.setText(<API key>(c));
holder.summaryContainer.setOnClickListener(new <API key>(c, this));
match.render(false, false, false, true).getView(c, inflater, holder.matchView);
return convertView;
}
private class ViewHolder {
public TextView header;
public TextView title;
public MatchView matchView;
public TextView time;
private View summaryContainer;
}
}
|
import { expect } from 'chai';
import { Curry } from './curry';
describe('curry', () => {
it('should curry the method with default arity', () => {
class MyClass {
@Curry()
add(a: any, b?: any) {
return a + b;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10)).to.equal(15);
});
it('should curry the method with default arity (paramless)', () => {
class MyClass {
@Curry
add(a: any, b?: any) {
return a + b;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10)).to.equal(15);
});
it('should curry the method with fixed arity', () => {
class MyClass {
@Curry(2)
add(a: any, b?: any, c?: any) {
return a + b * c;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10, 2)).to.equal(25);
});
it('should retain the class context', () => {
class MyClass {
value = 10;
@Curry()
add(a: any, b?: any): any {
return (a + b) * this.value;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5(2)).to.equal(70);
});
});
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DebugWindow : MonoBehaviour {
public Text textWindow;
string freshInput;
// Use this for initialization
void Start () {
if (textWindow == null)
throw new UnityException ("Debug Window has no text box to output to.");
}
// Update is called once per frame
void Update () {
textWindow.text = "Debug:\n" + freshInput;
freshInput = "";
}
public void LOG(string Text)
{
freshInput += Text + '\n';
}
}
|
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Pomelo.EntityFrameworkCore.MySql.Query.<API key>.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.Internal;
namespace Pomelo.EntityFrameworkCore.MySql.Json.Microsoft.Query.Internal
{
public class <API key> : <API key>
{
public <API key>(
<API key> typeMappingSource,
<API key> <API key>,
<API key> jsonPocoTranslator)
{
var <API key> = (<API key>)<API key>;
var <API key> = (<API key>)jsonPocoTranslator;
Translators = new IMemberTranslator[]
{
new <API key>(
<API key>,
typeMappingSource,
<API key>),
jsonPocoTranslator,
};
}
public virtual IEnumerable<IMemberTranslator> Translators { get; }
}
}
|
export { default } from 'ember-flexberry-gis/services/map-store';
|
from flask import Flask, render_template, flash
from flask_material_lite import Material_Lite
from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from flask_wtf.file import FileField
from wtforms import TextField, HiddenField, ValidationError, RadioField,\
BooleanField, SubmitField, IntegerField, FormField, validators
from wtforms.validators import Required
# straight from the wtforms docs:
class TelephoneForm(Form):
country_code = IntegerField('Country Code', [validators.required()])
area_code = IntegerField('Area Code/Exchange', [validators.required()])
number = TextField('Number')
class ExampleForm(Form):
field1 = TextField('First Field', description='This is field one.')
field2 = TextField('Second Field', description='This is field two.',
validators=[Required()])
hidden_field = HiddenField('You cannot see this', description='Nope')
recaptcha = RecaptchaField('A sample recaptcha field')
radio_field = RadioField('This is a radio field', choices=[
('head_radio', 'Head radio'),
('radio_76fm', "Radio '76 FM"),
('lips_106', 'Lips 106'),
('wctr', 'WCTR'),
])
checkbox_field = BooleanField('This is a checkbox',
description='Checkboxes can be tricky.')
# subforms
mobile_phone = FormField(TelephoneForm)
# you can change the label as well
office_phone = FormField(TelephoneForm, label='Your office phone')
ff = FileField('Sample upload')
submit_button = SubmitField('Submit Form')
def <API key>(form, field):
raise ValidationError('Always wrong')
def create_app(configfile=None):
app = Flask(__name__)
AppConfig(app, configfile) # Flask-Appconfig is not necessary, but
# highly recommend =)
Material_Lite(app)
# in a real app, these should be configured through Flask-Appconfig
app.config['SECRET_KEY'] = 'devkey'
app.config['<API key>'] = \
'<API key>'
@app.route('/', methods=('GET', 'POST'))
def index():
form = ExampleForm()
form.validate_on_submit() # to get error messages to the browser
flash('critical message', 'critical')
flash('error message', 'error')
flash('warning message', 'warning')
flash('info message', 'info')
flash('debug message', 'debug')
flash('different message', 'different')
flash('uncategorized message')
return render_template('index.html', form=form)
return app
if __name__ == '__main__':
create_app().run(debug=True)
|
#!/usr/bin/env python3
from __future__ import print_function, division
import numpy as np
from sht.grids import standard_grid, get_cartesian_grid
def test_grids():
L = 10
thetas, phis = standard_grid(L)
# Can't really test much here
assert thetas.size == L
assert phis.size == L**2
grid = get_cartesian_grid(thetas, phis)
assert grid.shape == (L**2, 3)
|
var Keyboard_Space = new function(){
this.initKeyboard = function(testing){
testmode = testing;
return new Keyboard();
}
var Keyboard = function(){
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
var this_obj = this;
Zip_Space.loadZip(currentSongData["filename"], function() {
this_obj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
this_obj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
this_obj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
this_obj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
this_obj.backend = BackendSpace.init();
this_obj.keyboardUI = Keyboard_UI_Space.initKeyboardUI();
console.log("New keyboard created");
})
}
// link the keyboard and the editor
Keyboard.prototype.linkEditor = function(editor){
this.editor = editor;
var mainObj = this;
setTimeout(function(){mainObj.editor.setBPM(currentSongData.bpm)},500);
}
Keyboard.prototype.getCurrentSounds = function(){
return currentSounds;
}
// loads sounds from srcArray for given chain into soundArr
Keyboard.prototype.loadSounds = function(srcArr, soundArr, chain){
for(var i = 0; i < srcArr.length; i++)
soundArr.push(null);
for(var i = 0; i < srcArr.length; i++){
if(srcArr[i] == "")
this.checkLoaded();
else
this.requestSound(i, srcArr, soundArr, chain);
}
}
// makes request for sounds
// if offline version, gets from local files
// if online version, gets from public folder
Keyboard.prototype.requestSound = function(i, srcArr, soundArr, chain){
var thisObj = this;
soundArr[i] = new Howl({
// for online version
urls: [Zip_Space.dataArray['sounds/chain'+chain+'/'+srcArr[i]+'.mp3']],
// old
// for offline version
// urls: ["audio/chain"+chain+"/"+srcArr[i]+".mp3"],
onload: function(){
thisObj.checkLoaded();
},
onloaderror: function(id, error){
console.log('error: '+id)
console.log(error);
console.log('sounds/chain'+chain+'/'+srcArr[i]+'.mp3');
$("#error_msg").html("There was an error. Please try clearing your browser's cache and reload the page.");
}
});
}
// checks if all of the sounds have loaded
// if they have, load the keyboard
Keyboard.prototype.checkLoaded = function(){
numSoundsLoaded++;
$(".soundPack").html("Loading sounds ("+numSoundsLoaded+"/"+(4*12*numChains)+")");
if(numSoundsLoaded == 4*12*numChains){
loadingSongs = false;
this.keyboardUI.loadKeyboard(this, currentSongData, currentSoundPack);
}
}
Keyboard.prototype.getKeyInd = function(kc){
var keyInd = keyPairs.indexOf(kc);
if(keyInd == -1)
keyInd = backupPairs.indexOf(kc);
return keyInd;
}
Keyboard.prototype.<API key> = function(kc){
if(kc == 39){
this.switchSoundPack(3);
return true;
}
// left
else if(kc == 37){
this.switchSoundPack(0);
return true;
}
// down
else if(kc == 38){
this.switchSoundPack(1);
return true;
}
// right
else if(kc == 40){
this.switchSoundPack(2);
return true;
}
}
// switch sound pack and update pressures
Keyboard.prototype.switchSoundPack = function(sp){
// release all keys
for(var i = 0; i < 4; i++)
for(var j = 0; j < 12; j++)
if($(".button-"+(i*12+j)+"").attr("released") == "false")
this.releaseKey(keyPairs[i*12+j]);
// set the new soundpack
currentSoundPack = sp;
$(".sound_pack_button").css("background-color","white");
$(".sound_pack_button_"+(currentSoundPack+1)).css("background-color","rgb(255,160,0)");
$(".soundPack").html("Sound Pack: "+(currentSoundPack+1));
// set pressures for buttons in new sound pack
for(var i = 0; i < 4; i++){
for(var j = 0; j < 12; j++){
var press = false;
if(currentSongData["holdToPlay"]["chain"+(currentSoundPack+1)].indexOf((i*12+j)) != -1)
press = true;
$('.button-'+(i*12+j)+'').attr("pressure", ""+press+"");
// holdToPlay coloring, turned off for now
//$('.button-'+(i*12+j)+'').css("background-color", $('.button-'+(i*12+j)+'').attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// key released
// stop playing sound if holdToPlay
Keyboard.prototype.releaseKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyUp(kc);
// send key code to MIDI editor
this.editor.recordKeyUp(kc);
}
}
Keyboard.prototype.midiKeyUp = function(kc){
if(this.<API key>(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
if($(".button-"+(kcInd)+"").attr("pressure") == "true")
currentSounds[currentSoundPack][kcInd].stop();
$(".button-"+(kcInd)+"").attr("released","true");
// holdToPlay coloring, turned off for now
// Removes Style Attribute to clean up HTML
$(".button-"+(kcInd)+"").removeAttr("style");
if($(".button-"+(kcInd)+"").hasClass("pressed") == true)
$(".button-"+(kcInd)+"").removeClass("pressed");
//$(".button-"+(kcInd)+"").css("background-color", $(".button-"+(kcInd)+"").attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// play the key by finding the mapping,
// stopping all sounds in key's linkedArea
// and then playing sound
Keyboard.prototype.playKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyDown(kc);
// send key code to midi editor
this.editor.recordKeyDown(kc);
}
}
Keyboard.prototype.midiKeyDown = function(kc){
if(this.<API key>(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
currentSounds[currentSoundPack][kcInd].stop();
currentSounds[currentSoundPack][kcInd].play();
// go through all linked Areas in current chain
currentSongData["linkedAreas"]["chain"+(currentSoundPack+1)].forEach(function(el, ind, arr){
// for ever linked area array
for(var j = 0; j < el.length; j++){
// if key code is in linked area array
if(kcInd == el[j]){
// stop all other sounds in linked area array
for(var k = 0; k < el.length; k++){
if(k != j)
currentSounds[currentSoundPack][el[k]].stop();
}
break;
}
}
});
// set button color and attribute
$(".button-"+(kcInd)+"").addClass("pressed");
$(".button-"+(kcInd)+"").attr("released","false");
//$(".button-"+(kcInd)+"").css("background-color","rgb(255,160,0)");
}
}
}
// shows and formats all of the UI elements
Keyboard.prototype.initUI = function(){
// create new editor and append it to the body element
if(testmode)
BasicMIDI.init("#<API key>", this, 170);
else
MIDI_Editor.init("#<API key>", this, 170);
// info and links buttons
// $(".click_button").css("display", "inline-block");
for(var s in songDatas)
$("#songs_container").append("<div class='song_selection' songInd='"+s+"'>"+songDatas[s].song_name+"</div>");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
var mainObj = this;
$(".song_selection").click(function() {
var tempS = parseInt($(this).attr("songInd"));
if(tempS != currentSongInd && !loadingSongs){
loadingSongs = true;
currentSongInd = tempS
currentSongData = songDatas[currentSongInd];
$(".song_selection").css("background-color","white");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
$(".button-row").remove();
for(var i = 0; i < currentSounds.length; i++){
for(var k = 0; k < currentSounds[i].length; k++){
if(currentSounds[i][k] != null)
currentSounds[i][k].unload();
}
}
currentSounds = [];
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
mainObj.editor.notesLoaded([],-1);
mainObj.editor.setBPM(currentSongData.bpm)
numSoundsLoaded = 0;
Zip_Space.loadZip(currentSongData["filename"], function() {
mainObj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
mainObj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
mainObj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
mainObj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
})
}
});
}
// send request to server to save the notes to the corresponding projectId (pid)
Keyboard.prototype.saveNotes = function(notes, pid){
var saveNote = [];
for(var n in notes)
saveNote.push({"note":notes[n].note, "beat":notes[n].beat, "length":notes[n].length});
//console.log(saveNote);
this.backend.saveSong(JSON.stringify(saveNote), pid, this.editor, currentSongData.song_number);
}
// ask the user for the project they would like to load and then load that project from the server
// send back a notes array of the loaded project with note,beat,and length and the project id
Keyboard.prototype.loadNotes = function(){
this.backend.loadSongs(this.editor, currentSongData.song_number);
}
// current soundpack (0-3)
var currentSoundPack = 0;
// number of sounds loaded
var numSoundsLoaded = 0;
// howl objects for current song
var currentSounds = [];
// reference to current song data
var songDatas = [equinoxData, animalsData, electroData, ghetData, kyotoData, aeroData];
var currentSongInd = 0;
var currentSongData = equinoxData;
// number of chains
var numChains = 4;
var testmode = false;
var loadingSongs = true;
}
// Global Variables
// ascii key mappings to array index
var keyPairs = [49,50,51,52,53,54,55,56,57,48,189,187,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,186,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// alternate keys for firefox
var backupPairs = [49,50,51,52,53,54,55,56,57,48,173,61,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,59,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// letter to show in each button
var letterPairs = ["1","2","3","4","5","6","7","8","9","0","-","=",
"Q","W","E","R","T","Y","U","I","O","P","[","]",
"A","S","D","F","G","H","J","K","L",";","'","\\n",
"Z","X","C","V","B","N","M",",",".","/","\\s","NA"];
|
angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books-table.html'
};
})
.directive('userTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-table.html'
};
})
.directive('userProfileInfo', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-profile-info.html'
};
})
.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}]);
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http:
<head>
<div th:fragment="common-header">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>WickedThymeleafDemo</title>
<link th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet" media="screen"/>
<link type="text/css" th:href="@{/css/styles.css}" rel="stylesheet" media="screen"/>
</div>
</head>
<body>
<div th:fragment="end-scripts">
<script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
</div>
</body>
</html>
|
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class <API key> < ActionController::Base
helper :all
helper_method :<API key>, :current_user
<API key> :password, :<API key>
layout 'application'
protected
def <API key>
return @<API key> if defined?(@<API key>)
@<API key> = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = <API key> && <API key>.record
end
def require_user
unless current_user
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to login_url
return false
end
end
def require_no_user
if current_user
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to account_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def <API key>(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
end
|
<?php
namespace App\AAS_Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\AAS_Bundle\Utils\AAS as AAS;
/**
* Person
*/
class Person
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $surname;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $patronymic;
/**
* @var string
*/
private $position;
/**
* @var \App\AAS_Bundle\Entity\Witness
*/
private $witness;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $phone_numbers;
/**
* @var \App\AAS_Bundle\Entity\Team
*/
private $team;
/**
* @var \DateTime
*/
private $created_at;
/**
* @var \DateTime
*/
private $updated_at;
/**
* Constructor
*/
public function __construct()
{
$this->phone_numbers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set surname
*
* @param string $surname
* @return Person
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
public function getSurnameSlug()
{
return AAS::slugify($this->getSurname());
}
/**
* Set name
*
* @param string $name
* @return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
public function getNameSlug()
{
return AAS::slugify($this->getName());
}
/**
* Set patronymic
*
* @param string $patronymic
* @return Person
*/
public function setPatronymic($patronymic)
{
$this->patronymic = $patronymic;
return $this;
}
/**
* Get patronymic
*
* @return string
*/
public function getPatronymic()
{
return $this->patronymic;
}
public function getPatronymicSlug()
{
return AAS::slugify($this->getPatronymic());
}
/**
* Set created_at
*
* @param \DateTime $createdAt
* @return Person
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* @param \DateTime $updatedAt
* @return Person
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* @ORM\PrePersist
*/
public function setCreatedAtValue()
{
if(!$this->getCreatedAt())
{
$this->created_at = new \DateTime();
}
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedAtValue()
{
$this->updated_at = new \DateTime();
}
/**
* @var \App\AAS_Bundle\Entity\SecurityPerson
*/
private $security_person;
/**
* Set security_person
*
* @param \App\AAS_Bundle\Entity\SecurityPerson $securityPerson
* @return Person
*/
public function setSecurityPerson(\App\AAS_Bundle\Entity\SecurityPerson $securityPerson = null)
{
$this->security_person = $securityPerson;
return $this;
}
/**
* Get security_person
*
* @return \App\AAS_Bundle\Entity\SecurityPerson
*/
public function getSecurityPerson()
{
return $this->security_person;
}
/**
* Set position
*
* @param string $position
* @return Person
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* @return string
*/
public function getPosition()
{
return $this->position;
}
/**
* Set witness
*
* @param \App\AAS_Bundle\Entity\Witness $witness
* @return Person
*/
public function setWitness(\App\AAS_Bundle\Entity\Witness $witness = null)
{
$this->witness = $witness;
return $this;
}
/**
* Get witness
*
* @return \App\AAS_Bundle\Entity\Witness
*/
public function getWitness()
{
return $this->witness;
}
/**
* Add phone_numbers
*
* @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers
* @return Person
*/
public function addPhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers)
{
$this->phone_numbers[] = $phoneNumbers;
return $this;
}
/**
* Remove phone_numbers
*
* @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers
*/
public function removePhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers)
{
$this->phone_numbers->removeElement($phoneNumbers);
}
/**
* Get phone_numbers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getPhoneNumbers()
{
return $this->phone_numbers;
}
/**
* Set team
*
* @param \App\AAS_Bundle\Entity\Team $team
* @return Person
*/
public function setTeam(\App\AAS_Bundle\Entity\Team $team = null)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* @return \App\AAS_Bundle\Entity\Team
*/
public function getTeam()
{
return $this->team;
}
/**
* @var \App\AAS_Bundle\Entity\MedicalCommission
*/
private $medical_commission;
/**
* Set medical_commission
*
* @param \App\AAS_Bundle\Entity\MedicalCommission $medicalCommission
* @return Person
*/
public function <API key>(\App\AAS_Bundle\Entity\MedicalCommission $medicalCommission = null)
{
$this->medical_commission = $medicalCommission;
return $this;
}
/**
* Get medical_commission
*
* @return \App\AAS_Bundle\Entity\MedicalCommission
*/
public function <API key>()
{
return $this->medical_commission;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $admissions;
/**
* Add admissions
*
* @param \App\AAS_Bundle\Entity\Admission $admissions
* @return Person
*/
public function addAdmission(\App\AAS_Bundle\Entity\Admission $admissions)
{
$this->admissions[] = $admissions;
return $this;
}
/**
* Remove admissions
*
* @param \App\AAS_Bundle\Entity\Admission $admissions
*/
public function removeAdmission(\App\AAS_Bundle\Entity\Admission $admissions)
{
$this->admissions->removeElement($admissions);
}
/**
* Get admissions
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAdmissions()
{
return $this->admissions;
}
/**
* @var \App\AAS_Bundle\Entity\BusinessTripGroup
*/
private $business_trip_group;
/**
* Set business_trip_group
*
* @param \App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup
* @return Person
*/
public function <API key>(\App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup = null)
{
$this->business_trip_group = $businessTripGroup;
return $this;
}
/**
* Get business_trip_group
*
* @return \App\AAS_Bundle\Entity\BusinessTripGroup
*/
public function <API key>()
{
return $this->business_trip_group;
}
}
|
package me.streib.janis.nanhotline.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.<API key>;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class Launcher {
public static void main(String[] args) throws Exception {
<API key> conf;
if (args.length != 1) {
InputStream ins;
File confFile = new File("conf/nanhotline.properties");
if (confFile.exists()) {
ins = new FileInputStream(confFile);
} else {
ins = Launcher.class
.getResourceAsStream("nanhotline.properties");
}
conf = new <API key>(ins);
} else {
conf = new <API key>(new FileInputStream(new File(
args[0])));
}
DatabaseConnection.init(conf);
Server s = new Server(new InetSocketAddress(conf.getHostName(),
conf.getPort()));
((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20);
<API key> h = new <API key>(
<API key>.SESSIONS);
h.setInitParameter(SessionManager.<API key>, "DB-Session");
|
const test = require('tap').test
const GF = require('core/galois-field')
test('Galois Field', function (t) {
t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1')
for (let i = 1; i < 255; i++) {
t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other')
t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other')
}
t.equal(GF.mul(0, 1), 0, 'Should return 0 if first param is 0')
t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0')
t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0')
for (let j = 1; j < 255; j++) {
t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative')
}
t.end()
})
|
import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../monad";
import { noop } from "lodash";
import { ImmutableObject, <API key> } from "../immutable";
import { LogLevel, LogAction, LogActionTypes, Logger } from "./base";
// beat TS type checking
chalk.enabled = true;
function createLogColorizer(tester: RegExp, replaceValue: any) {
return function(input: string) {
if (!tester.test(input)) return input;
return input.replace(tester, replaceValue);
}
}
export type ConsoleLogState = {
argv?: {
color?: boolean,
hlog?: boolean
},
log?: {
level: LogLevel,
prefix?: string
}
}
const cwd = process.cwd();
const highlighters = [
createLogColorizer(/^INF/, (match) => chalk.bgCyan(match)),
createLogColorizer(/^ERR/, (match) => chalk.bgRed(match)),
createLogColorizer(/^DBG/, (match) => chalk.grey.bgBlack(match)),
createLogColorizer(/^WRN/, (match) => chalk.bgYellow(match)),
// timestamp
createLogColorizer(/\[\d+\.\d+\.\d+\]/, (match, inner) => `[${chalk.grey(inner)}]`),
// URL
createLogColorizer(/((\w{3,}\:\/\/)|([^\/\s\("':]+)?\/)([^\/\)\s"':]+\/?)+/g, (match) => {
return chalk.yellow(/\w+:\/\//.test(match) ? match : match.replace(cwd + "/", ""))
}),
// duration
createLogColorizer(/\s\d+(\.\d+)?(s|ms|m|h|d)(\s|$)/g, (match) => chalk.bold.cyan(match)),
// numbers
createLogColorizer(/\b\d+(\.\d+)?\b/g, (match, inner) => `${chalk.cyan(match)}`),
// strings
createLogColorizer(/"(.*?)"/g, (match, inner) => `"${chalk.blue(inner)}"`),
// tokens
createLogColorizer(/([\:\{\}",\(\)]|->|null|undefined|Infinity)/g, (match) => chalk.grey(match)),
// <<output - green (from audio again)
createLogColorizer(/<<(.*)/g, (match, word) => chalk.green(word)),
// >>input - magenta (from audio)
createLogColorizer(/>>(.*)/g, (match, word) => chalk.magenta(word)),
// **BIG EMPHASIS**
createLogColorizer(/\*\*(.*?)\*\*/, (match, word) => chalk.bgBlue(word)),
// *emphasis*
createLogColorizer(/\*(.*?)\*/g, (match, word) => chalk.bold(word)),
createLogColorizer(/___(.*?)___/g, (match, word) => chalk.underline(word)),
// ~de emphasis~
createLogColorizer(/~(.*?)~/g, (match, word) => chalk.grey(word)),
];
function colorize(input: string) {
let output = input;
for (let i = 0, n = highlighters.length; i < n; i++) output = highlighters[i](output);
return output;
}
function styledConsoleLog(...args: any[]) {
var argArray = [];
if (args.length) {
var startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi;
var endTagRe = /<\/span>/gi;
var reResultArray;
argArray.push(arguments[0].replace(startTagRe, '%c').replace(endTagRe, '%c'));
while (reResultArray = startTagRe.exec(arguments[0])) {
argArray.push(reResultArray[2]);
argArray.push('');
}
// pass through subsequent args since chrome dev tools does not (yet) support console.log styling of the following form: console.log('%cBlue!', 'color: blue;', '%cRed!', 'color: red;');
for (var j = 1; j < arguments.length; j++) {
argArray.push(arguments[j]);
}
}
console.log.apply(console, argArray);
}
// I'm against abbreviations, but it's happening here
// since all of these are the same length -- saves space in stdout, and makes
// logs easier to read.
const PREFIXES = {
[LogLevel.DEBUG]: "DBG ",
[LogLevel.INFO]: "INF ",
[LogLevel.WARNING]: "WRN ",
[LogLevel.ERROR]: "ERR ",
};
const defaultState = { level: LogLevel.ALL, prefix: "" };
export function* consoleLogSaga() {
while(true) {
const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState;
let { text, level }: LogAction = (yield take(LogActionTypes.LOG));
if (!(acceptedLevel & level)) continue;
const log = {
[LogLevel.DEBUG]: console.log.bind(console),
[LogLevel.LOG]: console.log.bind(console),
[LogLevel.INFO]: console.info.bind(console),
[LogLevel.WARNING]: console.warn.bind(console),
[LogLevel.ERROR]: console.error.bind(console)
}[level];
text = PREFIXES[level] + (prefix || "") + text;
text = colorize(text);
if (typeof window !== "undefined" && !window["$synthetic"]) {
return styledConsoleLog(new AnsiUp().ansi_to_html(text));
}
log(text);
}
}
|
<?php
namespace Payname\Security;
use Payname\Exception\ApiCryptoException;
class Crypto
{
/**
* The algorithm used for encryption.
*
* @var string
*/
private static $cipher = 'AES-128-CBC';
/**
* Encrypt the given value.
*
* @param string $value
* @param string $key
* @return string
*/
public static function encrypt($value, $key)
{
$iv = <API key>(self::getIvSize());
$value = openssl_encrypt(serialize($value), self::$cipher, $key, 0, $iv);
if ($value === false) {
throw new ApiCryptoException('Could not encrypt the data.');
}
$mac = self::hash($iv = base64_encode($iv), $value, $key);
return base64_encode(json_encode(compact('iv', 'value', 'mac')));
}
/**
* Decrypt the given value.
*
* @param string $payload
* @param string $key
* @return string
*/
public static function decrypt($value, $key)
{
$payload = self::getJsonPayload($value, $key);
$iv = base64_decode($payload['iv']);
$decrypted = openssl_decrypt($payload['value'], self::$cipher, $key, 0, $iv);
if ($decrypted === false) {
throw new ApiCryptoException('Could not decrypt the data.');
}
return unserialize($decrypted);
}
/**
* Get the JSON array from the given payload.
*
* @param string $payload
* @param string $key
* @return array
*/
private static function getJsonPayload($payload, $key)
{
$payload = json_decode(base64_decode($payload), true);
if (!$payload || (!is_array($payload) || !isset($payload['iv']) || !isset($payload['value']) || !isset($payload['mac']))) {
throw new ApiCryptoException('The payload is invalid.');
}
if (!self::validMac($payload, $key)) {
throw new ApiCryptoException('The MAC is invalid.');
}
return $payload;
}
/**
* Determine if the MAC for the given payload is valid.
*
* @param array $payload
* @param string $key
* @return bool
*/
private static function validMac(array $payload, $key)
{
$bytes = null;
if (function_exists('random_bytes')) {
$bytes = random_bytes(16);
} elseif (function_exists('<API key>')) {
$bytes = <API key>(16, $strong);
if ($bytes === false || $strong === false) {
throw new ApiCryptoException('Unable to generate random string.');
}
} else {
throw new ApiCryptoException('OpenSSL extension is required for PHP 5 users.');
}
$calcMac = hash_hmac('sha256', self::hash($payload['iv'], $payload['value'], $key), $bytes, true);
return hash_hmac('sha256', $payload['mac'], $bytes, true) === $calcMac;
}
/**
* Create a MAC for the given value.
*
* @param string $iv
* @param string $value
* @return string
*/
private static function hash($iv, $value, $key)
{
return hash_hmac('sha256', $iv.$value, $key);
}
/**
* Get the IV size for the cipher.
*
* @return int
*/
private static function getIvSize()
{
return 16;
}
}
|
# Wildcard string matcher
## Requirements
- PHP 5.4 or greater (recommended).
## Installation
1. [Download all libraries](https://github.com/pedzed/libs/archive/master.zip)
or [specifically download this one](https://raw.githubusercontent.com/pedzed/libs/master/src/pedzed/libs/<API key>.php).
2. Move the file(s) to your server.
3. Include the file(s). *It's recommended to autoload them.*
## Examples
php
$strList = [
'*',
'*.ipsum',
'lorem.ipsum.dolor',
'lorem.ipsum.sit.amet',
'lorem.*.amet',
'lorem.*'
];
$match = 'lorem.ipsum.sit.amet';
echo $match.'<br /><br />';
foreach($strList as $str){
echo 'String: '.$str.':<br />';
var_dump(<API key>::match($str, $match));
}
/* OUTPUT:
lorem.ipsum.sit.amet
String: *:
boolean true
String: *.ipsum:
boolean false
String: lorem.ipsum.dolor:
boolean false
String: lorem.ipsum.sit.amet:
boolean true
String: lorem.*.amet:
boolean true
String: lorem.*:
boolean true
*/
Case-sensitivity is supported. On default, it is disabled. To enable
case-sensitivity, pass a third parameter.
php
<API key>::match($str1, $str2, true);
|
'use strict';
// Test dependencies are required and exposed in common/bootstrap.js
require('../../common/bootstrap');
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
var codeContents = 'console.log("testing deploy");';
var reference = new Buffer(codeContents);
var lists = deployment.js.lists;
var listRuleLength = lists.includes.length + lists.ignores.length + lists.blacklist.length;
var sandbox = sinon.sandbox.create();
var FIXTURE_PATH = path.join(__dirname, '/../../../test/unit/fixtures');
exports['Deployment: JavaScript'] = {
setUp(done) {
this.deploy = sandbox.spy(Tessel.prototype, 'deploy');
this.appStop = sandbox.spy(commands.app, 'stop');
this.appStart = sandbox.spy(commands.app, 'start');
this.deleteFolder = sandbox.spy(commands, 'deleteFolder');
this.createFolder = sandbox.spy(commands, 'createFolder');
this.untarStdin = sandbox.spy(commands, 'untarStdin');
this.execute = sandbox.spy(commands.js, 'execute');
this.openStdinToFile = sandbox.spy(commands, 'openStdinToFile');
this.chmod = sandbox.spy(commands, 'chmod');
this.push = sandbox.spy(deploy, 'push');
this.createShellScript = sandbox.spy(deploy, 'createShellScript');
this.injectBinaryModules = sandbox.stub(deployment.js, 'injectBinaryModules').callsFake(() => Promise.resolve());
this.<API key> = sandbox.stub(deployment.js, '<API key>').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.resolve(reference));
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
this.end = sandbox.spy(this.tessel._rps.stdin, 'end');
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve('<SHA1-like>'));
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pWrite = sandbox.stub(Preferences, 'write').returns(Promise.resolve());
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
<API key>()
.then(done);
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
<API key>()
.then(done)
.catch(function(err) {
throw err;
});
},
bundling(test) {
test.expect(1);
this.tarBundle.restore();
<API key>().then(() => {
var tb = deployment.js.tarBundle({
target: DEPLOY_DIR_JS
});
tb.then(bundle => {
/*
$ t2 run app.js
INFO Looking for your Tessel...
INFO Connected to arnold over LAN
INFO Writing app.js to RAM on arnold (2.048 kB)...
INFO Deployed.
INFO Running app.js...
testing deploy
INFO Stopping script...
*/
test.equal(bundle.length, 2048);
test.done();
})
.catch(error => {
test.ok(false, error.toString());
test.done();
});
});
},
<API key>(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
<API key>(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
<API key>(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
<API key>(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
<API key>(test) {
// Array of processes we've started but haven't completed yet
var <API key> = [];
this.tessel._rps.on('control', (data) => {
// Push new commands into the queue
<API key>.push(data);
});
// Create the temporary folder with example code
<API key>()
.then(() => {
var closeAdvance = (event) => {
// If we get an event listener for the close event of a process
if (event === 'close') {
// Wait some time before actually closing it
setTimeout(() => {
// We should only have one process waiting for completion
test.equal(<API key>.length, 1);
// Pop that process off
<API key>.shift();
// Emit the close event to keep it going
this.tessel._rps.emit('close');
}, 200);
}
};
// When we get a listener that the Tessel process needs to close before advancing
this.tessel._rps.on('newListener', closeAdvance);
// Actually deploy the script
this.tessel.deploy({
entryPoint: path.relative(process.cwd(), DEPLOY_FILE_JS),
compress: true,
push: false,
single: false
})
// If it finishes, it was successful
.then(() => {
this.tessel._rps.removeListener('newListener', closeAdvance);
test.done();
})
// If not, there was an issue
.catch(function(err) {
test.equal(err, undefined, 'We hit a catch statement that we should not have.');
});
});
}
};
exports['deployment.js.compress with uglify.es.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.es, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('es', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
<API key>(test) {
test.expect(2);
const result = deployment.js.compress('es', '
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const <API key> = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('es', '
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
<API key>.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(23);
const optionsCompress = {
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
dead_code: true,
unsafe_math: true,
keep_infinity: true,
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('es', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(23);
const ourExplicitSettings = {
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
dead_code: true,
unsafe_math: true,
keep_infinity: true,
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const <API key> = Object.keys(ourExplicitSettings);
deployment.js.compress('es', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
<API key>.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
<API key>(test) {
test.expect(20);
var <API key> = {
booleans: false,
cascade: false,
conditionals: false,
comparisons: false,
evaluate: false,
hoist_funs: false,
hoist_vars: false,
if_return: false,
join_vars: false,
loops: false,
properties: false,
sequences: false,
unsafe: false,
dead_code: false,
unsafe_math: false,
keep_infinity: false,
keep_fargs: true,
keep_fnames: true,
warnings: true,
drop_console: true,
};
var <API key> = Object.keys(<API key>);
deployment.js.compress('es', 'var a = 1;', {
compress: <API key>
});
const optionsSeen = this.minify.lastCall.args[1].compress;
<API key>.forEach(key => {
test.equal(optionsSeen[key], <API key>[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('es', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('es', codeContents), codeContents);
test.done();
},
<API key>(test) {
test.expect(1);
deployment.js.compress('es', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
<API key>(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
test.equal(deployment.js.compress('es', 'return;'), 'return;');
test.done();
},
};
exports['deployment.js.compress with uglify.js.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.js, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('js', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
<API key>(test) {
test.expect(2);
const result = deployment.js.compress('js', '
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const <API key> = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('js', '
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
<API key>.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(15);
const optionsCompress = {
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('js', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(15);
const ourExplicitSettings = {
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const <API key> = Object.keys(ourExplicitSettings);
deployment.js.compress('js', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
<API key>.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
<API key>(test) {
test.expect(15);
var <API key> = {
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
var <API key> = Object.keys(<API key>);
deployment.js.compress('js', 'var a = 1;', {
compress: <API key>
});
const optionsSeen = this.minify.lastCall.args[1].compress;
<API key>.forEach(key => {
test.equal(optionsSeen[key], <API key>[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('js', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('js', codeContents), codeContents);
test.done();
},
<API key>(test) {
test.expect(1);
deployment.js.compress('js', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
<API key>(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
const result = deployment.js.compress('js', 'return;');
test.equal(result, 'return;');
test.done();
},
<API key>(test) {
test.expect(2);
this.minify.restore();
this.es = sandbox.spy(uglify.es, 'minify');
this.js = sandbox.spy(uglify.js, 'minify');
const code = tags.stripIndents `
var Class = function() {};
Class.prototype.method = function() {};
module.exports = Class;
`;
deployment.js.compress('es', code);
deployment.js.compress('js', code);
test.equal(this.es.callCount, 1);
test.equal(this.js.callCount, 1);
test.done();
},
};
exports['deployment.js.tarBundle'] = {
setUp(done) {
this.copySync = sandbox.spy(fs, 'copySync');
this.outputFileSync = sandbox.spy(fs, 'outputFileSync');
this.writeFileSync = sandbox.spy(fs, 'writeFileSync');
this.remove = sandbox.spy(fs, 'remove');
this.readdirSync = sandbox.spy(fs, 'readdirSync');
this.globSync = sandbox.spy(glob, 'sync');
this.collect = sandbox.spy(Project.prototype, 'collect');
this.exclude = sandbox.spy(Project.prototype, 'exclude');
this.mkdirSync = sandbox.spy(fsTemp, 'mkdirSync');
this.addIgnoreRules = sandbox.spy(Ignore.prototype, 'addIgnoreRules');
this.project = sandbox.spy(deployment.js, 'project');
this.compress = sandbox.spy(deployment.js, 'compress');
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
actionsGlobRules(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
test.deepEqual(
rules.map(path.normalize), [
// Found in "test/unit/fixtures/ignore/.tesselignore"
'a*.*',
'mock-foo.js',
// Found in "test/unit/fixtures/ignore/nested/.tesselignore"
'nested/b*.*',
'nested/file.js'
].map(path.normalize)
);
test.done();
},
actionsGlobFiles(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
const files = glob.files(target, rules);
test.deepEqual(files, ['mock-foo.js']);
test.done();
},
<API key>(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['**/.tesselignore']);
test.deepEqual(files, [
'.tesselignore',
'nested/.tesselignore'
]);
test.done();
},
<API key>(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['.tesselignore']);
test.deepEqual(files, ['.tesselignore']);
test.done();
},
<API key>(test) {
test.expect(2);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
sandbox.spy(path, 'relative');
/*
project
.tesselignore
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselignore
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
compress: true,
full: true,
}).then(() => {
test.equal(path.relative.firstCall.args[0], path.normalize('test/unit/fixtures/project'));
test.equal(path.relative.firstCall.args[1], path.normalize('test/unit/fixtures/project'));
test.done();
});
},
full(test) {
test.expect(8);
const target = 'test/unit/fixtures/project';
/*
project
.tesselignore
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselignore
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
// One call for .tesselinclude
// One call for the single rule found within
// Three calls for the deploy lists
// * 2 (We need all ignore rules ahead of time for ignoring binaries)
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.exclude.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'nested/another.js',
'node_modules/foo/index.js',
'package.json',
]);
test.done();
});
});
},
<API key>(test) {
test.expect(1);
// Need to stub function in _actual_ fs (but we use fs-extra)
const fs = require('fs');
sandbox.stub(fs, 'readFile').callsFake((file, callback) => {
callback('foo');
});
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'foo');
test.done();
});
},
slim(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
/*
project
.tesselignore
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselignore
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
// These things happen in the --slim path
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
test.equal(this.mkdirSync.callCount, 1);
test.equal(this.outputFileSync.callCount, 3);
// End
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 1);
test.deepEqual(this.exclude.lastCall.args[0], [
'mock-foo.js',
'test/unit/fixtures/project/mock-foo.js',
'other.js',
'test/unit/fixtures/project/other.js',
'node_modules/foo/package.json',
'test/unit/fixtures/project/node_modules/foo/package.json'
].map(path.normalize));
const minified = this.compress.lastCall.returnValue;
test.equal(this.compress.callCount, 2);
test.equal(minified.indexOf('!!mock-foo!!') === -1, true);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'node_modules/foo/index.js',
'package.json'
]);
test.done();
});
});
},
<API key>(test) {
test.expect(1);
const pipe = fstream.Reader.prototype.pipe;
// Need to stub function in _actual_ fs (but we use fs-extra)
this.readerPipe = sandbox.stub(fstream.Reader.prototype, 'pipe').callsFake(function() {
this.emit('error', new Error('foo'));
return pipe.apply(this, arguments);
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
<API key>(test) {
test.expect(1);
this.remove.restore();
this.remove = sandbox.stub(fs, 'remove').callsFake((temp, handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
this.remove.reset();
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
<API key>(test) {
test.expect(1);
this.compress.restore();
this.compress = sandbox.stub(deployment.js, 'compress').callsFake(() => {
throw new Error('foo');
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
<API key>(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake((handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
<API key>(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake(function() {
this.emit('error', new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
<API key>(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
<API key>(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: false,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// compression mechanism is never called when --compress=false
test.equal(this.compress.callCount, 0);
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
slimTesselInit(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/init';
/*
init
index.js
package.json
0 directories, 2 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(this.mkdirSync.callCount, 1);
const minified = this.compress.lastCall.returnValue;
test.equal(minified, 'const e=require("tessel"),{2:o,3:l}=e.led;o.on(),setInterval(()=>{o.toggle(),l.toggle()},100),console.log("I\'m blinking! (Press CTRL + C to stop)");');
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js', 'package.json']);
test.done();
});
});
},
slimSingle(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
slimSingleNested(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
fullSingle(test) {
test.expect(3);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
full: true,
}).then(bundle => {
test.equal(this.addIgnoreRules.callCount, 3);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
fullSingleNested(test) {
test.expect(2);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
full: true,
}).then(bundle => {
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
<API key>(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.tesselignore
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselignore
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
/*
All .tesselignore rules are negated by all .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
test.equal(this.project.callCount, 1);
// 3 js files are compressed
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Since the .tesselignore rules are ALL negated by .tesselinclude rules,
// the additional files are copied into the temporary bundle dir, and
// then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
<API key>(test) {
test.expect(8);
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.tesselignore
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselignore
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// The .tesselignore rules are ALL overridden by .tesselinclude rules
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'other.js',
'package.json'
]);
test.done();
});
});
},
<API key>(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
<API key>(test) {
test.expect(8);
/*
!! TAKE NOTE!!
This is actually the default behavior. That is to say:
these files would be included, whether they are listed
in the .tesselinclude file or not.
*/
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
<API key>(test) {
test.expect(8);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
test.equal(this.exclude.callCount, 1);
// Called once for the extra file matching
// the .tesselinclude rules
test.equal(this.copySync.callCount, 1);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
// The 4 files discovered and listed in the dependency graph
// See bundle extraction below.
test.equal(this.outputFileSync.callCount, 4);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, but the .tesselinclude rules
// include a negated pattern. The additional, non-negated files
// are copied into the temporary bundle dir, and then included
// in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js MUST NOT BE PRESENT
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
<API key>(test) {
test.expect(8);
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// This is where the negated rule is transferred.
test.deepEqual(this.addIgnoreRules.getCall(1).args[0], [
// Note that the "!" was stripped from the rule
'mock-foo.js',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js is NOT present
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimSingleInclude(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
.tesselinclude
index.js
mock-foo.js
nested
another.js
node_modules
foo
.tesselinclude
index.js
package.json
other.js
package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
single: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are .tesselinclude rules, but the single flag is present
so they don't matter. The only file sent must be the file specified.
*/
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Only the explicitly specified `index.js` will
// be included in the deployed code.
test.deepEqual(entries, [
'index.js',
]);
test.done();
});
});
},
<API key>(test) {
test.expect(4);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
index.js
mock-foo.js
nested
another.js
node_modules
foo
index.js
package.json
other.js
package.json
3 directories, 7 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 1);
test.equal(this.warn.firstCall.args[0], 'Some assets in this project were not deployed (see: t2 run --help)');
test.done();
});
},
<API key>(test) {
test.expect(3);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
index.js
mock-foo.js
nested
another.js
node_modules
foo
index.js
package.json
package.json
3 directories, 6 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 0);
// Ultimately, all assets were accounted for, even though
// no tesselinclude existed.
test.done();
});
},
<API key>(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.deepEqual(this.project.lastCall.args[0], {
entry: path.join(target, entryPoint),
dirname: path.normalize(target),
});
test.done();
});
},
<API key>(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/<API key>';
/*
<API key>
index.js
node_modules
tessel
index.js
package.json
package.json
2 directories, 4 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then((bundle) => {
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'package.json'
]);
test.done();
});
});
},
<API key>(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
const details = {
modulePath: ''
};
this.minimatch = sandbox.stub(deployment.js, 'minimatch').returns(true);
this.rules = sandbox.stub(glob, 'rules').callsFake(() => {
return [
'a', 'b',
];
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler(details);
});
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.equal(this.forEach.callCount, 2);
test.equal(this.minimatch.callCount, 3);
test.deepEqual(this.minimatch.getCall(0).args, ['', 'a', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(1).args, ['', 'b', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(2).args, ['', 'node_modulestessel*', {
matchBase: true,
dot: true
}]);
test.done();
});
},
};
var fixtures = {
project: path.join(FIXTURE_PATH, '/find-project'),
explicit: path.join(FIXTURE_PATH, '/<API key>')
};
exports['deploy.findProject'] = {
setUp(done) {
done();
},
tearDown(done) {
sandbox.restore();
done();
},
home(test) {
test.expect(1);
var fake = path.normalize('/fake/test/home/dir');
this.homedir = sandbox.stub(os, 'homedir').returns(fake);
this.lstatSync = sandbox.stub(fs, 'lstatSync').callsFake((file) => {
return {
isDirectory: () => {
// naive for testing.
return file.slice(-1) === '/';
}
};
});
this.realpathSync = sandbox.stub(fs, 'realpathSync').callsFake((arg) => {
// Ensure that "~" was transformed
test.equal(arg, path.normalize('/fake/test/home/dir/foo'));
test.done();
return '';
});
deploy.findProject({
lang: deployment.js,
entryPoint: '~/foo/',
compress: true,
});
},
byFile(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target,
compress: true,
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
byDirectory(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
<API key>(test) {
test.expect(1);
var target = 'test/unit/fixtures/<API key>/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.explicit,
program: path.join(fixtures.explicit, 'app.js'),
entryPoint: 'app.js'
});
test.done();
});
},
<API key>(test) {
test.expect(1);
var target = 'test/unit/fixtures/<API key>/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(() => {
test.ok(false, 'findProject should not find a valid project here');
test.done();
}).catch(error => {
test.ok(error.includes('ENOENT'));
test.done();
});
},
<API key>(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/test/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'test/index.js'),
entryPoint: path.normalize('test/index.js')
});
test.done();
});
},
noPackageJsonSingle(test) {
test.expect(1);
var pushdir = path.normalize('test/unit/fixtures/project-no-package.json/');
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
single: true,
slim: true,
lang: deployment.js,
};
deploy.findProject(opts).then(project => {
// Without the `single` flag, this would've continued upward
// until it found a directory with a package.json.
test.equal(project.pushdir, fs.realpathSync(pushdir));
test.done();
});
},
<API key>(test) {
test.expect(1);
// This is no package.json here
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
lang: deployment.js,
single: false,
};
this.endOfLookup = sandbox.stub(deploy, 'endOfLookup').returns(true);
deploy.findProject(opts).then(project => {
test.equal(project.pushdir, path.dirname(path.join(process.cwd(), entryPoint)));
test.done();
});
},
};
exports['deploy.sendBundle, error handling'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve('<SHA1-like>'));
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pathResolve = sandbox.stub(path, 'resolve');
this.failure = 'FAIL';
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
findProject(test) {
test.expect(1);
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
<API key>(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.<API key> = sandbox.stub(deployment.js, '<API key>').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
tarBundle(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.<API key> = sandbox.stub(deployment.js, '<API key>').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
};
exports['deployment.js.preBundle'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.info = sandbox.stub(log, 'info');
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
});
this.receive = sandbox.stub(this.tessel, 'receive').callsFake((rps, callback) => {
rps.emit('close');
callback();
});
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve('<SHA1-like>'));
this.<API key> = sandbox.stub(this.tessel, '<API key>').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.findProject = sandbox.stub(deploy, 'findProject').returns(Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.<API key> = sandbox.stub(deployment.js, '<API key>').returns(Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').returns(Promise.resolve(new Buffer([0x00])));
this.pathResolve = sandbox.stub(path, 'resolve');
this.preBundle = sandbox.spy(deployment.js, 'preBundle');
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
<API key>(test) {
test.expect(1);
const warning = tags.stripIndents `This project is missing an ".npmrc" file!
To prepare your project for deployment, use the command:
t2 init
Once complete, retry:`;
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(false));
deployment.js.preBundle({
target: '/',
}).catch(error => {
test.equal(error.startsWith(warning), true);
test.done();
});
},
<API key>(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
deploy.sendBundle(this.tessel, {
target: '/',
entryPoint: 'foo.js',
lang: deployment.js
}).then(() => {
test.equal(this.preBundle.lastCall.args[0].tessel, this.tessel);
test.done();
});
},
// // We need to find a way to provde the build version directly from the
// // Tessel 2 itself. This approach makes deployment slow with a network
// // connection, or impossible without one.
// <API key>(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.<API key>.callCount, 1);
// test.equal(this.<API key>.callCount, 1);
// var args = this.<API key>.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// <API key>(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.requestBuildList.callCount, 1);
// test.equal(this.<API key>.callCount, 1);
// var args = this.<API key>.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// <API key>(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.<API key>.callCount, 1);
// test.equal(this.<API key>.callCount, 1);
// var args = this.<API key>.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
};
exports['deployment.js.<API key>'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/<API key>');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/<API key>/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.readGypFileSync = sandbox.stub(deployment.js.<API key>, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing"}]}';
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => Promise.resolve());
done();
},
tearDown(done) {
sandbox.restore();
done();
},
bailOnSkipBinary(test) {
test.expect(2);
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 1);
// test/unit/fixtures/skip-binary/ has the corresponding
// dependencies for the following binary modules:
// debug-1.1.<API key>
// release-1.1.<API key>
// However, the latter has a "tessel.skipBinary = true" key in its package.json
test.equal(this.exists.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/debug-1.1.<API key>')), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
buildPathExpWindow(test) {
test.expect(1);
let descriptor = Object.<API key>(process, 'platform');
Object.defineProperty(process, 'platform', {
value: 'win32'
});
this.match = sandbox.spy(String.prototype, 'match');
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(
this.match.lastCall.args[0].toString(),
'/(?:build\\\\(Debug|Release|bindings)\\\\)/'
);
// Restore this descriptor
Object.defineProperty(process, 'platform', descriptor);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(3);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.relative.callCount, 1);
test.equal(this.relative.lastCall.args[0], target);
test.equal(this.relative.lastCall.args[1], target);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(1);
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').returns('');
this.cwd = sandbox.stub(process, 'cwd').returns('');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.ok(false, '<API key> should not resolve');
test.done();
}).catch(error => {
// The thing to be found:
// node_modules/release/package.json
// Will not be found, because it doesn't exist,
// but in this case, that's exactly what we want.
test.equal(error.toString(), `Error: Cannot find module '${path.normalize('node_modules/release/package.json')}'`);
test.done();
});
},
<API key>(test) {
test.expect(2);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules*.node', 'node_modulesbinding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(1);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.<API key>, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: null
};
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.readGypFileSync.lastCall.returnValue, '');
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
spawnPythonScript(test) {
test.expect(7);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.<API key>, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: [
null, new Buffer('{"targets": [{"target_name": "missing","sources": ["capture.c", "missing.cc"]}]}', 'utf8')
]
};
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules*.node', 'node_modulesbinding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.equal(this.spawnSync.callCount, 1);
test.equal(this.spawnSync.lastCall.args[0], 'python');
var python = this.spawnSync.lastCall.args[1][1];
test.equal(python.startsWith('import ast, json; print json.dumps(ast.literal_eval(open('), true);
test.equal(python.endsWith(').read()));'), true);
test.equal(python.includes('missing'), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
failsWithMessage(test) {
test.expect(1);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.stub(deployment.js.<API key>, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing",}]}';
// That's intentional.
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
test.equal(binaryModulesUsed.get('missing@1.1.1').resolved, false);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
existsInLocalCache(test) {
test.expect(2);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(1);
this.readGypFileSync.restore();
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 2);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(5);
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
// To avoid making an actual network request,
// make the program think these things are already
// cached. The test to pass is that it calls fs.existsSync
// with the correct things from the project directory (this.target)
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 4);
// test/unit/fixtures/<API key>/ has the corresponding
// dependencies for the following binary modules:
var cachedBinaryPaths = [
'.tessel/binaries/debug-1.1.<API key>',
'.tessel/binaries/linked-1.1.<API key>',
'.tessel/binaries/release-1.1.<API key>',
'.tessel/binaries/missing-1.1.<API key>',
];
cachedBinaryPaths.forEach((cbp, callIndex) => {
test.equal(this.exists.getCall(callIndex).args[0].endsWith(path.normalize(cbp)), true);
});
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
requestsRemote(test) {
test.expect(12);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.<API key>')), true);
test.equal(this.request.callCount, 1);
var requestArgs = this.request.lastCall.args[0];
test.equal(requestArgs.url, 'http://packages.tessel.io/npm/release-1.1.<API key>.tgz');
test.equal(requestArgs.gzip, true);
test.equal(this.pipe.callCount, 2);
test.equal(this.createGunzip.callCount, 1);
test.equal(this.Extract.callCount, 1);
test.equal(this.transform.stubsUsed.length, 2);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(9);
this.removeSync = sandbox.stub(fs, 'removeSync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
// Hook into the ifReachable call to trigger an error at the gunzip stream
this.ifReachable.restore();
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => {
this.transform.emit('error', {
code: 'Z_DATA_ERROR',
});
return Promise.resolve();
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.<API key>')), true);
// The result of gunzip emitting an error:
test.equal(this.removeSync.callCount, 1);
test.equal(this.removeSync.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.<API key>')), true);
test.equal(this.request.callCount, 1);
test.equal(this.createGunzip.callCount, 1);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
};
exports['deployment.js.injectBinaryModules'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/<API key>');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/<API key>/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.globRoot = path.join(FIXTURE_PATH, '/<API key>/');
this.copySync = sandbox.stub(fs, 'copySync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
done();
},
tearDown(done) {
sandbox.restore();
done();
},
copies(test) {
test.expect(17);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
test.equal(this.copySync.callCount, 8);
var args = this.copySync.args;
/*
This is an abbreviated view of what should be copied by this operation:
[
[
'debug-1.1.<API key>/Debug/debug.node',
'debug/build/Debug/debug.node'
],
[
'debug/package.json',
'debug/package.json'
],
[
'linked-1.1.<API key>/bindings/linked.node',
'linked/build/bindings/linked.node'
],
[
'linked/package.json',
'linked/package.json'
],
[
'missing-1.1.<API key>/Release/missing.node',
'missing/build/Release/missing.node'
],
[
'missing/package.json',
'missing/package.json'
],
[
'release-1.1.<API key>/Release/release.node',
'release/build/Release/release.node'
],
[
'release/package.json',
'release/package.json'
]
]
*/
test.equal(
args[0][0].endsWith(path.normalize('debug-1.1.<API key>/Debug/debug.node')),
true
);
test.equal(
args[0][1].endsWith(path.normalize('debug/build/Debug/debug.node')),
true
);
test.equal(
args[1][0].endsWith(path.normalize('debug/package.json')),
true
);
test.equal(
args[1][1].endsWith(path.normalize('debug/package.json')),
true
);
test.equal(
args[2][0].endsWith(path.normalize('linked-1.1.<API key>/bindings/linked.node')),
true
);
test.equal(
args[2][1].endsWith(path.normalize('linked/build/bindings/linked.node')),
true
);
test.equal(
args[3][0].endsWith(path.normalize('linked/package.json')),
true
);
test.equal(
args[3][1].endsWith(path.normalize('linked/package.json')),
true
);
test.equal(
args[4][0].endsWith(path.normalize('missing-1.1.<API key>/Release/missing.node')),
true
);
test.equal(
args[4][1].endsWith(path.normalize('missing/build/Release/missing.node')),
true
);
test.equal(
args[5][0].endsWith(path.normalize('missing/package.json')),
true
);
test.equal(
args[5][1].endsWith(path.normalize('missing/package.json')),
true
);
test.equal(
args[6][0].endsWith(path.normalize('release-1.1.<API key>/Release/release.node')),
true
);
test.equal(
args[6][1].endsWith(path.normalize('release/build/Release/release.node')),
true
);
test.equal(
args[7][0].endsWith(path.normalize('release/package.json')),
true
);
test.equal(
args[7][1].endsWith(path.normalize('release/package.json')),
true
);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
<API key>(test) {
test.expect(1);
this.target = path.normalize('test/unit/fixtures/<API key>');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/<API key>/');
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
<API key>(test) {
test.expect(6);
this.target = path.normalize('test/unit/fixtures/<API key>');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/<API key>/');
});
// We WANT to glob the actual target directory
this.globSync.restore();
this.mapHas = sandbox.spy(Map.prototype, 'has');
this.mapGet = sandbox.spy(Map.prototype, 'get');
this.mapSet = sandbox.spy(Map.prototype, 'set');
this.arrayMap = sandbox.spy(Array.prototype, 'map');
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
// Ensure that 2 modules with the same name and version were found!
for (var i = 0; i < this.arrayMap.callCount; i++) {
let call = this.arrayMap.getCall(i);
if (call.thisValue.<API key>) {
test.equal(call.thisValue.length, 2);
}
}
test.equal(this.mapHas.callCount, 2);
test.equal(this.mapHas.getCall(0).args[0], 'release@1.1.1');
test.equal(this.mapHas.getCall(1).args[0], 'release@1.1.1');
// Ensure that only one of the two were included in the
// final list of binary modules to bundle
test.equal(binaryModulesUsed.size, 1);
// Ensure that the swap has occurred
test.equal(
path.normalize(binaryModulesUsed.get('release@1.1.1').globPath),
path.normalize('node_modules/release/build/Release/release.node')
);
test.done();
});
},
<API key>(test) {
test.expect(1);
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
binaryModulesUsed.clear();
// We need something to look at...
sandbox.stub(binaryModulesUsed, 'forEach');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync()).then(() => {
test.equal(binaryModulesUsed.forEach.callCount, 1);
test.done();
});
});
},
<API key>(test) {
test.expect(1);
// This would normally result in 8 calls to this.copySync
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.<API key>({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {
single: true
}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
<API key>(test) {
test.expect(2);
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'serialport.node',
buildPath: path.normalize('/build/Release/<API key>/'),
buildType: 'Release',
globPath: path.normalize('node_modules/serialport/build/Release/<API key>/serialport.node'),
ignored: false,
name: 'serialport',
modulePath: path.normalize('node_modules/serialport'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/serialport-2.0.<API key>')
});
});
var find = lists.<API key>['*'][0].find;
lists.<API key>['*'][0].find = '<API key>';
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// If the replacement operation did not work, these would still be
// "<API key>"
test.equal(this.copySync.firstCall.args[0].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
test.equal(this.copySync.firstCall.args[1].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
// Restore the path translation...
lists.<API key>['*'][0].find = find;
test.done();
});
},
<API key>(test) {
test.expect(3);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
// Fail the first try/catch on THEIR PATH
if (this.copySync.callCount === 1) {
throw new Error('ENOENT: no such file or directory');
}
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'node_sqlite3.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/sqlite3-3.1.4-Release/<API key>/node_sqlite3.node'
buildPath: path.normalize('/lib/binding/<API key>/'),
buildType: 'Release',
globPath: path.normalize('node_modules/sqlite3/lib/binding/<API key>/node_sqlite3.node'),
ignored: false,
name: 'sqlite3',
modulePath: path.normalize('node_modules/sqlite3'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/sqlite3-3.1.4-Release'),
});
});
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
// 1 call: copy the package.json
test.equal(fs.copySync.callCount, 3);
// THEIR PATH
test.equal(this.copySync.getCall(0).args[0].endsWith(path.normalize('<API key>/node_sqlite3.node')), true);
// OUR PATH
test.equal(this.copySync.getCall(1).args[0].endsWith(path.normalize('Release/node_sqlite3.node')), true);
test.done();
});
},
<API key>(test) {
test.expect(4);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
throw new Error('E_THIS_IS_NOT_REAL');
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'not-a-thing.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/not-a-thing-3.1.4-Release/<API key>/not-a-thing.node'
buildPath: path.normalize('/lib/binding/<API key>/'),
buildType: 'Release',
globPath: path.normalize('node_modules/not-a-thing/lib/binding/<API key>/not-a-thing.node'),
ignored: false,
name: 'not-a-thing',
modulePath: path.normalize('node_modules/not-a-thing'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/not-a-thing-3.1.4-Release'),
});
});
this.error = sandbox.stub(log, 'error');
this.<API key> = sandbox.stub(deployment.js, '<API key>');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
test.equal(this.copySync.callCount, 2);
// Result of failing both attempts to copy
test.equal(this.<API key>.callCount, 1);
test.equal(this.error.callCount, 1);
test.equal(String(this.error.lastCall.args[0]).includes('E_THIS_IS_NOT_REAL'), true);
test.done();
});
}
};
exports['deploy.createShellScript'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
<API key>(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: [],
subargs: [],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
},
<API key>(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
}
};
// Test dependencies are required and exposed in common/bootstrap.js
exports['deployment.js.lists'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
checkIncludes(test) {
test.expect(1);
var includes = [
'node_modulesaws-sdk/apis/*.json',
'node_modulesmime/types/*.types',
'node_modulesnegotiator*.js',
'node_modulessocket.io-client/socket.io.js',
'node_modulessocket.io-client/dist/socket.io.min.js',
'node_modulessocket.io-client/dist/socket.io.js',
];
test.deepEqual(lists.includes, includes);
test.done();
},
checkIgnores(test) {
test.expect(1);
var ignores = [
'node_modulestessel*',
];
test.deepEqual(lists.ignores, ignores);
test.done();
},
checkCompression(test) {
test.expect(1);
/*
This test just ensures that no one accidentally
messes up the contents of the deploy-lists file,
specifically for the compression options field
*/
var compressionOptions = {
extend: {
compress: {
keep_fnames: true
},
mangle: {}
},
};
test.deepEqual(lists.compressionOptions, compressionOptions);
test.done();
}
};
exports['deployment.js.postRun'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.<API key> = {
pipe: process.stdin.pipe,
setRawMode: process.stdin.setRawMode,
};
this.stdinPipe = sandbox.spy();
this.setRawMode = sandbox.spy();
process.stdin.pipe = this.stdinPipe;
process.stdin.setRawMode = this.setRawMode;
this.notRealTessel = {
connection: {
connectionType: 'LAN',
},
};
done();
},
tearDown(done) {
process.stdin.pipe = this.<API key>.pipe;
process.stdin.setRawMode = this.<API key>.setRawMode;
sandbox.restore();
done();
},
postRunLAN(test) {
test.expect(2);
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 1);
test.equal(process.stdin.setRawMode.callCount, 1);
test.done();
});
},
postRunUSB(test) {
test.expect(2);
this.notRealTessel.connection.connectionType = 'USB';
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 0);
test.equal(process.stdin.setRawMode.callCount, 0);
test.done();
});
},
};
exports['deployment.js.<API key>'] = {
setUp(done) {
this.warn = sandbox.stub(log, 'warn');
this.details = {
binName: 'compiled-binary.node',
buildPath: path.normalize('/build/Release/<API key>/'),
buildType: 'Release',
globPath: path.normalize('node_modules/compiled-binary/build/Release/<API key>/compiled-binary.node'),
ignored: false,
name: 'compiled-binary',
modulePath: path.normalize('node_modules/compiled-binary'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/compiled-binary-2.0.<API key>')
};
done();
},
tearDown(done) {
sandbox.restore();
done();
},
<API key>(test) {
test.expect(1);
deployment.js.<API key>(this.details);
test.equal(this.warn.callCount, 1);
test.done();
},
<API key>(test) {
test.expect(1);
deployment.js.<API key>(this.details);
var output = this.warn.lastCall.args[0];
test.equal(output.includes('Pre-compiled module is missing: compiled-binary@2.0.6'), true);
test.done();
},
};
exports['deployment.js.minimatch'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
<API key>(test) {
test.expect(1);
const result = deployment.js.minimatch('', '', {});
test.equal(result, true);
test.done();
},
};
|
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, titles, prog='neato', size=None,
type_format=None, filename=None):
"""
Display the results using matplotlib.
"""
if not size:
size = _get_size(len(graphs))
fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10))
fig.set_facecolor('white')
x_val = 0
y_val = 0
index = 0
if size[0] == 1:
axarr = np.array(axarr).reshape((1, size[1]))
for candidate in graphs:
# axarr[x_val, y_val].axis('off')
axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter())
axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter())
axarr[x_val, y_val].xaxis.set_ticks([])
axarr[x_val, y_val].yaxis.set_ticks([])
axarr[x_val, y_val].set_title(titles[index])
# axarr[x_val, y_val].set_axis_bgcolor("white")
if not type_format:
type_format = TYPE_FORMAT
_plot_subplot(candidate, request.nodes(), prog, type_format,
axarr[x_val, y_val])
y_val += 1
if y_val > size[1] - 1:
y_val = 0
x_val += 1
index += 1
fig.tight_layout()
if filename is not None:
plt.savefig(filename)
else:
plt.show()
plt.close()
def _plot_subplot(graph, new_nodes, prog, type_format, axes):
"""
Plot a single candidate graph.
"""
pos = nx.nx_agraph.graphviz_layout(graph, prog=prog)
# draw the nodes
for node, values in graph.nodes(data=True):
shape = 'o'
if values[stitcher.TYPE_ATTR] in type_format:
shape = type_format[values[stitcher.TYPE_ATTR]]
color = 'g'
alpha = 0.8
if node in new_nodes:
color = 'b'
alpha = 0.2
elif 'rank' in values and values['rank'] > 7:
color = 'r'
elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3:
color = 'y'
nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color,
node_shape=shape, alpha=alpha, ax=axes)
# draw the edges
dotted_line = []
normal_line = []
for src, trg in graph.edges():
if src in new_nodes and trg not in new_nodes:
dotted_line.append((src, trg))
else:
normal_line.append((src, trg))
nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted',
ax=axes)
nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes)
# draw labels
nx.<API key>(graph, pos, ax=axes)
def show_3d(graphs, request, titles, prog='neato', filename=None):
"""
Show the candidates in 3d - the request elevated above the container.
"""
fig = plt.figure(figsize=(18, 10))
fig.set_facecolor('white')
i = 0
size = _get_size(len(graphs))
for graph in graphs:
axes = fig.add_subplot(size[0], size[1], i+1,
projection=Axes3D.name)
axes.set_title(titles[i])
axes._axis3don = False
_plot_3d_subplot(graph, request, prog, axes)
i += 1
fig.tight_layout()
if filename is not None:
plt.savefig(filename)
else:
plt.show()
plt.close()
def _plot_3d_subplot(graph, request, prog, axes):
"""
Plot a single candidate graph in 3d.
"""
cache = {}
tmp = graph.copy()
for node in request.nodes():
tmp.remove_node(node)
pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog)
# the container
for item in tmp.nodes():
axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None",
marker="o", color='gray')
axes.text(pos[item][0], pos[item][1], 0, item)
for src, trg in tmp.edges():
axes.plot([pos[src][0], pos[trg][0]],
[pos[src][1], pos[trg][1]],
[0, 0], color='gray')
# the new nodes
for item in graph.nodes():
if item in request.nodes():
for nghb in graph.neighbors(item):
if nghb in tmp.nodes():
x_val = pos[nghb][0]
y_val = pos[nghb][1]
if (x_val, y_val) in list(cache.values()):
x_val = pos[nghb][0] + random.randint(10, SPACE)
y_val = pos[nghb][0] + random.randint(10, SPACE)
cache[item] = (x_val, y_val)
# edge
axes.plot([x_val, pos[nghb][0]],
[y_val, pos[nghb][1]],
[SPACE, 0], color='blue')
axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o",
color='blue')
axes.text(x_val, y_val, SPACE, item)
for src, trg in request.edges():
if trg in cache and src in cache:
axes.plot([cache[src][0], cache[trg][0]],
[cache[src][1], cache[trg][1]],
[SPACE, SPACE], color='blue')
def _get_size(n_items):
"""
Calculate the size of the subplot layouts based on number of items.
"""
n_cols = math.ceil(math.sqrt(n_items))
n_rows = math.floor(math.sqrt(n_items))
if n_cols * n_rows < n_items:
n_cols += 1
return int(n_rows), int(n_cols)
|
package de.verygame.surface.screen.base;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.Map;
/**
* @author Rico Schrage
*
* Context which can contain several subscreens.
*/
public class SubScreenContext implements ScreenContext {
/** List of subScreen's plus visibility flag */
protected final ScreenSwitch screenSwitch;
/** viewport of the screen (manages the glViewport) */
protected final Viewport viewport;
/** True if a subScreen is visible */
protected boolean showSubScreen = false;
/**
* Constructs a context with the given viewport.
*
* @param viewport viewport viewport of the screen
*/
public SubScreenContext(Viewport viewport) {
super();
this.viewport = viewport;
this.screenSwitch = new ScreenSwitch();
}
/**
* Sets the dependency map of the screen switch.
*
* @param dependencies map of dependencies
*/
public void setDependencies(Map<String, Object> dependencies) {
screenSwitch.setDependencyMap(dependencies);
}
/**
* Sets the batch of the context.
*
* @param polygonSpriteBatch batch
*/
public void setBatch(PolygonSpriteBatch polygonSpriteBatch) {
screenSwitch.setBatch(polygonSpriteBatch);
}
/**
* Sets the inputHandler of the context.
*
* @param inputHandler inputHandler
*/
public void setInputHandler(InputMultiplexer inputHandler) {
screenSwitch.setInputHandler(inputHandler);
}
public InputMultiplexer getInputHandler() {
return screenSwitch.getInputHandler();
}
public void onActivate(ScreenId screenKey) {
if (screenSwitch.getActiveScreen() != null) {
screenSwitch.getActiveScreen().onActivate(screenKey);
}
}
public float onDeactivate(ScreenId screenKey) {
if (screenSwitch.getActiveScreen() != null) {
return screenSwitch.getActiveScreen().onDeactivate(screenKey);
}
return 0;
}
/**
* Applies the viewport of the context. Calls {@link Viewport#apply(boolean)}.
*/
public void applyViewport() {
viewport.apply(true);
}
/**
* Updates the viewport of the context. Calls {@link Viewport#update(int, int, boolean)}.
*
* @param width width of the frame
* @param height height of the frame
*/
public void updateViewport(int width, int height) {
viewport.update(width, height, true);
}
public void update() {
screenSwitch.updateSwitch();
screenSwitch.updateScreen();
}
public void renderScreen() {
if (showSubScreen) {
screenSwitch.renderScreen();
}
}
public void resizeSubScreen(int width, int height) {
screenSwitch.resize(width, height);
}
public void pauseSubScreen() {
screenSwitch.pause();
}
public void resumeSubScreen() {
screenSwitch.resume();
}
public void dispose() {
screenSwitch.dispose();
}
@Override
public Viewport getViewport() {
return viewport;
}
@Override
public PolygonSpriteBatch getBatch() {
return screenSwitch.getBatch();
}
@Override
public void addSubScreen(SubScreenId id, SubScreen subScreen) {
if (screenSwitch.getBatch() == null) {
throw new <API key>("Parent screen have to be attached to a screen switch!");
}
this.screenSwitch.addScreen(id, subScreen);
}
@Override
public SubScreen getActiveSubScreen() {
return (SubScreen) screenSwitch.getActiveScreen();
}
@Override
public void showScreen(SubScreenId id) {
showSubScreen = true;
screenSwitch.setActive(id);
}
@Override
public void initialize(SubScreenId id) {
showSubScreen = true;
screenSwitch.setScreenSimple(id);
}
@Override
public void hideScreen() {
showSubScreen = false;
}
}
|
package x7c1.linen.scene.updater
import android.app.Service
import x7c1.linen.database.control.DatabaseHelper
import x7c1.linen.glue.service.ServiceControl
import x7c1.linen.repository.date.Date
import x7c1.linen.repository.dummy.DummyFactory
import x7c1.linen.repository.preset.PresetFactory
import x7c1.wheat.macros.logger.Log
import x7c1.wheat.modern.patch.TaskAsync.async
class UpdaterMethods(
service: Service with ServiceControl,
helper: DatabaseHelper,
startId: Int){
def createDummies(max: Int): Unit = async {
Log info "[init]"
val notifier = new <API key>(service, max, Date.current(), startId)
DummyFactory.createDummies0(service)(max){ n =>
notifier.notifyProgress(n)
}
notifier.notifyDone()
service stopSelf startId
}
def createPresetJp(): Unit = async {
Log info "[init]"
new PresetFactory(helper).<API key>()
}
def createDummySources(channelIds: Seq[Long]) = async {
Log info s"$channelIds"
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Dec 03 20:33:24 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)</title>
<meta name="date" content="2014-12-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 title="Package" class="title">Package net.sourceforge.pmd.lang.xsl.rule.xpath</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../net/sourceforge/pmd/lang/xsl/rule/xpath/XPathRulesTest.html" title="class in net.sourceforge.pmd.lang.xsl.rule.xpath">XPathRulesTest</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
import test from 'ava';
import escapeStringRegexp from './index.js';
test('main', t => {
t.is(
escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'),
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]'
);
});
test('escapes `-` in a way compatible with PCRE', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\x2d bar'
);
});
test('escapes `-` in a way compatible with the Unicode flag', t => {
t.regex(
'-',
new RegExp(escapeStringRegexp('-'), 'u')
);
});
|
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon(s) in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/<API key>.css" rel="stylesheet">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/myJqueryTimeline.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]
<!-- Add your site or application content here -->
<div class="container" style="padding-top: 30px;">
<div class="row-fluid">
<div id="mike" class="span12">
Timeline
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div id="myTimeline"></div>
</div>
<div class="teste">
</div>
</div>
</div>
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>-->
<script src="js/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!--<script src="js/classT.js"></script>-->
<script src="js/myJquery.Timeline.js"></script>
<script src="js/jquery.hoverIntent.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<!
<script>
(function(b,o,i,l,e,r){b.<API key>=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.<API key>(i)[0];
e.src='
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
</script>
</body>
</html>
|
require File.dirname(__FILE__) + '/../lib/ruby_js'
require 'test/unit'
require 'active_support/test_case'
RubyJS::Translator.load_paths << File.join(File.dirname(__FILE__), "mock")
RubyJS::Translator.load
|
const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, { tableName: 'pokemons' })
Pokemon.getByIdWithLock = function (pokemonId, transaction) {
return Pokemon.findOne({
where: {
id: pokemonId
},
lock: {
level: transaction.LOCK.UPDATE
}
})
}
Pokemon.getByName = function (name) {
return Pokemon.findOne({
where: {
name
}
}).then(checkExists(name))
}
Pokemon.prototype.decreaseStock = function (quantity) {
if (this.stock < quantity) {
return Promise.reject(new InventoryError(this.name, this.stock))
}
this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
}
|
// File auto generated by STUHashTool
using static STULib.Types.Generic.Common;
namespace STULib.Types.Dump {
[STU(0x6250465B)]
public class STU_6250465B : STUInstance {
[STUField(0x6674CA34)]
public string m_6674CA34;
[STUField(0xDC05EA3B)]
public ulong m_DC05EA3B;
[STUField(0x781349E1)]
public byte m_781349E1;
}
}
|
import hbs from '<API key>';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('advanced-form/integer', {
integration: true
});
test('Render component with attributes', function(assert) {
this.render(
hbs`{{advanced-form/integer min=10 max=20 value=5}}`
);
var $componentInput = this.$('.integer input');
assert.equal($componentInput.val(), '10');
});
|
class DeluxePublisher::Settings < ActiveRecord::Base
set_table_name '<API key>'
end
|
package com.azure.core.http.policy;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.logging.LogLevel;
import reactor.core.publisher.Mono;
/**
* Manages logging HTTP requests in {@link HttpLoggingPolicy}.
*/
@FunctionalInterface
public interface HttpRequestLogger {
/**
* Gets the {@link LogLevel} used to log the HTTP request.
* <p>
* By default this will return {@link LogLevel#INFORMATIONAL}.
*
* @param loggingOptions The information available during request logging.
* @return The {@link LogLevel} used to log the HTTP request.
*/
default LogLevel getLogLevel(<API key> loggingOptions) {
return LogLevel.INFORMATIONAL;
}
/**
* Logs the HTTP request.
* <p>
* To get the {@link LogLevel} used to log the HTTP request use {@link #getLogLevel(<API key>)}.
*
* @param logger The {@link ClientLogger} used to log the HTTP request.
* @param loggingOptions The information available during request logging.
* @return A reactive response that indicates that the HTTP request has been logged.
*/
Mono<Void> logRequest(ClientLogger logger, <API key> loggingOptions);
}
|
import React from 'react'
import { Hero } from '../../components'
const HeroContainer = () => (
<Hero />
)
export default HeroContainer
|
# -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import <API key>
except ImportError:
pass
from simple_help.models import PageHelp
from simple_help.forms import PageHelpAdminForm
from simple_help.utils import modeltranslation
try:
from simple_help.translation import <API key>
except ImportError:
pass
__all__ = [
"PageHelpAdmin",
]
class PageHelpAdmin(<API key> if modeltranslation() else admin.ModelAdmin):
"""
Customize PageHelp model for admin area.
"""
list_display = ["page", "title", ]
search_fields = ["title", ]
list_filter = ["page", ]
form = PageHelpAdminForm
if modeltranslation():
# registering translation options
translator.register(PageHelp, <API key>)
# registering admin custom classes
admin.site.register(PageHelp, PageHelpAdmin)
|
using UnityEngine;
using System.Collections;
public class MuteButton : MonoBehaviour {
public Sprite MuteSprite;
public Sprite PlaySprite;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
// Transform of the camera to shake. Grabs the gameObject's transform
// if null.
public Transform camTransform;
// How long the object should shake for.
public float shakeDuration = 0f;
// Amplitude of the shake. A larger value shakes the camera harder.
public float shakeAmount = 0.7f;
public float decreaseFactor = 1.0f;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
{
if (shakeDuration > 0)
{
camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
shakeDuration -= Time.deltaTime * decreaseFactor;
}
else
{
shakeDuration = 0f;
camTransform.localPosition = originalPos;
}
}
}
|
1.2.1
[Full Changelog](https://github.com/frdmn/alfred-imgur/compare/1.2.0...1.2.1)
* Bring back hotkey functionality
* Copy URL to uploaded file into clipboard
1.2.0
[Full Changelog](https://github.com/frdmn/alfred-imgur/compare/1ca0ed7...1.2.0)
* Complete rewrite in NodeJS and with [Alfy](https://github.com/sindresorhus/alfy)
1.1.0
[Full Changelog](https://github.com/frdmn/alfred-imgur/compare/2f3251f...1ca0ed7)
* Initial release
|
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;
namespace MyWebApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new <API key>()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.<API key>();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// 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(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.<API key>();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
# -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<width>', type=int,
help='desired width of image in pixels')
parser.add_argument('-H', '--height', metavar='<height>', type=int,
help='desired height of image in pixels')
parser.add_argument('-f', '--force', action='store_true',
help='whether to scale up for smaller images')
parser.add_argument('-d', '--display', action='store_true', default=False,
help='display the new image (don\'t write to file)')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write output to <file> instead of stdout.')
def main():
parsed_args = parser.parse_args()
image = Image.open(parsed_args.image)
size = (parsed_args.width, parsed_args.height)
new_image = crop_resize(image, size, parsed_args.force)
if parsed_args.display:
new_image.show()
elif parsed_args.output:
new_image.save(parsed_args.output)
else:
f = BytesIO()
new_image.save(f, image.format)
try:
stdout = sys.stdout.buffer
except AttributeError:
stdout = sys.stdout
stdout.write(f.getvalue())
|
'use strict';
let sounds = new Map();
let playSound = path => {
let sound = sounds.get(path);
if (sound) {
sound.play();
} else {
sound = new Audio(path);
sound.play();
}
};
export default playSound;
|
using System;
using System.Windows.Input;
namespace RFiDGear.ViewModel
{
<summary>
Description of RelayCommand.
</summary>
public class RelayCommand : ICommand
{
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private Action methodToExecute;
private Func<bool> canExecuteEvaluator;
public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
{
this.methodToExecute = methodToExecute;
this.canExecuteEvaluator = canExecuteEvaluator;
}
public RelayCommand(Action methodToExecute)
: this(methodToExecute, null)
{
}
public bool CanExecute(object parameter)
{
if (this.canExecuteEvaluator == null)
{
return true;
}
else
{
bool result = this.canExecuteEvaluator.Invoke();
return result;
}
}
public void Execute(object parameter)
{
this.methodToExecute.Invoke();
}
}
}
|
html { background-image: url('../../img/embed/will_encode.jpeg'); }
body { background-image: url('../../img/embed/not_encode.jpeg'); }
div { background-image: url('../../img/not_encode.png'); }
|
{% extends 'layouts/default.html' %}
{% block content %}
That site was not found!
{% endblock %}
|
// Generated automatically from com.google.common.collect.SortedSetMultimap for testing purposes
package com.google.common.collect;
import com.google.common.collect.SetMultimap;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
public interface SortedSetMultimap<K, V> extends SetMultimap<K, V>
{
Comparator<? super V> valueComparator();
Map<K, Collection<V>> asMap();
SortedSet<V> get(K p0);
SortedSet<V> removeAll(Object p0);
SortedSet<V> replaceValues(K p0, Iterable<? extends V> p1);
}
|
package com.etop.service;
import com.etop.dao.UserDAO;
import com.etop.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("UserService")
public class UserService implements Serializable {
@Autowired
private UserDAO userDAO;
/**
*
*
* @param username
* @return
*/
public User findByName(String username) {
Map<String, Object> params = new HashMap<>();
params.put("name", username);
return userDAO.findUniqueResult("from User u where u.username = :name", params);
}
public List<User> getAllUser() {
return userDAO.find("from User u");
}
}
|
from __future__ import print_function
import os
import sys
import subprocess
import pkg_resources
try:
import pkg_resources
_has_pkg_resources = True
except:
_has_pkg_resources = False
try:
import svn.local
_has_svn_local = True
except:
_has_svn_local = False
def test_helper():
return "test helper text"
def dict_to_str(d):
"""
Given a dictionary d, return a string with
each entry in the form 'key: value' and entries
separated by newlines.
"""
vals = []
for k in d.keys():
vals.append('{}: {}'.format(k, d[k]))
v = '\n'.join(vals)
return v
def module_version(module, label=None):
"""
Helper function for getting the module ("module") in the current
namespace and their versions.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
By default the key is '[module] version'.
"""
if not _has_pkg_resources:
return {}
version = pkg_resources.get_distribution(module).version
if label:
k = '{}'.format(label)
else:
k = '{} version'.format(module)
return {k: '{}'.format(version)}
def file_contents(filename, label=None):
"""
Helper function for getting the contents of a file,
provided the filename.
Returns a dictionary keyed (by default) with the filename
where the value is a string containing the contents of the file.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
"""
if not os.path.isfile(filename):
print('ERROR: {} NOT FOUND.'.format(filename))
return {}
else:
fin = open(filename, 'r')
contents = ''
for l in fin:
contents += l
if label:
d = {'{}'.format(label): contents}
else:
d = {filename: contents}
return d
def svn_information(svndir=None, label=None):
"""
Helper function for obtaining the SVN repository
information for the current directory (default)
or the directory supplied in the svndir argument.
Returns a dictionary keyed (by default) as 'SVN INFO'
where the value is a string containing essentially what
is returned by 'svn info'.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
"""
if not _has_svn_local:
print('SVN information unavailable.')
print('You do not have the "svn" package installed.')
print('Install "svn" from pip using "pip install svn"')
return {}
if svndir:
repo = svn.local.LocalClient(svndir)
else:
repo = svn.local.LocalClient(os.getcwd())
try:
# Get a dictionary of the SVN repository information
info = repo.info()
except:
print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.')
return {}
v = dict_to_str(info)
if label:
k = '{}'.format(label)
else:
k = 'SVN INFO'
return {k: v}
def get_git_hash(gitpath=None, label=None):
"""
Helper function for obtaining the git repository hash.
for the current directory (default)
or the directory supplied in the gitpath argument.
Returns a dictionary keyed (by default) as 'GIT HASH'
where the value is a string containing essentially what
is returned by subprocess.
The optional argument 'label' allows you to set the string
used as the dictionary key in the returned dictionary.
"""
if gitpath:
thisdir = os.getcwd()
os.chdir(gitpath)
try:
sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip()
except subprocess.CalledProcessError as e:
print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY")
return {}
if label:
l = '{}'.format(label)
else:
l = 'GIT HASH'
return {l:sha}
def get_source_code(scode,sourcepath=None, label=None):
"""
Helper function for obtaining the source code.
for the current directory (default) or the directory
supplied in the sourcepath argument.
Returns a dictionary keyed (by default) as 'source code'
where the value is a string containing the source code.
The optional argument 'label' allows you to set the string
used as the dictionary key in the returned dictionary.
"""
if sourcepath:
os.chdir(sourcepath)
if not os.path.isfile(scode):
print('ERROR: {} NOT FOUND.'.format(scode))
return {}
else:
with open(scode,'r') as f:
s = f.read()
if label:
n = {'{}'.format(label):s}
else:
n = {'source code':s}
return n
|
extern crate build;
fn main() {
build::link("urlmon", true)
}
|
package states;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import database.DeleteGame;
import database.LoadGame;
import game.Game;
import graphics.ButtonAction;
import graphics.Text;
import graphics.UIButton;
import graphics.UIList;
import graphics.UIScrollScreen;
import loader.ImageLoader;
public class MenuState extends State {
/* Menu screen state it is the initial screen of the game it control the new button and the load button*/
//Main Menu
private UIList menuButtons;
private BufferedImage menuBackground;
//Load Buttons Menu (second Screen)
private UIScrollScreen loadScreen;
private BufferedImage subMenuBackground;
private boolean loadScreenMenu;
//Selected Game Menu (Third Screen)
private UIList loadSubMenu;
private BufferedImage <API key>;
private boolean gameSelected;
public MenuState(Game game) {
super(game);
State.loadMenuState = true;
}
@Override
public UIList getUIButtons() {
/*Control of active buttons*/
if (!gameSelected) {
return menuButtons;
} else {
return loadSubMenu;
}
}
@Override
public UIScrollScreen getScreen() {
/*control if scroll buttons are active*/
if (loadScreenMenu)
return loadScreen;
else
return null;
}
@Override
public void tick() {
// If ESC is clicked on the menu screen then the game closes
if(State.loadMenuState) { //loadMenuState is true then init menu screen
initMenuScreen();
State.loadMenuState = false;
}
if (game.getKeyboard().mESC == true) { //If esc was pressed
if (loadScreenMenu) { //Release loadScreen memory
loadScreenMenu = false;
loadScreen.getButtons().clear();
loadScreen = null;
subMenuBackground = null;
} else if(gameSelected) { //Release memory of the screen after choose a saved game
gameSelected = false;
loadSubMenu.getButtons().clear();
loadSubMenu = null;
<API key> = null;
} else { // If esc was clicked on menu then close game
game.stop();
}
game.getKeyboard().mESC = false;
}
if(State.loadGame || State.newGame) // If load or new game true then it will change to gameState so release menu memory and changes state
{
menuButtons.getButtons().clear();
menuButtons = null;
menuBackground = null;
State.setCurrentState(game.getGameState());
}
}
@Override
public void render(Graphics graph) {
if(State.loadMenuState) // Make sure that only render after menu was loaded
return;
// Draw the menu background image and render the UI buttons
graph.drawImage(menuBackground, 0, 0, game.getWidth(), game.getHeight(), null);
menuButtons.render(graph);
if (loadScreenMenu) {
//Draw subMenu background and render buttons
graph.drawImage(subMenuBackground, 0, 0, game.getWidth(), game.getHeight(), null);
loadScreen.render(graph);
} else if (gameSelected) {
//Draw gameSelected background and render buttons
graph.drawImage(<API key>, 0, 0, game.getWidth(), game.getHeight(), null);
loadSubMenu.render(graph);
}
}
private void initMenuScreen()
{
/*Initialize the screen and buttons of the first menu screen*/
menuBackground = ImageLoader.loadImage("/background/menu_backgroud.png");
try {
initMenuButtons();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initLoadScreen()
{
/*Initialize the screen and buttons of the second menu screen (list of saved games)*/
subMenuBackground = ImageLoader.loadImage("/background/submenu_background.png");
<API key>();
}
private void <API key>()
{
/*Initialize the screen and of the third menu screen (game selected)*/
<API key> = ImageLoader.loadImage("/background/<API key>.png");
<API key>();
}
private void <API key>()
{
/*Init buttons of the selected game load, delete and cancel*/
BufferedImage loadSaveButton[] = new BufferedImage[2];
BufferedImage deleteSaveButton[] = new BufferedImage[2];
BufferedImage cancelButton[] = new BufferedImage[2];
loadSubMenu = new UIList();
loadSaveButton[0] = ImageLoader.loadImage("/button/load_submenu_d.png");
loadSaveButton[1] = ImageLoader.loadImage("/button/load_submenu_s.png");
int buttonWidth = (int) (loadSaveButton[0].getWidth() * game.getScale());
int buttonHeight = (int) (loadSaveButton[0].getHeight() * game.getScale());
//Load a saved game
loadSubMenu.getButtons().add(new UIButton((int) (50 * game.getScale()), (int)(300 * game.getScale()), buttonWidth, buttonHeight, loadSaveButton, -1,
new ButtonAction() {
@Override
public void action() {
State.loadGame = true; // Tells gameState to load a game
game.getKeyboard().mESC = true; // Set esc true to release memory from this screen (GameSelected screen)
}
}));
deleteSaveButton[0] = ImageLoader.loadImage("/button/delete_submenu_d.png");
deleteSaveButton[1] = ImageLoader.loadImage("/button/delete_submenu_s.png");
//Delete a saved game
loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(430 * game.getScale()), buttonWidth, buttonHeight, deleteSaveButton, -1,
new ButtonAction() {
@Override
public void action() {
try {
DeleteGame.Delete(State.savedGames.get(lastButtonIndex).split(" ")[0]); //Get the name of the button pressed and removes from database
} catch (Exception e) {
e.printStackTrace();
}
State.savedGames.clear(); //Clear database name loaded
State.savedGames = null;
game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen)
}
}));
cancelButton[0] = ImageLoader.loadImage("/button/cancel_submenu_d.png");
cancelButton[1] = ImageLoader.loadImage("/button/cancel_submenu_s.png");
//Cancel operation and goes back to the first menu screen
loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(550 * game.getScale()), buttonWidth, buttonHeight, cancelButton, -1,
new ButtonAction() {
@Override
public void action() {
State.savedGames.clear(); //Clear database name loaded
State.savedGames = null;
game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen)
}
}));
}
private void <API key>() {
/*Initialize all load screen buttons*/
BufferedImage loadScreenImage = ImageLoader.loadImage("/background/scrollScreen.png");
BufferedImage loadButton[] = new BufferedImage[2];
int scrollSpeed = 10;
//Init load screen
loadScreen = new UIScrollScreen(loadScreenImage, (int)(31 * game.getScale()), (int)(132 * game.getScale()), (int)(loadScreenImage.getWidth() * game.getScale()), (int)(loadScreenImage.getHeight() * game.getScale()), scrollSpeed);
loadButton[0] = ImageLoader.loadImage("/button/submenu_button_d.png");
loadButton[1] = ImageLoader.loadImage("/button/submenu_button_s.png");
float buttonWidth = loadButton[0].getWidth() * game.getScale();
float buttonHeight = loadButton[0].getHeight() * game.getScale();
Font font = new Font("Castellar", Font.PLAIN, (int)(25 * game.getScale()));
for (int i = 0, accumulator = (int) loadScreen.getScreen().getY(); (int) i < savedGames.size(); i++) { //Accumulator controls the button position on the screen
String split[] = savedGames.get(i).split(" "); //split the name that came from the database
float buttonX = (float) (loadScreen.getScreen().getX() + 3);
Text text[] = new Text[2];
//Initialize both colors of the text and create the visible buttons
text[0] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.black, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2));
text[1] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.white, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2));
loadScreen.getButtons().add(new UIButton((int) buttonX, accumulator,
(int) (buttonWidth), (int) buttonHeight, loadButton, i, text,
new ButtonAction() {
public void action() {
<API key>(); //Initialize gameSelect screen and buttons
gameSelected = true;
game.getKeyboard().mESC = true; // Select true to free memory used by the loadScreen
}
}));
accumulator += (buttonHeight);
}
}
private void initMenuButtons() throws Exception{
// Resize the button depending of the scale attribute of the game class
BufferedImage[] buttonNewGame = new BufferedImage[2];
BufferedImage[] buttonLoadGame = new BufferedImage[2];
buttonNewGame[0] = ImageLoader.loadImage("/button/new_game.png");
buttonNewGame[1] = ImageLoader.loadImage("/button/new_game_b.png");
buttonLoadGame[0] = ImageLoader.loadImage("/button/load_game.png");
buttonLoadGame[1] = ImageLoader.loadImage("/button/load_game_b.png");
menuButtons = new UIList();
/*
* Creates the load button and add to the UI button list, the first two
* parameters has the position of the button on the screen it uses the
* game.width to centralize the button and the game.height to control
* the y position on the screen for every button a Button action is
* defined when passing the argument, this way is possible to program
* the button when creating it
*/
float buttonWidth = buttonLoadGame[0].getWidth() * game.getScale();
float buttonHeight = buttonLoadGame[0].getHeight() * game.getScale();
menuButtons.getButtons().add(new UIButton((int)
((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3) + buttonHeight),
(int) (buttonWidth), (int) buttonHeight, buttonLoadGame, -1,
new ButtonAction() {
public void action() {
savedGames = new ArrayList<>();
try {
savedGames = LoadGame.loadNames();
} catch (Exception e) {
e.printStackTrace();
}
initLoadScreen();
loadScreenMenu = true;
}
}));
/*
* Creates the game button and add to the UI button list, the first two
* parameters has the position of the button on the screen it uses the
* game.width to centralize the button and the game.height to control
* the y position on the screen for every button a Button action is
* defined when passing the argument, this way is possible to program
* the button when creating it
*/
// Resize the button depending of the scale attribute of the game class
buttonWidth = buttonNewGame[0].getWidth() * game.getScale();
buttonHeight = buttonNewGame[0].getHeight() * game.getScale();
menuButtons.getButtons()
.add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3)),
(int) (buttonWidth), (int) (buttonHeight), buttonNewGame, -1, new ButtonAction() {
public void action() {
State.newGame = true;
}
}));
}
}
|
<?php
declare(strict_types = 1);
use PHPUnit\Framework\TestCase;
use Sop\JWX\JWA\JWA;
use Sop\JWX\JWS\Algorithm\NoneAlgorithm;
use Sop\JWX\JWT\Parameter\AlgorithmParameter;
use Sop\JWX\JWT\Parameter\JWTParameter;
/**
* @group jwt
* @group parameter
*
* @internal
*/
class <API key> extends TestCase
{
public function testCreate()
{
$param = new AlgorithmParameter(JWA::ALGO_NONE);
$this->assertInstanceOf(AlgorithmParameter::class, $param);
return $param;
}
/**
* @depends testCreate
*/
public function testParamName(JWTParameter $param)
{
$this->assertEquals(JWTParameter::PARAM_ALGORITHM, $param->name());
}
public function testFromAlgo()
{
$param = AlgorithmParameter::fromAlgorithm(new NoneAlgorithm());
$this->assertInstanceOf(AlgorithmParameter::class, $param);
}
}
|
# <API key>: true
module HelperFunctions
def log_in
email = 'test@sumofus.org'
password = 'password'
User.create! email: email, password: password
visit '/users/sign_in'
fill_in 'user_email', with: email
fill_in 'user_password', with: password
click_button 'Log in'
end
def create_tags
Tag.create!([
{ tag_name: '*Welcome_Sequence', actionkit_uri: '/rest/v1/tag/1000/' },
{ tag_name: '#Animal_Rights', actionkit_uri: '/rest/v1/tag/944/' },
{ tag_name: '#Net_Neutrality', actionkit_uri: '/rest/v1/tag/1078/' },
{ tag_name: '*FYI_and_VIP', actionkit_uri: '/rest/v1/tag/980/' },
{ tag_name: '@Germany', actionkit_uri: '/rest/v1/tag/1036/' },
{ tag_name: '@NewZealand', actionkit_uri: '/rest/v1/tag/1140/' },
{ tag_name: '@France', actionkit_uri: '/rest/v1/tag/1128/' },
{ tag_name: '#Sexism', actionkit_uri: '/rest/v1/tag/1208/' },
{ tag_name: '#Disability_Rights', actionkit_uri: '/rest/v1/tag/1040/' },
{ tag_name: '@Austria', actionkit_uri: '/rest/v1/tag/1042/' }
])
end
def <API key>(response)
JSON.parse(response.body)['errors'].inject([]) { |memo, error| memo << error['message'] }.uniq
end
end
|
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
export function <API key>(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const name = control.value;
const no = nameRe.test(name);
return no ? {forbiddenName: {name}} : null;
};
}
@Directive({
selector: '[forbiddenName]',
providers: [{provide: NG_VALIDATORS, useExisting: <API key>, multi: true}]
})
export class <API key> implements Validator, OnChanges {
@Input() public forbiddenName: string;
private valFn = Validators.nullValidator;
public ngOnChanges(changes: SimpleChanges): void {
// const change = changes['forbiddenName'];
// if (change) {
// const val: string | RegExp = change.currentValue;
// const re = val instanceof RegExp ? val : new RegExp(val, 'i');
// this.valFn = <API key>(re);
// } else {
// this.valFn = Validators.nullValidator;
}
public validate(control: AbstractControl): {[key: string]: any} {
return this.valFn(control);
}
}
|
namespace <API key>
{
partial class LockControlPanel
{
<summary>
Required designer variable.
</summary>
private System.ComponentModel.IContainer components = null;
<summary>
Clean up any resources being used.
</summary>
<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
<summary>
Required method for Designer support - do not modify
the contents of this method with the code editor.
</summary>
private void InitializeComponent()
{
this.lockParams = new System.Windows.Forms.GroupBox();
this.lockedLED = new NationalInstruments.UI.WindowsForms.Led();
this.label10 = new System.Windows.Forms.Label();
this.<API key> = new System.Windows.Forms.TextBox();
this.GainTextbox = new System.Windows.Forms.TextBox();
this.<API key> = new System.Windows.Forms.TextBox();
this.<API key> = new System.Windows.Forms.Button();
this.<API key> = new System.Windows.Forms.Button();
this.<API key> = new System.Windows.Forms.TextBox();
this.lockEnableCheck = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.<API key> = new NationalInstruments.UI.WindowsForms.ScatterGraph();
this.SlaveDataPlot = new NationalInstruments.UI.ScatterPlot();
this.xAxis1 = new NationalInstruments.UI.XAxis();
this.yAxis1 = new NationalInstruments.UI.YAxis();
this.SlaveFitPlot = new NationalInstruments.UI.ScatterPlot();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ErrorScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph();
this.ErrorPlot = new NationalInstruments.UI.ScatterPlot();
this.xAxis2 = new NationalInstruments.UI.XAxis();
this.yAxis2 = new NationalInstruments.UI.YAxis();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.slErrorResetButton = new System.Windows.Forms.Button();
this.VoltageTrackBar = new System.Windows.Forms.TrackBar();
this.lockParams.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.lockedLED)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.<API key>)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).BeginInit();
this.SuspendLayout();
// lockParams
this.lockParams.Controls.Add(this.lockedLED);
this.lockParams.Controls.Add(this.label10);
this.lockParams.Controls.Add(this.<API key>);
this.lockParams.Controls.Add(this.GainTextbox);
this.lockParams.Controls.Add(this.<API key>);
this.lockParams.Controls.Add(this.<API key>);
this.lockParams.Controls.Add(this.<API key>);
this.lockParams.Controls.Add(this.<API key>);
this.lockParams.Controls.Add(this.lockEnableCheck);
this.lockParams.Controls.Add(this.label4);
this.lockParams.Controls.Add(this.label2);
this.lockParams.Controls.Add(this.label3);
this.lockParams.Controls.Add(this.VoltageTrackBar);
this.lockParams.Location = new System.Drawing.Point(589, 3);
this.lockParams.Name = "lockParams";
this.lockParams.Size = new System.Drawing.Size(355, 162);
this.lockParams.TabIndex = 13;
this.lockParams.TabStop = false;
this.lockParams.Text = "Lock Parameters";
// lockedLED
this.lockedLED.LedStyle = NationalInstruments.UI.LedStyle.Round3D;
this.lockedLED.Location = new System.Drawing.Point(310, 6);
this.lockedLED.Name = "lockedLED";
this.lockedLED.Size = new System.Drawing.Size(32, 30);
this.lockedLED.TabIndex = 34;
// label10
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 66);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(123, 13);
this.label10.TabIndex = 33;
this.label10.Text = "Set Point Increment Size";
// <API key>
this.<API key>.Location = new System.Drawing.Point(168, 63);
this.<API key>.Name = "<API key>";
this.<API key>.Size = new System.Drawing.Size(55, 20);
this.<API key>.TabIndex = 32;
this.<API key>.Text = "0.01";
this.<API key>.TextChanged += new System.EventHandler(this.<API key>);
// GainTextbox
this.GainTextbox.Location = new System.Drawing.Point(167, 15);
this.GainTextbox.Name = "GainTextbox";
this.GainTextbox.Size = new System.Drawing.Size(81, 20);
this.GainTextbox.TabIndex = 31;
this.GainTextbox.Text = "0.5";
this.GainTextbox.TextChanged += new System.EventHandler(this.GainChanged);
// <API key>
this.<API key>.Location = new System.Drawing.Point(167, 89);
this.<API key>.Name = "<API key>";
this.<API key>.Size = new System.Drawing.Size(100, 20);
this.<API key>.TabIndex = 30;
this.<API key>.Text = "0";
this.<API key>.TextChanged += new System.EventHandler(this.<API key>);
// <API key>
this.<API key>.Location = new System.Drawing.Point(124, 37);
this.<API key>.Name = "<API key>";
this.<API key>.Size = new System.Drawing.Size(37, 23);
this.<API key>.TabIndex = 29;
this.<API key>.Text = "-";
this.<API key>.<API key> = true;
this.<API key>.Click += new System.EventHandler(this.<API key>);
// <API key>
this.<API key>.Location = new System.Drawing.Point(81, 37);
this.<API key>.Name = "<API key>";
this.<API key>.Size = new System.Drawing.Size(37, 23);
this.<API key>.TabIndex = 28;
this.<API key>.Text = "+";
this.<API key>.<API key> = true;
this.<API key>.Click += new System.EventHandler(this.<API key>);
// <API key>
this.<API key>.AcceptsReturn = true;
this.<API key>.Location = new System.Drawing.Point(167, 39);
this.<API key>.Name = "<API key>";
this.<API key>.Size = new System.Drawing.Size(57, 20);
this.<API key>.TabIndex = 27;
this.<API key>.Text = "0";
// lockEnableCheck
this.lockEnableCheck.AutoSize = true;
this.lockEnableCheck.Location = new System.Drawing.Point(254, 17);
this.lockEnableCheck.Name = "lockEnableCheck";
this.lockEnableCheck.Size = new System.Drawing.Size(50, 17);
this.lockEnableCheck.TabIndex = 9;
this.lockEnableCheck.Text = "Lock";
this.lockEnableCheck.<API key> = true;
this.lockEnableCheck.CheckedChanged += new System.EventHandler(this.<API key>);
// label4
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 18);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(29, 13);
this.label4.TabIndex = 20;
this.label4.Text = "Gain";
// label2
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 92);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(122, 13);
this.label2.TabIndex = 17;
this.label2.Text = "Voltage sent to laser (V):";
// label3
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 42);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(69, 13);
this.label3.TabIndex = 13;
this.label3.Text = "Set Point (V):";
// <API key>
this.<API key>.Location = new System.Drawing.Point(9, 17);
this.<API key>.Name = "<API key>";
this.<API key>.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] {
this.SlaveDataPlot,
this.SlaveFitPlot});
this.<API key>.Size = new System.Drawing.Size(567, 132);
this.<API key>.TabIndex = 12;
this.<API key>.XAxes.AddRange(new NationalInstruments.UI.XAxis[] {
this.xAxis1});
this.<API key>.YAxes.AddRange(new NationalInstruments.UI.YAxis[] {
this.yAxis1});
// SlaveDataPlot
this.SlaveDataPlot.LineStyle = NationalInstruments.UI.LineStyle.None;
this.SlaveDataPlot.PointSize = new System.Drawing.Size(3, 3);
this.SlaveDataPlot.PointStyle = NationalInstruments.UI.PointStyle.SolidCircle;
this.SlaveDataPlot.XAxis = this.xAxis1;
this.SlaveDataPlot.YAxis = this.yAxis1;
// SlaveFitPlot
this.SlaveFitPlot.LineStyle = NationalInstruments.UI.LineStyle.None;
this.SlaveFitPlot.PointColor = System.Drawing.Color.LawnGreen;
this.SlaveFitPlot.PointStyle = NationalInstruments.UI.PointStyle.EmptyTriangleUp;
this.SlaveFitPlot.XAxis = this.xAxis1;
this.SlaveFitPlot.YAxis = this.yAxis1;
// groupBox1
this.groupBox1.Controls.Add(this.ErrorScatterGraph);
this.groupBox1.Controls.Add(this.<API key>);
this.groupBox1.Location = new System.Drawing.Point(4, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(582, 286);
this.groupBox1.TabIndex = 15;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Slave laser";
// ErrorScatterGraph
this.ErrorScatterGraph.Location = new System.Drawing.Point(6, 155);
this.ErrorScatterGraph.Name = "ErrorScatterGraph";
this.ErrorScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] {
this.ErrorPlot});
this.ErrorScatterGraph.Size = new System.Drawing.Size(570, 125);
this.ErrorScatterGraph.TabIndex = 13;
this.ErrorScatterGraph.UseColorGenerator = true;
this.ErrorScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] {
this.xAxis2});
this.ErrorScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] {
this.yAxis2});
// ErrorPlot
this.ErrorPlot.LineColor = System.Drawing.Color.Red;
this.ErrorPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor;
this.ErrorPlot.XAxis = this.xAxis2;
this.ErrorPlot.YAxis = this.yAxis2;
// xAxis2
this.xAxis2.Mode = NationalInstruments.UI.AxisMode.StripChart;
this.xAxis2.Range = new NationalInstruments.UI.Range(0D, 500D);
// groupBox2
this.groupBox2.Controls.Add(this.slErrorResetButton);
this.groupBox2.Location = new System.Drawing.Point(589, 171);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(355, 118);
this.groupBox2.TabIndex = 16;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Error Signal Parameters";
// slErrorResetButton
this.slErrorResetButton.Location = new System.Drawing.Point(9, 19);
this.slErrorResetButton.Name = "slErrorResetButton";
this.slErrorResetButton.Size = new System.Drawing.Size(109, 23);
this.slErrorResetButton.TabIndex = 29;
this.slErrorResetButton.Text = "Reset Graph";
this.slErrorResetButton.<API key> = true;
this.slErrorResetButton.Click += new System.EventHandler(this.<API key>);
// VoltageTrackBar
this.VoltageTrackBar.BackColor = System.Drawing.SystemColors.ButtonFace;
this.VoltageTrackBar.Location = new System.Drawing.Point(6, 114);
this.VoltageTrackBar.Maximum = 1000;
this.VoltageTrackBar.Name = "VoltageTrackBar";
this.VoltageTrackBar.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.VoltageTrackBar.Size = new System.Drawing.Size(343, 45);
this.VoltageTrackBar.TabIndex = 53;
this.VoltageTrackBar.Value = 100;
this.VoltageTrackBar.Scroll += new System.EventHandler(this.<API key>);
// LockControlPanel
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.Controls.Add(this.lockParams);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "LockControlPanel";
this.Size = new System.Drawing.Size(952, 294);
this.lockParams.ResumeLayout(false);
this.lockParams.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.lockedLED)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.<API key>)).EndInit();
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).EndInit();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox lockParams;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox <API key>;
private System.Windows.Forms.TextBox GainTextbox;
private System.Windows.Forms.TextBox <API key>;
private System.Windows.Forms.Button <API key>;
private System.Windows.Forms.Button <API key>;
private System.Windows.Forms.TextBox <API key>;
private System.Windows.Forms.CheckBox lockEnableCheck;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
public NationalInstruments.UI.WindowsForms.ScatterGraph <API key>;
public NationalInstruments.UI.ScatterPlot SlaveDataPlot;
private NationalInstruments.UI.XAxis xAxis1;
private NationalInstruments.UI.YAxis yAxis1;
public NationalInstruments.UI.ScatterPlot SlaveFitPlot;
private System.Windows.Forms.GroupBox groupBox1;
private NationalInstruments.UI.WindowsForms.Led lockedLED;
private NationalInstruments.UI.WindowsForms.ScatterGraph ErrorScatterGraph;
private NationalInstruments.UI.ScatterPlot ErrorPlot;
private NationalInstruments.UI.XAxis xAxis2;
private NationalInstruments.UI.YAxis yAxis2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button slErrorResetButton;
public System.Windows.Forms.TrackBar VoltageTrackBar;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using <API key>.<API key>;
using IoC = LiveScore.App_Start.IoC;
namespace LiveScore
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
<API key>.Register(IoC.Initialize());
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.<API key>(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
|
#include "..\stdafx.h"
#pragma once
class CMutex
{
private:
HANDLE m_mutex;
bool m_isLocked;
void Lock()
{
WaitForSingleObject(this->m_mutex, INFINITE);
}
void Unlock()
{
if (this->m_isLocked)
{
this->m_isLocked = false;
ReleaseMutex(this->m_mutex);
}
}
public:
CMutex()
{
this->m_mutex = CreateMutex(NULL, FALSE, NULL);
}
~CMutex()
{
CloseHandle(this->m_mutex);
}
friend class CMutexLock;
};
class CMutexLock
{
private:
CMutex* m_mutexObj;
public:
CMutexLock(CMutex* mutex)
{
this->m_mutexObj = mutex;
this->m_mutexObj->Lock();
}
~CMutexLock()
{
this->m_mutexObj->Unlock();
}
};
|
const testLogs = require('../../utils').testLogs;
describe(
'Test repeat',
() => {
testLogs(
it,
'Should repeat ten times',
[
'proc main()',
' number i',
' i = 0',
' repeat',
' addr i',
' mod 0, 1',
' i += 1',
' if i > 9',
' break',
' end',
' end',
'end'
],
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
]
);
testLogs(
it,
'Should break to outer loop',
[
'proc main()',
' number x = 0',
' repeat loop',
' x += 1',
' repeat',
' x += 1',
' if (x > 10)',
' break loop',
' end',
' addr x',
' mod 0, 1',
' end',
' end',
'end'
],
[
2, 3, 4, 5, 6, 7, 8, 9, 10
]
);
}
);
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>tlc: 2 m 40 s</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / tlc - 20200328</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
tlc
<small>
20200328
<span class="label label-success">2 m 40 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-04-14 10:21:03 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-04-14 10:21:03 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.0 Official release 4.10.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "arthur.chargueraud@inria.fr"
homepage: "https://github.com/charguer/tlc"
dev-repo: "git+https://github.com/charguer/tlc.git"
bug-reports: "https://github.com/charguer/tlc/issues"
license: "MIT"
synopsis: "TLC: A Library for Classical Coq "
description: """
Provides an alternative to the core of the Coq standard library, using classic definitions.
"""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"coq" { >= "8.10" }
]
tags: [
"category:Miscellaneous/Coq Extensions"
"date:2020-03-28"
"keyword:library"
"keyword:classic"
"logpath:TLC"
]
authors: [
"Arthur Charguéraud"
]
url {
src: "https://github.com/charguer/tlc/archive/20200328.tar.gz"
checksum: [
"md5=<API key>"
"sha512=33996475d9b3adc1752fd91ddbac5ebbe5bd7f22583c788807dd7ca9cd0363476621135884cf2603c1003c9c280811633a5a66ab2a279bf21cb1b39e60ae47a3"
]
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-tlc.20200328 coq.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-tlc.20200328 coq.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>5 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-tlc.20200328 coq.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>2 m 40 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 9 M</p>
<ul>
<li>951 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.vo</code></li>
<li>591 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.vo</code></li>
<li>389 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.vo</code></li>
<li>348 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.glob</code></li>
<li>343 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.vo</code></li>
<li>307 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.glob</code></li>
<li>276 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.vo</code></li>
<li>245 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.vo</code></li>
<li>241 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.vo</code></li>
<li>224 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.vo</code></li>
<li>193 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.vo</code></li>
<li>188 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.v</code></li>
<li>180 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.glob</code></li>
<li>179 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.vo</code></li>
<li>178 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.vo</code></li>
<li>137 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.vo</code></li>
<li>135 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.vo</code></li>
<li>135 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.vo</code></li>
<li>127 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.glob</code></li>
<li>120 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.glob</code></li>
<li>120 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.vo</code></li>
<li>116 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.vo</code></li>
<li>111 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.vo</code></li>
<li>110 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.glob</code></li>
<li>100 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.glob</code></li>
<li>100 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.v</code></li>
<li>99 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.vo</code></li>
<li>93 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.vo</code></li>
<li>93 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.glob</code></li>
<li>87 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.glob</code></li>
<li>86 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.glob</code></li>
<li>84 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.vo</code></li>
<li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.glob</code></li>
<li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.vo</code></li>
<li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.glob</code></li>
<li>82 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.v</code></li>
<li>79 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.glob</code></li>
<li>78 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.glob</code></li>
<li>77 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.vo</code></li>
<li>72 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.vo</code></li>
<li>71 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.vo</code></li>
<li>71 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.vo</code></li>
<li>69 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.vo</code></li>
<li>68 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.vo</code></li>
<li>68 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.glob</code></li>
<li>65 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.vo</code></li>
<li>60 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.vo</code></li>
<li>59 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.v</code></li>
<li>56 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.vo</code></li>
<li>55 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.vo</code></li>
<li>52 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.glob</code></li>
<li>52 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.vo</code></li>
<li>50 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.vo</code></li>
<li>48 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.vo</code></li>
<li>48 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.vo</code></li>
<li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.glob</code></li>
<li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.vo</code></li>
<li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.vo</code></li>
<li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.vo</code></li>
<li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.v</code></li>
<li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.v</code></li>
<li>43 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.glob</code></li>
<li>39 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.vo</code></li>
<li>38 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.vo</code></li>
<li>38 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.v</code></li>
<li>34 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.glob</code></li>
<li>32 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.v</code></li>
<li>32 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.vo</code></li>
<li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.v</code></li>
<li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.vo</code></li>
<li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.v</code></li>
<li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.vo</code></li>
<li>30 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.v</code></li>
<li>30 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.glob</code></li>
<li>29 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.v</code></li>
<li>27 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.v</code></li>
<li>25 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.glob</code></li>
<li>25 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.glob</code></li>
<li>24 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.v</code></li>
<li>23 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.glob</code></li>
<li>23 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.v</code></li>
<li>21 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.v</code></li>
<li>19 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.glob</code></li>
<li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.glob</code></li>
<li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.v</code></li>
<li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.glob</code></li>
<li>15 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.v</code></li>
<li>15 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.v</code></li>
<li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.v</code></li>
<li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.glob</code></li>
<li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.glob</code></li>
<li>10 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.glob</code></li>
<li>10 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.v</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.v</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.v</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.glob</code></li>
<li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.v</code></li>
<li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.glob</code></li>
<li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.v</code></li>
<li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.v</code></li>
<li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.glob</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/Makefile.coq</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.glob</code></li>
<li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.glob</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.vo</code></li>
<li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.glob</code></li>
<li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/Makefile</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.glob</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-tlc.20200328</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
from django.db import models
from .workflow import TestStateMachine
class TestModel(models.Model):
name = models.CharField(max_length=100)
state = models.CharField(max_length=20, null=True, blank=True)
state_num = models.IntegerField(null=True, blank=True)
other_state = models.CharField(max_length=20, null=True, blank=True)
message = models.CharField(max_length=250, null=True, blank=True)
class Meta:
permissions = TestStateMachine.get_permissions('testmodel', 'Test')
|
<?php namespace Fisharebest\Localization\Locale;
use Fisharebest\Localization\Territory\TerritoryNi;
class LocaleEsNi extends LocaleEs {
public function territory() {
return new TerritoryNi;
}
}
|
use internal;
#[derive(Debug, PartialEq, PartialOrd, Copy, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Size {
pub width: f32,
pub height: f32,
}
impl From<Size> for internal::YGSize {
fn from(s: Size) -> internal::YGSize {
internal::YGSize {
width: s.width,
height: s.height,
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bignums: 1 m 56 s </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.10.0 / bignums - 8.10+beta1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
bignums
<small>
8.10+beta1
<span class="label label-success">1 m 56 s </span>
</small>
</h1>
<p> <em><script>document.write(moment("2020-07-29 03:23:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-29 03:23:42 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.0 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Laurent.Thery@inria.fr"
homepage: "https://github.com/coq/bignums"
dev-repo: "git+https://github.com/coq/bignums.git"
bug-reports: "https://github.com/coq/bignums/issues"
authors: [
"Laurent Théry"
"Benjamin Grégoire"
"Arnaud Spiwack"
"Evgeny Makarov"
"Pierre Letouzey"
]
license: "LGPL 2"
build: [
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword:integer numbers"
"keyword:rational numbers"
"keyword:arithmetic"
"keyword:arbitrary-precision"
"category:Miscellaneous/Coq Extensions"
"category:Mathematics/Arithmetic and Number Theory/Number theory"
"category:Mathematics/Arithmetic and Number Theory/Rational numbers"
"logpath:Bignums"
]
synopsis: "Bignums, the Coq library of arbitrary large numbers"
description:
"Provides BigN, BigZ, BigQ that used to be part of Coq standard library < 8.7."
url {
src: "https://github.com/coq/bignums/archive/V8.10+beta1.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-bignums.8.10+beta1 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-bignums.8.10+beta1 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>2 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y coq-bignums.8.10+beta1 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 56 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 10 M</p>
<ul>
<li>899 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.vo</code></li>
<li>786 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.vo</code></li>
<li>715 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.vo</code></li>
<li>564 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.vo</code></li>
<li>554 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.glob</code></li>
<li>535 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.vo</code></li>
<li>372 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.vo</code></li>
<li>346 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.glob</code></li>
<li>317 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.vo</code></li>
<li>300 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.vo</code></li>
<li>289 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.vo</code></li>
<li>286 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.vo</code></li>
<li>274 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.vo</code></li>
<li>264 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.glob</code></li>
<li>201 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.glob</code></li>
<li>198 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.glob</code></li>
<li>197 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.glob</code></li>
<li>186 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.vo</code></li>
<li>185 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.vo</code></li>
<li>185 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.vo</code></li>
<li>182 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.glob</code></li>
<li>168 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.vo</code></li>
<li>152 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.glob</code></li>
<li>145 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.glob</code></li>
<li>124 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.vo</code></li>
<li>118 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.vo</code></li>
<li>116 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.glob</code></li>
<li>109 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.vo</code></li>
<li>104 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.vo</code></li>
<li>99 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.vo</code></li>
<li>88 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.vo</code></li>
<li>88 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.glob</code></li>
<li>74 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.glob</code></li>
<li>72 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.glob</code></li>
<li>70 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.glob</code></li>
<li>68 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.glob</code></li>
<li>63 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/<API key>.cmxs</code></li>
<li>62 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.glob</code></li>
<li>62 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.glob</code></li>
<li>56 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.vo</code></li>
<li>55 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.v</code></li>
<li>52 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.v</code></li>
<li>52 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.vo</code></li>
<li>48 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.v</code></li>
<li>37 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.glob</code></li>
<li>35 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.glob</code></li>
<li>35 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.v</code></li>
<li>31 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.glob</code></li>
<li>28 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.v</code></li>
<li>24 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.v</code></li>
<li>21 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.v</code></li>
<li>20 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.v</code></li>
<li>19 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.v</code></li>
<li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.v</code></li>
<li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.v</code></li>
<li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.glob</code></li>
<li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.v</code></li>
<li>9 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/<API key>.cmi</code></li>
<li>8 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/<API key>.cmx</code></li>
<li>7 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/<API key>.cmxa</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-bignums.8.10+beta1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
require 'builder'
module MWS
module API
class Fulfillment < Base
include Feeds
## Takes an array of hash AmazonOrderID,FulfillmentDate,CarrierName,<API key>,sku,quantity
## Returns true if all the orders were updated successfully
## Otherwise raises an exception
def <API key>(merchant_id, ship_info)
# Shipping Confirmation is done by sending an XML "feed" to Amazon
xml = ""
builder = Builder::XmlMarkup.new(:indent => 2, :target => xml)
builder.instruct! # <?xml version="1.0" encoding="UTF-8"?>
builder.AmazonEnvelope(:"xmlns:xsi" => "http:
env.Header do |head|
head.DocumentVersion('1.01')
head.MerchantIdentifier(merchant_id)
end
env.MessageType('OrderFulfillment')
i = 0
ship_info.each do |shp|
env.Message do |msg|
msg.MessageID(i += 1)
msg.OrderFulfillment do |orf|
orf.AmazonOrderID(shp.AmazonOrderID)
orf.FulfillmentDate(shp.FulfillmentDate.to_time.iso8601)
orf.FulfillmentData do |fd|
fd.CarrierCode(shp.CarrierCode)
fd.ShippingMethod()
fd.<API key>(shp.<API key>)
end
if shp.sku != ''
orf.Item do |itm|
itm.MerchantOrderItemID(shp.sku)
itm.<API key>(shp.sku)
itm.Quantity(shp.quantity)
end
end
end
end
end
end
submit_feed('<API key>', xml)
end
end
end
end
|
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { HelloRoutingModule } from './hello-routing.module';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [
SharedModule,
HelloRoutingModule,
],
declarations: [
HelloComponent,
],
})
export class HelloModule { }
|
package de.espend.idea.shopware.util.dict;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.<API key>;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.<API key>;
import fr.adrienbrault.idea.symfony2plugin.<API key>;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.apache.commons.lang.StringUtils;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class <API key> implements Runnable {
private final Project project;
private final VirtualFile virtualFile;
private final Map<String, Collection<String>> events;
private final Set<String> configs;
public <API key>(Project project, VirtualFile virtualFile, Map<String, Collection<String>> events, Set<String> configs) {
this.project = project;
this.virtualFile = virtualFile;
this.events = events;
this.configs = configs;
}
public void run() {
final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
if (psiFile != null) {
psiFile.acceptChildren(new <API key>());
}
}
private class <API key> extends <API key> {
@Override
public void visitElement(PsiElement element) {
if (element instanceof MethodReference) {
<API key>((MethodReference) element);
}
super.visitElement(element);
}
private void <API key>(MethodReference methodReference) {
String name = methodReference.getName();
if (name != null && ("notify".equals(name) || "notifyUntil".equals(name) || "filter".equals(name))) {
PsiElement[] parameters = methodReference.getParameters();
if(parameters.length > 1) {
if(parameters[0] instanceof <API key>) {
PsiElement method = methodReference.resolve();
if(method instanceof Method) {
PhpClass phpClass = ((Method) method).getContainingClass();
if(phpClass != null && new <API key>().isInstanceOf(phpClass, "\\<API key>")) {
String content = PhpElementsUtil.getStringValue(parameters[0]);
if(StringUtils.isNotBlank(content)) {
if(!events.containsKey(content)) {
events.put(content, new HashSet<String>());
}
Collection<String> data = events.get(content);
Method parentOfType = PsiTreeUtil.getParentOfType(parameters[0], Method.class);
if(parentOfType != null && parentOfType.getContainingClass() != null) {
String methodName = parentOfType.getName();
String presentableFQN = parentOfType.getContainingClass().getPresentableFQN();
data.add(presentableFQN + '.' + methodName);
events.put(content, data);
}
}
}
}
}
}
}
if (name != null && ("addElement".equals(name) || "setElement".equals(name))) {
PsiElement[] parameters = methodReference.getParameters();
if(parameters.length > 2) {
if(parameters[1] instanceof <API key>) {
PsiElement method = methodReference.resolve();
if(method instanceof Method) {
PhpClass phpClass = ((Method) method).getContainingClass();
if(phpClass != null && new <API key>().isInstanceOf(phpClass, "\\Shopware\\Models\\Config\\Form")) {
String content = ((<API key>) parameters[1]).getContents();
if(StringUtils.isNotBlank(content)) {
configs.add(content);
}
}
}
}
}
}
}
}
}
|
#import <Foundation/Foundation.h>
#import "HL7SummaryProtocol.h"
@class HL7PatientSummary;
@class <API key>;
typedef NSDictionary<NSString *, id<HL7SummaryProtocol>> <API key>;
@interface HL7CCDSummary : NSObject <NSCopying, NSCoding>
- (<API key> *_Nullable)document;
- (HL7PatientSummary *_Nullable)patient;
- (<API key> *_Nullable)summaries;
- (id<HL7SummaryProtocol> _Nullable)getSummaryByClass:(Class _Nonnull)className;
@end
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('geokey_sapelli', '<API key>'),
]
operations = [
migrations.AddField(
model_name='sapelliproject',
name='sapelli_fingerprint',
field=models.IntegerField(default=-1),
preserve_default=False,
),
]
|
using UnityEngine;
using System.Collections;
public class HurtSusukeOnContact : MonoBehaviour {
public int damageToGive;
public float bounceOnEnemy;
private Rigidbody2D myRigidbody2D;
// Use this for initialization
void Start () {
myRigidbody2D = transform.parent.GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Susuke") {
other.GetComponent<EnemyHealthManager>().giveDamage(damageToGive);
myRigidbody2D.velocity = new Vector2 (myRigidbody2D.velocity.x, bounceOnEnemy);
}
}
}
|
#include "Internal.hpp"
#include <LuminoEngine/Graphics/Texture.hpp>
#include <LuminoEngine/Rendering/Material.hpp>
#include <LuminoEngine/Mesh/Mesh.hpp>
#include <LuminoEngine/Visual/StaticMeshComponent.hpp>
namespace ln {
// StaticMeshComponent
StaticMeshComponent::StaticMeshComponent()
: m_model(nullptr)
{
}
StaticMeshComponent::~StaticMeshComponent()
{
}
void StaticMeshComponent::init()
{
VisualComponent::init();
}
void StaticMeshComponent::setModel(StaticMeshModel* model)
{
m_model = model;
}
StaticMeshModel* StaticMeshComponent::model() const
{
return m_model;
}
void StaticMeshComponent::onRender(RenderingContext* context)
{
const auto& containers = m_model->meshContainers();
for (int iContainer = 0; iContainer < containers.size(); iContainer++)
{
const auto& meshContainer = containers[iContainer];
MeshResource* meshResource = meshContainer->meshResource();
if (meshResource) {
for (int iSection = 0; iSection < meshResource->sections().size(); iSection++) {
context->setMaterial(m_model->materials()[meshResource->sections()[iSection].materialIndex]);
context->drawMesh(meshResource, iSection);
}
}
//Mesh* mesh = meshContainer->mesh();
//if (mesh) {
// for (int iSection = 0; iSection < mesh->sections().size(); iSection++) {
// context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]);
// context->drawMesh(mesh, iSection);
}
for (const auto& node : m_model->meshNodes()) {
if (node->meshContainerIndex() >= 0) {
context->setTransfrom(m_model->nodeGlobalTransform(node->index()));
const auto& meshContainer = m_model->meshContainers()[node->meshContainerIndex()];
Mesh* mesh = meshContainer->mesh();
if (mesh) {
for (int iSection = 0; iSection < mesh->sections().size(); iSection++) {
context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]);
context->drawMesh(mesh, iSection);
}
}
}
}
}
} // namespace ln
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="../../lib/vue.js"></script>
<title>vue test</title>
</head>
<body>
<div id="app">
{{ message }}
<span id="test-1">message-2:{{getMemo}}</span>
</div>
<text></text>
</body>
<script>
import text from './Text'
export default {
data(){
return {
a:1,
b:2
}
},
created(){
console.log(this)
},
computed:{
getMemo(){
return `this is query params ${this.message}`
}
},
components: {
text
},
}
</script>
</html>
|
#!/usr/bin/env bats
die() {
echo "$@" >/dev/stderr
exit 1
}
export <API key>=1
## mocked docker command
#which docker &>/dev/null || die "ERROR: docker must be installed to run tests"
source $BATS_TEST_DIRNAME/mock_docker # for test fixture variables
export mock_docker="$BATS_TEST_DIRNAME/mock_docker"
docker() {
"$mock_docker" "$@"
}
export -f docker
@test "running with no args prints usage & exit code 2." {
run ./dockhack
[ "$status" -eq 2 ]
[[ "$output" =~ "Usage" ]]
}
@test "-h/--help print usage & exit code 0." {
run ./dockhack -h
[ "$status" -eq 0 ]
[[ "$output" =~ "Usage" ]]
run ./dockhack --help
[ "$status" -eq 0 ]
[[ "$output" =~ "Usage" ]]
}
@test "'dockhack lib' is a no-op" {
run ./dockhack lib
[ "$status" -eq 0 ]
[[ "$output" = "" ]]
}
@test "'get_id last' == 'get_id l' == 'id last'" {
local -a commands=('get_id last' 'get_id l' 'id last')
for com in "${commands[@]}"; do
eval "run ./dockhack $com"
echo ">> $com : $output"
[[ "$status" -eq 0 ]]
[[ "$output" = "$TEST_ID" ]] || die "bad out"
done
}
@test "'get_id $TEST_NAME' == 'id $TEST_NAME'" {
local -a commands=("get_id $TEST_NAME" "id $TEST_NAME")
for com in "${commands[@]}"; do
eval "run ./dockhack $com"
[[ "$status" -eq 0 ]]
[[ "$output" = "$TEST_ID" ]] || die "bad out"
done
}
@test "dummy test" {
true
}
|
<?php namespace App\Controllers\Admin;
use BaseController;
use DB, View, Datatables, Input, Redirect, Str, Validator, Image, File;
use App\Models\Music;
class MusicController extends BaseController {
private $upload_path = "uploads/music/";
public function getList()
{
$music_count = Music::count();
$data = array();
if($music_count > 0){
$data['formProcess'] = "editProcess";
$musicRecord = Music::orderBy('id', 'DESC')->first();
$id = $musicRecord->id;
$data['input'] = Music::find($id);
}
return View::make('admin.site.music',$data);
}
public function postSubmit(){
if(Input::get('_action') == 'addProcess'){
$validator = Validator::make(
array(
'Title' => Input::get('title'),
'MP3 File' => Input::file('file_name')
),
array(
'Title' => 'required',
'MP3 File' => 'required'
)
);
$mime = Input::file('file_name')->getMimeType();
if ($validator->fails()){
return Redirect::route('admin.music')->withErrors($validator)->withInput();
}
// if($mime !== 'audio/mpeg'){
// $error = "You have to input audio MP3 file";
// return Redirect::route('admin.music')->withErrors($error)->withInput();
$music = new Music;
$music->title = Input::get('title');
if(!file_exists($this->upload_path)) {
mkdir($this->upload_path, 0777, true);
}
if(!is_null(Input::file('file_name'))){
$file = Input::file('file_name');
if($file->isValid()){
$filename = "subud_".str_random(10);
$extension = $file-><API key>();
$upload_name = $filename.".".$extension;
$upload_success = $file->move($this->upload_path, $upload_name);
if( $upload_success ) {
$music->file_name = $this->upload_path.$upload_name;
} else {
$error = "Failed uploading file";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
$music->save();
}
else {
$error = "Invalid file";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
}
else {
$error = "Null file input";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
}
elseif(Input::get('_action') == 'editProcess'){
if(Input::has('id')){
$validator = Validator::make(
array(
'Title' => Input::get('title')
),
array(
'Title' => 'required'
)
);
if ($validator->fails()){
return Redirect::route('admin.music')->withErrors($validator)->withInput();
}
$music = Music::find(Input::get('id'));
$music->title = Input::get('title');
if(!is_null(Input::file('file_name'))){
$mime = Input::file('file_name')->getMimeType();
if($mime !== 'audio/mpeg'){
$error = "You have to input audio MP3 file";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
if(!file_exists($this->upload_path)) {
mkdir($this->upload_path, 0777, true);
}
$file = Input::file('file_name');
if($file->isValid()){
$filename = "subud_".str_random(10);
$extension = $file-><API key>();
$upload_name = $filename.".".$extension;
$upload_success = $file->move($this->upload_path, $upload_name);
if( $upload_success ) {
$music->file_name = $this->upload_path.$upload_name;
} else {
$error = "Failed uploading file";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
$music->save();
}
else {
$error = "Invalid file";
return Redirect::route('admin.music')->withErrors($error)->withInput();
}
}
$music->save();
}
}
return Redirect::route('admin.music');
}
}
|
package org.jabref.logic.importer.fetcher;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.jabref.logic.formatter.bibtexfields.ClearFormatter;
import org.jabref.logic.formatter.bibtexfields.<API key>;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.importer.EntryBasedFetcher;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.IdBasedFetcher;
import org.jabref.logic.importer.<API key>;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLDownload;
import org.jabref.model.cleanup.<API key>;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;
import org.jabref.model.util.<API key>;
import org.jabref.model.util.OptionalUtil;
public class DoiFetcher implements IdBasedFetcher, EntryBasedFetcher {
public static final String NAME = "DOI";
private final <API key> preferences;
public DoiFetcher(<API key> preferences) {
this.preferences = preferences;
}
@Override
public String getName() {
return DoiFetcher.NAME;
}
@Override
public Optional<HelpFile> getHelpPage() {
return Optional.of(HelpFile.FETCHER_DOI);
}
@Override
public Optional<BibEntry> performSearchById(String identifier) throws FetcherException {
Optional<DOI> doi = DOI.parse(identifier);
try {
if (doi.isPresent()) {
URL doiURL = new URL(doi.get().getURIAsASCIIString());
// BibTeX data
URLDownload download = new URLDownload(doiURL);
download.addHeader("Accept", "application/x-bibtex");
String bibtexString = download.asString();
// BibTeX entry
Optional<BibEntry> fetchedEntry = BibtexParser.singleFromString(bibtexString, preferences, new <API key>());
fetchedEntry.ifPresent(this::doPostCleanup);
return fetchedEntry;
} else {
throw new FetcherException(Localization.lang("Invalid DOI: '%0'.", identifier));
}
} catch (IOException e) {
throw new FetcherException(Localization.lang("Connection error"), e);
} catch (ParseException e) {
throw new FetcherException("Could not parse BibTeX entry", e);
}
}
private void doPostCleanup(BibEntry entry) {
new <API key>(StandardField.PAGES, new <API key>()).cleanup(entry);
new <API key>(StandardField.URL, new ClearFormatter()).cleanup(entry);
}
@Override
public List<BibEntry> performSearch(BibEntry entry) throws FetcherException {
Optional<String> doi = entry.getField(StandardField.DOI);
if (doi.isPresent()) {
return OptionalUtil.toList(performSearchById(doi.get()));
} else {
return Collections.emptyList();
}
}
}
|
from __future__ import division, print_function #, unicode_literals
"""
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
import numpy as np
# Setup.
num_max = 1000
basis = [3, 5]
factors = []
for i in range(num_max):
for k in basis:
if not i % k:
factors.append(i)
break
print('\nRange: {:d}'.format(num_max))
print('Number of factors: {:d}'.format(len(factors)))
print('The answer: {:d}'.format(np.sum(factors)))
# Done.
|
<
Microsoft provides programming examples for illustration only, without warranty either expressed or
implied, including, but not limited to, the implied warranties of merchantability and/or fitness
for a particular purpose.
This sample assumes that you are familiar with the programming language being demonstrated and the
tools used to create and debug procedures. Microsoft support professionals can help explain the
functionality of a particular procedure, but they will not modify these examples to provide added
functionality or construct procedures to meet your specific needs. if you have limited programming
experience, you may want to contact a Microsoft Certified Partner or the Microsoft fee-based consulting
line at (800) 936-5200.
HISTORY
08-28-2017 - Created
===========================================================
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
function <API key>
{
<
.SYNOPSIS
This cmdlet will return Site Url, Web Url, Name, Creation Date, Status and IsDefault value for each custom search resource source for
the specificed site collection.
.EXAMPLE
<API key> -Site $site -<API key> $ssa
.FUNCTIONALITY
PowerShell Language
[cmdletbinding()]
[OutputType([object[]])]
param
(
# SPSite to search for custom result sources
[Parameter(Mandatory=$true)][Microsoft.SharePoint.SPSite]$Site,
# <API key> associated with the site collection
[Parameter(Mandatory=$true)][Microsoft.Office.Server.Search.Administration.<API key>]$<API key>
)
begin
{
$siteLevel = [Microsoft.Office.Server.Search.Administration.SearchObjectLevel]::SPSite
$webLevel = [Microsoft.Office.Server.Search.Administration.SearchObjectLevel]::SPWeb
$defaultSource = $null
}
process
{
# we can't read from readlocked sites, so skip them
if (-not $site.IsReadLocked )
{
$owner = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectOwner( $siteLevel, $site.RootWeb )
$filter = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectFilter( $owner )
$filter.IncludeHigherLevel = $false
$federationManager = New-Object Microsoft.Office.Server.Search.Administration.Query.FederationManager($<API key>)
$siteSources = $federationManager.<API key>( $filter, $false, [ref]$defaultSource )
# filter out all built in and non-site level result sources
$siteSources | ? { -not $_.BuiltIn -and $_.Owner.Level -eq $siteLevel } | SELECT @{ Name="SiteUrl"; Expression={ $site.Url}}, @{ Name="WebUrl"; Expression={ $site.Url}}, Name, CreatedDate, @{ Name="Status"; Expression={ if ($_.Active) { return "Active"}else{ return "Inactive"} }}, @{ Name="IsDefault"; Expression={ $_.Id -eq $defaultSource.Id}}
foreach ($web in $site.AllWebs | ? { -not $_.IsAppWeb })
{
$owner = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectOwner( $webLevel, $web )
$filter = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectFilter( $owner )
$filter.IncludeHigherLevel = $false
$federationManager = New-Object Microsoft.Office.Server.Search.Administration.Query.FederationManager($<API key>)
$webSources = $federationManager.<API key>( $filter, $false, [ref]$defaultSource )
# filter out all built in and non-web level result sources
$webSources | ? { -not $_.BuiltIn -and $_.Owner.Level -eq $webLevel } | SELECT @{ Name="SiteUrl"; Expression={ $site.Url}}, @{ Name="WebUrl"; Expression={ $web.Url}}, Name, CreatedDate, @{ Name="Status"; Expression={ if ($_.Active) { return "Active"}else{ return "Inactive"} }}, @{ Name="IsDefault"; Expression={ $_.Id -eq $defaultSource.Id}}
}
}
}
end
{
}
}
# array to store results
$customResultSources = @()
# get the search service
$ssa = <API key> | SELECT -First 1
# get the custom result sources for all sites in the farm
Get-SPSite -Limit All | % { $customResultSources += <API key> -Site $_ -<API key> $ssa }
# save the results to the ULS logs directory in CSV format
$customResultSources | Export-Csv -Path "$($(<API key>).LogLocation)\CustomResultSources$($(Get-Date).ToString('yyyyMMdd')).csv" -NoTypeInformation
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ordinal: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.2 / ordinal - 0.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
ordinal
<small>
0.5.0
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2021-12-09 02:26:46 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-09 02:26:46 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "minki.cho@sf.snu.ac.kr"
synopsis: "Ordinal Numbers in Coq"
homepage: "https://github.com/minkiminki/Ordinal"
dev-repo: "git+https://github.com/minkiminki/Ordinal"
bug-reports: "https://github.com/minkiminki/Ordinal/issues"
authors: [
"Minki Cho <minki.cho@sf.snu.ac.kr>"
]
license: "MIT"
build: [make "-j%{jobs}%"]
install: [make "-f" "Makefile.coq" "install"]
depends: [
"coq" {>= "8.12" & < "8.14~"}
]
tags: [
"date:2021-06-15"
"category:Mathematics/Logic"
"keyword:ordinal number"
"keyword:set theory"
"logpath:Ordinal"
]
url {
http: "https://github.com/minkiminki/Ordinal/archive/refs/tags/v0.5.0.tar.gz"
checksum: "<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-ordinal.0.5.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-ordinal -> coq >= 8.12
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ordinal.0.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.