code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.common.domain;
import br.com.uol.pagseguro.api.common.domain.enums.DocumentType;
/**
* Interface for documents.
*
* @author PagSeguro Internet Ltda.
*/
public interface Document {
/**
* Get Document Type
*
* @return Document Type
* @see DocumentType
*/
DocumentType getType();
/**
* Get Value of document
*
* @return Value of document
*/
String getValue();
}
| Java |
# -*- 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 TabbedDjangoJqueryTranslationAdmin
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 PageHelpTranslationOptions
except ImportError:
pass
__all__ = [
"PageHelpAdmin",
]
class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin 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, PageHelpTranslationOptions)
# registering admin custom classes
admin.site.register(PageHelp, PageHelpAdmin)
| Java |
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 () {
}
}
| Java |
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;
}
}
} | Java |
### 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
| Java |
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 ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
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.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| Java |
# -*- 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())
| Java |
'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;
| Java |
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();
}
}
}
| Java |
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'); } | Java |
{% extends 'layouts/default.html' %}
{% block content %}
That site was not found!
{% endblock %} | Java |
// 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);
}
| Java |
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;
/**
* 用户服务,与dao进行对接
* <p/>
* Created by Jeremie on 2014/9/30.
*/
@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");
}
}
| Java |
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
| Java |
// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
extern crate build;
fn main() {
build::link("urlmon", true)
}
| Java |
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 gameSelectedBackground;
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;
gameSelectedBackground = 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(gameSelectedBackground, 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");
initLoadScreenButtons();
}
private void initGameSelectedScreen()
{
/*Initialize the screen and of the third menu screen (game selected)*/
gameSelectedBackground = ImageLoader.loadImage("/background/load_submenu_background.png");
initGameSelectedButtons();
}
private void initGameSelectedButtons()
{
/*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 initLoadScreenButtons() {
/*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() {
initGameSelectedScreen(); //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;
}
}));
}
}
| Java |
<?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 JWTAlgorithmParameterTest 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);
}
}
| Java |
# frozen_string_literal: 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 error_messages_from_response(response)
JSON.parse(response.body)['errors'].inject([]) { |memo, error| memo << error['message'] }.uniq
end
end
| Java |
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
export function forbiddenNameValidator(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: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective 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 = forbiddenNameValidator(re);
// } else {
// this.valFn = Validators.nullValidator;
// }
}
public validate(control: AbstractControl): {[key: string]: any} {
return this.valFn(control);
}
}
| Java |
namespace TransferCavityLock2012
{
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.setPointIncrementBox = new System.Windows.Forms.TextBox();
this.GainTextbox = new System.Windows.Forms.TextBox();
this.VoltageToLaserTextBox = new System.Windows.Forms.TextBox();
this.setPointAdjustMinusButton = new System.Windows.Forms.Button();
this.setPointAdjustPlusButton = new System.Windows.Forms.Button();
this.LaserSetPointTextBox = 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.SlaveLaserIntensityScatterGraph = 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.SlaveLaserIntensityScatterGraph)).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.setPointIncrementBox);
this.lockParams.Controls.Add(this.GainTextbox);
this.lockParams.Controls.Add(this.VoltageToLaserTextBox);
this.lockParams.Controls.Add(this.setPointAdjustMinusButton);
this.lockParams.Controls.Add(this.setPointAdjustPlusButton);
this.lockParams.Controls.Add(this.LaserSetPointTextBox);
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";
//
// setPointIncrementBox
//
this.setPointIncrementBox.Location = new System.Drawing.Point(168, 63);
this.setPointIncrementBox.Name = "setPointIncrementBox";
this.setPointIncrementBox.Size = new System.Drawing.Size(55, 20);
this.setPointIncrementBox.TabIndex = 32;
this.setPointIncrementBox.Text = "0.01";
this.setPointIncrementBox.TextChanged += new System.EventHandler(this.setPointIncrementBox_TextChanged);
//
// 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);
//
// VoltageToLaserTextBox
//
this.VoltageToLaserTextBox.Location = new System.Drawing.Point(167, 89);
this.VoltageToLaserTextBox.Name = "VoltageToLaserTextBox";
this.VoltageToLaserTextBox.Size = new System.Drawing.Size(100, 20);
this.VoltageToLaserTextBox.TabIndex = 30;
this.VoltageToLaserTextBox.Text = "0";
this.VoltageToLaserTextBox.TextChanged += new System.EventHandler(this.VoltageToLaserChanged);
//
// setPointAdjustMinusButton
//
this.setPointAdjustMinusButton.Location = new System.Drawing.Point(124, 37);
this.setPointAdjustMinusButton.Name = "setPointAdjustMinusButton";
this.setPointAdjustMinusButton.Size = new System.Drawing.Size(37, 23);
this.setPointAdjustMinusButton.TabIndex = 29;
this.setPointAdjustMinusButton.Text = "-";
this.setPointAdjustMinusButton.UseVisualStyleBackColor = true;
this.setPointAdjustMinusButton.Click += new System.EventHandler(this.setPointAdjustMinusButton_Click);
//
// setPointAdjustPlusButton
//
this.setPointAdjustPlusButton.Location = new System.Drawing.Point(81, 37);
this.setPointAdjustPlusButton.Name = "setPointAdjustPlusButton";
this.setPointAdjustPlusButton.Size = new System.Drawing.Size(37, 23);
this.setPointAdjustPlusButton.TabIndex = 28;
this.setPointAdjustPlusButton.Text = "+";
this.setPointAdjustPlusButton.UseVisualStyleBackColor = true;
this.setPointAdjustPlusButton.Click += new System.EventHandler(this.setPointAdjustPlusButton_Click);
//
// LaserSetPointTextBox
//
this.LaserSetPointTextBox.AcceptsReturn = true;
this.LaserSetPointTextBox.Location = new System.Drawing.Point(167, 39);
this.LaserSetPointTextBox.Name = "LaserSetPointTextBox";
this.LaserSetPointTextBox.Size = new System.Drawing.Size(57, 20);
this.LaserSetPointTextBox.TabIndex = 27;
this.LaserSetPointTextBox.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.UseVisualStyleBackColor = true;
this.lockEnableCheck.CheckedChanged += new System.EventHandler(this.lockEnableCheck_CheckedChanged);
//
// 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):";
//
// SlaveLaserIntensityScatterGraph
//
this.SlaveLaserIntensityScatterGraph.Location = new System.Drawing.Point(9, 17);
this.SlaveLaserIntensityScatterGraph.Name = "SlaveLaserIntensityScatterGraph";
this.SlaveLaserIntensityScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] {
this.SlaveDataPlot,
this.SlaveFitPlot});
this.SlaveLaserIntensityScatterGraph.Size = new System.Drawing.Size(567, 132);
this.SlaveLaserIntensityScatterGraph.TabIndex = 12;
this.SlaveLaserIntensityScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] {
this.xAxis1});
this.SlaveLaserIntensityScatterGraph.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.SlaveLaserIntensityScatterGraph);
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.UseVisualStyleBackColor = true;
this.slErrorResetButton.Click += new System.EventHandler(this.slErrorResetButton_Click);
//
// 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.VoltageTrackBar_Scroll);
//
// 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.SlaveLaserIntensityScatterGraph)).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 setPointIncrementBox;
private System.Windows.Forms.TextBox GainTextbox;
private System.Windows.Forms.TextBox VoltageToLaserTextBox;
private System.Windows.Forms.Button setPointAdjustMinusButton;
private System.Windows.Forms.Button setPointAdjustPlusButton;
private System.Windows.Forms.TextBox LaserSetPointTextBox;
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 SlaveLaserIntensityScatterGraph;
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;
}
}
| Java |
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 BasicInfrastructureWeb.DependencyResolution;
using IoC = LiveScore.App_Start.IoC;
namespace LiveScore
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ControllerConvention.Register(IoC.Initialize());
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
| Java |
#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();
}
};
| Java |
/**
* Wheel, copyright (c) 2017 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
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
]
);
}
);
| Java |
<!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=c62a434ed2d771d0d1814d0877d9a147"
"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://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
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')
| Java |
<?php namespace Fisharebest\Localization\Locale;
use Fisharebest\Localization\Territory\TerritoryNi;
/**
* Class LocaleEsNi
*
* @author Greg Roach <fisharebest@gmail.com>
* @copyright (c) 2015 Greg Roach
* @license GPLv3+
*/
class LocaleEsNi extends LocaleEs {
public function territory() {
return new TerritoryNi;
}
}
| Java |
use internal;
#[repr(C)]
#[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,
}
}
}
| Java |
<!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=7389fc52776af64717fc6b4550066aa8"
}
</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/bignums_syntax_plugin.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/bignums_syntax_plugin.cmi</code></li>
<li>8 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.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/bignums_syntax_plugin.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://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
require 'builder'
module MWS
module API
class Fulfillment < Base
include Feeds
## Takes an array of hash AmazonOrderID,FulfillmentDate,CarrierName,ShipperTrackingNumber,sku,quantity
## Returns true if all the orders were updated successfully
## Otherwise raises an exception
def post_ship_confirmation(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://www.w3.org/2001/XMLSchema-instance", :"xsi:noNamespaceSchemaLocation" => "amzn-envelope.xsd") do |env|
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.ShipperTrackingNumber(shp.ShipperTrackingNumber)
end
if shp.sku != ''
orf.Item do |itm|
itm.MerchantOrderItemID(shp.sku)
itm.MerchantFulfillmentItemID(shp.sku)
itm.Quantity(shp.quantity)
end
end
end
end
end
end
submit_feed('_POST_ORDER_FULFILLMENT_DATA_', xml)
end
end
end
end | Java |
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 { }
| Java |
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.PsiRecursiveElementWalkingVisitor;
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.StringLiteralExpression;
import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil;
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 PsiParameterStorageRunnable implements Runnable {
private final Project project;
private final VirtualFile virtualFile;
private final Map<String, Collection<String>> events;
private final Set<String> configs;
public PsiParameterStorageRunnable(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 MyPsiRecursiveElementWalkingVisitor());
}
}
private class MyPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor {
@Override
public void visitElement(PsiElement element) {
if (element instanceof MethodReference) {
visitMethodReference((MethodReference) element);
}
super.visitElement(element);
}
private void visitMethodReference(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 StringLiteralExpression) {
PsiElement method = methodReference.resolve();
if(method instanceof Method) {
PhpClass phpClass = ((Method) method).getContainingClass();
if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Enlight_Event_EventManager")) {
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 StringLiteralExpression) {
PsiElement method = methodReference.resolve();
if(method instanceof Method) {
PhpClass phpClass = ((Method) method).getContainingClass();
if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Shopware\\Models\\Config\\Form")) {
String content = ((StringLiteralExpression) parameters[1]).getContents();
if(StringUtils.isNotBlank(content)) {
configs.add(content);
}
}
}
}
}
}
}
}
}
| Java |
/********************************************************************************
* The MIT License (MIT) *
* *
* Copyright (C) 2016 Alex Nolasco *
* *
*Permission is hereby granted, free of charge, to any person obtaining a copy *
*of this software and associated documentation files (the "Software"), to deal *
*in the Software without restriction, including without limitation the rights *
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
*copies of the Software, and to permit persons to whom the Software is *
*furnished to do so, subject to the following conditions: *
*The above copyright notice and this permission notice shall be included in *
*all copies or substantial portions of the Software. *
* *
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
*THE SOFTWARE. *
*********************************************************************************/
#import <Foundation/Foundation.h>
#import "HL7SummaryProtocol.h"
@class HL7PatientSummary;
@class HL7ClinicalDocumentSummary;
typedef NSDictionary<NSString *, id<HL7SummaryProtocol>> NSDictionaryTemplateIdToSummary;
@interface HL7CCDSummary : NSObject <NSCopying, NSCoding>
- (HL7ClinicalDocumentSummary *_Nullable)document;
- (HL7PatientSummary *_Nullable)patient;
- (NSDictionaryTemplateIdToSummary *_Nullable)summaries;
- (id<HL7SummaryProtocol> _Nullable)getSummaryByClass:(Class _Nonnull)className;
@end
| Java |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('geokey_sapelli', '0005_sapellifield_truefalse'),
]
operations = [
migrations.AddField(
model_name='sapelliproject',
name='sapelli_fingerprint',
field=models.IntegerField(default=-1),
preserve_default=False,
),
]
| Java |
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);
}
}
}
| Java |
# lsyncd
Docker image allowing you to use lsyncd as a docker command
## Usage
```
docker run -d -v /docker/lsyncd/src:/src -v /docker/lsyncd/target:/target -v /docker/lsyncd/lrsync.lua:/etc/lrsync/lrsync.lua zeroboh/lsyncd:2.1-alpine
```
| Java |
#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
| Java |
<!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> | Java |
<!DOCTYPE html>
<html class="no-js" lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.">
<title tabindex="1">examples | p5.js</title>
<link rel="stylesheet" href="/assets/css/all.css?v=db3be6">
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inconsolata&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="/../../assets/img/favicon.ico">
<link rel="icon" href="/../../assets/img/favicon.ico">
<script src="/../../assets/js/vendor/jquery-1.12.4.min.js"></script>
<script src="/../../assets/js/vendor/ace-nc/ace.js"></script>
<script src="/../../assets/js/vendor/ace-nc/mode-javascript.js"></script>
<script src="/../../assets/js/vendor/prism.js"></script>
<script src="/assets/js/init.js?v=af215d"></script>
</head>
<body>
<a href="#content" class="sr-only">Ir al contenido</a>
<!-- p5*js language buttons -->
<div id="i18n-btn">
<h2 id="i18n-settings" class="sr-only">Preferencias de idioma</h2>
<ul id="i18n-buttons" aria-labelledby="i18n-settings">
<li><a href='#' lang='en' data-lang='en'>English</a></li>
<li><a href='#' lang='es' data-lang='es'>Español</a></li>
<li><a href='#' lang='zh-Hans' data-lang='zh-Hans'>简体中文</a></li>
<li><a href='#' lang='ko' data-lang='ko'>한국어</a></li>
</ul>
</div> <!-- .container -->
<div class="container">
<!-- logo -->
<header id="lockup">
<a href="/es/">
<img src="/../../assets/img/p5js.svg" alt="p5 homepage" id="logo_image" class="logo" />
<div id="p5_logo"></div>
</a>
</header>
<!-- close logo -->
<div id="examples-page">
<!-- site navigation -->
<div class="column-span">
<nav class="sidebar-menu-nav-element">
<h2 id="menu-title" class="sr-only">Navegación del sitio</h2>
<input class="sidebar-menu-btn" type="checkbox" id="sidebar-menu-btn" />
<label class="sidebar-menu-icon" for="sidebar-menu-btn"><span class="sidebar-nav-icon"></span></label>
<ul id="menu" class="sidebar-menu" aria-labelledby="menu-title">
<li><a href="/es/">Inicio</a></li>
<li><a href="https://editor.p5js.org">Editor</a></li>
<li><a href="/es/download/">Descargar</a></li>
<li><a href="/es/download/support.html">Donar</a></li>
<li><a href="/es/get-started/">Empezar</a></li>
<li><a href="/es/reference/">Referencia</a></li>
<li><a href="/es/libraries/">Bibliotecas</a></li>
<li><a href="/es/learn/">Aprender</a></li>
<li><a href="/es/examples/">Ejemplos</a></li>
<li><a href="/es/books/">Libros</a></li>
<li><a href="/es/community/">Comunidad</a></li>
<li><a href="https://showcase.p5js.org">Showcase</a></li>
<li><a href="https://discourse.processing.org/c/p5js" target=_blank class="other-link">Foro</a></li>
<li><a href="http://github.com/processing/p5.js" target=_blank class="other-link">GitHub</a></li>
<li><a href="http://twitter.com/p5xjs" target=_blank class="other-link">Twitter</a></li>
</ul>
</nav>
</div>
<div class="column-span">
<main id="content" >
<p id="backlink"><a href="./">< Volver a Ejemplos</a></p>
<h1 id='example-name'>example name placeholder</h1>
<p id='example-desc'>example description placeholder</p>
<div id="exampleDisplay">
<div class="edit_space">
<button id="toggleTextOutput" class="sr-only">toggle text output</button>
<button id="runButton" class="edit_button">run</button>
<button id="resetButton" class="reset_button">reset</button>
<button id="copyButton" class="copy_button">copy</button>
</div>
<div id="exampleEditor"></div>
<iframe id="exampleFrame" src="../../assets/examples/example.html" ></iframe>
</div>
<p><a style="border-bottom:none !important;" href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target=_blank><img src="https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png" alt="creative commons license" style="width:88px"/></a></p>
</main>
<footer>
<h2 class="sr-only">Créditos</h2>
<p> p5.js actualmente está dirigido por <a href='https://github.com/mcturner1995' target="_blank">Moira
Turner</a>y fue creado por<a href='http://lauren-mccarthy.com' target="_blank">Lauren
McCarthy</a> p5.js es desarrollado por una comunidad de colaboradores, con apoyo de <a href="http://processing.org/foundation/" target="_blank">Processing
Foundation</a> y
<a href="http://itp.nyu.edu/itp/" target="_blank">NYU ITP</a>. Identidad y diseño gráfico por <a
href="http://jereljohnson.com/" target="_blank">Jerel Johnson</a>. <a href="/es/copyright.html">©
Info.</a></p>
</footer>
</div> <!-- end column-span -->
<!-- outside of column for footer to go across both -->
<p class="clearfix"> </p>
<object type="image/svg+xml" data="../../assets/img/thick-asterisk-alone.svg" id="asterisk-design-element" aria-hidden="true">
</object>
<!-- <script src="../../assets/js/vendor/ace-nc/ace.js"></script>
<script src="../../assets/js/examples.js"></script> -->
<script>
window._p5jsExample = '../../assets/examples/es/09_Simulate/05_MultipleParticleSystems.js';
window.addEventListener('load', function() {
// examples.init('../../assets/examples/es/09_Simulate/05_MultipleParticleSystems.js');
if (false) {
var isMobile = window.matchMedia("only screen and (max-width: 767px)");
// isMobile is true if viewport is less than 768 pixels wide
document.getElementById('exampleFrame').style.display = 'none';
if (isMobile.matches) {
document.getElementById('notMobile-message').style.display = 'none';
document.getElementById('isMobile-displayButton').style.display = 'block';
} else {
document.getElementById('notMobile-message').style.display = 'block';
document.getElementById('isMobile-displayButton').style.display = 'none';
document.getElementById('runButton').style.display = 'none';
document.getElementById('resetButton').style.display = 'none';
document.getElementById('copyButton').style.display = 'none';
}
}
}, true);
</script>
</div><!-- end id="get-started-page" -->
<script src="/../../assets/js/examples.js"></script>
</div> <!-- close class='container'-->
<nav id="family" aria-labelledby="processing-sites-heading">
<h2 id="processing-sites-heading" class="sr-only">Processing Sister Sites</h2>
<ul id="processing-sites" aria-labelledby="processing-sites-heading">
<li><a href="http://processing.org">Processing</a></li>
<li><a class="here" href="/es/">p5.js</a></li>
<li><a href="http://py.processing.org/">Processing.py</a></li>
<li><a href="http://android.processing.org/">Processing for Android</a></li>
<li><a href="http://pi.processing.org/">Processing for Pi</a></li>
<li><a href="https://processingfoundation.org/">Processing Foundation</a></li>
</ul>
<a tabindex="1" href="#content" id="skip-to-content">Skip to main content</a>
<!-- <a id="promo-link" href="https://donorbox.org/supportpf2019-fundraising-campaign" target="_blank"><div id="promo">This season, we need your help! Click here to #SupportP5!</div></a> -->
</nav> <script>
var langs = ["en","es","ko","zh-Hans"];
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-53383000-1', 'auto');
ga('send', 'pageview');
$(window).ready(function() {
if (window.location.pathname !== '/' && window.location.pathname !== '/index.html') {
$('#top').remove();
} else {
$('#top').show();
}
});
</script>
</body>
</html>
| Java |
---
layout: tagpage
tag: quartz
--- | Java |
#!/usr/bin/env bats
## tests with https://github.com/sstephenson/bats
die() {
echo "$@" >/dev/stderr
exit 1
}
export DOCKHACK_SKIP_UID_CHECK=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 ]
# can't distinguish between stdout/err yet https://github.com/sstephenson/bats/pull/55
[[ "$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
}
| Java |
<?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->getClientOriginalExtension();
$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->getClientOriginalExtension();
$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');
}
} | Java |
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.NormalizePagesFormatter;
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.ImportFormatPreferences;
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.FieldFormatterCleanup;
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.DummyFileUpdateMonitor;
import org.jabref.model.util.OptionalUtil;
public class DoiFetcher implements IdBasedFetcher, EntryBasedFetcher {
public static final String NAME = "DOI";
private final ImportFormatPreferences preferences;
public DoiFetcher(ImportFormatPreferences 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 DummyFileUpdateMonitor());
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 FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry);
new FieldFormatterCleanup(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();
}
}
}
| Java |
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.
| Java |
<#
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 Get-CustomResultSource
{
<#
.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
Get-CustomResultSource -Site $site -SearchServiceApplication $ssa
.FUNCTIONALITY
PowerShell Language
#>
[cmdletbinding()]
[OutputType([object[]])]
param
(
# SPSite to search for custom result sources
[Parameter(Mandatory=$true)][Microsoft.SharePoint.SPSite]$Site,
# SearchServiceApplication associated with the site collection
[Parameter(Mandatory=$true)][Microsoft.Office.Server.Search.Administration.SearchServiceApplication]$SearchServiceApplication
)
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($SearchServiceApplication)
$siteSources = $federationManager.ListSourcesWithDefault( $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($SearchServiceApplication)
$webSources = $federationManager.ListSourcesWithDefault( $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 = Get-SPEnterpriseSearchServiceApplication | SELECT -First 1
# get the custom result sources for all sites in the farm
Get-SPSite -Limit All | % { $customResultSources += Get-CustomResultSource -Site $_ -SearchServiceApplication $ssa }
# save the results to the ULS logs directory in CSV format
$customResultSources | Export-Csv -Path "$($(Get-SPDiagnosticConfig).LogLocation)\CustomResultSources$($(Get-Date).ToString('yyyyMMdd')).csv" -NoTypeInformation
| Java |
<!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: "2fcc5d5a6ba96850341e13f16430b255"
}
</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://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:deletion)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :deletion
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end | Java |
s="the quick brown fox jumped over the lazy dog"
t = s.split(" ")
for v in t:
print(v)
r = s.split("e")
for v in r:
print(v)
x = s.split()
for v in x:
print(v)
# 2-arg version of split not supported
# y = s.split(" ",7)
# for v in y:
# print v
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Zefu Li</title>
<link rel="stylesheet" type="text/css" href="official.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="official.js"></script>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<header class="header">
<div id="home"><a href="home"></a>Home</div>
<div id="text">Hi, I am Zefu Li</marquee></div>
<img class="human"src="http://www.newdesignfile.com/postpic/2016/04/human-head-silhouette-vector_396827.png" width="600px" height="600px">
<div class="wifi"><i class="fa fa-feed" aria-hidden="true"></i></div>
<div class="questionmark"><i class="fa fa-question" aria-hidden="true"></i></div>
<div class="exclamationmark"><i class="fa fa-exclamation" aria-hidden="true"></i></div>
</header>
<div id="about"><a href="about"></a>About
<p>I am currently a senior at Oakland Charter High School. I am passionate about technology especially when it comes to computer science, I also like to solve problems and I will keep thinking about the solutions unless I solved them, I guess I am a little stubborn. Information Technology has started a significant revolution and influenced the world over a decade, therefore I decided to pursue a computer science degree. Technology will keep changing the world and moving us forward, that’s what I believe and I am so glad that I am part of the next generation of tech talent. </p></div>
<div id="blog"><a href="blog"></a>Blog
<h1>My Journey In dev/Mission</h1>
<h2>Coming Soon</h2>
</div>
<div id="contact"><a href="contact"></a>Contact
<a id="Linkedin" href="https://www.linkedin.com/in/zefu-li-23866b140/"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/LinkedIn_logo_initials.png/768px-LinkedIn_logo_initials.png" height="30" width="30"></a>
<a id="github" href="https://github.com/seriouswork/seriouswork.github.io"><img src="https://image.flaticon.com/icons/svg/25/25231.svg" height="30" width="30"></a>
</div>
</body>
</html>
| Java |
module Xronor
class DSL
module Checker
class ValidationError < StandardError
end
def required(name, value)
invalid = false
if value
case value
when String
invalid = value.strip.empty?
when Array, Hash
invalid = value.empty?
end
else
invalid = true
end
raise ValidationError.new("'#{name}' is required") if invalid
end
end
end
end
| Java |
var mongoose = require('mongoose');
var statuses = ['open', 'closed', 'as_expected'];
var priorities = ['major','regular','minor','enhancement'];
var Comment = new mongoose.Schema(
{
comment: String,
username: String,
name: String,
dca: {type: Date, default: Date.now}
}
);
var Bug = new mongoose.Schema(
{
id: {type: String},
name: {type: String, required: true},
desc: String,
status: {type: String, default: 'open'},
priority: {type: String, default: 'regular'},
username: { type: String, required: true},
reported_by: {type: String},
company: {type: String, required: true},
comments: [Comment],
dca: {type: Date, default: Date.now},
dua: Date
}
);
Bug.pre('save', function(next) {
if (this.id === undefined) {
this.id = (new Date()).getTime().toString();
}
now = new Date();
this.dua = now;
next();
});
module.exports = mongoose.model('Bug', Bug);
| Java |
#include "EngineImplDefine.h"
void BlendColor::Init(D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOLOR hiddenColor)
{
for (decltype(States.size()) i = 0; i != States.size(); ++i)
{
States[i] = defaultColor;
}
States[STATE_DISABLED] = disabledColor;
States[STATE_HIDDEN] = hiddenColor;
Current = hiddenColor;
}
void BlendColor::Blend(CONTROL_STATE iState, float fElapsedTime, float fRate)
{
D3DXCOLOR destColor = States[iState];
D3DXColorLerp(&Current, &Current, &destColor, 1.0f - powf(fRate, 30 * fElapsedTime));
}
void FontTexElement::SetTexture(UINT iTexture, RECT * prcTexture, D3DCOLOR defaultTextureColor)
{
this->iTexture = iTexture;
if (prcTexture)
rcTexture = *prcTexture;
else
SetRectEmpty(&rcTexture);
TextureColor.Init(defaultTextureColor);
}
void FontTexElement::SetFont(UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextFormat)
{
this->iFont = iFont;
this->dwTextFormat = dwTextFormat;
FontColor.Init(defaultFontColor);
}
void FontTexElement::Refresh()
{
TextureColor.Current = TextureColor.States[STATE_HIDDEN];
FontColor.Current = FontColor.States[STATE_HIDDEN];
} | Java |
class AddColumnToRequestSchema < ActiveRecord::Migration
def change
add_column :request_schemata, :name, :string, null: false, default: ""
end
end
| Java |
ActionController::Routing::Routes.draw do |map|
map.resources :companies,
:member => {
:filter_available_members => :get, :delete_member => :post, :add_members => :post,
:filter_available_projects => :get, :delete_project => :post, :add_projects => :post
}
end
| Java |
//
// ViewController.h
// MKDevice
//
// Created by Michal Konturek on 18/11/2013.
// Copyright (c) 2013 Michal Konturek. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIButton *button;
- (IBAction)onAction:(id)sender;
@end
| Java |
class AddVersionToComponents < ActiveRecord::Migration
def change
add_column :components, :version, :float
end
end
| Java |
package is.hail.expr.ir.functions
import is.hail.annotations.{Region, StagedRegionValueBuilder}
import is.hail.asm4s
import is.hail.asm4s._
import is.hail.expr.ir._
import is.hail.types.physical._
import is.hail.types.virtual._
import is.hail.utils._
import java.util.Locale
import java.time.{Instant, ZoneId}
import java.time.temporal.ChronoField
import is.hail.expr.JSONAnnotationImpex
import org.apache.spark.sql.Row
import org.json4s.JValue
import org.json4s.jackson.JsonMethods
import scala.collection.mutable
object StringFunctions extends RegistryFunctions {
def reverse(s: String): String = {
val sb = new StringBuilder
sb.append(s)
sb.reverseContents().result()
}
def upper(s: String): String = s.toUpperCase
def lower(s: String): String = s.toLowerCase
def strip(s: String): String = s.trim()
def contains(s: String, t: String): Boolean = s.contains(t)
def startswith(s: String, t: String): Boolean = s.startsWith(t)
def endswith(s: String, t: String): Boolean = s.endsWith(t)
def firstMatchIn(s: String, regex: String): IndexedSeq[String] = {
regex.r.findFirstMatchIn(s).map(_.subgroups.toArray.toFastIndexedSeq).orNull
}
def regexMatch(regex: String, s: String): Boolean = regex.r.findFirstIn(s).isDefined
def concat(s: String, t: String): String = s + t
def replace(str: String, pattern1: String, pattern2: String): String =
str.replaceAll(pattern1, pattern2)
def split(s: String, p: String): IndexedSeq[String] = s.split(p, -1)
def translate(s: String, d: Map[String, String]): String = {
val charD = new mutable.HashMap[Char, String]
d.foreach { case (k, v) =>
if (k.length != 1)
fatal(s"translate: mapping keys must be one character, found '$k'")
charD += ((k(0), v))
}
val sb = new StringBuilder
var i = 0
while (i < s.length) {
val charI = s(i)
charD.get(charI) match {
case Some(replacement) => sb.append(replacement)
case None => sb.append(charI)
}
i += 1
}
sb.result()
}
def splitLimited(s: String, p: String, n: Int): IndexedSeq[String] = s.split(p, n)
def arrayMkString(a: IndexedSeq[String], sep: String): String = a.mkString(sep)
def setMkString(s: Set[String], sep: String): String = s.mkString(sep)
def escapeString(s: String): String = StringEscapeUtils.escapeString(s)
def softBounds(i: IR, len: IR): IR =
If(i < -len, 0, If(i < 0, i + len, If(i >= len, len, i)))
private val locale: Locale = Locale.US
def strftime(fmtStr: String, epochSeconds: Long, zoneId: String): String =
DateFormatUtils.parseDateFormat(fmtStr, locale).withZone(ZoneId.of(zoneId))
.format(Instant.ofEpochSecond(epochSeconds))
def strptime(timeStr: String, fmtStr: String, zoneId: String): Long =
DateFormatUtils.parseDateFormat(fmtStr, locale).withZone(ZoneId.of(zoneId))
.parse(timeStr)
.getLong(ChronoField.INSTANT_SECONDS)
def registerAll(): Unit = {
val thisClass = getClass
registerPCode1("length", TString, TInt32, (_: Type, _: PType) => PInt32()) { case (r: EmitRegion, cb, rt, s: PStringCode) =>
PCode(rt, s.loadString().invoke[Int]("length"))
}
registerCode3("substring", TString, TInt32, TInt32, TString, {
(_: Type, _: PType, _: PType, _: PType) => PCanonicalString()
}) {
case (r: EmitRegion, rt, (sT: PString, s: Code[Long]), (startT, start: Code[Int]), (endT, end: Code[Int])) =>
unwrapReturn(r, rt)(asm4s.coerce[String](wrapArg(r, sT)(s)).invoke[Int, Int, String]("substring", start, end))
}
registerIR3("slice", TString, TInt32, TInt32, TString) { (_, str, start, end) =>
val len = Ref(genUID(), TInt32)
val s = Ref(genUID(), TInt32)
val e = Ref(genUID(), TInt32)
Let(len.name, invoke("length", TInt32, str),
Let(s.name, softBounds(start, len),
Let(e.name, softBounds(end, len),
invoke("substring", TString, str, s, If(e < s, s, e)))))
}
registerIR2("index", TString, TInt32, TString) { (_, s, i) =>
val len = Ref(genUID(), TInt32)
val idx = Ref(genUID(), TInt32)
Let(len.name, invoke("length", TInt32, s),
Let(idx.name,
If((i < -len) || (i >= len),
Die(invoke("concat", TString,
Str("string index out of bounds: "),
invoke("concat", TString,
invoke("str", TString, i),
invoke("concat", TString, Str(" / "), invoke("str", TString, len)))), TInt32, -1),
If(i < 0, i + len, i)),
invoke("substring", TString, s, idx, idx + 1)))
}
registerIR2("sliceRight", TString, TInt32, TString) { (_, s, start) => invoke("slice", TString, s, start, invoke("length", TInt32, s)) }
registerIR2("sliceLeft", TString, TInt32, TString) { (_, s, end) => invoke("slice", TString, s, I32(0), end) }
registerCode1("str", tv("T"), TString, (_: Type, _: PType) => PCanonicalString()) { case (r, rt, (aT, a)) =>
val annotation = boxArg(r, aT)(a)
val str = r.mb.getType(aT.virtualType).invoke[Any, String]("str", annotation)
unwrapReturn(r, rt)(str)
}
registerEmitCode1("showStr", tv("T"), TString, {
(_: Type, _: PType) => PCanonicalString(true)
}) { case (r, rt, a) =>
val annotation = Code(a.setup, a.m).muxAny(Code._null(boxedTypeInfo(a.pt)), boxArg(r, a.pt)(a.v))
val str = r.mb.getType(a.pt.virtualType).invoke[Any, String]("showStr", annotation)
EmitCode.present(PCode(rt, unwrapReturn(r, rt)(str)))
}
registerEmitCode2("showStr", tv("T"), TInt32, TString, {
(_: Type, _: PType, truncType: PType) => PCanonicalString(truncType.required)
}) { case (r, rt, a, trunc) =>
val annotation = Code(a.setup, a.m).muxAny(Code._null(boxedTypeInfo(a.pt)), boxArg(r, a.pt)(a.v))
val str = r.mb.getType(a.pt.virtualType).invoke[Any, Int, String]("showStr", annotation, trunc.value[Int])
EmitCode(trunc.setup, trunc.m, PCode(rt, unwrapReturn(r, rt)(str)))
}
registerEmitCode1("json", tv("T"), TString, (_: Type, _: PType) => PCanonicalString(true)) { case (r, rt, a) =>
val bti = boxedTypeInfo(a.pt)
val annotation = Code(a.setup, a.m).muxAny(Code._null(bti), boxArg(r, a.pt)(a.v))
val json = r.mb.getType(a.pt.virtualType).invoke[Any, JValue]("toJSON", annotation)
val str = Code.invokeScalaObject1[JValue, String](JsonMethods.getClass, "compact", json)
EmitCode(Code._empty, false, PCode(rt, unwrapReturn(r, rt)(str)))
}
registerWrappedScalaFunction1("reverse", TString, TString, (_: Type, _: PType) => PCanonicalString())(thisClass,"reverse")
registerWrappedScalaFunction1("upper", TString, TString, (_: Type, _: PType) => PCanonicalString())(thisClass,"upper")
registerWrappedScalaFunction1("lower", TString, TString, (_: Type, _: PType) => PCanonicalString())(thisClass,"lower")
registerWrappedScalaFunction1("strip", TString, TString, (_: Type, _: PType) => PCanonicalString())(thisClass,"strip")
registerWrappedScalaFunction2("contains", TString, TString, TBoolean, {
case (_: Type, _: PType, _: PType) => PBoolean()
})(thisClass, "contains")
registerWrappedScalaFunction2("translate", TString, TDict(TString, TString), TString, {
case (_: Type, _: PType, _: PType) => PCanonicalString()
})(thisClass, "translate")
registerWrappedScalaFunction2("startswith", TString, TString, TBoolean, {
case (_: Type, _: PType, _: PType) => PBoolean()
})(thisClass, "startswith")
registerWrappedScalaFunction2("endswith", TString, TString, TBoolean, {
case (_: Type, _: PType, _: PType) => PBoolean()
})(thisClass, "endswith")
registerWrappedScalaFunction2("regexMatch", TString, TString, TBoolean, {
case (_: Type, _: PType, _: PType) => PBoolean()
})(thisClass, "regexMatch")
registerWrappedScalaFunction2("concat", TString, TString, TString, {
case (_: Type, _: PType, _: PType) => PCanonicalString()
})(thisClass, "concat")
registerWrappedScalaFunction2("split", TString, TString, TArray(TString), {
case (_: Type, _: PType, _: PType) =>
PCanonicalArray(PCanonicalString(true))
})(thisClass, "split")
registerWrappedScalaFunction3("split", TString, TString, TInt32, TArray(TString), {
case (_: Type, _: PType, _: PType, _: PType) =>
PCanonicalArray(PCanonicalString(true))
})(thisClass, "splitLimited")
registerWrappedScalaFunction3("replace", TString, TString, TString, TString, {
case (_: Type, _: PType, _: PType, _: PType) => PCanonicalString()
})(thisClass, "replace")
registerWrappedScalaFunction2("mkString", TSet(TString), TString, TString, {
case (_: Type, _: PType, _: PType) => PCanonicalString()
})(thisClass, "setMkString")
registerWrappedScalaFunction2("mkString", TArray(TString), TString, TString, {
case (_: Type, _: PType, _: PType) => PCanonicalString()
})(thisClass, "arrayMkString")
registerIEmitCode2("firstMatchIn", TString, TString, TArray(TString), {
case(_: Type, _: PType, _: PType) => PCanonicalArray(PCanonicalString(true))
}) { case (cb: EmitCodeBuilder, region: Value[Region], rt: PArray,
s: (() => IEmitCode), r: (() => IEmitCode)) =>
s().flatMap(cb) { case sc: PStringCode =>
r().flatMap(cb) { case rc: PStringCode =>
val out = cb.newLocal[IndexedSeq[String]]("out",
Code.invokeScalaObject2[String, String, IndexedSeq[String]](
thisClass, "firstMatchIn", sc.loadString(), rc.loadString()))
IEmitCode(cb, out.isNull, {
val len = cb.newLocal[Int]("len", out.invoke[Int]("size"))
val srvb: StagedRegionValueBuilder = new StagedRegionValueBuilder(cb.emb, rt, region)
val elt = cb.newLocal[String]("elt")
val value = Code(
srvb.start(len),
Code.whileLoop(srvb.arrayIdx < len,
elt := out.invoke[Int, String]("apply", srvb.arrayIdx),
elt.ifNull(
srvb.setMissing(),
srvb.addString(elt)),
srvb.advance()),
srvb.end())
PCode(rt, value)
})
}
}
}
registerEmitCode2("hamming", TString, TString, TInt32, {
case(_: Type, _: PType, _: PType) => PInt32()
}) { case (r: EmitRegion, rt, e1: EmitCode, e2: EmitCode) =>
EmitCode.fromI(r.mb) { cb =>
e1.toI(cb).flatMap(cb) { case (sc1: PStringCode) =>
e2.toI(cb).flatMap(cb) { case (sc2: PStringCode) =>
val n = cb.newLocal("hamming_n", 0)
val i = cb.newLocal("hamming_i", 0)
val v1 = sc1.asBytes().memoize(cb, "hamming_bytes_1")
val v2 = sc2.asBytes().memoize(cb, "hamming_bytes_2")
val m = v1.loadLength().cne(v2.loadLength())
IEmitCode(cb, m, {
cb.whileLoop(i < v1.loadLength(), {
cb.ifx(v1.loadByte(i).cne(v2.loadByte(i)),
cb.assign(n, n + 1))
cb.assign(i, i + 1)
})
PCode(rt, n)
})
}
}
}
}
registerWrappedScalaFunction1("escapeString", TString, TString, (_: Type, _: PType) => PCanonicalString())(thisClass, "escapeString")
registerWrappedScalaFunction3("strftime", TString, TInt64, TString, TString, {
case(_: Type, _: PType, _: PType, _: PType) => PCanonicalString()
})(thisClass, "strftime")
registerWrappedScalaFunction3("strptime", TString, TString, TString, TInt64, {
case (_: Type, _: PType, _: PType, _: PType) => PInt64()
})(thisClass, "strptime")
registerPCode("parse_json", Array(TString), TTuple(tv("T")),
(rType: Type, _: Seq[PType]) => PType.canonical(rType, true), typeParameters = Array(tv("T"))) { case (er, cb, resultType, Array(s: PStringCode)) =>
PCode(resultType, StringFunctions.unwrapReturn(er, resultType)(
Code.invokeScalaObject2[String, Type, Row](JSONAnnotationImpex.getClass, "irImportAnnotation",
s.loadString(), er.mb.ecb.getType(resultType.virtualType.asInstanceOf[TTuple].types(0)))
))
}
}
}
| Java |
using GalaSoft.MvvmLight;
namespace Operation.WPF.ViewModels
{
public interface IViewModelFactory
{
T ResolveViewModel<T>() where T : ViewModelBase;
}
} | Java |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MageTurret : Turret
{
[SerializeField]
float range;
[SerializeField]
float baseDamage = 0.00f;
float currentDamage = 0.00f;
[SerializeField]
float damageIncrease;
[SerializeField]
float attackCooldown;
float currentCooldown;
[SerializeField]
float damageMultiplier;
float currentMultiplier;
bool isAttacking;
[SerializeField]
List<Enemy> enemiesCanAttack;
Enemy oldClosestEnemy;
Enemy closestEnemy;
Enemy target;
[Header("AttackRay")]
[SerializeField]
Transform raySpawnPoint;
[SerializeField]
LineRenderer lr;
[SerializeField]
ParticleSystem partSystemTurret;
[SerializeField]
ParticleSystem finalRaySystem;
void Start()
{
enemiesCanAttack = new List<Enemy>();
currentDamage = baseDamage;
currentMultiplier = damageMultiplier;
}
public override void PooledStart()
{
enemiesCanAttack = new List<Enemy>();
currentDamage = baseDamage;
currentMultiplier = damageMultiplier;
}
void Update()
{
if (enemiesCanAttack.Count > 0)
{
if (isAttacking)
{
Attack();
return;
}
finalRaySystem.Stop();
currentCooldown -= Time.deltaTime;
if (currentCooldown <= 0)
{
FindClosestTarget();
currentCooldown = attackCooldown;
}
}
else
{
lr.enabled = false;
}
}
void Attack()
{
if (currentDamage <= 200)
{
currentDamage += damageIncrease * currentMultiplier;
}
target.TakeDamage(currentDamage);
if (target.isDead)
{
ClearDeadTarget();
return;
}
currentMultiplier += damageIncrease;
lr.enabled = true;
lr.SetPosition(0, raySpawnPoint.position);
lr.SetPosition(1, target.transform.position);
finalRaySystem.Play();
finalRaySystem.transform.position = lr.GetPosition(1);
}
void ClearDeadTarget()
{
lr.enabled = false;
enemiesCanAttack.Remove(target);
target = null;
currentDamage = baseDamage;
currentMultiplier = damageMultiplier;
isAttacking = false;
finalRaySystem.Stop();
}
void ClearTarget()
{
target.ClearDamage();
lr.enabled = false;
enemiesCanAttack.Remove(target);
target = null;
currentDamage = baseDamage;
currentMultiplier = damageMultiplier;
isAttacking = false;
finalRaySystem.Stop();
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
enemiesCanAttack.Add(other.GetComponent<Enemy>());
if (target == null)
{
FindClosestTarget();
}
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Enemy"))
{
if (target != null && Vector3.Distance(target.transform.
position, transform.position) > range)
{
ClearTarget();
}
enemiesCanAttack.Remove(other.GetComponent<Enemy>());
}
}
public override void Sell()
{
base.Sell();
EndSell();
}
protected virtual void FindClosestTarget()
{
for (int i = 0; i < enemiesCanAttack.Count; i++)
{
if (closestEnemy != null)
{
if (Vector3.Distance(transform.position, enemiesCanAttack[i].transform.position) <=
Vector3.Distance(transform.position, closestEnemy.transform.position))
{
closestEnemy = enemiesCanAttack[i];
}
}
else closestEnemy = enemiesCanAttack[i];
target = closestEnemy.GetComponent<Enemy>();
oldClosestEnemy = closestEnemy;
isAttacking = true;
}
}
void OnDrawGizmos()
{
Color color = Color.blue;
Gizmos.color = color;
Gizmos.DrawWireSphere(transform.position, range);
}
}
| Java |
import torch
from hypergan.train_hooks.base_train_hook import BaseTrainHook
class NegativeMomentumTrainHook(BaseTrainHook):
def __init__(self, gan=None, config=None, trainer=None):
super().__init__(config=config, gan=gan, trainer=trainer)
self.d_grads = None
self.g_grads = None
def gradients(self, d_grads, g_grads):
if self.d_grads is None:
self.d_grads = [torch.zeros_like(_g) for _g in d_grads]
self.g_grads = [torch.zeros_like(_g) for _g in g_grads]
new_d_grads = [g.clone() for g in d_grads]
new_g_grads = [g.clone() for g in g_grads]
d_grads = [_g - self.config.gamma * _g2 for _g, _g2 in zip(d_grads, self.d_grads)]
g_grads = [_g - self.config.gamma * _g2 for _g, _g2 in zip(g_grads, self.g_grads)]
self.d_grads = new_d_grads
self.g_grads = new_g_grads
return [d_grads, g_grads]
| Java |
#include "Namespace_Base.h"
#include <co/Coral.h>
#include <co/IComponent.h>
#include <co/IPort.h>
#include <co/IInterface.h>
namespace co {
//------ co.Namespace has a facet named 'namespace', of type co.INamespace ------//
co::IInterface* Namespace_co_INamespace::getInterface()
{
return co::typeOf<co::INamespace>::get();
}
co::IPort* Namespace_co_INamespace::getFacet()
{
co::IComponent* component = static_cast<co::IComponent*>( co::getType( "co.Namespace" ) );
assert( component );
co::IPort* facet = static_cast<co::IPort*>( component->getMember( "namespace" ) );
assert( facet );
return facet;
}
//------ Namespace_Base ------//
Namespace_Base::Namespace_Base()
{
// empty
}
Namespace_Base::~Namespace_Base()
{
// empty
}
co::IObject* Namespace_Base::getProvider()
{
return this;
}
void Namespace_Base::serviceRetain()
{
incrementRefCount();
}
void Namespace_Base::serviceRelease()
{
decrementRefCount();
}
co::IComponent* Namespace_Base::getComponent()
{
co::IType* type = co::getType( "co.Namespace" );
assert( type->getKind() == co::TK_COMPONENT );
return static_cast<co::IComponent*>( type );
}
co::IService* Namespace_Base::getServiceAt( co::IPort* port )
{
checkValidPort( port );
co::IService* res = NULL;
switch( port->getIndex() )
{
case 0: res = static_cast<co::INamespace*>( this ); break;
default: raiseUnexpectedPortIndex();
}
return res;
}
void Namespace_Base::setServiceAt( co::IPort* receptacle, co::IService* service )
{
checkValidReceptacle( receptacle );
raiseUnexpectedPortIndex();
CORAL_UNUSED( service );
}
} // namespace co
| Java |
/*** AppView ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var SlideshowView = require('views/SlideshowView');
function ProjectView() {
View.apply(this, arguments);
}
ProjectView.prototype = Object.create(View.prototype);
ProjectView.prototype.constructor = ProjectView;
ProjectView.DEFAULT_OPTIONS = {};
module.exports = ProjectView;
});
| Java |
# Development Guidelines
This document describes tools, tasks and workflow that one needs to be familiar with in order to effectively maintain
this project. If you use this package within your own software as is but don't plan on modifying it, this guide is
**not** for you.
## Tools
* [Phing](http://www.phing.info/): used to run predefined tasks. Installed via Composer into the vendor directory. You
can run phing but using the command line script `./vendor/bin/phing` or you can put it on your PATH.
* [Composer](https://getcomposer.org/): used to manage dependencies for the project.
* [Box](http://box-project.org/): used to generate a phar archive, which is useful for users who
don't use Composer in their own project.
## Tasks
### Testing
This project's tests are written as PHPUnit test cases. Common tasks:
* `./vendor/bin/phing test` - run the test suite.
### Releasing
In order to create a release, the following should be completed in order.
1. Ensure all the tests are passing (`./vendor/bin/phing test`) and that there is enough test coverage.
1. Make sure you are on the `master` branch of the repository, with all changes merged/commited already.
1. Update the version number in the source code and the README. See [Versioning](#versioning) for information
about selecting an appropriate version number. Files to inspect for possible need to change:
- src/OpenTok/Util/Client.php
- tests/OpenTok/OpenTokTest.php
- tests/OpenTok/ArchiveTest.php
- README.md (only needs to change when MINOR version is changing)
1. Commit the version number change with the message "Update to version x.x.x", substituting the new version number.
1. Create a git tag: `git tag -a vx.x.x -m "Release vx.x.x"`
1. Change the version number for future development by incrementing the PATH number and adding
"-alpha.1" in each file except samples and documentation. Then make another commit with the
message "Begin development on next version".
1. Push the changes to the source repository: `git push origin master; git push --tags origin`s
1. Generate a phar archive for distribution using [Box](https://github.com/box-project/box2): `box build`. Be sure that the
dependencies in the `/vendor` directory are current before building. Upload it to the GitHub Release. Add
release notes with a description of changes and fixes.
## Workflow
### Versioning
The project uses [semantic versioning](http://semver.org/) as a policy for incrementing version numbers. For planned
work that will go into a future version, there should be a Milestone created in the Github Issues named with the version
number (e.g. "v2.2.1").
During development the version number should end in "-alpha.x" or "-beta.x", where x is an increasing number starting from 1.
### Branches
* `master` - the main development branch.
* `feat.foo` - feature branches. these are used for longer running tasks that cannot be accomplished in one commit.
once merged into master, these branches should be deleted.
* `vx.x.x` - if development for a future version/milestone has begun while master is working towards a sooner
release, this is the naming scheme for that branch. once merged into master, these branches should be deleted.
### Tags
* `vx.x.x` - commits are tagged with a final version number during release.
### Issues
Issues are labelled to help track their progress within the pipeline.
* no label - these issues have not been triaged.
* `bug` - confirmed bug. aim to have a test case that reproduces the defect.
* `enhancement` - contains details/discussion of a new feature. it may not yet be approved or placed into a
release/milestone.
* `wontfix` - closed issues that were never addressed.
* `duplicate` - closed issue that is the same to another referenced issue.
* `question` - purely for discussion
### Management
When in doubt, find the maintainers and ask.
| Java |
<?php
/**
* Go! AOP framework
*
* @copyright Copyright 2013, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Demo\Example;
/**
* Human class example
*/
class HumanDemo
{
/**
* Eat something
*/
public function eat()
{
echo "Eating...", PHP_EOL;
}
/**
* Clean the teeth
*/
public function cleanTeeth()
{
echo "Cleaning teeth...", PHP_EOL;
}
/**
* Washing up
*/
public function washUp()
{
echo "Washing up...", PHP_EOL;
}
/**
* Working
*/
public function work()
{
echo "Working...", PHP_EOL;
}
/**
* Go to sleep
*/
public function sleep()
{
echo "Go to sleep...", PHP_EOL;
}
}
| Java |
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Routing;
using Migrap.AspNet.Multitenant;
using System;
using System.Collections.Generic;
namespace Migrap.AspNet.Routing {
public class TenantRouteConstraint : IRouteConstraint {
public const string TenantKey = "tenant";
private readonly ISet<string> _tenants = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly ITenantService _tenantService;
public TenantRouteConstraint(ITenantService tenantService) {
_tenantService = tenantService;
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) {
var address = httpContext.Request.Headers["Host"][0].Split('.');
if(address.Length < 2) {
return false;
}
var tenant = address[0];
if(!values.ContainsKey("tenant")) {
values.Add("tenant", tenant);
}
return true;
}
}
} | Java |
import numpy as np
__author__ = 'David John Gagne <djgagne@ou.edu>'
def main():
# Contingency Table from Wilks (2011) Table 8.3
table = np.array([[50, 91, 71],
[47, 2364, 170],
[54, 205, 3288]])
mct = MulticlassContingencyTable(table, n_classes=table.shape[0],
class_names=np.arange(table.shape[0]).astype(str))
print(mct.peirce_skill_score())
print(mct.gerrity_score())
class MulticlassContingencyTable(object):
"""
This class is a container for a contingency table containing more than 2 classes.
The contingency table is stored in table as a numpy array with the rows corresponding to forecast categories,
and the columns corresponding to observation categories.
"""
def __init__(self, table=None, n_classes=2, class_names=("1", "0")):
self.table = table
self.n_classes = n_classes
self.class_names = class_names
if table is None:
self.table = np.zeros((self.n_classes, self.n_classes), dtype=int)
def __add__(self, other):
assert self.n_classes == other.n_classes, "Number of classes does not match"
return MulticlassContingencyTable(self.table + other.table,
n_classes=self.n_classes,
class_names=self.class_names)
def peirce_skill_score(self):
"""
Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score)
"""
n = float(self.table.sum())
nf = self.table.sum(axis=1)
no = self.table.sum(axis=0)
correct = float(self.table.trace())
return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2)
def gerrity_score(self):
"""
Gerrity Score, which weights each cell in the contingency table by its observed relative frequency.
:return:
"""
k = self.table.shape[0]
n = float(self.table.sum())
p_o = self.table.sum(axis=0) / n
p_sum = np.cumsum(p_o)[:-1]
a = (1.0 - p_sum) / p_sum
s = np.zeros(self.table.shape, dtype=float)
for (i, j) in np.ndindex(*s.shape):
if i == j:
s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:j]) + np.sum(a[j:k - 1]))
elif i < j:
s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:i]) - (j - i) + np.sum(a[j:k - 1]))
else:
s[i, j] = s[j, i]
return np.sum(self.table / float(self.table.sum()) * s)
def heidke_skill_score(self):
n = float(self.table.sum())
nf = self.table.sum(axis=1)
no = self.table.sum(axis=0)
correct = float(self.table.trace())
return (correct / n - (nf * no).sum() / n ** 2) / (1 - (nf * no).sum() / n ** 2)
if __name__ == "__main__":
main()
| Java |
.navbar-brand {
font-family: "Bungee", cursive;
font-size: 200%;
padding: 0; }
#image_billiard {
height: 70px;
padding: 15px;
width: auto;
float: left; }
.brand-text {
float: right;
padding-top: 25px;
padding-left: 10px; }
.navbar-default {
height: 70px; }
.navbar-default .navbar-nav > li > a {
padding-top: 20px;
padding-bottom: 20px;
line-height: 30px; }
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus,
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: white;
background-color: transparent; }
form#id_search_group {
margin-top: 16px; }
.jumbotron {
padding-top: 6rem;
padding-bottom: 6rem;
margin-bottom: 0;
background-color: white; }
.jumbotron .container {
max-width: 80rem; }
#lower_container {
background-color: #f7f7f7; }
| Java |
"use strict";
var ArrayCollection_1 = require('./ArrayCollection');
exports.ArrayCollection = ArrayCollection_1.ArrayCollection;
var ArrayList_1 = require('./ArrayList');
exports.ArrayList = ArrayList_1.ArrayList;
var SequenceBase_1 = require('./SequenceBase');
exports.SequenceBase = SequenceBase_1.SequenceBase;
var Buckets_1 = require('./Buckets');
exports.Buckets = Buckets_1.Buckets;
var Collection_1 = require('./Collection');
exports.Collection = Collection_1.Collection;
var Dictionary_1 = require('./Dictionary');
exports.Dictionary = Dictionary_1.Dictionary;
exports.Pair = Dictionary_1.Pair;
var Hash_1 = require('./Hash');
exports.HashFunc = Hash_1.HashFunc;
exports.DefaultHashFunc = Hash_1.DefaultHashFunc;
var HashSet_1 = require('./HashSet');
exports.HashSet = HashSet_1.HashSet;
var Iterable_1 = require('./Iterable');
exports.Iterable = Iterable_1.Iterable;
var LinkedList_1 = require('./LinkedList');
exports.LinkedList = LinkedList_1.LinkedList;
var Native_1 = require('./Native');
exports.NativeIndex = Native_1.NativeIndex;
exports.NativeMap = Native_1.NativeMap;
var Sequence_1 = require('./Sequence');
exports.Sequence = Sequence_1.Sequence;
var Stack_1 = require('./Stack');
exports.Stack = Stack_1.Stack;
var Util_1 = require('./Util');
exports.Util = Util_1.Util;
//# sourceMappingURL=index.js.map | Java |
<!-- dx-header -->
# IDR for ChIP-seq (DNAnexus Platform App)
Generate peaks that pass the IDR threshold
This is the source code for an app that runs on the DNAnexus Platform.
For more information about how to run or modify it, see
https://wiki.dnanexus.com/.
<!-- /dx-header -->
Take peaks. Generate pseudoreplicates and pool controls (as appropriate). Run the IDR framework.
<!--
TODO: This app directory was automatically generated by dx-app-wizard;
please edit this Readme.md file to include essential documentation about
your app that would be helpful to users. (Also see the
Readme.developer.md.) Once you're done, you can remove these TODO
comments.
For more info, see https://wiki.dnanexus.com/Developer-Portal.
-->
| Java |
<span class="S-prose">
{% for item in site.data.testimonials %}{% if forloop.last %}
{% assign testimonial = item[1] %}
<figure class="O-block C-testimonial-highlight">
<blockquote>“{{ testimonial.content }}”</blockquote>
<figcaption class="C-quote-person">
<img class="C-quote-person__avatar" alt="photo of {{ testimonial.name }}" src="{{ testimonial.avatar_url | prepend: site.testimonials_images_path }}">
{{ testimonial.name }}
<span class="C-quote-person__role">
{{ testimonial.role }}
at
{% if testimonial.company %}
{% if testimonial.company_url %}
<a href="{{ testimonial.company_url }}">{{ testimonial.company }}</a>
{% else %}
{{ testimonial.company }}
{% endif %}
{% endif %}
</span>
</figcaption>
</figure>
<!-- <a class="C-button T-transparent" href="#">See the project</a> -->
{% endif %}{% endfor %}
</span> | Java |
<?php
/**
* Provides low-level debugging, error and exception functionality
*
* @copyright Copyright (c) 2007-2011 Will Bond, others
* @author Will Bond [wb] <will@flourishlib.com>
* @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net>
* @author Nick Trew [nt]
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fCore
*
* @version 1.0.0b20
* @changes 1.0.0b20 Backwards Compatibility Break - Updated ::expose() to not wrap the data in HTML when running via CLI, and instead just append a newline [wb, 2011-02-24]
* @changes 1.0.0b19 Added detection of AIX to ::checkOS() [wb, 2011-01-19]
* @changes 1.0.0b18 Updated ::expose() to be able to accept multiple parameters [wb, 2011-01-10]
* @changes 1.0.0b17 Fixed a bug with ::backtrace() triggering notices when an argument is not UTF-8 [wb, 2010-08-17]
* @changes 1.0.0b16 Added the `$types` and `$regex` parameters to ::startErrorCapture() and the `$regex` parameter to ::stopErrorCapture() [wb, 2010-08-09]
* @changes 1.0.0b15 Added ::startErrorCapture() and ::stopErrorCapture() [wb, 2010-07-05]
* @changes 1.0.0b14 Changed ::enableExceptionHandling() to only call fException::printMessage() when the destination is not `html` and no callback has been defined, added ::configureSMTP() to allow using fSMTP for error and exception emails [wb, 2010-06-04]
* @changes 1.0.0b13 Added the `$backtrace` parameter to ::backtrace() [wb, 2010-03-05]
* @changes 1.0.0b12 Added ::getDebug() to check for the global debugging flag, added more specific BSD checks to ::checkOS() [wb, 2010-03-02]
* @changes 1.0.0b11 Added ::detectOpcodeCache() [nt+wb, 2009-10-06]
* @changes 1.0.0b10 Fixed ::expose() to properly display when output includes non-UTF-8 binary data [wb, 2009-06-29]
* @changes 1.0.0b9 Added ::disableContext() to remove context info for exception/error handling, tweaked output for exceptions/errors [wb, 2009-06-28]
* @changes 1.0.0b8 ::enableErrorHandling() and ::enableExceptionHandling() now accept multiple email addresses, and a much wider range of emails [wb-imarc, 2009-06-01]
* @changes 1.0.0b7 ::backtrace() now properly replaces document root with {doc_root} on Windows [wb, 2009-05-02]
* @changes 1.0.0b6 Fixed a bug with getting the server name for error messages when running on the command line [wb, 2009-03-11]
* @changes 1.0.0b5 Fixed a bug with checking the error/exception destination when a log file is specified [wb, 2009-03-07]
* @changes 1.0.0b4 Backwards compatibility break - ::getOS() and ::getPHPVersion() removed, replaced with ::checkOS() and ::checkVersion() [wb, 2009-02-16]
* @changes 1.0.0b3 ::handleError() now displays what kind of error occured as the heading [wb, 2009-02-15]
* @changes 1.0.0b2 Added ::registerDebugCallback() [wb, 2009-02-07]
* @changes 1.0.0b The initial implementation [wb, 2007-09-25]
*/
class fCore
{
// The following constants allow for nice looking callbacks to static methods
const backtrace = 'fCore::backtrace';
const call = 'fCore::call';
const callback = 'fCore::callback';
const checkOS = 'fCore::checkOS';
const checkVersion = 'fCore::checkVersion';
const configureSMTP = 'fCore::configureSMTP';
const debug = 'fCore::debug';
const detectOpcodeCache = 'fCore::detectOpcodeCache';
const disableContext = 'fCore::disableContext';
const dump = 'fCore::dump';
const enableDebugging = 'fCore::enableDebugging';
const enableDynamicConstants = 'fCore::enableDynamicConstants';
const enableErrorHandling = 'fCore::enableErrorHandling';
const enableExceptionHandling = 'fCore::enableExceptionHandling';
const expose = 'fCore::expose';
const getDebug = 'fCore::getDebug';
const handleError = 'fCore::handleError';
const handleException = 'fCore::handleException';
const registerDebugCallback = 'fCore::registerDebugCallback';
const reset = 'fCore::reset';
const sendMessagesOnShutdown = 'fCore::sendMessagesOnShutdown';
const startErrorCapture = 'fCore::startErrorCapture';
const stopErrorCapture = 'fCore::stopErrorCapture';
/**
* A regex to match errors to capture
*
* @var string
*/
static private $captured_error_regex = NULL;
/**
* The previous error handler
*
* @var callback
*/
static private $captured_errors_previous_handler = NULL;
/**
* The types of errors to capture
*
* @var integer
*/
static private $captured_error_types = NULL;
/**
* An array of errors that have been captured
*
* @var array
*/
static private $captured_errors = NULL;
/**
* If the context info has been shown
*
* @var boolean
*/
static private $context_shown = FALSE;
/**
* If global debugging is enabled
*
* @var boolean
*/
static private $debug = NULL;
/**
* A callback to pass debug messages to
*
* @var callback
*/
static private $debug_callback = NULL;
/**
* If dynamic constants should be created
*
* @var boolean
*/
static private $dynamic_constants = FALSE;
/**
* Error destination
*
* @var string
*/
static private $error_destination = 'html';
/**
* An array of errors to be send to the destination upon page completion
*
* @var array
*/
static private $error_message_queue = array();
/**
* Exception destination
*
* @var string
*/
static private $exception_destination = 'html';
/**
* Exception handler callback
*
* @var mixed
*/
static private $exception_handler_callback = NULL;
/**
* Exception handler callback parameters
*
* @var array
*/
static private $exception_handler_parameters = array();
/**
* The message generated by the uncaught exception
*
* @var string
*/
static private $exception_message = NULL;
/**
* If this class is handling errors
*
* @var boolean
*/
static private $handles_errors = FALSE;
/**
* If this class is handling exceptions
*
* @var boolean
*/
static private $handles_exceptions = FALSE;
/**
* If the context info should be shown with errors/exceptions
*
* @var boolean
*/
static private $show_context = TRUE;
/**
* An SMTP connection for sending error and exception emails
*
* @var fSMTP
*/
static private $smtp_connection = NULL;
/**
* The email address to send error emails from
*
* @var string
*/
static private $smtp_from_email = NULL;
/**
* Creates a nicely formatted backtrace to the the point where this method is called
*
* @param integer $remove_lines The number of trailing lines to remove from the backtrace
* @param array $backtrace A backtrace from [http://php.net/backtrace `debug_backtrace()`] to format - this is not usually required or desired
* @return string The formatted backtrace
*/
static public function backtrace($remove_lines=0, $backtrace=NULL)
{
if ($remove_lines !== NULL && !is_numeric($remove_lines)) {
$remove_lines = 0;
}
settype($remove_lines, 'integer');
$doc_root = realpath($_SERVER['DOCUMENT_ROOT']);
$doc_root .= (substr($doc_root, -1) != DIRECTORY_SEPARATOR) ? DIRECTORY_SEPARATOR : '';
if ($backtrace === NULL) {
$backtrace = debug_backtrace();
}
while ($remove_lines > 0) {
array_shift($backtrace);
$remove_lines--;
}
$backtrace = array_reverse($backtrace);
$bt_string = '';
$i = 0;
foreach ($backtrace as $call) {
if ($i) {
$bt_string .= "\n";
}
if (isset($call['file'])) {
$bt_string .= str_replace($doc_root, '{doc_root}' . DIRECTORY_SEPARATOR, $call['file']) . '(' . $call['line'] . '): ';
} else {
$bt_string .= '[internal function]: ';
}
if (isset($call['class'])) {
$bt_string .= $call['class'] . $call['type'];
}
if (isset($call['class']) || isset($call['function'])) {
$bt_string .= $call['function'] . '(';
$j = 0;
if (!isset($call['args'])) {
$call['args'] = array();
}
foreach ($call['args'] as $arg) {
if ($j) {
$bt_string .= ', ';
}
if (is_bool($arg)) {
$bt_string .= ($arg) ? 'true' : 'false';
} elseif (is_null($arg)) {
$bt_string .= 'NULL';
} elseif (is_array($arg)) {
$bt_string .= 'Array';
} elseif (is_object($arg)) {
$bt_string .= 'Object(' . get_class($arg) . ')';
} elseif (is_string($arg)) {
// Shorten the UTF-8 string if it is too long
if (strlen(utf8_decode($arg)) > 18) {
// If we can't match as unicode, try single byte
if (!preg_match('#^(.{0,15})#us', $arg, $short_arg)) {
preg_match('#^(.{0,15})#s', $arg, $short_arg);
}
$arg = $short_arg[0] . '...';
}
$bt_string .= "'" . $arg . "'";
} else {
$bt_string .= (string) $arg;
}
$j++;
}
$bt_string .= ')';
}
$i++;
}
return $bt_string;
}
/**
* Performs a [http://php.net/call_user_func call_user_func()], while translating PHP 5.2 static callback syntax for PHP 5.1 and 5.0
*
* Parameters can be passed either as a single array of parameters or as
* multiple parameters.
*
* {{{
* #!php
* // Passing multiple parameters in a normal fashion
* fCore::call('Class::method', TRUE, 0, 'test');
*
* // Passing multiple parameters in a parameters array
* fCore::call('Class::method', array(TRUE, 0, 'test'));
* }}}
*
* To pass parameters by reference they must be assigned to an
* array by reference and the function/method being called must accept those
* parameters by reference. If either condition is not met, the parameter
* will be passed by value.
*
* {{{
* #!php
* // Passing parameters by reference
* fCore::call('Class::method', array(&$var1, &$var2));
* }}}
*
* @param callback $callback The function or method to call
* @param array $parameters The parameters to pass to the function/method
* @return mixed The return value of the called function/method
*/
static public function call($callback, $parameters=array())
{
// Fix PHP 5.0 and 5.1 static callback syntax
if (is_string($callback) && strpos($callback, '::') !== FALSE) {
$callback = explode('::', $callback);
}
$parameters = array_slice(func_get_args(), 1);
if (sizeof($parameters) == 1 && is_array($parameters[0])) {
$parameters = $parameters[0];
}
return call_user_func_array($callback, $parameters);
}
/**
* Translates a Class::method style static method callback to array style for compatibility with PHP 5.0 and 5.1 and built-in PHP functions
*
* @param callback $callback The callback to translate
* @return array The translated callback
*/
static public function callback($callback)
{
if (is_string($callback) && strpos($callback, '::') !== FALSE) {
return explode('::', $callback);
}
return $callback;
}
/**
* Checks an error/exception destination to make sure it is valid
*
* @param string $destination The destination for the exception. An email, file or the string `'html'`.
* @return string|boolean `'email'`, `'file'`, `'html'` or `FALSE`
*/
static private function checkDestination($destination)
{
if ($destination == 'html') {
return 'html';
}
if (preg_match('~^(?: # Allow leading whitespace
(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") # An "atom" or a quoted string
(?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* # A . plus another "atom" or a quoted string, any number of times
)@(?: # The @ symbol
(?:[a-z0-9\\-]+\.)+[a-z]{2,}| # Domain name
(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]) # (or) IP addresses
)
(?:\s*,\s* # Any number of other emails separated by a comma with surrounding spaces
(?:
(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+")
(?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))*
)@(?:
(?:[a-z0-9\\-]+\.)+[a-z]{2,}|
(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])
)
)*$~xiD', $destination)) {
return 'email';
}
$path_info = pathinfo($destination);
$dir_exists = file_exists($path_info['dirname']);
$dir_writable = ($dir_exists) ? is_writable($path_info['dirname']) : FALSE;
$file_exists = file_exists($destination);
$file_writable = ($file_exists) ? is_writable($destination) : FALSE;
if (!$dir_exists || ($dir_exists && ((!$file_exists && !$dir_writable) || ($file_exists && !$file_writable)))) {
return FALSE;
}
return 'file';
}
/**
* Returns is the current OS is one of the OSes passed as a parameter
*
* Valid OS strings are:
* - `'linux'`
* - `'aix'`
* - `'bsd'`
* - `'freebsd'`
* - `'netbsd'`
* - `'openbsd'`
* - `'osx'`
* - `'solaris'`
* - `'windows'`
*
* @param string $os The operating system to check - see method description for valid OSes
* @param string ...
* @return boolean If the current OS is included in the list of OSes passed as parameters
*/
static public function checkOS($os)
{
$oses = func_get_args();
$valid_oses = array('linux', 'aix', 'bsd', 'freebsd', 'openbsd', 'netbsd', 'osx', 'solaris', 'windows');
if ($invalid_oses = array_diff($oses, $valid_oses)) {
throw new fProgrammerException(
'One or more of the OSes specified, %$1s, is invalid. Must be one of: %2$s.',
join(' ', $invalid_oses),
join(', ', $valid_oses)
);
}
$uname = php_uname('s');
if (stripos($uname, 'linux') !== FALSE) {
return in_array('linux', $oses);
} elseif (stripos($uname, 'aix') !== FALSE) {
return in_array('aix', $oses);
} elseif (stripos($uname, 'netbsd') !== FALSE) {
return in_array('netbsd', $oses) || in_array('bsd', $oses);
} elseif (stripos($uname, 'openbsd') !== FALSE) {
return in_array('openbsd', $oses) || in_array('bsd', $oses);
} elseif (stripos($uname, 'freebsd') !== FALSE) {
return in_array('freebsd', $oses) || in_array('bsd', $oses);
} elseif (stripos($uname, 'solaris') !== FALSE || stripos($uname, 'sunos') !== FALSE) {
return in_array('solaris', $oses);
} elseif (stripos($uname, 'windows') !== FALSE) {
return in_array('windows', $oses);
} elseif (stripos($uname, 'darwin') !== FALSE) {
return in_array('osx', $oses);
}
throw new fEnvironmentException('Unable to determine the current OS');
}
/**
* Checks to see if the running version of PHP is greater or equal to the version passed
*
* @return boolean If the running version of PHP is greater or equal to the version passed
*/
static public function checkVersion($version)
{
static $running_version = NULL;
if ($running_version === NULL) {
$running_version = preg_replace(
'#^(\d+\.\d+\.\d+).*$#D',
'\1',
PHP_VERSION
);
}
return version_compare($running_version, $version, '>=');
}
/**
* Composes text using fText if loaded
*
* @param string $message The message to compose
* @param mixed $component A string or number to insert into the message
* @param mixed ...
* @return string The composed and possible translated message
*/
static private function compose($message)
{
$args = array_slice(func_get_args(), 1);
if (class_exists('fText', FALSE)) {
return call_user_func_array(
array('fText', 'compose'),
array($message, $args)
);
} else {
return vsprintf($message, $args);
}
}
/**
* Sets an fSMTP object to be used for sending error and exception emails
*
* @param fSMTP $smtp The SMTP connection to send emails over
* @param string $from_email The email address to use in the `From:` header
* @return void
*/
static public function configureSMTP($smtp, $from_email)
{
self::$smtp_connection = $smtp;
self::$smtp_from_email = $from_email;
}
/**
* Prints a debugging message if global or code-specific debugging is enabled
*
* @param string $message The debug message
* @param boolean $force If debugging should be forced even when global debugging is off
* @return void
*/
static public function debug($message, $force=FALSE)
{
if ($force || self::$debug) {
if (self::$debug_callback) {
call_user_func(self::$debug_callback, $message);
} else {
self::expose($message);
}
}
}
/**
* Detects if a PHP opcode cache is installed
*
* The following opcode caches are currently detected:
*
* - [http://pecl.php.net/package/APC APC]
* - [http://eaccelerator.net eAccelerator]
* - [http://www.nusphere.com/products/phpexpress.htm Nusphere PhpExpress]
* - [http://turck-mmcache.sourceforge.net/index_old.html Turck MMCache]
* - [http://xcache.lighttpd.net XCache]
* - [http://www.zend.com/en/products/server/ Zend Server (Optimizer+)]
* - [http://www.zend.com/en/products/platform/ Zend Platform (Code Acceleration)]
*
* @return boolean If a PHP opcode cache is loaded
*/
static public function detectOpcodeCache()
{
$apc = ini_get('apc.enabled');
$eaccelerator = ini_get('eaccelerator.enable');
$mmcache = ini_get('mmcache.enable');
$phpexpress = function_exists('phpexpress');
$xcache = ini_get('xcache.size') > 0 && ini_get('xcache.cacher');
$zend_accelerator = ini_get('zend_accelerator.enabled');
$zend_plus = ini_get('zend_optimizerplus.enable');
return $apc || $eaccelerator || $mmcache || $phpexpress || $xcache || $zend_accelerator || $zend_plus;
}
/**
* Creates a string representation of any variable using predefined strings for booleans, `NULL` and empty strings
*
* The string output format of this method is very similar to the output of
* [http://php.net/print_r print_r()] except that the following values
* are represented as special strings:
*
* - `TRUE`: `'{true}'`
* - `FALSE`: `'{false}'`
* - `NULL`: `'{null}'`
* - `''`: `'{empty_string}'`
*
* @param mixed $data The value to dump
* @return string The string representation of the value
*/
static public function dump($data)
{
if (is_bool($data)) {
return ($data) ? '{true}' : '{false}';
} elseif (is_null($data)) {
return '{null}';
} elseif ($data === '') {
return '{empty_string}';
} elseif (is_array($data) || is_object($data)) {
ob_start();
var_dump($data);
$output = ob_get_contents();
ob_end_clean();
// Make the var dump more like a print_r
$output = preg_replace('#=>\n( )+(?=[a-zA-Z]|&)#m', ' => ', $output);
$output = str_replace('string(0) ""', '{empty_string}', $output);
$output = preg_replace('#=> (&)?NULL#', '=> \1{null}', $output);
$output = preg_replace('#=> (&)?bool\((false|true)\)#', '=> \1{\2}', $output);
$output = preg_replace('#string\(\d+\) "#', '', $output);
$output = preg_replace('#"(\n( )*)(?=\[|\})#', '\1', $output);
$output = preg_replace('#(?:float|int)\((-?\d+(?:.\d+)?)\)#', '\1', $output);
$output = preg_replace('#((?: )+)\["(.*?)"\]#', '\1[\2]', $output);
$output = preg_replace('#(?:&)?array\(\d+\) \{\n((?: )*)((?: )(?=\[)|(?=\}))#', "Array\n\\1(\n\\1\\2", $output);
$output = preg_replace('/object\((\w+)\)#\d+ \(\d+\) {\n((?: )*)((?: )(?=\[)|(?=\}))/', "\\1 Object\n\\2(\n\\2\\3", $output);
$output = preg_replace('#^((?: )+)}(?=\n|$)#m', "\\1)\n", $output);
$output = substr($output, 0, -2) . ')';
// Fix indenting issues with the var dump output
$output_lines = explode("\n", $output);
$new_output = array();
$stack = 0;
foreach ($output_lines as $line) {
if (preg_match('#^((?: )*)([^ ])#', $line, $match)) {
$spaces = strlen($match[1]);
if ($spaces && $match[2] == '(') {
$stack += 1;
}
$new_output[] = str_pad('', ($spaces)+(4*$stack)) . $line;
if ($spaces && $match[2] == ')') {
$stack -= 1;
}
} else {
$new_output[] = str_pad('', ($spaces)+(4*$stack)) . $line;
}
}
return join("\n", $new_output);
} else {
return (string) $data;
}
}
/**
* Disables including the context information with exception and error messages
*
* The context information includes the following superglobals:
*
* - `$_SERVER`
* - `$_POST`
* - `$_GET`
* - `$_SESSION`
* - `$_FILES`
* - `$_COOKIE`
*
* @return void
*/
static public function disableContext()
{
self::$show_context = FALSE;
}
/**
* Enables debug messages globally, i.e. they will be shown for any call to ::debug()
*
* @param boolean $flag If debugging messages should be shown
* @return void
*/
static public function enableDebugging($flag)
{
self::$debug = (boolean) $flag;
}
/**
* Turns on a feature where undefined constants are automatically created with the string value equivalent to the name
*
* This functionality only works if ::enableErrorHandling() has been
* called first. This functionality may have a very slight performance
* impact since a `E_STRICT` error message must be captured and then a
* call to [http://php.net/define define()] is made.
*
* @return void
*/
static public function enableDynamicConstants()
{
if (!self::$handles_errors) {
throw new fProgrammerException(
'Dynamic constants can not be enabled unless error handling has been enabled via %s',
__CLASS__ . '::enableErrorHandling()'
);
}
self::$dynamic_constants = TRUE;
}
/**
* Turns on developer-friendly error handling that includes context information including a backtrace and superglobal dumps
*
* All errors that match the current
* [http://php.net/error_reporting error_reporting()] level will be
* redirected to the destination and will include a full backtrace. In
* addition, dumps of the following superglobals will be made to aid in
* debugging:
*
* - `$_SERVER`
* - `$_POST`
* - `$_GET`
* - `$_SESSION`
* - `$_FILES`
* - `$_COOKIE`
*
* The superglobal dumps are only done once per page, however a backtrace
* in included for each error.
*
* If an email address is specified for the destination, only one email
* will be sent per script execution. If both error and
* [enableExceptionHandling() exception handling] are set to the same
* email address, the email will contain both errors and exceptions.
*
* @param string $destination The destination for the errors and context information - an email address, a file path or the string `'html'`
* @return void
*/
static public function enableErrorHandling($destination)
{
if (!self::checkDestination($destination)) {
return;
}
self::$error_destination = $destination;
self::$handles_errors = TRUE;
set_error_handler(self::callback(self::handleError));
}
/**
* Turns on developer-friendly uncaught exception handling that includes context information including a backtrace and superglobal dumps
*
* Any uncaught exception will be redirected to the destination specified,
* and the page will execute the `$closing_code` callback before exiting.
* The destination will receive a message with the exception messaage, a
* full backtrace and dumps of the following superglobals to aid in
* debugging:
*
* - `$_SERVER`
* - `$_POST`
* - `$_GET`
* - `$_SESSION`
* - `$_FILES`
* - `$_COOKIE`
*
* The superglobal dumps are only done once per page, however a backtrace
* in included for each error.
*
* If an email address is specified for the destination, only one email
* will be sent per script execution.
*
* If an email address is specified for the destination, only one email
* will be sent per script execution. If both exception and
* [enableErrorHandling() error handling] are set to the same
* email address, the email will contain both exceptions and errors.
*
* @param string $destination The destination for the exception and context information - an email address, a file path or the string `'html'`
* @param callback $closing_code This callback will happen after the exception is handled and before page execution stops. Good for printing a footer. If no callback is provided and the exception extends fException, fException::printMessage() will be called.
* @param array $parameters The parameters to send to `$closing_code`
* @return void
*/
static public function enableExceptionHandling($destination, $closing_code=NULL, $parameters=array())
{
if (!self::checkDestination($destination)) {
return;
}
self::$handles_exceptions = TRUE;
self::$exception_destination = $destination;
self::$exception_handler_callback = $closing_code;
if (!is_object($parameters)) {
settype($parameters, 'array');
} else {
$parameters = array($parameters);
}
self::$exception_handler_parameters = $parameters;
set_exception_handler(self::callback(self::handleException));
}
/**
* Prints the ::dump() of a value
*
* The dump will be printed in a `<pre>` tag with the class `exposed` if
* PHP is running anywhere but via the command line (cli). If PHP is
* running via the cli, the data will be printed, followed by a single
* line break (`\n`).
*
* If multiple parameters are passed, they are exposed as an array.
*
* @param mixed $data The value to show
* @param mixed ...
* @return void
*/
static public function expose($data)
{
$args = func_get_args();
if (count($args) > 1) {
$data = $args;
}
if (PHP_SAPI != 'cli') {
echo '<pre class="exposed">' . htmlspecialchars((string) self::dump($data), ENT_QUOTES) . '</pre>';
} else {
echo self::dump($data) . "\n";
}
}
/**
* Generates some information about the context of an error or exception
*
* @return string A string containing `$_SERVER`, `$_GET`, `$_POST`, `$_FILES`, `$_SESSION` and `$_COOKIE`
*/
static private function generateContext()
{
return self::compose('Context') . "\n-------" .
"\n\n\$_SERVER: " . self::dump($_SERVER) .
"\n\n\$_POST: " . self::dump($_POST) .
"\n\n\$_GET: " . self::dump($_GET) .
"\n\n\$_FILES: " . self::dump($_FILES) .
"\n\n\$_SESSION: " . self::dump((isset($_SESSION)) ? $_SESSION : NULL) .
"\n\n\$_COOKIE: " . self::dump($_COOKIE);
}
/**
* If debugging is enabled
*
* @param boolean $force If debugging is forced
* @return boolean If debugging is enabled
*/
static public function getDebug($force=FALSE)
{
return self::$debug || $force;
}
/**
* Handles an error, creating the necessary context information and sending it to the specified destination
*
* @internal
*
* @param integer $error_number The error type
* @param string $error_string The message for the error
* @param string $error_file The file the error occured in
* @param integer $error_line The line the error occured on
* @param array $error_context A references to all variables in scope at the occurence of the error
* @return void
*/
static public function handleError($error_number, $error_string, $error_file=NULL, $error_line=NULL, $error_context=NULL)
{
if (self::$dynamic_constants && $error_number == E_NOTICE) {
if (preg_match("#^Use of undefined constant (\w+) - assumed '\w+'\$#D", $error_string, $matches)) {
define($matches[1], $matches[1]);
return;
}
}
$capturing = is_array(self::$captured_errors);
$level_match = (bool) (error_reporting() & $error_number);
if (!$capturing && !$level_match) {
return;
}
$doc_root = realpath($_SERVER['DOCUMENT_ROOT']);
$doc_root .= (substr($doc_root, -1) != '/' && substr($doc_root, -1) != '\\') ? '/' : '';
$backtrace = self::backtrace(1);
// Remove the reference to handleError
$backtrace = preg_replace('#: fCore::handleError\(.*?\)$#', '', $backtrace);
$error_string = preg_replace('# \[<a href=\'.*?</a>\]: #', ': ', $error_string);
// This was added in 5.2
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', 4096);
}
// These were added in 5.3
if (!defined('E_DEPRECATED')) {
define('E_DEPRECATED', 8192);
}
if (!defined('E_USER_DEPRECATED')) {
define('E_USER_DEPRECATED', 16384);
}
switch ($error_number) {
case E_WARNING: $type = self::compose('Warning'); break;
case E_NOTICE: $type = self::compose('Notice'); break;
case E_USER_ERROR: $type = self::compose('User Error'); break;
case E_USER_WARNING: $type = self::compose('User Warning'); break;
case E_USER_NOTICE: $type = self::compose('User Notice'); break;
case E_STRICT: $type = self::compose('Strict'); break;
case E_RECOVERABLE_ERROR: $type = self::compose('Recoverable Error'); break;
case E_DEPRECATED: $type = self::compose('Deprecated'); break;
case E_USER_DEPRECATED: $type = self::compose('User Deprecated'); break;
}
if ($capturing) {
$type_to_capture = (bool) (self::$captured_error_types & $error_number);
$string_to_capture = !self::$captured_error_regex || (self::$captured_error_regex && preg_match(self::$captured_error_regex, $error_string));
if ($type_to_capture && $string_to_capture) {
self::$captured_errors[] = array(
'number' => $error_number,
'type' => $type,
'string' => $error_string,
'file' => str_replace($doc_root, '{doc_root}/', $error_file),
'line' => $error_line,
'backtrace' => $backtrace,
'context' => $error_context
);
return;
}
// If the old handler is not this method, then we must have been trying to match a regex and failed
// so we pass the error on to the original handler to do its thing
if (self::$captured_errors_previous_handler != array('fCore', 'handleError')) {
if (self::$captured_errors_previous_handler === NULL) {
return FALSE;
}
return call_user_func(self::$captured_errors_previous_handler, $error_number, $error_string, $error_file, $error_line, $error_context);
// If we get here, this method is the error handler, but we don't want to actually report the error so we return
} elseif (!$level_match) {
return;
}
}
$error = $type . "\n" . str_pad('', strlen($type), '-') . "\n" . $backtrace . "\n" . $error_string;
self::sendMessageToDestination('error', $error);
}
/**
* Handles an uncaught exception, creating the necessary context information, sending it to the specified destination and finally executing the closing callback
*
* @internal
*
* @param object $exception The uncaught exception to handle
* @return void
*/
static public function handleException($exception)
{
$message = ($exception->getMessage()) ? $exception->getMessage() : '{no message}';
if ($exception instanceof fException) {
$trace = $exception->formatTrace();
} else {
$trace = $exception->getTraceAsString();
}
$code = ($exception->getCode()) ? ' (code ' . $exception->getCode() . ')' : '';
$info = $trace . "\n" . $message . $code;
$headline = self::compose("Uncaught") . " " . get_class($exception);
$info_block = $headline . "\n" . str_pad('', strlen($headline), '-') . "\n" . trim($info);
self::sendMessageToDestination('exception', $info_block);
if (self::$exception_handler_callback === NULL) {
if (self::$exception_destination != 'html' && $exception instanceof fException) {
$exception->printMessage();
}
return;
}
try {
self::call(self::$exception_handler_callback, self::$exception_handler_parameters);
} catch (Exception $e) {
trigger_error(
self::compose(
'An exception was thrown in the %s closing code callback',
'setExceptionHandling()'
),
E_USER_ERROR
);
}
}
/**
* Registers a callback to handle debug messages instead of the default action of calling ::expose() on the message
*
* @param callback $callback A callback that accepts a single parameter, the string debug message to handle
* @return void
*/
static public function registerDebugCallback($callback)
{
self::$debug_callback = self::callback($callback);
}
/**
* Resets the configuration of the class
*
* @internal
*
* @return void
*/
static public function reset()
{
if (self::$handles_errors) {
restore_error_handler();
}
if (self::$handles_exceptions) {
restore_exception_handler();
}
if (is_array(self::$captured_errors)) {
restore_error_handler();
}
self::$captured_error_regex = NULL;
self::$captured_errors_previous_handler = NULL;
self::$captured_error_types = NULL;
self::$captured_errors = NULL;
self::$context_shown = FALSE;
self::$debug = NULL;
self::$debug_callback = NULL;
self::$dynamic_constants = FALSE;
self::$error_destination = 'html';
self::$error_message_queue = array();
self::$exception_destination = 'html';
self::$exception_handler_callback = NULL;
self::$exception_handler_parameters = array();
self::$exception_message = NULL;
self::$handles_errors = FALSE;
self::$handles_exceptions = FALSE;
self::$show_context = TRUE;
}
/**
* Sends an email or writes a file with messages generated during the page execution
*
* This method prevents multiple emails from being sent or a log file from
* being written multiple times for one script execution.
*
* @internal
*
* @return void
*/
static public function sendMessagesOnShutdown()
{
$subject = self::compose(
'[%1$s] One or more errors or exceptions occured at %2$s',
isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : php_uname('n'),
date('Y-m-d H:i:s')
);
$messages = array();
if (self::$error_message_queue) {
$message = join("\n\n", self::$error_message_queue);
$messages[self::$error_destination] = $message;
}
if (self::$exception_message) {
if (isset($messages[self::$exception_destination])) {
$messages[self::$exception_destination] .= "\n\n";
} else {
$messages[self::$exception_destination] = '';
}
$messages[self::$exception_destination] .= self::$exception_message;
}
foreach ($messages as $destination => $message) {
if (self::$show_context) {
$message .= "\n\n" . self::generateContext();
}
if (self::checkDestination($destination) == 'email') {
if (self::$smtp_connection) {
$email = new fEmail();
foreach (explode(',', $destination) as $recipient) {
$email->addRecipient($recipient);
}
$email->setFromEmail(self::$smtp_from_email);
$email->setSubject($subject);
$email->setBody($message);
$email->send(self::$smtp_connection);
} else {
mail($destination, $subject, $message);
}
} else {
$handle = fopen($destination, 'a');
fwrite($handle, $subject . "\n\n");
fwrite($handle, $message . "\n\n");
fclose($handle);
}
}
}
/**
* Handles sending a message to a destination
*
* If the destination is an email address or file, the messages will be
* spooled up until the end of the script execution to prevent multiple
* emails from being sent or a log file being written to multiple times.
*
* @param string $type If the message is an error or an exception
* @param string $message The message to send to the destination
* @return void
*/
static private function sendMessageToDestination($type, $message)
{
$destination = ($type == 'exception') ? self::$exception_destination : self::$error_destination;
if ($destination == 'html') {
if (self::$show_context && !self::$context_shown) {
self::expose(self::generateContext());
self::$context_shown = TRUE;
}
self::expose($message);
return;
}
static $registered_function = FALSE;
if (!$registered_function) {
register_shutdown_function(self::callback(self::sendMessagesOnShutdown));
$registered_function = TRUE;
}
if ($type == 'error') {
self::$error_message_queue[] = $message;
} else {
self::$exception_message = $message;
}
}
/**
* Temporarily enables capturing error messages
*
* @param integer $types The error types to capture - this should be as specific as possible - defaults to all (E_ALL | E_STRICT)
* @param string $regex A PCRE regex to match against the error message
* @return void
*/
static public function startErrorCapture($types=NULL, $regex=NULL)
{
if ($types === NULL) {
$types = E_ALL | E_STRICT;
}
self::$captured_error_types = $types;
self::$captured_errors = array();
self::$captured_errors_previous_handler = set_error_handler(self::callback(self::handleError));
self::$captured_error_regex = $regex;
}
/**
* Stops capturing error messages, returning all that have been captured
*
* @param string $regex A PCRE regex to filter messages by
* @return array The captured error messages
*/
static public function stopErrorCapture($regex=NULL)
{
$captures = self::$captured_errors;
self::$captured_error_regex = NULL;
self::$captured_errors_previous_handler = NULL;
self::$captured_error_types = NULL;
self::$captured_errors = NULL;
restore_error_handler();
if ($regex) {
$new_captures = array();
foreach ($captures as $capture) {
if (!preg_match($regex, $capture['string'])) { continue; }
$new_captures[] = $capture;
}
$captures = $new_captures;
}
return $captures;
}
/**
* Forces use as a static class
*
* @return fCore
*/
private function __construct() { }
}
/**
* Copyright (c) 2007-2011 Will Bond <will@flourishlib.com>, others
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/ | Java |
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved.
package com.blinkboxbooks.android.list;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MergeCursor;
import android.support.v4.content.AsyncTaskLoader;
import android.util.SparseArray;
import com.blinkboxbooks.android.model.Book;
import com.blinkboxbooks.android.model.BookItem;
import com.blinkboxbooks.android.model.Bookmark;
import com.blinkboxbooks.android.model.Query;
import com.blinkboxbooks.android.model.helper.BookHelper;
import com.blinkboxbooks.android.model.helper.BookmarkHelper;
import com.blinkboxbooks.android.util.LogUtils;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.List;
/*
* A loader that queries the {@link ContentResolver} and returns a {@link Cursor}.
* This class implements the {@link Loader} protocol in a standard way for
* querying cursors, building on {@link AsyncTaskLoader} to perform the cursor
* query on a background thread so that it does not block the application's UI.
*
* <p>A LibraryLoader must be built with the full information for the query to
* perform.
*/
public class LibraryLoader extends AsyncTaskLoader<List<BookItem>> {
final ForceLoadContentObserver mObserver;
List<BookItem> mBookItems;
private List<Query> mQueryList;
/**
* Creates an empty unspecified CursorLoader. You must follow this with
* calls to {@link #setQueryList(List<Query>)} to specify the query to
* perform.
*/
public LibraryLoader(Context context) {
super(context);
mObserver = new ForceLoadContentObserver();
}
/**
* Creates a fully-specified LibraryLoader.
*/
public LibraryLoader(Context context, List<Query> queryList) {
super(context);
mObserver = new ForceLoadContentObserver();
mQueryList = queryList;
}
public void setQueryList(List<Query> queryList) {
mQueryList = queryList;
}
/* Runs on a worker thread */
@Override
public List<BookItem> loadInBackground() {
Cursor cursor = null;
List<Cursor> cursorList = new ArrayList<Cursor>();
for (Query query : mQueryList) {
cursor = getContext().getContentResolver().query(query.uri, query.projection, query.selection, query.selectionArgs, query.sortOrder);
if (cursor != null) {
// Ensure the cursor window is filled
cursor.getCount();
// registerContentObserver(cursor, mObserver);
cursorList.add(cursor);
}
}
Cursor[] cursorArray = new Cursor[cursorList.size()];
List<BookItem> bookItemList;
if (cursorList.size() > 0) {
bookItemList = createBookItems(new MergeCursor(cursorList.toArray(cursorArray)));
for (Cursor c : cursorList) {
c.close();
}
} else {
// Return an empty book list
bookItemList = new ArrayList<BookItem>();
}
return bookItemList;
}
/**
* Registers an observer to get notifications from the content provider
* when the cursor needs to be refreshed.
*/
void registerContentObserver(Cursor cursor, ContentObserver observer) {
cursor.registerContentObserver(mObserver);
}
/* Runs on the UI thread */
@Override
public void deliverResult(List<BookItem> bookItems) {
if (isReset()) {
// An async query came in while the loader is stopped
return;
}
mBookItems = bookItems;
if (isStarted()) {
super.deliverResult(bookItems);
}
}
/**
* Starts an asynchronous load of the book list data. When the result is ready the callbacks
* will be called on the UI thread. If a previous load has been completed and is still valid
* the result may be passed to the callbacks immediately.
* <p/>
* Must be called from the UI thread
*/
@Override
protected void onStartLoading() {
if (mBookItems != null) {
deliverResult(mBookItems);
}
if (takeContentChanged() || mBookItems == null) {
forceLoad();
}
}
/**
* Must be called from the UI thread
*/
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
}
/**
* Takes a list of books from the Cursor and arranges them into a list of BookItem objects
*/
private List<BookItem> createBookItems(Cursor cursor) {
// Check for error cases
if (cursor == null || cursor.isClosed()) {
String error = String.format("Trying to create a new library item list with %s cursor.", cursor == null ? "null" : "closed");
Crashlytics.logException(new Exception(error));
LogUtils.stack();
List<BookItem> bookItems = new ArrayList<BookItem>();
return bookItems;
}
cursor.moveToFirst();
Book book;
Bookmark bookmark;
BookItem bookItem;
List<BookItem> booksList = new ArrayList<BookItem>();
while (!cursor.isAfterLast()) {
book = BookHelper.createBook(cursor);
bookmark = BookmarkHelper.createBookmark(cursor);
bookItem = new BookItem(book, bookmark, "", "", null);
booksList.add(bookItem);
cursor.moveToNext();
}
return booksList;
}
}
| Java |
# React
Implement a basic reactive system.
Reactive programming is a programming paradigm that focuses on how values
are computed in terms of each other to allow a change to one value to
automatically propagate to other values, like in a spreadsheet.
Implement a basic reactive system with cells with settable values ("input"
cells) and cells with values computed in terms of other cells ("compute"
cells). Implement updates so that when an input value is changed, values
propagate to reach a new stable system state.
In addition, compute cells should allow for registering change notification
callbacks. Call a cell’s callbacks when the cell’s value in a new stable
state has changed from the previous stable state.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## Writing the Code
Execute the tests with:
```bash
$ cargo test
```
All but the first test have been ignored. After you get the first test to
pass, remove the ignore flag (`#[ignore]`) from the next test and get the tests
to pass again. The test file is located in the `tests` directory. You can
also remove the ignore flag from all the tests to get them to run all at once
if you wish.
Make sure to read the [Modules](https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html) chapter if you
haven't already, it will help you with organizing your files.
## Feedback, Issues, Pull Requests
The [exercism/rust](https://github.com/exercism/rust) repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the [rust track team](https://github.com/orgs/exercism/teams/rust) are happy to help!
If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md).
[help-page]: http://exercism.io/languages/rust
[modules]: https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html
[cargo]: https://doc.rust-lang.org/book/second-edition/ch14-00-more-about-cargo.html
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
| Java |
<?php
return array (
'id' => 'samsung_d500_ver1_sub6226',
'fallback' => 'samsung_d500_ver1',
'capabilities' =>
array (
'max_data_rate' => '40',
),
);
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-multinomials: 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.13.2 / mathcomp-multinomials - 1.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-multinomials
<small>
1.1
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-11-25 05:11:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-25 05:11:20 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq 8.13.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "pierre-yves@strub.nu"
homepage: "https://github.com/math-comp/multinomials-ssr"
bug-reports: "https://github.com/math-comp/multinomials-ssr/issues"
dev-repo: "git+https://github.com/math-comp/multinomials.git"
license: "CeCILL-B"
authors: ["Pierre-Yves Strub"]
build: [
[make "INSTMODE=global" "config"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/SsrMultinomials"]
depends: [
"ocaml"
"coq" {>= "8.5"}
"coq-mathcomp-ssreflect" {>= "1.6" & < "1.8.0~"}
"coq-mathcomp-algebra" {>= "1.6" & < "1.8.0~"}
"coq-mathcomp-bigenough" {>= "1.0.0" & < "1.1.0~"}
"coq-mathcomp-finmap" {>= "1.0.0" & < "1.1.0~"}
]
tags: [
"keyword:multinomials"
"keyword:monoid algebra"
"category:Math/Algebra/Multinomials"
"category:Math/Algebra/Monoid algebra"
"date:2016"
"logpath:SsrMultinomials"
]
synopsis: "A multivariate polynomial library for the Mathematical Components Library"
flags: light-uninstall
url {
src: "https://github.com/math-comp/multinomials/archive/1.1.tar.gz"
checksum: "md5=e22b275b1687878d2bdc9b6922d9fde5"
}
</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-mathcomp-multinomials.1.1 coq.8.13.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.13.2).
The following dependencies couldn't be met:
- coq-mathcomp-multinomials -> coq-mathcomp-finmap < 1.1.0~ -> coq-mathcomp-ssreflect < 1.8~ -> coq < 8.10~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
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-mathcomp-multinomials.1.1</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://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
using System;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Castle.Core;
using DotJEM.Json.Storage.Adapter;
using DotJEM.Pipelines;
using DotJEM.Web.Host.Diagnostics.Performance;
using DotJEM.Web.Host.Providers.Concurrency;
using DotJEM.Web.Host.Providers.Services.DiffMerge;
using Newtonsoft.Json.Linq;
namespace DotJEM.Web.Host.Providers.Services
{
public interface IContentService
{
IStorageArea StorageArea { get; }
Task<JObject> GetAsync(Guid id, string contentType);
Task<JObject> PostAsync(string contentType, JObject entity);
Task<JObject> PutAsync(Guid id, string contentType, JObject entity);
Task<JObject> PatchAsync(Guid id, string contentType, JObject entity);
Task<JObject> DeleteAsync(Guid id, string contentType);
}
//TODO: Apply Pipeline for all requests.
[Interceptor(typeof(PerformanceLogAspect))]
public class ContentService : IContentService
{
private readonly IStorageArea area;
private readonly IStorageIndexManager manager;
private readonly IPipelines pipelines;
private readonly IContentMergeService merger;
public IStorageArea StorageArea => area;
public ContentService(IStorageArea area,
IStorageIndexManager manager,
IPipelines pipelines,
IJsonMergeVisitor merger)
{
this.area = area;
this.manager = manager;
this.pipelines = pipelines;
this.merger = new ContentMergeService(merger, area);
}
public Task<JObject> GetAsync(Guid id, string contentType)
{
HttpGetContext context = new (contentType, id);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Get(ctx.Id)));
return pipeline.Invoke();
}
public async Task<JObject> PostAsync(string contentType, JObject entity)
{
HttpPostContext context = new (contentType, entity);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Insert(ctx.ContentType, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> PutAsync(Guid id, string contentType, JObject entity)
{
JObject prev = area.Get(id);
entity = merger.EnsureMerge(id, entity, prev);
HttpPutContext context = new (contentType, id, entity, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> PatchAsync(Guid id, string contentType, JObject entity)
{
JObject prev = area.Get(id);
//TODO: This can be done better by simply merging the prev into the entity but skipping
// values that are present in the entity. However, we might wan't to inclide the raw patch
// content in the pipeline as well, so we need to consider pro/cons
JObject clone = (JObject)prev.DeepClone();
clone.Merge(entity);
entity = clone;
entity = merger.EnsureMerge(id, entity, prev);
HttpPatchContext context = new (contentType, id, entity, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> DeleteAsync(Guid id, string contentType)
{
JObject prev = area.Get(id);
if (prev == null)
return null;
HttpDeleteContext context = new (contentType, id, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Delete(ctx.Id)));
JObject deleted = await pipeline.Invoke().ConfigureAwait(false);
//Note: This may pose a bit of a problem, because we don't lock so far out (performance),
// this can theoretically happen if two threads or two nodes are trying to delete the
// same object at the same time.
if (deleted == null)
return null;
manager.QueueDelete(deleted);
return deleted;
}
}
public class HttpPipelineContext : PipelineContext
{
public HttpPipelineContext(string method, string contentType)
{
this.Set(nameof(method), method);
this.Set(nameof(contentType), contentType);
}
}
public class HttpGetContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid) Get("id");
public HttpGetContext(string contentType, Guid id)
: base("GET", contentType)
{
Set(nameof(id), id);
}
}
public class HttpPostContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public JObject Entity => (JObject)Get("entity");
public HttpPostContext( string contentType, JObject entity)
: base("POST", contentType)
{
Set(nameof(entity), entity);
}
}
public class HttpPutContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid) Get("id");
public JObject Entity => (JObject)Get("entity");
public JObject Previous => (JObject)Get("previous");
public HttpPutContext(string contentType, Guid id, JObject entity, JObject previous)
: base("PUT", contentType)
{
Set(nameof(id), id);
Set(nameof(entity), entity);
Set(nameof(previous), previous);
}
}
public class HttpPatchContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid)Get("id");
public JObject Entity => (JObject)Get("entity");
public JObject Previous => (JObject)Get("previous");
public HttpPatchContext(string contentType, Guid id, JObject entity, JObject previous)
: base("PATCH", contentType)
{
Set(nameof(id), id);
Set(nameof(entity), entity);
Set(nameof(previous), previous);
}
}
public class HttpDeleteContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid)Get("id");
public HttpDeleteContext(string contentType, Guid id, JObject previous)
: base("DELETE", contentType)
{
Set(nameof(id), id);
Set(nameof(previous), previous);
}
}
} | Java |
package com.gdgand.rxjava.rxjavasample.hotandcold;
import android.app.Application;
import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent;
import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent;
import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule;
import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule;
public class SampleApplication extends Application {
private ApplicationComponent applicationComponent;
@Override
public void onCreate() {
super.onCreate();
applicationComponent = createComponent();
}
private ApplicationComponent createComponent() {
return DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.dataModule(new DataModule())
.build();
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
| Java |
'use strict'
var solc = require('solc/wrapper')
var compileJSON = function () { return '' }
var missingInputs = []
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data
switch (data.cmd) {
case 'loadVersion':
delete self.Module
// NOTE: workaround some browsers?
self.Module = undefined
compileJSON = null
self.importScripts(data.data)
var compiler = solc(self.Module)
compileJSON = function (input) {
try {
return compiler.compileStandardWrapper(input, function (path) {
missingInputs.push(path)
return { 'error': 'Deferred import' }
})
} catch (exception) {
return JSON.stringify({ error: 'Uncaught JavaScript exception:\n' + exception })
}
}
self.postMessage({
cmd: 'versionLoaded',
data: compiler.version()
})
break
case 'compile':
missingInputs.length = 0
self.postMessage({cmd: 'compiled', job: data.job, data: compileJSON(data.input), missingInputs: missingInputs})
break
}
}, false)
}
| Java |
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { SettingsComponent } from './settings.component';
describe('HomeComponent', () => {
let component: SettingsComponent;
let fixture: ComponentFixture<SettingsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SettingsComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SettingsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Java |
//Express, Mongo & Environment specific imports
var express = require('express');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var errorHandler = require('errorhandler');
var mongo = require('./api/config/db');
var env = require('./api/config/env');
// Controllers/Routes import
var BookController = require('./api/controller/BookController');
//MongoDB setup
mongo.createConnection(env.mongoUrl);
//Express setup
var app = express();
//Express middleware
app.use(morgan('short'));
app.use(serveStatic(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
var environment = process.env.NODE_ENV || 'development';
if ('development' == environment) {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
var ImportController = require('./api/controller/ImportController');
app.get('/import', ImportController.import);
app.get('/import/reset', ImportController.reset);
}
// Route definitions
app.get('/api/books', BookController.list);
app.get('/api/books/:id', BookController.show);
app.post('api/books', BookController.create);
app.put('/api/books/:id', BookController.update);
app.delete('/api/books/:id', BookController.remove);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Books app listening at http://%s:%s', host, port);
console.log("Configured MongoDB URL: " + env.mongoUrl);
});
| Java |
[instagram-private-api](../../README.md) / [index](../../modules/index.md) / DirectInboxFeedResponseInbox
# Interface: DirectInboxFeedResponseInbox
[index](../../modules/index.md).DirectInboxFeedResponseInbox
## Table of contents
### Properties
- [blended\_inbox\_enabled](DirectInboxFeedResponseInbox.md#blended_inbox_enabled)
- [has\_older](DirectInboxFeedResponseInbox.md#has_older)
- [oldest\_cursor](DirectInboxFeedResponseInbox.md#oldest_cursor)
- [threads](DirectInboxFeedResponseInbox.md#threads)
- [unseen\_count](DirectInboxFeedResponseInbox.md#unseen_count)
- [unseen\_count\_ts](DirectInboxFeedResponseInbox.md#unseen_count_ts)
## Properties
### blended\_inbox\_enabled
• **blended\_inbox\_enabled**: `boolean`
#### Defined in
[src/responses/direct-inbox.feed.response.ts:15](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L15)
___
### has\_older
• **has\_older**: `boolean`
#### Defined in
[src/responses/direct-inbox.feed.response.ts:11](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L11)
___
### oldest\_cursor
• **oldest\_cursor**: `string`
#### Defined in
[src/responses/direct-inbox.feed.response.ts:14](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L14)
___
### threads
• **threads**: [`DirectInboxFeedResponseThreadsItem`](../../classes/index/DirectInboxFeedResponseThreadsItem.md)[]
#### Defined in
[src/responses/direct-inbox.feed.response.ts:10](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L10)
___
### unseen\_count
• **unseen\_count**: `number`
#### Defined in
[src/responses/direct-inbox.feed.response.ts:12](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L12)
___
### unseen\_count\_ts
• **unseen\_count\_ts**: `string`
#### Defined in
[src/responses/direct-inbox.feed.response.ts:13](https://github.com/Nerixyz/instagram-private-api/blob/0e0721c/src/responses/direct-inbox.feed.response.ts#L13)
| Java |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var ConversationHeaderComponent = (function () {
function ConversationHeaderComponent() {
}
ConversationHeaderComponent.prototype.ngOnInit = function () {
};
__decorate([
core_1.Input(),
__metadata('design:type', Object)
], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0);
ConversationHeaderComponent = __decorate([
core_1.Component({
selector: 'ngm-conversation-header',
styleUrls: ['./conversation-header.component.scss'],
templateUrl: './conversation-header.component.html'
}),
__metadata('design:paramtypes', [])
], ConversationHeaderComponent);
return ConversationHeaderComponent;
}());
exports.ConversationHeaderComponent = ConversationHeaderComponent;
//# sourceMappingURL=conversation-header.component.js.map | Java |
const describe = require("mocha").describe;
const it = require("mocha").it;
const assert = require("chai").assert;
const HttpError = require("./HttpError");
describe("HttpError", function () {
it("should be instance of Error", function () {
const testSubject = new HttpError();
assert.isOk(testSubject instanceof Error);
});
});
| Java |
import { inject, injectable } from 'inversify';
import TYPES from '../../di/types';
import * as i from '../../i';
import { RunOptions } from '../../models';
import { IInputConfig } from '../../user-extensibility';
import { BaseInputManager } from '../base-input-manager';
var NestedError = require('nested-error-stacks');
@injectable()
export class CustomInputManager extends BaseInputManager {
constructor(
@inject(TYPES.HandlerService) private handlerService: i.IHandlerService
) {
super();
}
async ask(config: IInputConfig, options: RunOptions): Promise<{ [key: string]: any }> {
try {
const handler: Function = await this.handlerService
.resolveAndLoad(this.tmplRootPath, config.handler);
return handler(config);
} catch (ex) {
throw new NestedError("Error running handler for input configuration", ex);
}
}
} | Java |
<?php
if (!file_exists('./../include/config.php')){
header('Location:install.php');
}
include('./../include/config.php');
include('./../include/functions.php');
if (isset($_POST['step']))
$step = intval($_POST['step']);
else{
$step = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SPC - DB Upgrade</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./../css/spc.css" type="text/css" media="screen" />
<link rel="icon" type="image/png" href="./../favicon.png" />
<style type="text/css">
body{
font-size: 16px;
}
h1, h2{
color: #ff0056;
margin: 6px;
}
h1{
font-size: 60px;
}
dt{
color: #999;
}
dd, dl{
margin-left: 10px;
}
p{
margin-left: 10px;
margin-bottom: 10px;
}
.code{
border: 1px solid #ff0056;
padding: 6px;
}
</style>
</head>
<body>
<div id="wrap">
<h1>Welcome to Simple Photos Contest DataBase Upgrader</h1>
<?php
switch($step){
case 0: ?>
<form class="large" method="POST" action="upgrade.php">
<p><em>This installer will be displayed in english only</em>.</p>
<p>It's <b>highly recommended</b> to do an SQL backup before upgrading.</p>
<div class="form_buttons">
<input type="submit" value="Upgrade" name="submit"/>
<input type="hidden" name="step" value="1"/>
</div>
<?php
break;
case 1 :?>
<form class="large" method="POST" action="../index.php">
<p>Upgrade from <a href="#"><?php
if(!isset($settings->spc_version) or $settings->spc_version=="")
echo "Unknown(2.0?)";
else
echo $settings->spc_version;
?></a> to <a href="#" title="<?php echo SPC_VERSION; ?>"><?php echo SPC_VERSION_DB; ?></a></p>
<?php
if(!isset($settings->spc_version) or $settings->spc_version=="")
$ver = 0;
else
$ver = $settings->spc_version;
function sqlalter($command){
global $bd;
if (!mysqli_query($bd,"ALTER TABLE ".$command)) {
die("Error : ". mysqli_error($bd));
}
}
switch($ver)
{
case SPC_VERSION_DB:
echo " <p>No upgraded needed</p>";
break;
case 0:
sqlalter("`contests` ADD `icon` VARCHAR(200) NOT NULL");
sqlalter("`settings` ADD `language_auto` BOOLEAN NOT NULL") ;
sqlalter("`settings` ADD `homepage` BOOLEAN NOT NULL") ;
sqlalter("`settings` ADD `auth_method` INT(2) NOT NULL , ADD `spc_version` VARCHAR(8) NOT NULL") ;
sqlalter("`image_ip` CHANGE `ip_add` `ip_add` BIGINT NULL DEFAULT NULL;");
//case "3.0 A2":
if (!mysqli_query($bd, "UPDATE `settings` SET `spc_version`='".SPC_VERSION_DB."' WHERE 1")) {
die("Error : ". mysqli_error($bd));
}
echo " <p>Done!</a></p>";
break;
default:
echo " <p>Your version were not found. </p>";
break;
}
?>
<div class="form_buttons">
<input type="submit" value="Home" name="submit"/>
<input type="hidden" name="step" value="1"/>
</div>
</form>
<?php
break;
}
?>
</form>
</div>
<script>
var noTiling = true;
</script>
<script type="text/javascript" src="./../js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="./../js/jquery.freetile.min.js"></script>
<script type="text/javascript" src="./../js/contest.js"></script>
</body>
</html>
| Java |
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2>_PS_CLIENT_SECURITY_CONTEXT</h2>
<font face="arial"> +0x000 ImpersonationData : Uint8B<br>
+0x000 ImpersonationToken : Ptr64 Void<br>
+0x000 ImpersonationLevel : Pos 0, 2 Bits<br>
+0x000 EffectiveOnly : Pos 2, 1 Bit<br>
</font></body></html> | Java |
package io.blitz.curl.exception;
/**
* Exceptions thrown when a validation error occur during a test execution
* @author ghermeto
*/
public class ValidationException extends BlitzException {
/**
* Constructs an instance of <code>ValidationException</code> with the
* specified error and reason message.
* @param reason the detailed error message.
*/
public ValidationException(String reason) {
super("validation", reason);
}
}
| Java |
<html><body>
<h4>Windows 10 x64 (19041.508)</h4><br>
<h2>_RTL_FEATURE_CONFIGURATION_PRIORITY</h2>
<font face="arial"> FeatureConfigurationPriorityAll = 0n0<br>
FeatureConfigurationPriorityService = 0n4<br>
FeatureConfigurationPriorityUser = 0n8<br>
FeatureConfigurationPriorityTest = 0n12<br>
FeatureConfigurationPriorityMax = 0n15<br>
</font></body></html> | Java |
/**
* jQuery object.
* @external jQuery
* @see {@link http://api.jquery.com/jQuery/}
*/
/**
* The jQuery plugin namespace.
* @external "jQuery.fn"
* @see {@link http://docs.jquery.com/Plugins/Authoring The jQuery Plugin Guide}
*/
/**
* The plugin global configuration object.
* @external "jQuery.vulcanup"
* @property {String} version - The plugin version.
* @property {settings} defaults - The default configuration.
* @property {Object} templates - The default templates.
*/
require('./jup-validation');
const templates = require('./templates');
const constants = require('./constants');
const defaults = require('./defaults');
const methods = require('./methods');
const utils = require('./utils');
const version = '1.0.0-beta';
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
/**
* Invoke on a `<input type="file">` to set it as a file uploader.
*
* By default the configuration is {@link settings} but you can pass an object
* to configure it as you want.
*
* Listen to event changes on the same input, review demo to see how to implement them
* and what parameters they receive:
*
* **`vulcanup-val`** - On validation error. Receives as parameter an object with the error message.
*
* **`vulcanup-upload`** - On file started to being uploaded.
*
* **`vulcanup-progress`** - On upload progress update. Receives as parameter the progress number.
*
* **`vulcanup-error`** - On server error. Receives as parameter an object with details.
*
* **`vulcanup-change`** - On file change. This is triggered when the user uploads
* a file in the server, when it is deleted or when it is changed programmatically.
* Receives as parameter an object with the new file details.
*
* **`vulcanup-delete`** - On file deleted. Receives as parameter the deleted file details.
*
* **`vulcanup-uploaded`** - On file uploaded in the server.
*
* **`vulcanup-complete`** - On upload process completed. This is fired when the
* XHR is finished, regardless of fail or success.
*
* @function external:"jQuery.fn".vulcanup
*
* @param {settings} [settings] - Optional configuration.
*
* @example
* $('input[type=file]').vulcanup({
* url: '/initial/file/url.ext'
* });
*/
jQuery.fn.vulcanup = function (settings) {
'use strict';
const $input = $(this).first();
if (typeof settings === 'string') {
if (methods[settings]) {
if (!$input.data(`vulcanup-config`)) {
throw new Error(`vulcanup element is not instantiated, cannot invoke methods`);
}
const args = Array.prototype.slice.call(arguments, 1);
return methods[settings].apply($input, args);
} else {
throw new Error(`vulcanup method unrecognized "${settings}".`);
}
}
if ($input.data(`vulcanup-config`)) return this;
//
// CONFIGURATION
//
let id = $input.attr('id');
if (!id) {
id = 'vulcanup-'+ (new Date()).getTime();
$input.attr('id', id);
}
if ($input.attr('multiple') !== undefined) {
throw new Error('Input type file cannot be multiple');
}
const conf = $.extend(true, {}, defaults, settings, {
_id: id,
fileupload: {
fileInput: $input
}
});
// File type validation.
if (conf.types[conf.type]) {
conf._type = conf.types[conf.type];
conf.fileupload.acceptFileTypes = conf._type.formats;
} else {
throw new Error('A valid type of file is required');
}
$input.data(`vulcanup-config`, conf);
//
// DOM
//
const $container = $(utils.format(templates.main, conf));
const $validations = $(utils.format(templates.validations, conf));
const $remove = $container.find('.vulcanup__remove');
const $dropzone = $container.find('.vulcanup__dropzone');
const $msg = $container.find('.vulcanup__msg');
$remove.attr('title', utils.format(conf.messages.REMOVE, conf._type));
$input.addClass('vulcanup-input vulcanup-input__hidden');
$input.after($container);
$container.after($validations);
conf.fileupload.dropZone = $container;
conf._$validations = $validations;
conf._$container = $container;
conf._$dropzone = $dropzone;
conf._$msg = $msg;
if (conf.type === 'image') {
$container.addClass('vulcanup_isimage');
}
if (conf.imageContain) {
$container.addClass('vulcanup_isimagecontain');
}
if (!conf.enableReupload) {
$container.addClass('vulcanup_noreupload');
}
if (conf.canRemove) {
$container.addClass('vulcanup_canremove');
}
//
// EVENTS
//
$input.
// On click.
on('click', function (e) {
if (conf._uploading || (conf._url && !conf.enableReupload)) {
e.preventDefault();
return false;
}
}).
// On user error.
on('fileuploadprocessfail', function (e, info) {
const err = info.files[0].error;
methods.setValidation.call($input, err);
}).
// On send.
on('fileuploadsend', function (e, data) {
methods.setUploading.call($input);
}).
// On server progress.
on('fileuploadprogressall', function (e, data) {
const progress = parseInt(data.loaded / data.total * 100, 10);
methods.updateProgress.call($input, progress);
}).
// On server success.
on('fileuploaddone', function (e, data) {
const files = data.files;
const result = data.result;
if (conf.handler) {
const info = conf.handler(result);
if (typeof info !== 'object') {
methods.setError.call($input);
throw new Error('handler should return file object info');
}
if (typeof info.url !== 'string') {
methods.setError.call($input);
throw new Error('handler should return file url property');
}
methods.setUploaded.call($input, {
url: info.url,
file: files[0]
});
}
else if (result && result.files && result.files.length) {
methods.setUploaded.call($input, {
url: result.files[0].url,
file: files[0]
});
}
else {
methods.setError.call($input);
}
}).
// On server error.
on('fileuploadfail', function (e, data) {
methods.setError.call($input);
});
$dropzone.
on('dragenter dragover', e => {
$container.addClass('vulcanup_dragover');
}).
on('dragleave drop', e => {
$container.removeClass('vulcanup_dragover');
});
$container.find('.vulcanup__remove').on('click', function (e) {
e.preventDefault();
$input.trigger(`vulcanup-delete`, { url: conf._url, name: conf._name });
$input.trigger(`vulcanup-change`, { url: null, name: null });
methods.updateProgress.call($input, 0, {silent: true});
methods.setUpload.call($input);
return false;
});
//
// CREATING AND SETTING
//
$input.fileupload(conf.fileupload);
if (conf.url) {
methods.setUploaded.call(this, {
url: conf.url,
name: conf.name,
initial: true
});
} else {
methods.setUpload.call(this);
}
return this;
};
module.exports = jQuery.vulcanup = { version, defaults, templates };
| Java |
const test = require('tape')
const nlp = require('../_lib')
test('match min-max', function(t) {
let doc = nlp('hello1 one hello2').match('#Value{7,9}')
t.equal(doc.out(), '', 'match was too short')
doc = nlp('hello1 one two three four five hello2').match('#Value{3}')
t.equal(doc.out(), 'one two three', 'exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,3}')
t.equal(doc.out(), 'one two three', 'still exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,}')
t.equal(doc.out(), 'one two three four five', 'minimum three')
doc = nlp('hello1 one two three four five hello2').match('hello1 .{3}')
t.equal(doc.out(), 'hello1 one two three', 'unspecific greedy exact length')
doc = nlp('hello1 one two').match('hello1 .{3}')
t.equal(doc.out(), '', 'unspecific greedy not long enough')
t.end()
})
| Java |
# encoding: utf-8
require 'webmock/rspec'
require 'vcr'
require_relative '../lib/spotifiery'
VCR.configure do |config|
config.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
config.hook_into :webmock
end
| Java |
class Tweet < ActiveRecord::Base
# Remember to create a migration!
belongs_to :user
end
| Java |
using System.IO;
using System.Runtime.InteropServices;
internal static class Example
{
[STAThread()]
public static void Main()
{
SolidEdgeFramework.Application objApplication = null;
SolidEdgeAssembly.AssemblyDocument objAssemblyDocument = null;
SolidEdgeAssembly.StructuralFrames objStructuralFrames = null;
// SolidEdgeAssembly.StructuralFrame objStructuralFrame = null;
try
{
OleMessageFilter.Register();
objApplication = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
objAssemblyDocument = objApplication.ActiveDocument;
objStructuralFrames = objAssemblyDocument.StructuralFrames;
// Loop through all of the structural frames.
foreach (SolidEdgeAssembly.StructuralFrame objStructuralFrame in objStructuralFrames)
{
objStructuralFrame.RetrieveHoleLocation();
objStructuralFrame.DeleteHoleLocation();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
OleMessageFilter.Revoke();
}
}
} | Java |
#!/usr/bin/env ruby
require 'json'
SRC_RANDOM = Random.new(1984)
MAX_VALUES = Hash.new(1).update "rcat" => 50, "vcat" => 50, "infq" => 5, "kws" => 10
MRG_VALUES = {
"dev" => ["oth","oth","oth","oth","oth","oth"],
"bwsm" => ["ff", "sf", "op", "ng", "kq", "an", "ms", "kk", "mo"],
"pos" => [2, 4, 5, 6, 7],
"mob" => [0] * 8,
"loc" => ["en","en","en","en","en","en","en","en","en","en","en","en","es","es","es","es"],
}
targets = []
attrs = {}
File.open(File.expand_path("../targets.json", __FILE__)) do |file|
targets = JSON.load(file)
end
targets.each do |target|
target['rules'].each do |rule|
attrs[rule['attr']] ||= []
attrs[rule['attr']].concat rule['values']
end
end
attrs.keys.each do |name|
attrs[name] = attrs[name].sort.uniq
attrs[name].concat(MRG_VALUES[name] || [])
end
File.open(File.expand_path("../facts.json", __FILE__), "w") do |file|
10000.times do |_|
fact = {}
attrs.each do |name, values|
vals = if MAX_VALUES[name] == 1
values.sample
else
values.sample(SRC_RANDOM.rand(MAX_VALUES[name])+1)
end
fact[name] = vals
end
file.puts JSON.dump(fact)
end
end
p attrs.keys
| Java |
#Upselling
2016-06-01
Upselling is a sales technique whereby a seller induces the customer to purchase more expensive items, upgrades or other add-ons in an attempt to make a more profitable sale. While it usually involves marketing more profitable services or products, it can be simply exposing the customer to other options that were perhaps not considered. (A different technique is cross-selling in which a seller tries to sell something else.) In practice, large businesses usually combine upselling and cross-selling to maximize profit. In doing so, an organization must ensure that its relationship with the client is not disrupted.
Business models as freemium or premium could enter in this techniques.
***Tags***: Marketing, Business
#### See also
[Business Intelligence](/business_intelligence), [Business models](/business_models), [Cross-selling](/cross-selling)
| Java |
package com.lht.dot.ui.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.bumptech.glide.Glide;
/**
* Created by lht-Mac on 2017/7/11.
*/
public class PhotoShotRecyclerView extends RecyclerView {
View mDispatchToView;
public PhotoShotRecyclerView(Context context) {
super(context);
init();
}
public PhotoShotRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
switch (newState) {
case RecyclerView.SCROLL_STATE_SETTLING:
Glide.with(getContext()).pauseRequests();
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
case RecyclerView.SCROLL_STATE_IDLE:
Glide.with(getContext()).resumeRequests();
break;
}
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(mDispatchToView==null){
return super.dispatchTouchEvent(event);
}else{
return mDispatchToView.dispatchTouchEvent(event);
}
}
public View getDispatchToView() {
return mDispatchToView;
}
public void setDispatchToView(View dispatchToView) {
this.mDispatchToView = dispatchToView;
}
public void clearDispatchToView() {
setDispatchToView(null);
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GPS.SimpleMVC.Views;
namespace GPS.SimpleMVC.Tests.ControllerImplementations
{
public interface ITestView : ISimpleView
{
Guid UID { get; set; }
string Name { get; set; }
string Value { get; set; }
event Func<Guid, Guid, Task> LoadDataAsync;
event Action<ITestView> DataBound;
void Databind();
}
}
| Java |
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// We explicitly import the modular kernels so they get registered in the
// global registry when we compile the library. A modular build would replace
// the contents of this file and import only the kernels that are needed.
import {KernelConfig, registerKernel} from '../../kernel_registry';
import {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';
import {squareConfig} from './kernels/Square';
import {squaredDifferenceConfig} from './kernels/SquaredDifference';
// List all kernel configs here
const kernelConfigs: KernelConfig[] = [
nonMaxSuppressionV5Config,
squareConfig,
squaredDifferenceConfig,
];
for (const kernelConfig of kernelConfigs) {
registerKernel(kernelConfig);
}
| Java |
function ones(rows, columns) {
columns = columns || rows;
if (typeof rows === 'number' && typeof columns === 'number') {
const matrix = [];
for (let i = 0; i < rows; i++) {
matrix.push([]);
for (let j = 0; j < columns; j++) {
matrix[i].push(1);
}
}
return matrix;
}
throw new TypeError('Matrix dimensions should be integers.');
}
module.exports = ones;
| Java |
<?php
namespace LolApi\Classes\TournamentProvider;
/**
* TournamentCodeParameters
*
* @author Javier
*/
class TournamentCodeParameters {
// ~ maptype ~
const MAPTYPE_SUMMONERS_RIFT='SUMMONERS_RIFT';
const MAPTYPE_TWISTED_TREELINE='TWISTED_TREELINE';
const MAPTYPE_HOWLING_ABYSS='HOWLING_ABYSS';
// ~ pickType ~
const PICKTYPE_BLIND_PICK='BLIND_PICK';
const PICKTYPE_DRAFT_MODE='DRAFT_MODE';
const PICKTYPE_ALL_RANDOM='ALL_RANDOM';
const PICKTYPE_TOURNAMENT_DRAFT='TOURNAMENT_DRAFT';
// ~ SPECTATORTYPE ~
const SPECTATORTYPE_NONE='NONE';
const SPECTATORTYPE_LOBBYONLY='LOBBYONLY';
const SPECTATORTYPE_ALL='';
/**
* Optional list of participants in order to validate the players eligible
* to join the lobby. NOTE: We currently do not enforce participants at the
* team level, but rather the aggregate of teamOne and teamTwo. We may add
* the ability to enforce at the team level in the future.
* @var SummonerIdParams
*/
public $allowedSummonerIds;
/**
* The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, and HOWLING_ABYSS.
* @var string
*/
public $mapType;
/**
* Optional string that may contain any data in any format, if specified at all. Used to denote any custom information about the game.
* @var string
*/
public $metadata;
/**
* The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT.
* @var string
*/
public $pickType;
/**
* The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL.
* @var string
*/
public $spectatorType;
/**
* The team size of the game. Valid values are 1-5.
* @var int
*/
public $teamSize;
function __construct($d) {
$this->allowedSummonerIds = new SummonerIdParams($d->allowedSummonerIds);
$this->mapType = $d->mapType;
$this->metadata = $d->metadata;
$this->pickType = $d->pickType;
$this->spectatorType = $d->spectatorType;
$this->teamSize = $d->teamSize;
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.4.0/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Animate Position Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var hexagon = new Konva.RegularPolygon({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
sides: 6,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
layer.add(hexagon);
stage.add(layer);
var amplitude = 100;
var period = 2000;
// in ms
var centerX = stage.getWidth() / 2;
var anim = new Konva.Animation(function(frame) {
hexagon.setX(amplitude * Math.sin(frame.time * 2 * Math.PI / period) + centerX);
}, layer);
anim.start();
</script>
</body>
</html> | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.