code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
#------------------------------------------------------------------------------
# Copyright (c) 2013 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
class TavernaPlayer::RunsController < ApplicationController
# Do not remove the next line.
include TavernaPlayer::Concerns::Controllers::RunsController
# Extend the RunsController here.
private
alias_method :old_find_run, :find_run
def update_params
params.require(:run).permit(:name, :policy_attributes => [:id, :public_permissions => []])
end
def run_params
params.require(:run).permit(
:create_time, :delayed_job, :embedded, :finish_time, :inputs_attributes,
:log, :name, :parent_id, :results, :run_id, :start_time,
:status_message_key, :user_id, :workflow_id,
:inputs_attributes => [:depth, :file, :metadata, :name, :value],
:policy_attributes => [:id, :public_permissions => []]
)
end
def find_runs
select = { :embedded => false }
select[:workflow_id] = params[:workflow_id] if params[:workflow_id]
@runs = TavernaPlayer::Run.where(select).order("created_at DESC").with_permissions(current_user, :view).page(params[:page])
end
def find_run
old_find_run
authorize(@run.can?(current_user, action_name))
end
end
| Java |
package com.pablodomingos.classes.rps.servicos;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import com.pablodomingos.classes.FabricaDeObjetosFake;
public class LoteRpsConsultaTest {
@Test
public void xmlDeveSerGeradoCorretamente() throws IOException{
String xmlTest = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("loteRPSConsulta.xml"));
LoteRpsConsulta consultaLote = new LoteRpsConsulta("AP1057893n16X103sfhF4RPm", FabricaDeObjetosFake.getRpsPrestador());
String xml = consultaLote.converterParaXml();
Assert.assertEquals(xml, xmlTest);
}
}
| Java |
var common = require('../common');
var connection = common.createConnection({port: common.fakeServerPort});
var assert = require('assert');
var server = common.createFakeServer();
var connectErr;
server.listen(common.fakeServerPort, function(err) {
if (err) throw err;
connection.connect(function(err) {
connectErr = err;
server.destroy();
});
});
server.on('connection', function(incomingConnection) {
var errno = 1130; // ER_HOST_NOT_PRIVILEGED
incomingConnection.deny('You suck.', errno);
});
process.on('exit', function() {
assert.equal(connectErr.code, 'ER_HOST_NOT_PRIVILEGED');
assert.equal(connectErr.fatal, true);
});
| Java |
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Export de la structure de la base pour chacal
CREATE DATABASE IF NOT EXISTS `chacal` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `chacal`;
-- Export de la structure de table chacal. items
CREATE TABLE IF NOT EXISTS `items` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`category` varchar(255) NOT NULL DEFAULT '""',
`desc` text NOT NULL DEFAULT '""',
`notation` time NOT NULL DEFAULT '00:00:00',
`positionlat` double DEFAULT NULL,
`postionlong` double DEFAULT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Export de la structure de table chacal. what
CREATE TABLE IF NOT EXISTS `what` (
`item_id` bigint(20) NOT NULL,
`what` varchar(255) NOT NULL,
`how` varchar(255) NOT NULL,
KEY `FK_what_items` (`item_id`),
CONSTRAINT `FK_what_items` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| Java |
/*!
* @license MIT
* Copyright (c) 2017 Bernhard Grünewaldt - codeclou.io
* https://github.com/cloukit/legal
*/
import { Component, Input } from '@angular/core';
import * as _ from 'lodash';
@Component({
selector: 'app-component-info-header',
template: `
<div class="info-header">
<div class="info-header-buttons">
<span
class="vendor-logo-link"
[ngStyle]="getButtonStyle(getStatusSwitchNameForComponentStatus(componentStatus))"
(mouseover)="hoverStatus(componentStatus)"
(mouseleave)="resetSwitchState()"
><img [src]="getComponentStatusUri()" class="vendor-logo"></span>
<a
href="https://www.npmjs.com/package/@cloukit/{{componentName}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('npm')"
(mouseover)="switchState.npm=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('npm')" class="vendor-logo"></a>
<a
href="https://github.com/cloukit/{{componentName}}/tree/{{componentVersion}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('github')"
(mouseover)="switchState.github=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('github')" class="vendor-logo"></a>
<a
href="https://unpkg.com/@cloukit/{{componentName}}@{{componentVersion}}/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('unpkg')"
(mouseover)="switchState.unpkg=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('unpkg')" class="vendor-logo"></a>
<a
href="https://cloukit.github.io/{{componentName}}/{{componentVersion}}/documentation/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('compodoc')"
(mouseover)="switchState.compodoc=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('compodoc')" class="vendor-logo"></a>
</div>
<div class="info-header-bar" [ngStyle]="getInfoHeaderStyle()">
<div class="info-header-bar-content">
<div *ngIf="isSwitchStateOn()">
{{switchState.statusExperimental ? 'API might change unexpectedly. Use at own risk. It is alive!' : ''}}
{{switchState.statusStable ? 'API should be stable.' : ''}}
{{switchState.npm ? 'Show package page on npmjs.com' : ''}}
{{switchState.github ? 'Show example project on github.com' : ''}}
{{switchState.unpkg ? 'Show dist contents on unpkg.com' : ''}}
{{switchState.compodoc ? 'Show detailed Component Documentation' : ''}}
</div>
</div>
</div>
</div>`,
styles: [
'.vendor-logo { width:120px; }',
'.info-header-bar { height:40px; width:100%; }',
'.info-header-bar-content { width:100%; padding: 10px; text-align:center; }',
'.info-header-buttons { display: flex; justify-content: space-between; }',
'.vendor-logo-link { display:flex; width: 120px; min-width:120px; max-width: 120px; padding:0; height:65px; }',
],
})
export class ComponentInfoHeaderComponent {
@Input()
componentName: string;
@Input()
componentVersion: string;
@Input()
componentStatus: string;
private initialSwitchState = {
npm: false,
unpkg: false,
github: false,
compodoc: false,
statusStable: false,
statusExperimental: false,
};
private colors = {
npm: {
bg: '#cb3837',
fg: '#fff',
},
unpkg: {
bg: '#000',
fg: '#fff',
},
github: {
bg: '#0366d6',
fg: '#fff',
},
compodoc: {
bg: '#2582d5',
fg: '#fff',
},
statusStable: {
bg: '#4ad57d',
fg: '#fff',
},
statusExperimental: {
bg: '#d55900',
fg: '#fff',
},
};
switchState = Object.assign({}, this.initialSwitchState);
getSwitchState(name: string) {
return this.switchState[name] ? 'on' : 'off';
}
isSwitchStateOn() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return true;
}
}
return false;
}
getOnSwitchName() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return pair[0];
}
}
return null;
}
getVendorLogo(name: string) {
return `/assets/images/vendor-logos/${name}-${this.getSwitchState(name)}.svg`;
}
resetSwitchState() {
this.switchState = Object.assign({}, this.initialSwitchState);
}
getButtonStyle(name: string) {
return this.switchState[name] ? {
border: `3px solid ${this.colors[name]['bg']}`,
transition: 'border-color 200ms linear'
} : {
border: `3px solid transparent`,
transition: 'border-color 200ms linear'
};
}
getInfoHeaderStyle() {
return this.isSwitchStateOn() ? {
backgroundColor: this.colors[this.getOnSwitchName()]['bg'],
color: this.colors[this.getOnSwitchName()]['fg'],
transition: 'background-color 200ms linear'
} : {
backgroundColor: 'transparent',
transition: 'background-color 200ms linear'
};
}
//
// STATUS
//
getStatusSwitchNameForComponentStatus(status: string) {
if (status === 'STABLE') {
return 'statusStable';
}
if (status === 'EXPERIMENTAL') {
return 'statusExperimental';
}
return null;
}
hoverStatus(status: string) {
if (status === 'STABLE') {
this.switchState.statusStable = true;
}
if (status === 'EXPERIMENTAL') {
this.switchState.statusExperimental = true;
}
}
getComponentStatusUri() {
if (this.componentStatus === 'STABLE') {
if (this.switchState.statusStable) {
return '/assets/images/status-icons/status-stable-on.svg';
}
return '/assets/images/status-icons/status-stable-off.svg';
}
if (this.componentStatus === 'EXPERIMENTAL') {
if (this.switchState.statusExperimental) {
return '/assets/images/status-icons/status-experimental-on.svg';
}
return '/assets/images/status-icons/status-experimental-off.svg';
}
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>elpi: 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.7.1+1 / elpi - 1.12.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
elpi
<small>
1.12.1
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-11 17:12:35 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-11 17:12:35 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+1 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.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Enrico Tassi <enrico.tassi@inria.fr>"
authors: [ "Enrico Tassi" ]
license: "LGPL-2.1-or-later"
homepage: "https://github.com/LPCIC/coq-elpi"
bug-reports: "https://github.com/LPCIC/coq-elpi/issues"
dev-repo: "git+https://github.com/LPCIC/coq-elpi"
build: [ [ make "build" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" "OCAMLWARN=" ]
[ make "test" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ] {with-test}
]
install: [ make "install" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ]
depends: [
"stdlib-shims"
"ocaml" {>= "4.07"}
"elpi" {>= "1.13.6" & < "1.14.0~"}
"coq" {>= "8.15" & < "8.16~" }
]
tags: [ "logpath:elpi" ]
synopsis: "Elpi extension language for Coq"
description: """
Coq-elpi provides a Coq plugin that embeds ELPI.
It also provides a way to embed Coq's terms into λProlog using
the Higher-Order Abstract Syntax approach
and a way to read terms back. In addition to that it exports to ELPI a
set of Coq's primitives, e.g. printing a message, accessing the
environment of theorems and data types, defining a new constant and so on.
For convenience it also provides a quotation and anti-quotation for Coq's
syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural
numbers, or `{{A -> B}}` to the representation of a product by unfolding
the `->` notation. Finally it provides a way to define new vernacular commands
and
new tactics."""
url {
src: "https://github.com/LPCIC/coq-elpi/archive/v1.12.1.tar.gz"
checksum: "sha256=32eac6be5172eb945df6e80b1b6e0b784cbf1d7dca15ee780bb60716a0bb9ce5"
}
</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-elpi.1.12.1 coq.8.7.1+1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1).
The following dependencies couldn't be met:
- coq-elpi -> coq >= 8.15
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-elpi.1.12.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.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace DynamicSerializer.Test
{
public class IX
{
public int IP { get; set; }
}
[Serializable]
public class A
{
public A()
{
}
public A(string _name, C _c)
{
name = _name;
cref = _c;
}
public string name { get; set; }
public C cref { get; set; }
public override bool Equals(object obj)
{
return ((obj is A) && ((A) obj).name == this.name);
}
public override int GetHashCode()
{
return 1;
}
public static bool operator ==(A a, A b)
{
return a.Equals(b);
}
public static bool operator !=(A a, A b)
{
return !(a == b);
}
}
public class B : A
{
public B()
{
}
public int number { get { return Number; } set { Number = value; } }
[NonSerialized]
private int Number;
public B(string name, int num, C c)
: base(name, c)
{
number = num;
}
}
[Serializable]
public class C
{
public C()
{
}
public int adat { get; set; }
public C(int _b)
{
adat = _b;
}
}
public class CircularA
{
public List<CircularB> BArray { get; set; }
public List<CircularB> CArray { get; set; }
public CircularB BField { get; set; }
}
public class CircularB
{
public CircularA A { get; set; }
public int Id { get; set; }
public CircularB(int id)
{
Id = id;
}
}
public class NoCtor
{
public int i;
//public string s { get; set; }
public string s;
public NoCtor(int i, string s)
{
this.i = i;
this.s = s;
}
}
public class Basic
{
public int num;
}
}
| Java |
#ifndef _HC_EXCEPTION_HPP_
#define _HC_EXCEPTION_HPP_
//////////////
// Includes //
#include <exception>
#include <string>
//////////
// Code //
// To distinguish between different HCExceptions.
enum HCType {
// When the game cannot open the SDL window.
HC_WINDOW_EXCEPTION,
// When the game cannot load an asset, or it has been destroyed.
HC_ASSET_EXCEPTION
};
// A custom exception for this project.
class HCException : public std::exception {
private:
std::string msg;
HCType type;
public:
// Creating an HCException with a message and a type.
HCException(std::string, HCType);
// The message of this HCException.
const char* what() throw();
};
#endif
| Java |
<?php
namespace Proxies\__CG__\Cabinet\PatientBundle\Entity;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class Patient extends \Cabinet\PatientBundle\Entity\Patient implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
/** @private */
public function __isInitialized()
{
return $this->__isInitialized__;
}
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) $this->_identifier["id"];
}
$this->__load();
return parent::getId();
}
public function setNom($nom)
{
$this->__load();
return parent::setNom($nom);
}
public function getNom()
{
$this->__load();
return parent::getNom();
}
public function setPrenom($prenom)
{
$this->__load();
return parent::setPrenom($prenom);
}
public function getPrenom()
{
$this->__load();
return parent::getPrenom();
}
public function setDateNaissance($dateNaissance)
{
$this->__load();
return parent::setDateNaissance($dateNaissance);
}
public function getDateNaissance()
{
$this->__load();
return parent::getDateNaissance();
}
public function setAdresse($adresse)
{
$this->__load();
return parent::setAdresse($adresse);
}
public function getAdresse()
{
$this->__load();
return parent::getAdresse();
}
public function setTel($tel)
{
$this->__load();
return parent::setTel($tel);
}
public function getTel()
{
$this->__load();
return parent::getTel();
}
public function setCin($cin)
{
$this->__load();
return parent::setCin($cin);
}
public function getCin()
{
$this->__load();
return parent::getCin();
}
public function setMedecin(\Cabinet\UserBundle\Entity\Medecin $medecin = NULL)
{
$this->__load();
return parent::setMedecin($medecin);
}
public function getMedecin()
{
$this->__load();
return parent::getMedecin();
}
public function setFiche(\Cabinet\PatientBundle\Entity\Fiche $fiche = NULL)
{
$this->__load();
return parent::setFiche($fiche);
}
public function getFiche()
{
$this->__load();
return parent::getFiche();
}
public function __toString()
{
$this->__load();
return parent::__toString();
}
public function __sleep()
{
return array('__isInitialized__', 'id', 'nom', 'prenom', 'dateNaissance', 'adresse', 'tel', 'cin', 'medecin', 'fiche');
}
public function __clone()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
$class = $this->_entityPersister->getClassMetadata();
$original = $this->_entityPersister->load($this->_identifier);
if ($original === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
foreach ($class->reflFields as $field => $reflProperty) {
$reflProperty->setValue($this, $reflProperty->getValue($original));
}
unset($this->_entityPersister, $this->_identifier);
}
}
} | Java |
//package sgl.scene
//package ui
//
///** SceneElement that is part of a layout
// *
// * This is the root class providing logic for
// * how to render widgets in a hierarchical user
// * interface.
// */
//abstract class Widget(_x: Float, _y: Float) extends SceneElement(_x, _y) {
//
// def minWidth: Float
// def minHeight: Float
//
// def preferredWidth: Float
// def preferredHeight: Float
//
// def maxWidth: Option[Float]
// def maxHeight: Option[Float]
//
//
//}
| Java |
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
box-shadow: 0 6px 25px 0 rgba(0,0,0,.25);
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
cursor:pointer;
}
li a:hover:not(.active) {
background-color: #464C5C;
}
.active {
background-color: #8C98B8;
}
.img-right{
float: right;
padding-left: 1000px;
}
| Java |
export default {
// 购物车的商品数量
cartCommodityCount: state => {
const totalCount = state.cartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
},
removeCommodityCount: state => {
const totalCount = state.removeCartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
}
}
| Java |
<template name="odd-one-out">
<!-- Template for odd-one-out exercise -->
<section class="mainSection">
<form>
<input name=exercisesID type="hidden" value={{_id}}>
<input name=type type="hidden" value={{type}}>
{{#each options}}
<div class="checkbox">
<label>
<input name="option" type="radio" value={{this}}>
{{this}}
</label>
</div>
{{/each}}
<br>
<button type="submit" class="btn btn-default btn-primary js-verify">Submit your Answer</button>
</form>
</section>
</template>
| Java |
require "uri"
require "net/http"
module JingdongFu
module Rest
class << self
def get(url, hashed_vars)
res = request(url, 'GET', hashed_vars)
process_result(res, url)
end
def post(url, hashed_vars)
res = request(url, 'POST', hashed_vars)
process_result(res, url)
end
def put(url, hashed_vars)
res = request(url, 'PUT', hashed_vars)
process_result(res, url)
end
def delete(url, hashed_vars)
res = request(url, 'DELETE', hashed_vars)
process_result(res, url)
end
protected
def request(url, method=nil, params = {})
if !url || url.length < 1
raise ArgumentError, 'Invalid url parameter'
end
if method && !['GET', 'POST', 'DELETE', 'PUT'].include?(method)
raise NotImplementedError, 'HTTP %s not implemented' % method
end
if method && method == 'GET'
url = build_get_uri(url, params)
end
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if method && method == 'GET'
req = Net::HTTP::Get.new(uri.request_uri)
elsif method && method == 'DELETE'
req = Net::HTTP::Delete.new(uri.request_uri)
elsif method && method == 'PUT'
req = Net::HTTP::Put.new(uri.request_uri)
req.set_form_data(params)
else
req = Net::HTTP::Post.new(uri.request_uri)
req.set_form_data(params)
end
http.request(req)
end
def build_get_uri(uri, params)
if params && params.length > 0
uri += '?' unless uri.include?('?')
uri += urlencode(params)
end
URI.escape(uri)
end
def urlencode(params)
params.to_a.collect! { |k, v| "#{k.to_s}=#{v.to_s}" }.join("&")
end
def process_result(res, raw_url)
if res.code =~ /\A2\d{2}\z/
res.body
elsif %w(301 302 303).include? res.code
url = res.header['Location']
if url !~ /^http/
uri = URI.parse(raw_url)
uri.path = "/#{url}".squeeze('/')
url = uri.to_s
end
raise RuntimeError, "Redirect #{url}"
elsif res.code == "304"
raise RuntimeError, "NotModified #{res}"
elsif res.code == "401"
raise RuntimeError, "Unauthorized #{res}"
elsif res.code == "404"
raise RuntimeError, "Resource not found #{res}"
else
raise RuntimeError, "Maybe request timed out #{res}. HTTP status code #{res.code}"
end
end
end
end
end
| Java |
package source
import (
log "github.com/Sirupsen/logrus"
"github.com/howardplus/lirest/describe"
"github.com/howardplus/lirest/util"
"os"
"strconv"
"strings"
"time"
)
// Extractor returns a generic data based
// on the converter.
// An object that implements the Extractor interface needs
// to know where to get the data, which then feeds to the
// converter.
type Extractor interface {
Extract() (*ExtractOutput, error)
}
// ExtractOutput is the output of the extracted data
// with json tags
type ExtractOutput struct {
Name string `json:"name"`
Time time.Time `json:"time"`
Data interface{} `json:"data"`
}
// NewExtractor create a new extractor based on the description
func NewExtractor(s describe.DescriptionSource, rd describe.DescriptionReadFormat, c Converter, vars map[string]string) (Extractor, error) {
var extractor Extractor
refresh := time.Duration(0)
switch s.Refresh {
case "never":
// never say never, 10 day is long enough
refresh = 240 * time.Hour
default:
// something s/m/h
v, err := strconv.Atoi(s.Refresh[:len(s.Refresh)-1])
if err == nil {
if strings.HasSuffix(s.Refresh, "s") {
refresh = time.Duration(v) * time.Second
} else if strings.HasSuffix(s.Refresh, "m") {
refresh = time.Duration(v) * time.Minute
} else if strings.HasSuffix(s.Refresh, "h") {
refresh = time.Duration(v) * time.Hour
}
}
case "":
// Did not specify, which implies always refresh
}
switch s.Type {
case "procfs", "sysfs", "sysctl":
extractor = NewGenericExtractor(rd.Path, refresh, c, vars)
case "command":
extractor = NewCommandExtractor(rd.Command, c, vars)
}
// found an extractor, use it
if extractor != nil {
return extractor, nil
}
// return error on default
return nil, util.NewError("Internal error: unknown input type")
}
// GenericExtractor extract data from reading from a file
// use this until it's not enough
type GenericExtractor struct {
path string
conv Converter
refresh time.Duration
vars map[string]string
}
// NewGenericExtractor creates a GenericExtractor
func NewGenericExtractor(path string, refresh time.Duration, conv Converter, vars map[string]string) *GenericExtractor {
return &GenericExtractor{path: path, refresh: refresh, conv: conv, vars: vars}
}
func (e *GenericExtractor) Extract() (*ExtractOutput, error) {
log.WithFields(log.Fields{
"path": e.path,
"vars": e.vars,
}).Debug("Extract from file system")
// create path from variables
path, err := util.FillVars(e.path, e.vars)
if err != nil {
return nil, util.NewError("Failed to generate path")
}
// ask data from cache
var hash string
if e.refresh != time.Duration(0) {
hash = CacheHash("command" + path)
if data, time, err := Cache(hash); err == nil {
log.WithFields(log.Fields{
"hash": hash,
"path": e.path,
}).Debug("Serve from cache")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time,
Data: data,
}, nil
}
}
// open file from path
f, err := os.Open(path)
if err != nil {
return nil, util.NewError("Failed to open system path")
}
defer f.Close()
// TODO: verify the rw format on this path
// give it to the converter
data, err := e.conv.ConvertStream(f)
if err != nil {
return nil, err
}
// send to cache
if e.refresh != time.Duration(0) {
if err := SendCache(hash, data, e.refresh); err != nil {
// cache error, non-fatal
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Failed to send cache")
}
}
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Convert successful")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time.Now(),
Data: data,
}, nil
}
| Java |
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Extensions;
using Sitecore.Data.Items;
using Sitecore.Layouts;
namespace Cognifide.PowerShell.Commandlets.Presentation
{
[Cmdlet(VerbsCommon.Get, "Rendering")]
[OutputType(typeof (RenderingDefinition))]
public class GetRenderingCommand : BaseRenderingCommand
{
protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
IEnumerable<RenderingDefinition> renderings)
{
renderings.ToList().ForEach(r => WriteObject(ItemShellExtensions.WrapInItemOwner(SessionState, item, r)));
}
}
} | Java |
/**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.darksci.pardot.api.parser.user;
import com.darksci.pardot.api.parser.JacksonFactory;
import com.darksci.pardot.api.parser.ResponseParser;
import com.darksci.pardot.api.response.user.UserAbilitiesResponse;
import java.io.IOException;
/**
* Handles parsing UserAbilities API responses into POJOs.
*/
public class UserAbilitiesParser implements ResponseParser<UserAbilitiesResponse.Result> {
@Override
public UserAbilitiesResponse.Result parseResponse(final String responseStr) throws IOException {
return JacksonFactory.newInstance().readValue(responseStr, UserAbilitiesResponse.class).getResult();
}
}
| Java |
<?php
namespace App\Controller;
use Core\http;
use Core\view;
use Core\db;
class main
{
protected $http;
protected $view;
protected $db;
public function __construct()
{
$this->http = new http();
$this->view = new view();
$this->db = new db();
}
} | Java |
<?php
/**
* The MIT License
*
* Copyright (c) 2016, Coding Matters, Inc. (Gab Amba <gamba@gabbydgab.com>)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace CodingMatters\EmployeeTest;
use PHPUnit\Framework\TestCase;
class ModuleConfigTest extends TestCase
{
public function testConfigProvider()
{
$this->markTestIncomplete("Not yet implemented");
}
}
| Java |
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double NSObject_SerializeVersionNumber;
FOUNDATION_EXPORT const unsigned char NSObject_SerializeVersionString[];
| Java |
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.ImageCropperController",
function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager) {
var config = angular.copy($scope.model.config);
//move previously saved value to the editor
if ($scope.model.value) {
//backwards compat with the old file upload (incase some-one swaps them..)
if (angular.isString($scope.model.value)) {
config.src = $scope.model.value;
$scope.model.value = config;
} else if ($scope.model.value.crops) {
//sync any config changes with the editor and drop outdated crops
_.each($scope.model.value.crops, function (saved) {
var configured = _.find(config.crops, function (item) { return item.alias === saved.alias });
if (configured && configured.height === saved.height && configured.width === saved.width) {
configured.coordinates = saved.coordinates;
}
});
$scope.model.value.crops = config.crops;
//restore focalpoint if missing
if (!$scope.model.value.focalPoint) {
$scope.model.value.focalPoint = { left: 0.5, top: 0.5 };
}
}
$scope.imageSrc = $scope.model.value.src;
}
//crop a specific crop
$scope.crop = function (crop) {
$scope.currentCrop = crop;
$scope.currentPoint = undefined;
};
//done cropping
$scope.done = function () {
$scope.currentCrop = undefined;
$scope.currentPoint = undefined;
};
//crop a specific crop
$scope.clear = function (crop) {
//clear current uploaded files
fileManager.setFiles($scope.model.alias, []);
//clear the ui
$scope.imageSrc = undefined;
if ($scope.model.value) {
delete $scope.model.value;
}
};
//show previews
$scope.togglePreviews = function () {
if ($scope.showPreviews) {
$scope.showPreviews = false;
$scope.tempShowPreviews = false;
} else {
$scope.showPreviews = true;
}
};
//on image selected, update the cropper
$scope.$on("filesSelected", function (ev, args) {
$scope.model.value = config;
if (args.files && args.files[0]) {
fileManager.setFiles($scope.model.alias, args.files);
var reader = new FileReader();
reader.onload = function (e) {
$scope.$apply(function () {
$scope.imageSrc = e.target.result;
});
};
reader.readAsDataURL(args.files[0]);
}
});
})
.run(function (mediaHelper, umbRequestHelper) {
if (mediaHelper && mediaHelper.registerFileResolver) {
mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) {
if (property.value.src) {
if (thumbnail === true) {
return property.value.src + "?width=600&mode=max";
}
else {
return property.value.src;
}
//this is a fallback in case the cropper has been asssigned a upload field
}
else if (angular.isString(property.value)) {
if (thumbnail) {
if (mediaHelper.detectIfImageByExtension(property.value)) {
var thumbnailUrl = umbRequestHelper.getApiUrl(
"imagesApiBaseUrl",
"GetBigThumbnail",
[{ originalImagePath: property.value }]);
return thumbnailUrl;
}
else {
return null;
}
}
else {
return property.value;
}
}
return null;
});
}
}); | Java |
+++
author = "飞狐"
categories = ["Java编程","翻译"]
tags = ["Java","Java Concurrency"]
date = "2017-08-05T00:10:11+08:00"
description = "Blog of Rosen Lu"
keywords = ["java concurrency"]
title = "4. [译]并发的模型"
+++
本文翻译自**[Java Concurrency / Concurrency Models](http://tutorials.jenkov.com/java-concurrency/concurrency-models.html)**
并发系统可以使用不同的并发模型来实现,并发模型是指线程在系统中如何写作来完成给定的任务。不同的并发模型以不同的方式拆分任务,线程间以不同的方式协作和通信,本文将深入研究在撰写本文时最流行并发模型(2015年)。
<!--more-->
## 并发模型和分布式系统相似之处
本文中描述的并发模型与分布式系统中使用的架构类似,在一个并发系统中,不同的线程之间互相通信,在一个分布式系统中,不同的进程间彼此通信(这些进程可能在不同的电脑上)。线程和进程在本质上时非常相似的,这就是为什么不同的并发模型与不同的分布式系统架构通常看起来相似。
虽然分布式系统还有额外的挑战,如网络故障、远程计算机或进程关闭等,但一个运行在大型服务器上的并发系统也可能会遇到类似的问题,如CPU故障、网卡故障、硬盘故障等,虽然其发生的概率较低,但理论上仍然可以发生。
由于并发模型和分布式系统架构类似,它们通常可以相互借鉴,比如在线程中分配工作的模型通常与分布式系统中的负载均衡类似,它们的错误处理手段也类似,例如日志(logging)、故障切换(fail-over)和等幂性任务(idempotency of jobs)等。
## 并行工作者模型(Parallel Workers model)
并行工作者模型是本文要说明的第一个并发模型,该模型会将系统中到来的任务分配给不同的工作者,如下图所示:

并发模型中有一个“委托者”将到来的任务分配给不同的工作者,每个工作者完成整个任务,每个工作者在不同的线程中(也有可能在不同的CPU)并行工作。
如果一个汽车厂采用了并行工作者模型,那么每辆汽车将由一个工人根据说明书从头到尾来制造。
并行工作者模型是Java应用程序中使用最广泛的并发模型(尽管这种情形正在发生变化),**[java.util.concurrent ](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html)** 中的许多包都被设计用于此模型,你也可以在Java企业级服务器的设计中找到此模型的应用踪迹。
## 并行工作者模型的优点
并行工作者模型的优点是理解容易,当要增加应用程序的并行能力时我们只需添加更多的工作者即可。
例如,假设你想实现一个网络爬虫,你可以使用不同数量的工作者线程来爬取制定数量的页面,根据结果来决定使用多少个工作者线程具有最短的抓取时间(同时意味着最优性能)。由于网络爬虫是IO密集型工作,在等待下载数据时会浪费大量时间,若每个CPU只运行一个线程时效率不高,所以最终的结果可能会是在电脑中一个CPU/内核运行多个线程。
## 并行工作者模型的缺点
并行工作者模式在其简单外表之下还有若干缺点,我将在以下部分说明其中最为明显的几个。
### 状态共享将使复杂性增加
实际上并行工作者模型比上面说明的还要复杂一些,并行工作者通常需要访问一些共享数据,它们可能存储在内存中也可能存在数据库中,下面的图标展示了这种情形是如何是的并行工作者模型变得复杂的。

其中的一些共享状态可能在类似于任务队列的通信过程中,但是另外一些共享状态可能是商业数据、缓存数据、数据库的连接池等。一旦共享状态引入到了并行工作者模型,问题就开始变得复杂。线程需要一种方式来访问共享数据以确保一个线程对共享数据的更改对其它线程是可见的(将其推送到主内存中,而不是仅停留在执行线程的CPU缓存中)。线程间需要避免竞争条件、死锁和其它共享状态相关的问题。
另外,当线程间在等待彼此访问共享数据结构时,会降低应用程序的并行性。许多并发数据结构都是阻塞式的,这意味着在给定时间只有一个或一组有限的线程可以访问它们,这可能导致线程对这些共享数据的竞争,高度竞争将会导致访问共享数据的代码从本质上变为串行执行。
现代的 **[非阻塞并行算法(non-blocking concurrency algorithms )](http://tutorials.jenkov.com/java-concurrency/non-blocking-algorithms.html)** 可能会减少竞争和提高性能,但是非阻塞算法很难实现。
持久化数据结构是另外一种选择,一个持久化数据在自身被修改时会始终保留之前的值。因此,如果多个线程同时操作一个持久化数据并且其中一个修改了该数据,该线程会得到新数据的引用,而其它线程在则保持着对未修改的旧数据的引用,从而依旧保持一致。在Scala编程中包含若干个持久化的数据结构。
虽然持久化数据结构是并发修改共享数据的一种看似优雅的解决方案,但其执行性能并不理想。例如,一个持久化的列表会把新元素加入其首部并且返回对该新增元素的引用(它将会指向列表的其余元素)。所有其它的线程仍然保持着对先前列表中第一个元素的引用,对这些线程而言该列表并没有发生修改,它们看不见新增加的元素。
这种持久化的列表可以用链表来实现,不幸的是,现在的硬件并不能很好的支持链表,链表中的每一个元素都是一个单独的对象,这些对象可以遍布计算机的内存。现在的CPU在访问连续的内存地址时速度更快,因此实现为数组(Array)结构会获得更高的性能。对于一个以数组方式存储的数据而言,CPU缓存可以一次将更大的数组块加载到缓存中,一旦数据加载完毕,CPU可以直接在缓存中访问这些数据,而这对于元素分散在RAM中的链表而言是不太可能实现的。
### 无状态的工作者
共享状态可以被系统中的其它线程修改,因此工作者(workers)在每次需要它们时都必须重新读取该状态,以确保它在最新的副本上工作,无论共享状态是保存在内存还是外部数据库中,都是如此。一个工作者不在其内部保存状态(而是在每次需要时都重新读取),我们称之为无状态。
### 任务顺序的不确定
并行工作者模型的另一个缺点是任务执行的顺序无法确定。没有办法来确保某个任务最先执行或最后执行,任务A在任务B之前分配给一个工作者,但是任务B可能先于任务A执行。
并能工作者模型的不确定性使得很难在任何给定的时间点推理系统的状态,它同样使得确保一个任务在另外一个任务之前执行变得更难(如果可能)。
## 流水线模型(Assembly Line)
第二种并发模型我称之为流水线模型,我选择名称以符合早期“并行工作者”的含义。在不同的平台/社区中,其他的开发人员或许使用其它的名称,如反应式系统(reactive systems),或事件驱动系统(event driven systems),下图是流水线并发模型的一个展示

这些工作者就像工厂里的工人一样组织起来,每个工作者只完成整个任务的一部分,当该部分任务完成时,该工作者将任务转移到下一个工作者。每个工作者都在自己的线程中运行,并且没有与其它的工作者共享状态,因此流水线模型有时也被称之为无共享的并发模型。
流水线模型通常用于系统中的非阻塞IO操作,非阻塞IO意味着当一个工作者(worker)开始一个IO操作时(如从网络读取文件或数据),该工作者(worker)不必等待IO操作结束。IO操作通常较慢,因此等待IO操作完成是对CPU时间的浪费,CPU可以在此时做一些其它事情。当IO操作完成时,IO操作的结果(如数据状态读取或输入写入)会传给下一个工作者(worker)。
使用非阻塞IO时,IO操作的结果决定了工作者(worker)之间的边界,一个工作者(worker)在不得不开始IO操作之前可以尽可能的完成任务,然后放弃对该任务的控制,当IO操作结束时,在流水线上的另一个工作者(worker)以类似的方式继续完成该任务,直到它不得不开始IO操作。

实际中,上述这些任务可能不会沿着一条流水线流动,因为大多数操作系统可以同时运行多个任务,这些任务根据实际需求沿着流水线逐个的被工作者处理。在实际使用中可能会有多个虚拟流水线同时运行,下图展示了在实际使用中任务如何在这种流水线上流转。

任务甚至可以转发给多个工作者进行并发处理,例如,一个任务可以被同时转发给一个任务执行器和一个任务日志记录器。下图展示了如何将三条装配线的中任务转发给同一个工作者完成(中间装配线上的最后一个工人):

流水线甚至可以做的比上面展示的更复杂。
### 响应式、事件驱动系统
使用流水线并发模型的系统有时候也被称之为 *响应式系统* 或 *事件驱动系统* 。系统工作者在事件发生时做出对应的响应:从外部接收消息或转发给其它工作者等。事件驱动的例子可能是传入的HTTP请求,也可能是某个文件完成加载到内存中等。
在写作本文时,已经有一些有趣的响应式/事件驱动平台可以使用,并且在将来会出现更多的。其中一些比较受欢迎的如下:
* **[Vert.x](http://tutorials.jenkov.com/vert.x/index.html)**
* Akka
* Node.JS (JavaScript)
对我个人而言,我发现Vert.x十分有趣(尤其是像我这种对Java/JVM落伍的人)。
### 参与者(Actors)与管道(Channels)对比
参与者(Actors)和管道(Channels)是两种类似的流水线(响应式/事件驱动)模型。
在参与者模型中,每个工作者被称之为一个参与者,参与者之间可以直接发消息给对方,这些消息以异步方式来发送和处理。参与者可以用于处理如前所述的一个或多个流水线任务,下图展示了这种模型:

在管道(Channel)模型中,工作者之间不直接互相沟通,相反地,他们会将消息发布到不同的管道中,其他的工作者可以在这些管道上收听消息,同时消息发送者不必知道谁在收听消息。下图展示了该模型:

在写作本文时,管道模型对我而言似乎更灵活:一个工作者不必知道在流水线上的哪个工作者要处理接下来的任务,它只需要知道需要将任务转发到哪个管道(或发送消息哪个管道等),在管道中的收听者可以订阅和取消订阅而不会影响到往管道中正在写入的工作者,这允许工作者之间有某种程度的低耦合。
## 流水线模型(Assembly Line)的优点
相对于并行工作者模型,流水线模型有一些优点,在接下来的部分,我会叙述其中最突出的几个优点。
### 无共享状态
工作者之间不共享状态的情形意味着它们可以在实现时不必考虑在状态共享时所遇到的各种并发问题,这让工作者的实现变得更加容易,在实现工作者时可以假设只有一个线程在处理该工作,本质上就是一个单线程实现。
### 有状态的工作者
由于工作者知道没有其它线程修改它们的数据,这些工作者可以具有状态。在说有状态时我的意思是它们可以保留在内存中操作所需的数据,只有写入才会改变最终的外部存储系统。因此,一个有状态的工作者通常比无状态的工作者执行更快。
### 更好的硬件协同
单线程代码的优点在于它通常更符合底层硬件的工作原理。首先你通常可以创建更优化的数据结构和算法当你能假定代码会以单线程模式执行。
其次,如前所述单线程有状态的工作者可以在内存中缓存数据,当数据在内存中缓存时,有很大的概率该数据也会被缓存到CPU缓存中,这样数据获取变得更快。
当代码以一种自然受益于底层硬件工作原理的方式编写时,我称之为 *硬件协调*,有些开发者称之为 *mechanical sympathy* ,我更倾向于硬件协同因为计算机只有很少的机械部件,同时单词“sympathy”在这种情况下被用作比喻“更高的匹配”,而我认为单词“conform”能更高的传达其含义。不管怎么说,这些都是吹毛求疵,可以使用你喜欢的任何术语来描述。
### 任务可排序
根据流水线模型实现的并发系统使得排序变得可能,任务排序使得在任何给定时间点更容易理解系统的状态。此外,你可以将所有传入的任务写入日志,如果系统的任何部分发生故障,则可以使用该日志从头重建系统的状态。这些任务以某种顺序写入日志,这个顺序称为该任务顺序,下图展示了这种设置如何实现:

确保一个任务的顺序实现起来不一定容易,但通常是可能的。如果你可以实现的话,它将会大大简化类似于数据备份、恢复数据、复制数据等的任务,这些都可以通过日志文件来完成。
## 流水线模型(Assembly Line)的缺点
流水线模型的最主要缺点是通常将执行一个任务分配到多个工作者,因此,当项目中有多个类时,将难以准确的看出哪段代码在执行给定的任务。
代码编写也可能会变得更难,工作者代码有时候被写作回调处理器(callback handlers)。在代码中有太多嵌套的回调处理器时可能会导致某些开发人员所谓的 *回调陷阱(callback hell)* 。回调陷阱简单的说就是在所有的回调中很难追踪代码真正在干啥以及确保每个回调都可以访问它需要的数据。
而使用并行工作者模型,这往往很容易。你可以打开对应的工作者代码,并从头到尾读取要执行的代码。当然,并行工作者模型也可能传播到不同的类中,但是要执行的序列通常更容易从代码中读取。
## 功能并行(Functional Parallelism)模型
功能\函数并行模型是第三种并发模型,最近谈论得很多(2015)。
功能\函数并行性的基本思想是通过函数调用实现程序,功能可以被看作是发送消息到彼此的“代理”或“角色”,就像流水线并发模型(AKA反应或事件驱动系统)一样,当一个函数调用另一个函数时,类似于消息发送。
传递给函数的所有参数都被复制,所以在接收函数之外没有任何实体可以操纵数据,这种复制对于对于避免共享数据的条件竞争至关重要,它使得函数执行类似于原子操作,每个函数调用都可以独立于任何其他函数调用执行。
当每个函数调用可以独立执行时,可以在单独的CPU上执行每个函数调用,这意味着,在多个CPU上可以并行执行功能实现的算法。
使用Java 7,我们得到了包含 *ForkJoinPool* 模型的 **java.util.concurrent** 包,可以帮助您实现类似于功能并行性的功能,而使用Java 8,我们将得到并行流,可以帮助您并行化大型集合的迭代。请记住,有开发人员批评 *ForkAndJoinPool* 模型(您可以在我的ForkAndJoinPool教程中找到一个相应的批评链接)。
关于功能\函数并行的难点在于知道哪个函数调用需要并行化,跨CPU的协调功能调用带来了一定的开销。只有由功能/函数完成的工作单位具有一定的大小,才能值得这个开销,如果函数调用非常小,尝试并行化它们可能比单个线程的单个CPU执行更慢。
从我的理解(事实上根本不完美),您可以使用事件响应驱动模型来实现实现算法,并实现与功能并行性相似的工作分解。在我看来,通过事件响应驱动模型,你可以掌握如何来实现并行化。
另外,只有当前任务是程序执行的唯一任务时,将任务分配给多个CPU,协调开销才有意义。然而,如果系统同时执行多个其他任务(如Web服务器,数据库服务器和许多其它系统),则无需尝试并行化单个任务。计算机中的其它CPU可能正在忙于处理其它任务,所以没有理由试图用较慢的功能并行任务来打扰他们。如有可能,你最好使用流水线并发模型,因为它在以单线程模式顺序执行的程序中具有更少的开销,并且更好的符合底层硬件的工作原理。
## 孰优孰劣
那么,哪种并发模型更好呢?
通常情况下,答案取决于你的系统应该做什么。 如果你的工作自然并行,独立,无需共享状态,则可以使用并行工作模型来实现系统。但许多任务不是自然并行和独立的,对于这些类型的系统,我相信流水线并发模型比缺点有更多的优点,比并行工作模型更有优势。你甚至不需要自己编写所有的流水线路基础设施,像Vert.x这样的现代平台为你已经实现了很多。 就个人而言,我将探索在Vert.x等平台上运行的设计,以便我的下一个项目。我个人感觉JavaEE没有尽头。
<–翻译结束!–> | Java |
package data_struct.in_class.d10_02;
/**
* A class to test basic 'Object' methods
*
* @author Eddie Gurnee
* @version 10/02/13
* @see TestingSam
*
*/
public class Sam {
public int mikesplan = 8;
/**
* No argument constructor for the Sam class
*
*/
public Sam() {
}
/**
* Indicates if some other "Sam" object is equal to this one.
*
*/
public boolean equals(Sam otherObject) {
if (otherObject == null) {
System.out.println("check1");
return false;
}
else if (this.getClass() != otherObject.getClass()) {
System.out.println("check2");
return false;
}
else {
System.out.println("if this shows then fuck the police");
Sam otherSam = (Sam)otherObject;
return this.mikesplan == otherSam.mikesplan;
}
}
public int getMikesPlan() {
return mikesplan;
}
} | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>URI.js - URI-Template</title>
<meta name="description" content="URI.js is a Javascript library for working with URLs." />
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="prettify/prettify.js" type="text/javascript"></script>
<script src="screen.js" type="text/javascript"></script>
<link href="screen.css" rel="stylesheet" type="text/css" />
<link href="prettify/prettify.sunburst.css" rel="stylesheet" type="text/css" />
<script src="src/URI.min.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-8922143-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<style type="text/css">
.tpl-operator {
font-weight: bold;
color: #669933;
}
.tpl-variable {
font-weight: bold;
color: #336699;
}
.tpl-modifier {
font-weight: bold;
color: #663399;
}
pre {
padding: 10px;
background: #EEE;
}
table {
width: 100%;
border: 1px solid #AAA;
border-collapse: collapse;
}
td, th {
border: 1px solid #AAA;
text-align: left;
padding: 3px;
}
th {
background: #EEE;
}
</style>
</head>
<body>
<a id="github-forkme" href="https://github.com/medialize/URI.js"><img src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
<div id="container">
<h1><a href="https://github.com/medialize/URI.js">URI.js</a></h1>
<ul class="menu">
<li><a href="/URI.js/">Intro</a></li>
<li><a href="about-uris.html">Understanding URIs</a></li>
<li><a href="docs.html">API-Documentation</a></li>
<li><a href="jquery-uri-plugin.html">jQuery Plugin</a></li>
<li class="active"><a href="uri-template.html">URI Template</a></li>
<li><a href="build.html">Build</a></li>
<li><a href="http://rodneyrehm.de/en/">Author</a></li>
</ul>
<h2>URI Template</h2>
<p>As of version 1.7.0 URI.js includes an implementation of URI Templates, as specified in <a href="http://tools.ietf.org/html/rfc6570">RFC 6570</a> (Level 4, March 2012).</p>
<h2>Using URI Templates</h2>
<pre class="prettyprint lang-js">
// creating a new URI Template
var template = new URITemplate("http://example.org/{file}");
var result = template.expand({file: "hello world.html"});
result === "http://example.org/hello%20world.html";
// of course you can call the constructor like a function and chain things:
result = URITemplate("http://example.org/{file}")
.expand({file: "hello world.html"});
result === "http://example.org/hello%20world.html";
// access via URI
result = URI.expand("http://example.org/{file}", {file: "hello world.html"});
// result == new URI("http://example.org/hello%20world.html");
// expand() accepts data-callbacks:
template.expand(function(key) {
var data = {file: "hello world.html"};
return data[key];
});
// expand() accepts key-callbacks:
template.expand({file : function(key) {
return "hello world.html";
}});
// Using strict mode
var template = new URITemplate("http://example.org/{file}");
var result = template.expand({filename: "hello world.html"}, { strict: true });
// Uncaught Error: Missing expansion value for variable "file"
</pre>
<h2>URI Template Syntax</h2>
<p><em>Expressions</em> are placeholders which are to be substituted by the values their variables reference.</p>
<ul>
<li><code>http://example.org/~<strong>{<em class="tpl-variable">username</em>}</strong>/</code></li>
<li><code>http://example.org/dictionary/<strong>{<em class="tpl-variable">term</em><span class="tpl-modifier">:1</span>}</strong>/<strong>{<em class="tpl-variable">term</em>}</strong></code></li>
<li><code>http://example.org/search<strong>{<span class="tpl-operator">?</span><em class="tpl-variable">q</em><span class="tpl-modifier">*</span>,<em class="tpl-variable">lang</em>}</strong></code></li>
</ul>
<p>
An expression consists of an <span class="tpl-operator">operator</span> and a (comma-separated) list of <em>variable-specifications</em>.
A variable-specification consists of a <em class="tpl-variable">variable</em> and an optional <em class="tpl-modifier">modifier</em>.
</p>
<hr>
<p>Given the template</p>
<pre><code>http://example.org/~<strong>{<em class="tpl-variable">username</em>}</strong>/<strong>{<em class="tpl-variable">term</em><span class="tpl-modifier">:1</span>}</strong>/<strong>{<em class="tpl-variable">term</em>}</strong><strong>{<span class="tpl-operator">?</span><em class="tpl-variable">q</em><span class="tpl-modifier">*</span>,<em class="tpl-variable">lang</em>}</strong></code></pre>
<p>and the following data: </p>
<pre><code>{username: "rodneyrehm", term: "hello world", q: {a: "mars", b: "jupiter"}, lang: "en"}</code></pre>
<p>the expansion looks as follows:
<pre><code>"http://example.org/~rodneyrehm/h/hello%20world?a=mars&b=jupiter&lang=en"</code></pre>
<hr>
<p>List of supported <span class="tpl-operator">operators</span>:</p>
<table>
<tr><th>Operator</th><th>Description</th></tr>
<tr><td><code><em>None</em></code></td><td>Simple String Expansion;</td></tr>
<tr><td><code>+</code></td><td>Reserved character strings;</td></tr>
<tr><td><code>#</code></td><td>Fragment identifiers prefixed by "#";</td></tr>
<tr><td><code>.</code></td><td>Name labels or extensions prefixed by ".";</td></tr>
<tr><td><code>/</code></td><td>Path segments prefixed by "/";</td></tr>
<tr><td><code>;</code></td><td>Path parameter name or name=value pairs prefixed by ";";</td></tr>
<tr><td><code>?</code></td><td>Query component beginning with "?" and consisting of name=value pairs separated by "&"; and,</td></tr>
<tr><td><code>&</code></td><td>Continuation of query-style &name=value pairs within a literal query component.</td></tr>
</table>
<p>List of supported <span class="tpl-modifier">modifiers</span>:</p>
<table>
<tr><th>Modifier</th><th>Description</th></tr>
<tr><td><code><em>None</em></code></td><td>No modification, arrays and objects are joined with ","</td></tr>
<tr><td><code>*</code></td><td>Explode arrays and objects (see tables below)</td></tr>
<tr><td><code>:3</code></td><td>Substring of the first 3 characters of the variable's value</td></tr>
</table>
<h3>Strings and Numbers</h3>
<p>
Given <code>{"var": "hello[world]"}</code>, the expression <code>{var}</code> expands to <code>hello%5Bworld%5D</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>string</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>hello%5Bworld%5D</code></td><td><code>hello%5Bworld%5D</code></td><td><code>he</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>hello[world]</code></td><td><code>hello[world]</code></td><td><code>he</code></td></tr>
<tr><td><code>#</code></td><td><code>#hello[world]</code></td><td><code>#hello[world]</code></td><td><code>#he</code></td></tr>
<tr><td><code>.</code></td><td><code>.hello%5Bworld%5D</code></td><td><code>.hello%5Bworld%5D</code></td><td><code>.he</code></td></tr>
<tr><td><code>/</code></td><td><code>/hello%5Bworld%5D</code></td><td><code>/hello%5Bworld%5D</code></td><td><code>/he</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=hello%5Bworld%5D</code></td><td><code>;var=hello%5Bworld%5D</code></td><td><code>;var=he</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=hello%5Bworld%5D</code></td><td><code>?var=hello%5Bworld%5D</code></td><td><code>?var=he</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=hello%5Bworld%5D</code></td><td><code>&var=hello%5Bworld%5D</code></td><td><code>&var=he</code></td></tr>
</table>
<h3>Arrays</h3>
<p>
Given <code>{"var": ["one", "two", "three"]}</code>, the expression <code>{var}</code> expands to <code>one,two,three</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>array</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>one,two,three</code></td><td><code>one,two,three</code></td><td><code>on,tw,th</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>one,two,three</code></td><td><code>one,two,three</code></td><td><code>on,tw,th</code></td></tr>
<tr><td><code>#</code></td><td><code>#one,two,three</code></td><td><code>#one,two,three</code></td><td><code>#on,tw,th</code></td></tr>
<tr><td><code>.</code></td><td><code>.one,two,three</code></td><td><code>.one.two.three</code></td><td><code>.on,tw,th</code></td></tr>
<tr><td><code>/</code></td><td><code>/one,two,three</code></td><td><code>/one/two/three</code></td><td><code>/on,tw,th</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=one,two,three</code></td><td><code>;var=one;var=two;var=three</code></td><td><code>;var=on,tw,th</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=one,two,three</code></td><td><code>?var=one&var=two&var=three</code></td><td><code>?var=on,tw,th</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=one,two,three</code></td><td><code>&var=one&var=two&var=three</code></td><td><code>&var=on,tw,th</code></td></tr>
</table>
<h3>Objects ("plain objects" / "hash maps")</h3>
<p>
Given <code>{"var": {"one": "alpha", "two": "bravo"}}</code>, the expression <code>{var}</code> expands to <code>one,two,three</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>object</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>one,alpha,two,bravo</code></td><td><code>one=alpha,two=bravo</code></td><td><code>on,al,tw,br</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>one,alpha,two,bravo</code></td><td><code>one=alpha,two=bravo</code></td><td><code>on,al,tw,br</code></td></tr>
<tr><td><code>#</code></td><td><code>#one,alpha,two,bravo</code></td><td><code>#one=alpha,two=bravo</code></td><td><code>#on,al,tw,br</code></td></tr>
<tr><td><code>.</code></td><td><code>.one,alpha,two,bravo</code></td><td><code>.one=alpha.two=bravo</code></td><td><code>.on,al,tw,br</code></td></tr>
<tr><td><code>/</code></td><td><code>/one,alpha,two,bravo</code></td><td><code>/one=alpha/two=bravo</code></td><td><code>/on,al,tw,br</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=one,alpha,two,bravo</code></td><td><code>;one=alpha;two=bravo</code></td><td><code>;var=on,al,tw,br</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=one,alpha,two,bravo</code></td><td><code>?one=alpha&two=bravo</code></td><td><code>?var=on,al,tw,br</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=one,alpha,two,bravo</code></td><td><code>&one=alpha&two=bravo</code></td><td><code>&var=on,al,tw,br</code></td></tr>
</table>
<h2>Limitations</h2>
<p>URI Template is a <em>Proposed Standard</em> and because of that I did not want to deviate from it. That said I'm not at all happy with how the specification turned out. Here are some of my thoughts:</p>
<ul>
<li>The <em>explode modifier</em> works the wrong way. <code>{?some_object}</code> should lead to <code>?foo=bar&hello=world</code>, as this is the common expansion</li>
<li>The <em>prefix modifier</em> (which I would've named <em>truncate modifier</em>) only has an end-offset.
The specification says it's »used to partition an identifier space hierarchically«. <code>abc</code> may become <code>a/bc</code> or <code>a/ab/abc</code>.
But there is no way of modifying output to <code>a/b/c</code> or <code>a/b/abc</code>. Whenever I had to partition identifier spaces, I used one of the latter patterns.</li>
<li>Operators like <code>.</code> automatically prefix the expansion. So <code>{"var": ["filename", "extension"]}</code> and <code>{.var*}</code> results in <code>.filename.extension</code> - obviously not what I wanted.</li>
<li>Variable names (<em>varname</em>) may only contain <code>ALPHA / DIGIT / "_" / pct-encoded</code> and may not be decoded for resolving the reference. This simply feels weird, especially the "may not be decoded" part.</li>
<li>Other possible modifiers could include some simple character-munging like <em>UPPERCASE</em>, <em>LOWERCASE</em>, <em>CAPITALCASE</em></li>
<li><code>{/var,empty,empty}</code> results in <code>/foobar//</code> - clearly not what one intended</li>
<li><code>{var}</code> and <code>{"var" : {"a": "1", "b": "2"}}</code> results in <code>a,1,b,2</code> - excusemewhat? I would've expected <code>a=1,b=2</code> or <code>a:1,b:2</code> (in a perverse parallel universe).</li>
<li>Spaces in the <em>query string</em> should be encoded to <code>+</code>, not <code>%20</code> according to <a href="http://www.w3.org/TR/html401/interact/forms.html#form-content-type">application/x-www-form-urlencoded</a></li>
</ul>
</div>
</body>
</html>
| Java |
--[[
DVScrollBar
Usage:
Place this control in your panel. You will ideally have another panel or
control which is bigger than the original panel. This is the Canvas.
scrollbar:SetUp( _barsize_, _canvassize_ ) should be called whenever
the size of your 'canvas' changes.
scrollbar:GetOffset() can be called to get the offset of the canvas.
You should call this in your PerformLayout function and set the Y
pos of your canvas to this value.
Example:
function PANEL:PerformLayout()
local Wide = self:GetWide()
local YPos = 0
-- Place the scrollbar
self.VBar:SetPos( self:GetWide() - 16, 0 )
self.VBar:SetSize( 16, self:GetTall() )
-- Make sure the scrollbar knows how big our canvas is
self.VBar:SetUp( self:GetTall(), self.pnlCanvas:GetTall() )
-- Get data from the scrollbar
YPos = self.VBar:GetOffset()
-- If the scrollbar is enabled make the canvas thinner so it will fit in.
if ( self.VBar.Enabled ) then Wide = Wide - 16 end
-- Position the canvas according to the scrollbar's data
self.pnlCanvas:SetPos( self.Padding, YPos + self.Padding )
self.pnlCanvas:SetSize( Wide - self.Padding * 2, self.pnlCanvas:GetTall() )
end
--]]
local PANEL = {}
function PANEL:Init()
self.Offset = 0
self.Scroll = 0
self.CanvasSize = 1
self.BarSize = 1
self.btnUp = vgui.Create( "DButton", self )
self.btnUp:SetText( "" )
self.btnUp.DoClick = function( self ) self:GetParent():AddScroll( -1 ) end
self.btnUp.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "ButtonUp", panel, w, h ) end
self.btnDown = vgui.Create( "DButton", self )
self.btnDown:SetText( "" )
self.btnDown.DoClick = function( self ) self:GetParent():AddScroll( 1 ) end
self.btnDown.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "ButtonDown", panel, w, h ) end
self.btnGrip = vgui.Create( "DScrollBarGrip", self )
self:SetSize( 15, 15 )
end
function PANEL:SetEnabled( b )
if ( !b ) then
self.Offset = 0
self:SetScroll( 0 )
self.HasChanged = true
end
self:SetMouseInputEnabled( b )
self:SetVisible( b )
-- We're probably changing the width of something in our parent
-- by appearing or hiding, so tell them to re-do their layout.
if ( self.Enabled != b ) then
self:GetParent():InvalidateLayout()
if ( self:GetParent().OnScrollbarAppear ) then
self:GetParent():OnScrollbarAppear()
end
end
self.Enabled = b
end
function PANEL:Value()
return self.Pos
end
function PANEL:BarScale()
if ( self.BarSize == 0 ) then return 1 end
return self.BarSize / ( self.CanvasSize + self.BarSize )
end
function PANEL:SetUp( _barsize_, _canvassize_ )
self.BarSize = _barsize_
self.CanvasSize = math.max( _canvassize_ - _barsize_, 1 )
self:SetEnabled( _canvassize_ > _barsize_ )
self:InvalidateLayout()
end
function PANEL:OnMouseWheeled( dlta )
if ( !self:IsVisible() ) then return false end
-- We return true if the scrollbar changed.
-- If it didn't, we feed the mousehweeling to the parent panel
return self:AddScroll( dlta * -2 )
end
function PANEL:AddScroll( dlta )
local OldScroll = self:GetScroll()
dlta = dlta * 25
self:SetScroll( self:GetScroll() + dlta )
return OldScroll != self:GetScroll()
end
function PANEL:SetScroll( scrll )
if ( !self.Enabled ) then self.Scroll = 0 return end
self.Scroll = math.Clamp( scrll, 0, self.CanvasSize )
self:InvalidateLayout()
-- If our parent has a OnVScroll function use that, if
-- not then invalidate layout (which can be pretty slow)
local func = self:GetParent().OnVScroll
if ( func ) then
func( self:GetParent(), self:GetOffset() )
else
self:GetParent():InvalidateLayout()
end
end
function PANEL:AnimateTo( scrll, length, delay, ease )
local anim = self:NewAnimation( length, delay, ease )
anim.StartPos = self.Scroll
anim.TargetPos = scrll
anim.Think = function( anim, pnl, fraction )
pnl:SetScroll( Lerp( fraction, anim.StartPos, anim.TargetPos ) )
end
end
function PANEL:GetScroll()
if ( !self.Enabled ) then self.Scroll = 0 end
return self.Scroll
end
function PANEL:GetOffset()
if ( !self.Enabled ) then return 0 end
return self.Scroll * -1
end
function PANEL:Think()
end
function PANEL:Paint( w, h )
derma.SkinHook( "Paint", "VScrollBar", self, w, h )
return true
end
function PANEL:OnMousePressed()
local x, y = self:CursorPos()
local PageSize = self.BarSize
if ( y > self.btnGrip.y ) then
self:SetScroll( self:GetScroll() + PageSize )
else
self:SetScroll( self:GetScroll() - PageSize )
end
end
function PANEL:OnMouseReleased()
self.Dragging = false
self.DraggingCanvas = nil
self:MouseCapture( false )
self.btnGrip.Depressed = false
end
function PANEL:OnCursorMoved( x, y )
if ( !self.Enabled ) then return end
if ( !self.Dragging ) then return end
local x, y = self:ScreenToLocal( 0, gui.MouseY() )
-- Uck.
y = y - self.btnUp:GetTall()
y = y - self.HoldPos
local TrackSize = self:GetTall() - self:GetWide() * 2 - self.btnGrip:GetTall()
y = y / TrackSize
self:SetScroll( y * self.CanvasSize )
end
function PANEL:Grip()
if ( !self.Enabled ) then return end
if ( self.BarSize == 0 ) then return end
self:MouseCapture( true )
self.Dragging = true
local x, y = self.btnGrip:ScreenToLocal( 0, gui.MouseY() )
self.HoldPos = y
self.btnGrip.Depressed = true
end
function PANEL:PerformLayout()
local Wide = self:GetWide()
local Scroll = self:GetScroll() / self.CanvasSize
local BarSize = math.max( self:BarScale() * ( self:GetTall() - ( Wide * 2 ) ), 10 )
local Track = self:GetTall() - ( Wide * 2 ) - BarSize
Track = Track + 1
Scroll = Scroll * Track
self.btnGrip:SetPos( 0, Wide + Scroll )
self.btnGrip:SetSize( Wide, BarSize )
self.btnUp:SetPos( 0, 0, Wide, Wide )
self.btnUp:SetSize( Wide, Wide )
self.btnDown:SetPos( 0, self:GetTall() - Wide, Wide, Wide )
self.btnDown:SetSize( Wide, Wide )
end
derma.DefineControl( "DVScrollBar", "A Scrollbar", PANEL, "Panel" )
| Java |
__author__ = 'brianoneill'
from log_calls import log_calls
global_settings = dict(
log_call_numbers=True,
log_exit=False,
log_retval=True,
)
log_calls.set_defaults(global_settings, args_sep=' $ ')
| Java |
angular.module('phonebook')
.config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider,$stateProvider){
$stateProvider
// Greeting State
.state('user.main',{
url : '/',
templateUrl : 'user/view/welcome.html',
controller : 'welcomeCtrl'
})
// Phonebook Display State
.state('user.PB',{
url : '/contacts',
templateUrl : 'user/view/displayContacts.html',
controller : 'cntctCtrl'
})
}]); | Java |
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="<?php echo base_url() ?>css/bootstrap.min.css">
<style>
</style>
<script src="<?php echo base_url() ?>js/libs/jquery-2.2.1.min.js"></script>
<script src="<?php echo base_url() ?>js/libs/angular.min.js"></script>
<script src="<?php echo base_url() ?>js/libs/bootstrap.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('articlesCtrl', function ($scope, $http) {
var latestLastIndex = 0;
var popularLastIndex = 0;
$scope.hotArticles = [];
$scope.latestArticles = [];
$scope.loadPopular = function () {
$http({
method: 'GET',
url: '../index.php/article/getPopularPosts/' + popularLastIndex
}).then(function successCallback(response) {
popularLastIndex += 10;
$scope.hotArticles = $scope.hotArticles.concat(response.data);
}, function errorCallback(response) {
});
};
$scope.loadLatest = function () {
$http({
method: 'GET',
url: '../index.php/article/getLatestPosts/1'
}).then(function successCallback(response) {
latestLastIndex += 10;
$scope.latestArticles = response.data;
}, function errorCallback(response) {
});
};
$scope.loadPopular();
$scope.loadLatest();
});
</script>
</head>
<body>
<div class="container">
<div class="">
<div class="form-inline">
<input class="form-control" ><button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span> </button>
</div>
</div>
<div class="" ng-controller="articlesCtrl">
<h2> posts for you </h2>
<div class="pops-post row" >
<h4>popular articles</h4>
<div class="pops-block col-sm-3" ng-repeat="articlex in hotArticles">
<a ng-href="../index.php/article/{{articlex.post_id}}">
<h3>{{articlex.title}}</h3>
<img ng-src="http://lorempixel.com/300/200/transport/{{$index}}" alt="" class="img-responsive">
<div class="des">
discription of the post
</div>
</a>
</div>
</div>
<div class="">
<button class="btn btn-info" ng-click="loadPopular()">load more</button>
</div>
<h2> Latest posts</h2>
<div class="pops-post row">
<h4>popular articles</h4>
<div class="pops-block col-sm-3" ng-repeat="articlex in latestArticles">
<h3>{{articlex.title}}</h3>
<img ng-src="http://lorempixel.com/300/200/transport/{{$index}}" alt="" class="img-responsive">
<div class="des">
discription of the post
</div>
</div>
</div>
<div class="">
<button class="btn btn-info" ng-click="loadLatest()">load more</button>
</div>
</div>
</div>
</body>
</html> | Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PineTree.Language.Syntax
{
public abstract class ExpressionTerminal : Expression
{
}
} | Java |
<script>
var detail = $("#cb_post_title_url");
if (detail.text() !== ""){$("div#sideBar").hide();var mainArticleArea = $("div#mainContent");mainArticleArea.width("100%");mainArticleArea.css("margin-left","0");
$("div.forFlow #comment_form").css("margin-left","40px");
$("div.post h1.postTitle").after("<div id='mycpright'><strong>严正声明:</strong><br/>作者:<a href='http://www.cnblogs.com/psklf/' target='_blank'>psklf</a></br>出处: <a href=''>" + window.location.href + "</a></br>欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任!</div>");
}
window.onload = function() {};
</script>
<ul id="my_admin"><li id="nav_newpost" class="inline_li"><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li><li id="nav_admin" class="inline_li"><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">admin</a></li><ul>
| Java |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>KeyExportOptions | picturepark-sdk-v1-pickers API</title>
<meta name="description" content="Documentation for picturepark-sdk-v1-pickers API">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.json" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">picturepark-sdk-v1-pickers API</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_crypto_.html">"crypto"</a>
</li>
<li>
<a href="_crypto_.keyexportoptions.html">KeyExportOptions</a>
</li>
</ul>
<h1>Interface KeyExportOptions<T></h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-type-parameters">
<h3>Type parameters</h3>
<ul class="tsd-type-parameters">
<li>
<h4>T<span class="tsd-signature-symbol">: </span><a href="../modules/_crypto_.html#keyformat" class="tsd-signature-type">KeyFormat</a></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">KeyExportOptions</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#cipher" class="tsd-kind-icon">cipher</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#format" class="tsd-kind-icon">format</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#passphrase" class="tsd-kind-icon">passphrase</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#type" class="tsd-kind-icon">type</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="cipher" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> cipher</h3>
<div class="tsd-signature tsd-kind-icon">cipher<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:150</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="format" class="tsd-anchor"></a>
<h3>format</h3>
<div class="tsd-signature tsd-kind-icon">format<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">T</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:149</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="passphrase" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> passphrase</h3>
<div class="tsd-signature tsd-kind-icon">passphrase<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol"> | </span><a href="../classes/buffer.html" class="tsd-signature-type">Buffer</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:151</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="type" class="tsd-anchor"></a>
<h3>type</h3>
<div class="tsd-signature tsd-kind-icon">type<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">"pkcs1"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"spki"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"pkcs8"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"sec1"</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:148</li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-module tsd-is-external">
<a href="../modules/_crypto_.html">"crypto"</a>
<ul>
<li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external">
<a href="../modules/_crypto_.constants.html">constants</a>
</li>
<li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external">
<a href="../modules/_crypto_.generatekeypair.html">generate<wbr>Key<wbr>Pair</a>
</li>
</ul>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-has-type-parameter tsd-is-external">
<a href="_crypto_.keyexportoptions.html" class="tsd-kind-icon">Key<wbr>Export<wbr>Options</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#cipher" class="tsd-kind-icon">cipher</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#format" class="tsd-kind-icon">format</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#passphrase" class="tsd-kind-icon">passphrase</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#type" class="tsd-kind-icon">type</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
</body>
</html> | Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace STextViewControl.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| Java |
#include "Common.h"
#include "Script.h"
#include <atlimage.h>
#include <hidsdi.h>
#include <SetupAPI.h>
#define HID_SFIP 'SFIP'
#define HID_X52P 'X52P'
#define HID_UNKN 'UNKN'
// CHECKME : Do we still need all this code since we now have a GetSerialNumber() in the DO API?
DeviceManager *DevMan = DeviceManager::GetInstance();
SaitekDevice HID[HID_COUNT];
int HIDCount = HID_EMPTY;
int ToDeviceShortName(const char *type) {
if (strcmp(type, "SFIP") == 0)
return HID_SFIP;
if (strcmp(type, "X52P") == 0)
return HID_X52P;
return HID_UNKN;
}
int GetDeviceShortName(GUID type) {
if (type == DeviceType_Fip)
return HID_SFIP;
if (type == DeviceType_X52Pro)
return HID_X52P;
return HID_UNKN;
}
const char *GetDeviceStringName(GUID type) {
if (type == DeviceType_Fip)
return "SFIP";
if (type == DeviceType_X52Pro)
return "X52P";
return "UNKN";
}
int HIDLookupByType(const char *type, int index) {
int count = 1; // Index starts at 1 in Lua
int dev = ToDeviceShortName(type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (count++ == index)
return i;
}
}
return HID_NOTFOUND;
}
int HIDLookupByIndex(int index) {
int count = 1; // Index starts at 1 in Lua
int dev = GetDeviceShortName(HID[index].type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (index == i)
return count;
count++;
}
}
return HID_NOTFOUND;
}
static void CALLBACK DO_Enumerate(void* hDevice, void* pCtxt) {
DevMan->HandleDeviceChange(hDevice, true);
}
static void CALLBACK DO_DeviceChange(void* hDevice, bool bAdded, void* pCtxt) {
int index = DevMan->HandleDeviceChange(hDevice, bAdded);
LuaMan->CallDeviceChangeCallbacks(index, bAdded);
}
void DeviceManager::Initialize() {
_lockInit.Acquire();
if (_initializedCounter > 0) {
_initializedCounter++;
_lockInit.Release();
return;
}
// Initialize...
memset(HID, 0, sizeof(SaitekDevice) * HID_COUNT);
HIDCount = HID_EMPTY;
//Initialize DirectInput
HRESULT hdi = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID *)&this->_di, NULL);
if (!SUCCEEDED(hdi)) {
_lockInit.Release();
return;
}
//Initialize Saitek DirectOutput
_do = new CDirectOutput();
HRESULT hdo = _do->Initialize(L"" LUALIB_IDENT);
if (!SUCCEEDED(hdo)) {
_di->Release();
_lockInit.Release();
return;
}
// Register callbacks
HRESULT h1 = _do->Enumerate((Pfn_DirectOutput_EnumerateCallback)DO_Enumerate, NULL);
HRESULT h2 = _do->RegisterDeviceCallback((Pfn_DirectOutput_DeviceChange)DO_DeviceChange, NULL);
// Everything OK
_initializedCounter = 1;
_lockInit.Release();
}
void DeviceManager::Release() {
_lockInit.Acquire();
if (_initializedCounter-- > 1) {
_lockInit.Release();
return;
}
_do->Deinitialize();
_di->Release();
_initializedCounter = 0;
_lockInit.Release();
}
void DeviceManager::GetDeviceInfo(void *hDevice, DeviceData &dd) {
GUID gi;
HRESULT hr = DO()->GetDeviceInstance(hDevice, &gi);
GetDeviceInfo(gi, dd);
}
void DeviceManager::GetDeviceInfo(const GUID &iid, DeviceData &dd) {
SP_DEVINFO_DATA DeviceInfoData;
SP_DEVICE_INTERFACE_DATA did;
struct { DWORD cbSize; TCHAR DevicePath[256]; } ciddd;
TCHAR s[64];
GUID HidGuid;
//Empty
dd.instanceID[0] = 0;
dd.name[0] = 0;
dd.serialNumber[0] = 0;
// Try to create a device
LPDIRECTINPUTDEVICE8 pDevice;
HRESULT hd = DevMan->DI()->CreateDevice(iid, &pDevice, NULL);
if (FAILED(hd)) {
return;
}
// Get the GUID and Path
DIPROPGUIDANDPATH h;
h.diph.dwSize = sizeof(DIPROPGUIDANDPATH);
h.diph.dwHeaderSize = sizeof(DIPROPHEADER);
h.diph.dwObj = 0;
h.diph.dwHow = DIPH_DEVICE;
HRESULT hp = pDevice->GetProperty(DIPROP_GUIDANDPATH, (LPDIPROPHEADER)&h);
if (FAILED(hd))
return;
// Change # to \ to match structure of instance ID
for (size_t i = 0; i < wcslen(h.wszPath); i++) {
if (h.wszPath[i] == L'#') {
h.wszPath[i] = L'\\';
}
}
// Prepare enumeration
HidD_GetHidGuid(&HidGuid);
HDEVINFO hdi = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
did.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ciddd.cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
for (int i = 0; SetupDiEnumDeviceInterfaces(hdi, 0, &HidGuid, i, &did); i++) {
if (!SetupDiGetDeviceInterfaceDetail(hdi, &did, PSP_INTERFACE_DEVICE_DETAIL_DATA(&ciddd), sizeof(ciddd.DevicePath), 0, &DeviceInfoData))
continue;
if (!SetupDiGetDeviceInstanceId(hdi, &DeviceInfoData, s, sizeof(s), 0))
continue;
_wcslwr_s(s);
if(!wcsstr(h.wszPath, s))
continue;
strncpy_s(dd.instanceID, CT2A(s), sizeof(dd.instanceID) - 1);
HANDLE h = CreateFile(ciddd.DevicePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (HidD_GetProductString(h, s, sizeof(s)))
strncpy_s(dd.name, CT2A(s), sizeof(dd.name) - 1);
if (HidD_GetSerialNumberString(h, s, sizeof(s)))
strncpy_s(dd.serialNumber, CT2A(s), sizeof(dd.serialNumber) - 1);
CloseHandle(h);
}
SetupDiDestroyDeviceInfoList(hdi);
}
int DeviceManager::Prepare(void *hDevice) {
if (HIDCount == HID_COUNT)
return HID_NOTFOUND;
int index = HIDCount++;
HID[index].hDevice = hDevice;
return index;
}
void DeviceManager::Set(int index) {
void *hDevice = HID[index].hDevice;
GUID gt, gi;
DeviceData dd;
GetDeviceInfo(hDevice, dd);
DO()->GetDeviceType(hDevice, >);
DO()->GetDeviceInstance(hDevice, &gi);
HID[index].type = gt;
HID[index].instance = gi;
strcpy_s(HID[index].instanceID, dd.instanceID);
strcpy_s(HID[index].name, dd.name);
strcpy_s(HID[index].serialNumber, dd.serialNumber);
}
int DeviceManager::HandleDeviceChange(void *hDevice, bool bAdded) {
int index = LookupByHandle(hDevice);
_lockHID.Acquire();
if (bAdded) {
if (index == HID_NOTFOUND)
index = LookupByDeviceInfo(hDevice, false);
if (index == HID_NOTFOUND)
index = Prepare(hDevice);
}
if (index != HID_NOTFOUND) {
HID[index].isActive = bAdded;
if (bAdded) {
HID[index].hDevice = hDevice;
Set(index);
}
}
_lockHID.Release();
return index;
}
int DeviceManager::LookupByHandle(void* hDevice) {
_lockHID.Acquire();
for (int i = 0; i < HIDCount; i++) {
if (hDevice == HID[i].hDevice) {
_lockHID.Release();
return i;
}
}
_lockHID.Release();
return HID_NOTFOUND;
}
int DeviceManager::LookupByDeviceInfo(void *hDevice, bool isActive) {
GUID gt;
DeviceData dd;
DO()->GetDeviceType(hDevice, >);
GetDeviceInfo(hDevice, dd);
return LookupByDeviceInfo(gt, dd, isActive);
}
int DeviceManager::LookupByDeviceInfo(GUID &type, DeviceData &dd, bool isActive) {
for (int i = 0; i < HIDCount; i++) {
if (HID[i].isActive == isActive && HID[i].type == type &&
strcmp(dd.instanceID, HID[i].instanceID) == 0 &&
strcmp(dd.serialNumber, HID[i].serialNumber) == 0) {
return i;
}
}
return HID_NOTFOUND;
}
| Java |
game.TitleScreen = me.ScreenObject.extend({
init: function(){
this.font = null;
},
onResetEvent: function() {
me.audio.stop("theme");
game.data.newHiScore = false;
me.game.world.addChild(new BackgroundLayer('bg', 1));
me.input.bindKey(me.input.KEY.ENTER, "enter", true);
me.input.bindKey(me.input.KEY.SPACE, "enter", true);
me.input.bindMouse(me.input.mouse.LEFT, me.input.KEY.ENTER);
this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
if (action === "enter") {
me.state.change(me.state.PLAY);
}
});
//logo
var logoImg = me.loader.getImage('logo');
var logo = new me.SpriteObject (
me.game.viewport.width/2 - 170,
-logoImg,
logoImg
);
me.game.world.addChild(logo, 10);
var logoTween = new me.Tween(logo.pos).to({y: me.game.viewport.height/2 - 100},
1000).easing(me.Tween.Easing.Exponential.InOut).start();
this.ground = new TheGround();
me.game.world.addChild(this.ground, 11);
me.game.world.addChild(new (me.Renderable.extend ({
// constructor
init: function() {
// size does not matter, it's just to avoid having a zero size
// renderable
this.parent(new me.Vector2d(), 100, 100);
//this.font = new me.Font('Arial Black', 20, 'black', 'left');
this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START';
this.font = new me.Font('gamefont', 20, '#000');
},
update: function () {
return true;
},
draw: function (context) {
var measure = this.font.measureText(context, this.text);
this.font.draw(context, this.text, me.game.viewport.width/2 - measure.width/2, me.game.viewport.height/2 + 50);
}
})), 12);
},
onDestroyEvent: function() {
// unregister the event
me.event.unsubscribe(this.handler);
me.input.unbindKey(me.input.KEY.ENTER);
me.input.unbindKey(me.input.KEY.SPACE);
me.input.unbindMouse(me.input.mouse.LEFT);
me.game.world.removeChild(this.ground);
}
});
| Java |
# Extensions
A collection of useful, generic extensions.
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First Steps Into PHP</title>
</head>
<body>
<form>
X: <input type="text" name="num1" />
Y: <input type="text" name="num2" />
Z: <input type="text" name="num3" />
<input type="submit" />
</form>
<?php
if (!isset($_GET['num1']) || !isset($_GET['num2']) || !isset($_GET['num3'])){
exit(1);
}
$numbers = [$_GET['num1'], $_GET['num2'], $_GET['num3']];
$numbers = array_map('intval',$numbers);
if (in_array(0, $numbers)){
echo "Positive";
exit(0);
}
$numbers = array_filter($numbers,function ($num){
return $num<0;
});
$negativeNumbersCount = count($numbers);
$isPositive = $negativeNumbersCount%2==0;
if ($isPositive){
echo "Positive";
}
else{
echo "Negative";
}
?>
</body>
</html> | Java |
'use strict';
var _ = require('underscore'),
Util = require('../../shared/util'),
Base = require('./base'),
Action = require('../../action'),
Types = require('./types');
var _parent = Base.prototype;
var RandomWalk = Util.extend(Base, {
properties: ['walkPropability'],
type: Types.RANDOM_WALK,
_walkPropability: 0.3,
create: function(config) {
var me = this;
me.getConfig(config, ['walkPropability']);
_parent.create.apply(me, arguments);
},
decide: function() {
var me = this;
if (Math.random() > me._walkPropability) {
return null;
}
switch (_.random(3)) {
case 0:
return new Action.Move({deltaX: 1});
case 1:
return new Action.Move({deltaX: -1});
case 2:
return new Action.Move({deltaY: 1});
case 3:
return new Action.Move({deltaY: -1});
}
return null;
}
});
module.exports = RandomWalk; | Java |
<?php
/* SRVDVServerBundle:ChangePassword:changePassword.html.twig */
class __TwigTemplate_e5da0f0553fed635f2774271a2ef3982b389e99e651b1a8527dd0c0b6ca90bd7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'fos_user_content' => array($this, 'block_fos_user_content'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->enter($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SRVDVServerBundle:ChangePassword:changePassword.html.twig"));
// line 1
echo "
";
// line 3
$this->displayBlock('fos_user_content', $context, $blocks);
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->leave($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof);
}
public function block_fos_user_content($context, array $blocks = array())
{
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->enter($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "fos_user_content"));
// line 4
echo " ";
$this->loadTemplate("SRVDVServerBundle:ChangePassword:changePassword_content.html.twig", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", 4)->display($context);
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->leave($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof);
}
public function getTemplateName()
{
return "SRVDVServerBundle:ChangePassword:changePassword.html.twig";
}
public function getDebugInfo()
{
return array ( 39 => 4, 27 => 3, 23 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("
{% block fos_user_content %}
{% include \"SRVDVServerBundle:ChangePassword:changePassword_content.html.twig\" %}
{% endblock fos_user_content %}
", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", "C:\\wamp64\\www\\serveurDeVoeux\\src\\SRVDV\\ServerBundle/Resources/views/ChangePassword/changePassword.html.twig");
}
}
| Java |
//
// Created by root on 07.05.17.
//
#ifndef BASICMODEL_BASEMANAGER_H
#define BASICMODEL_BASEMANAGER_H
#include <mysql++.h>
#include <vector>
#include "dbConfig.h"
namespace model {
namespace manager {
template<class ModelName>
class baseManager {
public:
baseManager() {
try {
_con.connect(db_name, db_ip, db_user, db_password);
}
catch (...) {
return;
}
}
baseManager(const std::string &table) : _tableName(table) {
try {
_con.connect(db_name, db_ip, db_user, db_password);
}
catch (...) {
return;
}
}
baseManager(const baseManager &rhs) : _con(rhs._con), _query(rhs._query),
_tableName(rhs._tableName) {}
virtual ~baseManager() {
_con.disconnect();
}
virtual void update(ModelName &model) = 0;
virtual void get(const std::string &filter) = 0;
virtual void get() = 0;
virtual void all() = 0;
virtual void filter(const std::string &filter) = 0;
virtual void execute() = 0;
virtual void execute(ModelName &result) = 0;
virtual void execute(std::vector<ModelName> &result) = 0;
protected:
mysqlpp::Connection _con;
std::string _query;
std::string _tableName;
};
}
}
#endif //BASICMODEL_BASEMANAGER_H
| Java |
<?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\Order\Service\OfflineInterface;
/**
* @author shadonTools<localhost.shell@gmail.com>
*/
class Offline implements OfflineInterface
{
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
}
| Java |
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$CONFIGURATION_BUILD_DIR/WTCalendarController/WTCalendarController.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$CONFIGURATION_BUILD_DIR/WTCalendarController/WTCalendarController.framework"
fi
| Java |
---
title: Consuming a Moodle webservice
categories:
- Moodle
- dev
- webservices
tags:
---
This post describes how to consume a Moodle core webservice.
##Set up Moodle
### Enable REST protocol
In `Dashboard / ► Site administration / ► Plugins / ► Web services / ► Manage protocols`
- enable REST protocol.
- enable `Web services documentation` too.
###Create a custom webservice
In `Dashboard / ► Site administration / ► Plugins / ► Web services / ► External services`
- add a custom services named `test ws` for example
###Create a custom user for webservice
In `Dashboard / ► Site administration / ► Users / ► Accounts / ► Add a new user`
- create a `wsuser` user.
###Create a custom role for webservice
In `Dashboard / ► Site administration / ► Users / ► Permissions / ► Define roles`
- create a `ws_user_role`.
- allow at least `Create a web service token`
###Assign role to user
`Dashboard / ► Site administration / ► Users / ► Permissions / ► Assign system roles`
##Test
### Get a cool REST client
Getting a user friendly REST client is important, [POSTMAN is pretty cool](https://www.getpostman.com/).
###Get a token
Make a GET request to get a token.
For instance:`https://192.168.33.10/login/token.php?service=test_ws&username=wsuser&password=Wsuser123456-`. You should get:
{
"token": "19f315a127eef1f7f381da40fefd7b75"
}
###Consuming a Moodle core webservice
Now we get a token! So let's consume the `core_course_get_courses` WS. Results in JSON with `moodlewsrestformat=json`.
Make a POST request on `https://192.168.33.10/webservice/rest/server.php?wstoken=19f315a127eef1f7f381da40fefd7b75&wsfunction=core_course_get_courses&options[ids][0]=1&moodlewsrestformat=json`. You should get :
[
{
"id": 1,
"shortname": "test",
"categoryid": 0,
"fullname": "Site de test",
"summary": "",
"summaryformat": 1,
"format": "site",
"startdate": 0,
"numsections": 1
}
]
###API DOCUMENTATION
This can be found at `Dashboard / ► Site administration / ► Plugins / ► Web services / ► API Documentation` | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rice Diseases</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap.min.css">
<script src="static/jquery.min.js"></script>
<script src="static/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">Forecast</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Rice Diseases
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/1">Brown Spot Disease</a></li>
<li><a href="/2">Blast Disease</a></li>
<li><a href="/3">Bacterial Leaf Streak Disease</a></li>
<li><a href="/4">Dirty Panicle Disease</a></li>
<li><a href="/5">Bacterial Leaf Blight Disease</a></li>
</ul>
</li>
<li><a href="/graph">Graph</a></li>
<li><a href="/read">Data</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>Bacterial Leaf Streak Disease</h1>
<h2>Symptoms</h2>
<p>
Symptoms are narrow, dark-greenish, water-soaked, interveinal streaks of various lengths, initially restricted to the leaf blades. The lesions enlarge, turn yellowish-orange to brown (depending on cultivar), and eventually coalesce. Tiny amber droplets of bacterial exudate are often present on the lesions.</p>
<p>Causal agent : <i>Xanthomonas oryzae pv. oryzicola</i>
<br>
Percentage of damage: Seedling 70%, Grains production period 30%
</p>
<div class="container">
<div style="float:left;"><img class="img-responsive" src="static/31.png" alt="Bacterial leaf streak disease" width="200"></div>
<div style="float:left;"><img class="img-responsive" src="static/32.png" alt="Bacterial leaf streak disease" width="200"></div>
<div style="float:left;"><img class="img-responsive" src="static/33.png" alt="Bacterial leaf streak disease" width="200"></div>
</div>
<h2>Managements</h2>
<p>
1. Phytosanitary measures to prevent the distribution of seed infected.
<br>
2. Healthy seed is used.
<br>
3. Suitable using nitrogenous fertilizer because the use of excess nitrogenous fertilizer has shown an increase in incidence.
<br>
4. Biological control such as Trichoderma spp., Bacillus subtilis, Pseudomonas fluorescens.
<br>
5. Other control measures are not likely to be necessary.
<p>
</div>
</div>
</div>
</body>
</html>
| Java |
import_module('Athena.Math');
m1 = new Athena.Math.Matrix3(1, 2, 3,
4, 5, 6,
7, 8, 9);
for (var row = 0; row < 3; ++row)
{
for (var col = 0; col < 3; ++col)
CHECK_CLOSE(row * 3 + col + 1, m1.get(row, col));
}
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:27606576bf3cd46c15755bdec387cc97145a4a0c0a5b3933c11d30ab8c6c5ec7
size 1825
| Java |
<?php
/**
* The default template for displaying content
*
* Used for both single and index/archive/search.
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
?>
<div id="post-<?php the_ID(); ?>" <?php post_class('blogpost-entry'); ?>>
<header>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php foundationpress_entry_meta(); ?>
</header>
<div class="entry-content">
<?php the_content( __( 'Continue reading...', 'foundationpress' ) ); ?>
</div>
<footer>
<?php $tag = get_the_tags(); if ( $tag ) { ?><p><?php the_tags(); ?></p><?php } ?>
</footer>
<hr />
</div>
| Java |
# Users
With the **Enterprise Edition** there are two categories of users which have different roles and permissions.
## General Users
General users of the **Enterprise Edition** have the same permissions and features at hand as compared to users of the **Community Edition**. The only difference is, that new users need to be invited by an administrator and can't simply sign up. Further they are not allowed to invite or add new users.
## Administrators
Administrators (admins) of the **Enterprise Edition** have access to the administration area of the website to manage general users, admin users, but also Projects, Protocols, Measurements, etc. The purpose of the admin is purely to manage the page, content and users.
::: warning Note
An admin user is not permitted to login to the web app, desktop app, or mobile app. The admin must also be added as a general user in order to contribute data and collaborate on projects via the web, desktop, and mobile applications.
:::
| Java |
class EnsureNoLimitOnUserDataField < ActiveRecord::Migration
def up
change_column :users, :user_data, :text, :limit => nil
end
def down
end
end
| Java |
<?php
/*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2004 Bharat Mediratta
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id: User.php,v 1.7 2004/03/23 17:53:16 cryptographite Exp $
*/
?>
<?php
class PostNuke_User extends Abstract_User {
function loadByUid($uid) {
global $name; /* Gallery PN module name */
/*
* Consider the case where we're trying to load a $uid
* that stemmed from a user created by a standalone
* Gallery. That $uid won't be valid for PostNuke.
* We don't want this to cause problems, so in that
* case we'll just pretend that it was Nobody.
*
* But how do we detect those users? Well, let's take
* the quick and dirty approach of making sure that
* the uid is numeric.
*/
if (ereg("[^0-9]", $uid)) {
$newuser = new NobodyUser();
foreach ($newuser as $k => $v) {
$this->$k = $v;
}
return;
}
$this->username = pnUserGetVar('uname', $uid);
$this->fullname = pnUserGetVar('name', $uid);
$this->email = pnUserGetVar('email', $uid);
$this->canCreateAlbums = 0;
$this->uid = $uid;
/*
* XXX: this sets the admin-ness according to the user who's
* currently logged in -- NOT the $uid in question! This would
* be an issue, except that it just so happens that it doesn't
* affect anything we're doing in the app level code.
*/
$this->isAdmin = (pnSecAuthAction(0, "$name::", '::', ACCESS_ADMIN));
}
function loadByUserName($uname) {
list($dbconn) = pnDBGetConn();
$pntable = pnDBGetTables();
$userscolumn = &$pntable['users_column'];
$userstable = $pntable['users'];
/* Figure out the uid for this uname */
$query = "SELECT $userscolumn[uid] " .
"FROM $userstable " .
"WHERE $userscolumn[uname] = '" . pnVarPrepForStore($uname) ."'";
$result = $dbconn->Execute($query);
list($uid) = $result->fields;
$result->Close();
$this->loadByUid($uid);
}
}
?>
| Java |
module MuhrTable
VERSION = "1.0.22"
end
| Java |
import Objective from '../objective';
export default class KillShipsObjective extends Objective {
constructor (game, ships) {
super(game);
if (!Array.isArray(ships)) {
ships = [ships];
}
this.bots = _.filter(ships, ship => { return ship.alive; });
this.ships = ships;
}
isComplete () {
var all_dead = true;
for (var i = 0; i < this.ships.length; i++) {
if (this.ships[i].alive) {
all_dead = false;
break;
}
}
return all_dead;
}
};
| Java |
body {
background-color:#948664;
font-size:16px;
font-family:Georgia, "Times New Roman", Times, serif;
color:#F4ECD3;
text-shadow:-1px -1px 5px #000;
padding:0;
margin:0;
}
a {
color:#fbfcef;
}
a:visited {
color:#eed69b;
}
a:hover {
color:#d7bc7b;
}
a:active {
color:#eed69b;
}
h1 {
font-size:11px;
text-transform:uppercase;
background-color:#948664;
padding:5px 15px;
margin:0
}
h2 {
font-size:24px;
font-weight:normal;
padding:5px 10px;
margin:0;
color:#F4ECD3;
}
h3 {
font-size:16px;
font-weight:bold;
font-variant:small-caps;
padding:5px 10px;
margin:0;
}
h3 img {
border:1px solid #e3d9ac;
width:170px;
height:auto;
}
img.download {
vertical-align:middle;
}
#container {
width:900px;
margin-bottom:10px;
margin:0 auto;
background-color:#948664;
}
#banner {
background-color:#948664;
text-align:right;
padding:0px;
margin:0px;
}
#banner img {
padding:0px 0px;
}
#content {
background-color:#3a2514;
padding:0px;
margin:0 200px;
text-align:center;
}
#content_left {
float:left;
width:250px;
height:250px;
}
#content_left img{
padding-top:5px;
padding-bottom:5px;
}
#content_right {
float:right;
width:250px;
height:250px;
}
#content li {
text-align:left;
}
div#content {
min-height:1100px;
height:expression(this.scrollHeight > 1100 ?"auto":"1100px");
}
p, pre {
padding:5px 10px;
margin:0px;
}
#left {
float:left;
width:200px;
height:1100px;
background-image:url(../img/left.gif);
text-align:center;
}
#left_center {
margin-top:30px;
}
#right {
float:right;
width:200px;
height:1100px;
background-image:url(../img/right.gif);
text-align:center;
}
#right_center {
margin-top:55px;
margin-left:9px;
}
#footer {
clear:both;
margin:0;
padding:0;
text-align:right;
}
| Java |
module Storegine
class Category
include Mongoid::Document
field :title, type: String
has_many :products
end
end
| Java |
export * from './privacy.component';
| Java |
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<!--<style>
* {
padding: 0;
margin: 0;
}
.fit { /* set relative picture size */
max-width: 100%;
max-height: 100%;
}
.center {
display: block;
margin: auto;
}
.content{
position: absolute;
top: 50%;
left: 50%;
}
</style>-->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container-fluid">
<div class="row">
<div class="col-lg-4 col-lg-offset-9">
<a href="#">Home</a>
<a href="#">How it works?</a>
<a href="#">About us</a>
</div>
</div>
<div class="row">
<div class="col-lg-12"> </div>
</div>
<div class="row">
<div class="col-lg-12">
<div style="background-color:lightblue; height:100px;">
<p class="text-center">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12"> </div>
</div>
<div class="row">
<div class="col-lg-2 col-lg-offset-4">
<a class="btn btn-default" href="#" role="button">I'm a car park owner</a>
</div>
<div class="col-lg-2">
<a class="btn btn-default" href="Find.html" role="button">I'm looking for a car park</a>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
<script type="text/javascript" language="JavaScript">
function set_body_height() { // set body height = window height
$('body').height($(window).height());
}
$(document).ready(function () {
$(window).bind('resize', set_body_height);
set_body_height();
});
</script>
| Java |
// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// full day names
Calendar._DN = new Array
("NedeÄľa",
"Pondelok",
"Utorok",
"Streda",
"Ĺ tvrtok",
"Piatok",
"Sobota",
"NedeÄľa");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Uto",
"Str",
"Ĺ tv",
"Pia",
"Sob",
"Ned");
// full month names
Calendar._MN = new Array
("Január",
"Február",
"Marec",
"AprĂl",
"Máj",
"JĂşn",
"JĂşl",
"August",
"September",
"OktĂłber",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Máj",
"JĂşn",
"JĂşl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/projects/calendar/\n" +
"Distribuované pod GNU LGPL. Viď http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"Výber dátumu:\n" +
"- Použite tlačidlá \xab, \xbb pre výber roku\n" +
"- Použite tlačidlá " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre výber mesiaca\n" +
"- Ak ktorĂ©koÄľvek z tĂ˝chto tlaÄŤidiel podrĹľĂte dlhšie, zobrazĂ sa rĂ˝chly vĂ˝ber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výber času:\n" +
"- Kliknutie na niektorú položku času ju zvýši\n" +
"- Shift-klik ju znĂĹľi\n" +
"- Ak podrĹľĂte tlaÄŤĂtko stlaÄŤenĂ©, posĂşvanĂm menĂte hodnotu.";
Calendar._TT["PREV_YEAR"] = "Predošlý rok (podržte pre menu)";
Calendar._TT["PREV_MONTH"] = "Predošlý mesiac (podržte pre menu)";
Calendar._TT["GO_TODAY"] = "Prejsť na dnešok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podrĹľte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podrĹľte pre menu)";
Calendar._TT["SEL_DATE"] = "Zvoľte dátum";
Calendar._TT["DRAG_TO_MOVE"] = "PodrĹľanĂm tlaÄŤĂtka zmenĂte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "ZobraziĹĄ pondelok ako prvĂ˝";
Calendar._TT["SUN_FIRST"] = "ZobraziĹĄ nedeÄľu ako prvĂş";
Calendar._TT["CLOSE"] = "ZavrieĹĄ";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ĹĄahanie zmenĂ hodnotu";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";
Calendar._TT["WK"] = "týž";
| Java |
@charset "utf-8";
body {
color: #7d7d7d;
/*background: #f5f4f2;*/
font-size: .875rem;
line-height: 24px;
background: #eeede8;
}
h1, h2, h3, h4, h5, h6, ul, li, ol, p {
margin: 0;
padding: 0;
}
a {
color: #7d7d7d;
text-decoration: none;
cursor: pointer;
}
a:hover {
color: #54abd4;
}
h1, h2, h3, h4, h5, h6 {
color: #666;
/*font-weight: bold;*/
}
h4 {
margin: 0 0 10px 0;
}
li {
display: list-item;
text-align: -webkit-match-parent;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
p {
margin: 12px 0;
}
input[type="text"],
input[type="password"],
input[type="email"],
input[type="date"],
textarea {
height: 40px;
/*line-height: 40px;*/
padding: 6px 10px;
background: #f5f5f5;
border: 1px solid #f5f5f5;
border-radius: 2px;
box-shadow: none;
color: #777;
}
input:focus,
input:active,
input:hover,
input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus,
input[type="date"]:focus,
textarea:focus,
textarea:active,
textarea:hover {
background: #fff;
border: 1px solid #54abd4;
box-shadow: none;
transition: all .25s ease-in-out;
}
/*蓝色矩形*/
.tag-info {
display: inline-block;
margin: 0 4px 4px 0;
padding: 0 8px;
color: #fff;
background: #88C5E1;
border-radius: 4px;
}
.tag-info:hover {
color: #fff;
background: #54abd4;
text-decoration: none;
}
/*字体设置工具类*/
.tag-sm {
padding: 0 6px;
font-size: .75rem;
}
.f-12 {
font-size: .75rem;
}
.f-14 {
font-size: .875rem;
}
.f-16 {
font-size: 1rem;
}
.f-18 {
font-size: 1.125rem;
}
.f-weight{
font-weight: 600;
}
.f-hot{
color:#333;
}
.f-main {
color: #88C5E1;
}
.f-sub {
color: #f9ca5a;
}
.f-light {
color: #b5b5b5;
}
.f-orange{
color: #fbd16f;
}
.f-white {
color: #fff;
}
.f-user{
color: #54abd4;
}
.f-ln18{
line-height: 1.8em;
}
/*content*/
.content {
margin: 80px 0 0 0;
min-height: 720px;
}
/*section*/
.section {
margin: 0 0 20px 0;
padding: 40px 25px 30px 25px;
background-color: #FFFFFF;
-moz-border-radius: 1px 1px 1px 1px;
-webkit-border-radius: 1px 1px 1px 1px;
border-radius: 1px 1px 1px 1px;
box-shadow: 0 14px 10px -10px rgba(0,0,0,0.1);
}
.section h4 {
margin: 0 0 24px 0;
padding: 8px 16px;
border-left: 3px solid #88C5E1;
}
/*item*/
.item {
padding: 12px 0 20px 0;
}
.score img{
display: inline;
width: 12px;
}
/*汉堡菜单*/
.nav-hamburger {
height: 40px;
padding: 0 10px;
color: #fff;
border: 1px solid #fff;
border-radius: 2px;
font-size: 1.125rem;
line-height: 40px;
}
.nav-hamburger a {
display: block;
color: #fff;
}
.navbar{
padding: 12px 0;
background-color: #88c5e1;
border: none;
border-bottom: 5px solid #54abd4;
}
.navbar-nav > li > a {
font-size: 1rem;
color: #fff;
margin: 0 0 0 8px;
background: transparent;
padding: 10px;
}
.navbar-nav > .active > a{
background: none;
color: #fff;
border-bottom: 2px solid #fff;
}
.navbar-nav > li > a:hover{
color: #fff;
border-bottom: 2px solid #fff;
}
.navbar-brand-mc{
padding: 6px 0;
font-weight: 100;
}
.navbar-brand-mc img{
height: 40px;
display: inline-block;
margin-right: 3px;
}
.navbar-default .navbar-nav>.active>a,
.navbar-default .navbar-nav>.active>a:focus,
.navbar-default .navbar-nav>.active>a:hover{
background: transparent;
color: #fff;
}
.nav>li>a:focus, .nav>li>a:hover{
background: transparent;
}
.navbar-form-mc .input-group {
width: 100%;
}
#input-search {
border-radius: 2px;
}
.input-group-nav .input-group-btn:last-child > .btn,
.input-group-nav .input-group-btn:last-child > .btn-group {
z-index: 2;
margin-left: -42px;
}
.input-group-nav .input-group-btn .btn {
background: #f5f5f5;
border: 1px solid #f5f5f5;
border-radius: 2px;
color: #54abd4;
}
.navbar-toggle{
margin: 18px 10px 8px 10px;
}
.home .content{
margin: 60px 0 0 0;
}
.wrapper{
padding: 35px 0;
margin: 40px auto;
background: url(../images/homeImg.png);
background-size: cover;
}
.wrapper .form-control{
margin: 15px 0;
}
.wrapper .wrapper-intro{
text-align: center;
}
.wrapper .wrapper-intro img:first-child{
margin: -10px 0 20px 0;
}
.wrapper .wrapper-title{
margin: 7px 0;
font-size: 20px;
}
.wrapper .wrapper-slogan{
font-size: 16px;
}
.wrapper .log-or-sign{
padding-left: 20px;
}
.wrapper .log-or-sign a{
color: #fff;
}
.wrapper .checkbox{
color: #333;
}
.section h4 small {
margin-left: 8px;
}
.hot-course .item{
margin: 0 0 20px 0;
padding: 0 10px;
border: none;
}
.item-card{
background-color:#f5f5f5;
text-align: center;
padding: 52px 16px;
box-shadow: 0 1px 2px #ddd;
}
.card-icon {
display: inline-block;
width: 64px;
padding: 12px 0 4px 0;
}
.card-name {
display: block;
padding: 2px 0 16px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.score img{
width: 12px;
}
.nav-tabs {
border: none;
border-bottom: 2px solid transparent;
}
.nav-tabs>li.active>a,.log-or-sign .nav-tabs>li.active>a:focus,
.log-or-sign .nav-tabs>li.active>a:hover{
border: none;
border-bottom: 2px solid transparent;
}
.log-or-sign .nav-tabs>li>a,
.log-or-sign .nav-tabs>li>a:focus,
.log-or-sign .nav-tabs>li>a:hover{
border-bottom: 2px solid #fff;
}
.log-or-sign .nav-tabs>li.active>a:hover{
border-bottom: 2px solid #fff;
}
.log-or-sign .nav-tabs>li>a{
border: none;
border-bottom: 2px solid transparent;
}
.log-or-sign .nav-tabs{
/*border-bottom: 2px solid #eee;*/
}
.log-or-sign .nav-tabs li{
padding: 0 0 10px 0;
}
.log-or-sign .nav-tabs li a{
padding: 10px 0 3px 0;
margin-right: 15px;
font-size: 16px;
text-align: center;
}
.log-or-sign .nav-tabs li.active a{
color: #fff;
background-color: transparent;
border-bottom: 2px solid #fff;
}
.tab-info {
display: none;
padding: 12px 12px;
color: #fff;
background: #88c5e1;
border-radius: 2px;
}
.tag-section {
padding: 0 0 18px 0;
}
.tag-section h5 {
padding: 8px 0 12px 0;
}
.thumbnail {
padding: 0;
background-color: #f5f5f5;
border: none;
box-shadow: 1px 1px 2px #ddd;
}
.carousel-inner .thumbnail .caption{
margin: 8px 0 20px 0;
color: #999;
font-size: 1rem;
text-align: center;
}
.carousel-indicators{
bottom: -10px;
}
.carousel-indicators li{
width: 13px;
height: 13px;
}
.carousel-indicators .active{
width: 15px;
height: 15px;
}
.caption p{
margin-bottom: 20px;
}
.carousel-indicators li{
border: 1px solid #f8c038;
}
.carousel-indicators .active{
background-color: #f8c038;
}
@media screen and (max-width: 768px){
.wrapper .log-or-sign{
border-left: none;
margin-left: 0px;
padding-left: 15px;
padding-top: 20px;
}
.wrapper-intro img{
display:none;
}
}
@media (min-width: 992px){
.wrapper {
padding: 96px 0;
}
}
/*footer部分*/
footer {
padding: 28px 0 18px 0;
background: #eeece1;
}
.footer-icon {
width: 10%;
}
.footer-seg {
width: 88%;
padding: 0 0 12px 0;
}
.footer-seg h5 {
padding: 3px 0 7px 0;
font-size: .875rem;
}
.footer-seg p {
margin: 0;
padding: 0;
font-size: .75rem;
line-height: 1.125rem;
}
.footer-info {
font-size: .75rem;
text-align: center;
line-height: 1.125rem;
}
.footer-info p {
margin: 0;
padding: 0;
} | Java |
.highlight {
padding: 1px 3px;
font-weight: bold;
background-color: #fff34d;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
-moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
-webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
} | Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("03. Rage Quit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Rage Quit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("102e97e8-a5dc-4989-9bff-d9818c2cabbf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
module Jdt
class GeneratorCLI < Thor
desc "library NAME", "generate library with NAME"
def library(name)
LibraryGenerator.new.generate(name)
end
end
end | Java |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.annotations.cascade;
import java.util.HashSet;
import org.junit.Test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.fail;
/**
* @author Jeff Schnitzer
* @author Gail Badner
*/
@SuppressWarnings("unchecked")
public class NonNullableCircularDependencyCascadeTest extends BaseCoreFunctionalTestCase {
@Test
public void testIdClassInSuperclass() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Parent p = new Parent();
p.setChildren( new HashSet<Child>() );
Child ch = new Child(p);
p.getChildren().add(ch);
p.setDefaultChild(ch);
try {
s.persist(p);
s.flush();
fail( "should have failed because of transient entities have non-nullable, circular dependency." );
}
catch ( HibernateException ex) {
// expected
}
tx.rollback();
s.close();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{
Child.class,
Parent.class
};
}
}
| Java |
System.config({
baseURL: ".",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
bundles: {
"build.js": [
"lib/main.js",
"lib/filelayer/ajaxUtil.js",
"lib/filelayer/corslite.js",
"github:shramov/leaflet-plugins@1.4.2",
"npm:leaflet@0.7.7",
"npm:togeojson@0.13.0",
"lib/filelayer/leaflet.filelayer.js",
"github:mholt/PapaParse@4.1.2",
"npm:font-awesome@4.5.0/css/font-awesome.min.css!github:systemjs/plugin-css@0.1.20",
"github:shramov/leaflet-plugins@1.4.2/control/Distance",
"npm:leaflet@0.7.7/dist/leaflet-src",
"npm:togeojson@0.13.0/togeojson",
"github:mholt/PapaParse@4.1.2/papaparse",
"github:jspm/nodelibs-process@0.1.2",
"github:jspm/nodelibs-process@0.1.2/index",
"npm:process@0.11.2",
"npm:process@0.11.2/browser"
]
},
map: {
"adm-zip": "npm:adm-zip@0.4.7",
"babel": "npm:babel-core@5.8.34",
"babel-runtime": "npm:babel-runtime@5.8.34",
"clean-css": "npm:clean-css@3.4.9",
"core-js": "npm:core-js@1.2.6",
"css": "github:systemjs/plugin-css@0.1.20",
"font-awesome": "npm:font-awesome@4.5.0",
"gildas-lormeau/zip.js": "github:gildas-lormeau/zip.js@master",
"leaflet": "npm:leaflet@0.7.7",
"mapbox/togeojson": "github:mapbox/togeojson@0.13.0",
"mholt/PapaParse": "github:mholt/PapaParse@4.1.2",
"shramov/leaflet-plugins": "github:shramov/leaflet-plugins@1.4.2",
"togeojson": "npm:togeojson@0.13.0",
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.6.0"
},
"github:jspm/nodelibs-constants@0.1.0": {
"constants-browserify": "npm:constants-browserify@0.0.1"
},
"github:jspm/nodelibs-crypto@0.1.0": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
},
"github:jspm/nodelibs-events@0.1.1": {
"events": "npm:events@1.0.2"
},
"github:jspm/nodelibs-http@1.7.1": {
"Base64": "npm:Base64@0.2.1",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-https@0.1.0": {
"https-browserify": "npm:https-browserify@0.0.0"
},
"github:jspm/nodelibs-os@0.1.0": {
"os-browserify": "npm:os-browserify@0.1.2"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-stream@0.1.0": {
"stream-browserify": "npm:stream-browserify@1.0.0"
},
"github:jspm/nodelibs-string_decoder@0.1.0": {
"string_decoder": "npm:string_decoder@0.10.31"
},
"github:jspm/nodelibs-url@0.1.0": {
"url": "npm:url@0.10.3"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"github:jspm/nodelibs-zlib@0.1.0": {
"browserify-zlib": "npm:browserify-zlib@0.1.4"
},
"npm:adm-zip@0.4.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:amdefine@1.0.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"module": "github:jspm/nodelibs-module@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:asn1.js@4.3.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.34": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:browserify-aes@1.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"buffer-xor": "npm:buffer-xor@1.0.3",
"cipher-base": "npm:cipher-base@1.0.2",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:browserify-cipher@1.0.0": {
"browserify-aes": "npm:browserify-aes@1.0.5",
"browserify-des": "npm:browserify-des@1.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
},
"npm:browserify-des@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"des.js": "npm:des.js@1.0.0",
"inherits": "npm:inherits@2.0.1"
},
"npm:browserify-rsa@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:browserify-sign@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2",
"inherits": "npm:inherits@2.0.1",
"parse-asn1": "npm:parse-asn1@5.0.0",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:browserify-zlib@0.1.4": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"pako": "npm:pako@0.2.8",
"process": "github:jspm/nodelibs-process@0.1.2",
"readable-stream": "npm:readable-stream@2.0.5",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:buffer-xor@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:buffer@3.6.0": {
"base64-js": "npm:base64-js@0.0.8",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ieee754": "npm:ieee754@1.1.6",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:cipher-base@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0"
},
"npm:clean-css@3.4.9": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"commander": "npm:commander@2.8.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"http": "github:jspm/nodelibs-http@1.7.1",
"https": "github:jspm/nodelibs-https@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.4.4",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:commander@2.8.1": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"graceful-readlink": "npm:graceful-readlink@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:concat-stream@1.4.10": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13",
"typedarray": "npm:typedarray@0.0.6"
},
"npm:constants-browserify@0.0.1": {
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-js@1.2.6": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-util-is@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:create-ecdh@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.0.2"
},
"npm:create-hash@1.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"ripemd160": "npm:ripemd160@1.0.1",
"sha.js": "npm:sha.js@2.4.4"
},
"npm:create-hmac@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:crypto-browserify@3.11.0": {
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"browserify-sign": "npm:browserify-sign@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"diffie-hellman": "npm:diffie-hellman@5.0.1",
"inherits": "npm:inherits@2.0.1",
"pbkdf2": "npm:pbkdf2@3.0.4",
"public-encrypt": "npm:public-encrypt@4.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:des.js@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
},
"npm:diffie-hellman@5.0.1": {
"bn.js": "npm:bn.js@4.6.2",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:elliptic@6.0.2": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5",
"hash.js": "npm:hash.js@1.0.3",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:evp_bytestokey@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0"
},
"npm:font-awesome@4.5.0": {
"css": "github:systemjs/plugin-css@0.1.20"
},
"npm:graceful-readlink@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:hash.js@1.0.3": {
"inherits": "npm:inherits@2.0.1"
},
"npm:https-browserify@0.0.0": {
"http": "github:jspm/nodelibs-http@1.7.1"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:leaflet@0.7.7": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "github:jspm/nodelibs-util@0.1.0",
"zlib": "github:jspm/nodelibs-zlib@0.1.0"
},
"npm:miller-rabin@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"brorand": "npm:brorand@1.0.5"
},
"npm:os-browserify@0.1.2": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:pako@0.2.8": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:parse-asn1@5.0.0": {
"asn1.js": "npm:asn1.js@4.3.0",
"browserify-aes": "npm:browserify-aes@1.0.5",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"pbkdf2": "npm:pbkdf2@3.0.4",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pbkdf2@3.0.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:process-nextick-args@1.0.6": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:public-encrypt@4.0.0": {
"bn.js": "npm:bn.js@4.6.2",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:punycode@1.3.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:randombytes@2.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:readable-stream@1.1.13": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:readable-stream@2.0.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"process-nextick-args": "npm:process-nextick-args@1.0.6",
"string_decoder": "npm:string_decoder@0.10.31",
"util-deprecate": "npm:util-deprecate@1.0.2"
},
"npm:ripemd160@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sha.js@2.4.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.4.4": {
"amdefine": "npm:amdefine@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:stream-browserify@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13"
},
"npm:string_decoder@0.10.31": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:togeojson@0.13.0": {
"concat-stream": "npm:concat-stream@1.4.10",
"minimist": "npm:minimist@0.0.8",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:url@0.10.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util-deprecate@1.0.2": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
}
}
});
| Java |
// languages index
var localeIndex = {
"en" : 0,
"ja" : 1,
"es" : 2,
"hu" : 3,
"lt" : 4,
"ru" : 5,
"it" : 6,
"pt" : 7,
"sp_ch" : 8,
"fr" : 9,
"ge" : 10,
"ua" : 11,
"lv" : 12,
"no" : 13,
"pt_br" : 14
};
| Java |
<?php
/**
* This file is part of gh-dashboard.
*
* (c) Daniel Londero <daniel.londero@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
function includeIfExists($file)
{
return file_exists($file) ? include $file : false;
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
echo "Cannot find an autoload.php file, have you executed composer install command?" . PHP_EOL;
exit(1);
}
return $loader;
| Java |
<html><body>
<h4>Windows 10 x64 (18363.836)</h4><br>
<h2>_LUID</h2>
<font face="arial"> +0x000 LowPart : Uint4B<br>
+0x004 HighPart : Int4B<br>
</font></body></html> | Java |
/*******************************************************************************
* Filename: irc_comm.h
*
* These are functions and definitions that can be used for both the client
* and the server programs.
*
* Written by: James Ross
******************************************************************************/
#ifndef _IRC_COMM_H_
#define _IRC_COMM_H_
#include "utility_sys.h" /* useful macros, definitions and libraries */
#define NO_FLAGS 0 /* used for functions where no flag argument is used. */
/* Server connectivity information */
#define _COM_SERV_ADDR "10.200.248.135"
#define _COM_SERV_LEN sizeof(_COM_SERV_ADDR)
#define _COM_SERV_PORT 50059 /* port listening on server */
#define _COM_NET_DOMAIN AF_INET /* network domain we are using. IPV4 */
#define _COM_SOCK_TYPE SOCK_STREAM /* tcp socket */
#define _COM_IP_PROTOCOL 0 /* Default for type in socket() */
#define _COM_IO_BUFF 512 /* max bytes that can be sent/recieved */
#define _NAME_SIZE_MAX 11 /* includes '\0' */
#define MSG_TYPE_SIZE 1
/******************************************************************************
* Command Code Definition
******************************************************************************/
#define RC_FA 0x1
#define RC_FL 0x2
#define RC_JOIN 0x7
#define RC_EXIT 0x8
#define RC_LOGOUT 0xA
#define RC_RL 0xC
#define RC_FR 0x10
#define RC_LOGON 0x11
#define RC_LEAVE 0x15
#define RC_MSG 0x16
#define RC_RUL 0x17 /* list users in a room */
#define RESERVED_Z 0x0 /* was useful to reserve for error checking */
#define RESERVE_CR 0x13 /* reserved since we use \r in messages */
/* server to client reply success/failure */
#define _REPLY_SUCCESS 1
#define _REPLY_FAILURE 0
/* length of the reply to logon. */
#define _LOGON_REPLY_SIZE 3
typedef struct server_info {
in_addr_t addr; /* network binary of server address */
char *dot_addr; /* dotted representation of IP address */
in_port_t port; /* port used at IP address, network ordered */
int domain; /* AF_INET or AF_INET6 */
int sock_type; /* type of socket, socket() definition. */
int pcol; /* Protocol argument used in socket() */
int sockfd; /* socket file descriptior */
struct sockaddr_in *socket_info; /* socket API struct, IPV4 */
} struct_serv_info;
typedef struct parsed_cli_message {
char *cli_name;
int type;
char *msg;
} struct_cli_message;
typedef struct parsed_serv_message {
uint8_t type;
char *msg;
} struct_serv_message;
struct_serv_info* _com_init_serv_info(void);
void _com_free_serv_info(struct_serv_info *dest);
void _com_free_cli_message(struct_cli_message *rem);
void _com_free_serv_message(struct_serv_message *rem);
/*******************************************************************************
* TODO: Maybe make these functions since they are long, though my current
* protocol with them just calls a seperate stack frame and just calls the
* inline, which the compiler should notice and just make that 1 stack frame
* this code...
*
* An analyze binary size, which i think is okay since it is only called in a
* single line function that returns this. Other issues though? Memory
* imprint in a different way?
******************************************************************************/
static inline ssize_t socket_transmit(int sockfd, uint8_t *tx,
size_t len, int flags)
{
ssize_t sent; /* number of bytes written to socket */
size_t remaining = len; /* number of bytes left to write */
sent = send(sockfd, tx, remaining, flags);
if (_usrUnlikely(sent == FAILURE)) {
err_msg("socket_transmit: send() failed");
return FAILURE;
}
/* in case there was something not written, try again */
remaining -= sent;
tx += sent;
return (len - remaining);
} /* end socket_transmit */
static inline ssize_t socket_receive(int sockfd, uint8_t *rx,
size_t len, int flags)
{
ssize_t received = 1; /* bytes read from a socket, non-EOF init */
size_t remaining = len; /* bytes still in buffer */
received = recv(sockfd, rx, remaining, flags);
if (received == FAILURE) {
err_msg("socket_recieve: recv() failed");
return FAILURE;
}
remaining -= received;
rx += received;
return (len - remaining);
} /* end socket_recieve */
#endif
| Java |
import React, { PropTypes, Component } from 'react';
import { Breadcrumb, Table, Button, Col } from 'react-bootstrap';
import cx from 'classnames';
import _ from 'lodash';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProductList.css';
import Link from '../Link';
class ProductList extends Component {
static propTypes = {
isFetching: PropTypes.bool,
rs: PropTypes.array,
popAddApp: PropTypes.func,
};
static defaultProps = {
isFetching: true,
rs: [],
popAddApp: () => {},
};
constructor() {
super();
this.renderRow = this.renderRow.bind(this);
}
renderRow(rowData, index) {
const appName = _.get(rowData, 'name');
return (
<tr key={_.get(rowData, 'name')}>
<td>
<Link to={`/apps/${appName}`}>{appName}</Link>
</td>
<td style={{ textAlign: 'left' }}>
<ul>
{
_.map(_.get(rowData, 'collaborators'), (item, email) => (
<li key={email}>
{email}
<span className={s.permission}>
(<em>{_.get(item, 'permission')}</em>)
</span>
{
_.get(item, 'isCurrentAccount') ?
<span className={cx(s.label, s.labelSuccess)}>
it's you
</span>
: null
}
</li>
))
}
</ul>
</td>
<td>
<ul>
{
_.map(_.get(rowData, 'deployments'), (item, email) => (
<li key={email} style={item === 'Production' ? { color: 'green' } : null} >
<Link to={`/apps/${appName}/${item}`}>{item}</Link>
</li>
))
}
</ul>
</td>
<td />
</tr>
);
}
render() {
const self = this;
const tipText = '暂无数据';
return (
<div className={s.root}>
<div className={s.container}>
<Breadcrumb>
<Breadcrumb.Item active>
应用列表
</Breadcrumb.Item>
</Breadcrumb>
<Col style={{ marginBottom: '20px' }}>
<Button
onClick={this.props.popAddApp}
bsStyle="primary"
>
添加应用
</Button>
</Col>
<Table striped bordered condensed hover responsive>
<thead>
<tr>
<th style={{ textAlign: 'center' }} >产品名</th>
<th style={{ textAlign: 'center' }} >成员</th>
<th style={{ textAlign: 'center' }} >Deployments</th>
<th style={{ textAlign: 'center' }} >操作</th>
</tr>
</thead>
<tbody>
{
this.props.rs.length > 0 ?
_.map(this.props.rs, (item, index) => self.renderRow(item, index))
:
<tr>
<td colSpan="4" >{tipText}</td>
</tr>
}
</tbody>
</Table>
</div>
</div>
);
}
}
export default withStyles(s)(ProductList);
| Java |
# Scala Documentation
* [Command Line Input](command-line-input/command-line-input.md)
* [String](string/string.md)
* [Array](array/array.md)
* [List](list/list.md)
* [Vector](vector/vector.md)
* [Iterator](iterator/iterator.md)
* [HashMap](hashmap/hashmap.md)
* [Math](math/math.md) | Java |
define(['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var globalExtraOptions = exports.globalExtraOptions = {
mappingDataStructure: {
class: 'class',
content: 'content',
disabled: 'disabled',
divider: 'divider',
groupLabel: 'group',
groupDisabled: 'disabled',
icon: 'icon',
maxOptions: 'maxOptions',
option: 'option',
subtext: 'subtext',
style: 'style',
title: 'title',
tokens: 'tokens'
}
};
var globalPickerOptions = exports.globalPickerOptions = {
dropupAuto: true,
showTick: true,
width: 'auto'
};
}); | Java |
//=================================================================================================
/*!
// \file blaze/math/views/subvector/SubvectorData.h
// \brief Header file for the implementation of the SubvectorData class template
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_MATH_VIEWS_SUBVECTOR_SUBVECTORDATA_H_
#define _BLAZE_MATH_VIEWS_SUBVECTOR_SUBVECTORDATA_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/util/MaybeUnused.h>
#include <blaze/util/Types.h>
namespace blaze {
//=================================================================================================
//
// CLASS DEFINITION
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Auxiliary class template for the data members of the Subvector class.
// \ingroup subvector
//
// The auxiliary SubvectorData class template represents an abstraction of the data members of
// the Subvector class template. The necessary set of data members is selected depending on the
// number of compile time subvector arguments.
*/
template< size_t... CSAs > // Compile time subvector arguments
class SubvectorData
{};
//*************************************************************************************************
//=================================================================================================
//
// CLASS TEMPLATE SPECIALIZATION FOR ZERO COMPILE TIME ARGUMENTS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of the SubvectorData class template for zero compile time subvector
// arguments.
// \ingroup subvector
//
// This specialization of SubvectorData adapts the class template to the requirements of zero
// compile time subvector arguments.
*/
template<>
class SubvectorData<>
{
public:
//**Compile time flags**************************************************************************
//! Compilation flag for compile time optimization.
/*! The \a compileTimeArgs compilation flag indicates whether the view has been created by
means of compile time arguments and whether these arguments can be queried at compile
time. In that case, the \a compileTimeArgs compilation flag is set to \a true, otherwise
it is set to \a false. */
static constexpr bool compileTimeArgs = false;
//**********************************************************************************************
//**Constructors********************************************************************************
/*!\name Constructors */
//@{
template< typename... RSAs >
inline SubvectorData( size_t index, size_t n, RSAs... args );
SubvectorData( const SubvectorData& ) = default;
//@}
//**********************************************************************************************
//**Destructor**********************************************************************************
/*!\name Destructor */
//@{
~SubvectorData() = default;
//@}
//**********************************************************************************************
//**Assignment operators************************************************************************
/*!\name Assignment operators */
//@{
SubvectorData& operator=( const SubvectorData& ) = delete;
//@}
//**********************************************************************************************
//**Utility functions***************************************************************************
/*!\name Utility functions */
//@{
inline size_t offset() const noexcept;
inline size_t size () const noexcept;
//@}
//**********************************************************************************************
private:
//**Member variables****************************************************************************
/*!\name Member variables */
//@{
const size_t offset_; //!< The offset of the subvector within the vector.
const size_t size_; //!< The size of the subvector.
//@}
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief The constructor for SubvectorData.
//
// \param index The offset of the subvector within the given vector.
// \param n The size of the subvector.
// \param args The optional subvector arguments.
*/
template< typename... RSAs > // Optional subvector arguments
inline SubvectorData<>::SubvectorData( size_t index, size_t n, RSAs... args )
: offset_( index ) // The offset of the subvector within the vector
, size_ ( n ) // The size of the subvector
{
MAYBE_UNUSED( args... );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the offset of the subvector within the underlying vector.
//
// \return The offset of the subvector.
*/
inline size_t SubvectorData<>::offset() const noexcept
{
return offset_;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the current size/dimension of the subvector.
//
// \return The size of the subvector.
*/
inline size_t SubvectorData<>::size() const noexcept
{
return size_;
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// CLASS TEMPLATE SPECIALIZATION FOR TWO COMPILE TIME ARGUMENTS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of the SubvectorData class template for two compile time subvector
// arguments.
// \ingroup subvector
//
// This specialization of SubvectorData adapts the class template to the requirements of two
// compile time arguments.
*/
template< size_t I // Index of the first element
, size_t N > // Number of elements
class SubvectorData<I,N>
{
public:
//**Compile time flags**************************************************************************
//! Compilation flag for compile time optimization.
/*! The \a compileTimeArgs compilation flag indicates whether the view has been created by
means of compile time arguments and whether these arguments can be queried at compile
time. In that case, the \a compileTimeArgs compilation flag is set to \a true, otherwise
it is set to \a false. */
static constexpr bool compileTimeArgs = true;
//**********************************************************************************************
//**Constructors********************************************************************************
/*!\name Constructors */
//@{
template< typename... RSAs >
explicit inline SubvectorData( RSAs... args );
SubvectorData( const SubvectorData& ) = default;
//@}
//**********************************************************************************************
//**Destructor**********************************************************************************
/*!\name Destructor */
//@{
~SubvectorData() = default;
//@}
//**********************************************************************************************
//**Assignment operators************************************************************************
/*!\name Assignment operators */
//@{
SubvectorData& operator=( const SubvectorData& ) = delete;
//@}
//**********************************************************************************************
//**Utility functions***************************************************************************
/*!\name Utility functions */
//@{
static constexpr size_t offset() noexcept;
static constexpr size_t size () noexcept;
//@}
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief The constructor for SubvectorData.
//
// \param args The optional subvector arguments.
*/
template< size_t I // Index of the first element
, size_t N > // Number of elements
template< typename... RSAs > // Optional subvector arguments
inline SubvectorData<I,N>::SubvectorData( RSAs... args )
{
MAYBE_UNUSED( args... );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the offset of the subvector within the underlying vector.
//
// \return The offset of the subvector.
*/
template< size_t I // Index of the first element
, size_t N > // Number of elements
constexpr size_t SubvectorData<I,N>::offset() noexcept
{
return I;
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Returns the current size/dimension of the subvector.
//
// \return The size of the subvector.
*/
template< size_t I // Index of the first element
, size_t N > // Number of elements
constexpr size_t SubvectorData<I,N>::size() noexcept
{
return N;
}
/*! \endcond */
//*************************************************************************************************
} // namespace blaze
#endif
| Java |
# frozen_string_literal: true
require 'sunrise/config/base'
require 'sunrise/config/has_fields'
module Sunrise
module Config
class Form < Base
include Sunrise::Config::HasFields
include Sunrise::Config::HasGroups
# List of permissible attributes
register_instance_option :permited_attributes do
:all
end
end
end
end
| Java |
"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
| Java |
package softuni.io;
import org.springframework.stereotype.Component;
import java.io.*;
@Component
public class FileParser {
public String readFile(String path) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream is = this.getClass().getResourceAsStream(path);
BufferedReader bfr = new BufferedReader(new InputStreamReader(is))) {
String line = bfr.readLine();
while (line != null) {
stringBuilder.append(line);
line = bfr.readLine();
}
}
return stringBuilder.toString();
}
public void writeFile(String path, String content) throws IOException {
File file = new File(System.getProperty("user.dir") + File.separator + path);
if (!file.exists()) {
file.createNewFile();
}
try (OutputStream os = new FileOutputStream(System.getProperty("user.dir")+ File.separator + path);
BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(os))) {
bfw.write(content);
}
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bignums: 2 m 35 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.0 / bignums - 8.14.0</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.14.0
<span class="label label-success">2 m 35 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-01-22 01:07:46 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-22 01:07: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
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.0 Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.12.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.1 Official release 4.12.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
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: "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"
license: "LGPL-2.1-only"
synopsis: "Bignums, the Coq library of arbitrary large numbers"
description: """
Provides BigN, BigZ, BigQ that used to be part of Coq standard library < 8.6
"""
build: [make "-j%{jobs}%" {ocaml:version >= "4.06"}]
install: [make "install"]
depends: [
"ocaml" {>= "4.05"}
"coq" {>= "8.14" & < "8.15~"}
]
tags: [
"category:Miscellaneous/Coq Extensions"
"category:Mathematics/Arithmetic and Number Theory/Number theory"
"category:Mathematics/Arithmetic and Number Theory/Rational numbers"
"keyword:integer numbers"
"keyword:rational numbers"
"keyword:arithmetic"
"keyword:arbitrary-precision"
"logpath:Bignums"
"date:2021-09-17"
]
authors: [
"Laurent Théry"
"Benjamin Grégoire"
"Arnaud Spiwack"
"Evgeny Makarov"
"Pierre Letouzey"
]
url {
src: "https://github.com/coq/bignums/archive/V8.14.0.tar.gz"
checksum: "sha512=72be63a6be2600026ee4f5f24ea3479ff4c5d3f2a67ab65ec96ede56fbc35380ef6c721ad467c1b6d39f1447c28fe594fa5570d4228f1a05c6386b2b9955f2bc"
}
</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.14.0 coq.8.14.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 4h opam install -y --deps-only coq-bignums.8.14.0 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-bignums.8.14.0 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>2 m 35 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 8 M</p>
<ul>
<li>935 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/BigN.vo</code></li>
<li>562 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.glob</code></li>
<li>543 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.vo</code></li>
<li>493 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake.vo</code></li>
<li>344 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.glob</code></li>
<li>290 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.vo</code></li>
<li>277 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake.glob</code></li>
<li>264 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.vo</code></li>
<li>258 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/QMake.vo</code></li>
<li>246 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.vo</code></li>
<li>209 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.glob</code></li>
<li>204 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.glob</code></li>
<li>201 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.glob</code></li>
<li>197 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.vo</code></li>
<li>187 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.glob</code></li>
<li>176 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.vo</code></li>
<li>168 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.vo</code></li>
<li>167 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.vo</code></li>
<li>154 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.glob</code></li>
<li>151 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/QMake.glob</code></li>
<li>149 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.vo</code></li>
<li>127 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.vo</code></li>
<li>123 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.vo</code></li>
<li>122 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.glob</code></li>
<li>108 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.vo</code></li>
<li>98 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.vo</code></li>
<li>89 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.glob</code></li>
<li>79 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.vo</code></li>
<li>77 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.glob</code></li>
<li>75 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.glob</code></li>
<li>74 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.glob</code></li>
<li>67 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigNumPrelude.vo</code></li>
<li>66 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.vo</code></li>
<li>66 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.glob</code></li>
<li>66 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.glob</code></li>
<li>64 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigNumPrelude.glob</code></li>
<li>64 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.vo</code></li>
<li>58 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/plugin/bignums_syntax_plugin.cmxs</code></li>
<li>57 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.vo</code></li>
<li>55 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.v</code></li>
<li>54 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.vo</code></li>
<li>52 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake.v</code></li>
<li>50 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.vo</code></li>
<li>44 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.v</code></li>
<li>40 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.glob</code></li>
<li>37 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.glob</code></li>
<li>35 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/QMake.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.glob</code></li>
<li>33 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.v</code></li>
<li>28 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.v</code></li>
<li>24 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.v</code></li>
<li>22 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.v</code></li>
<li>20 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.v</code></li>
<li>19 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.glob</code></li>
<li>16 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.v</code></li>
<li>14 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/BigN.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.v</code></li>
<li>12 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigNumPrelude.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/plugin/bignums_syntax_plugin.cmi</code></li>
<li>9 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/plugin/bignums_syntax_plugin.cmx</code></li>
<li>7 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigN/BigN.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/plugin/bignums_syntax_plugin.cmxa</code></li>
<li>5 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-bignums.8.14.0</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 |
<#
.SYNOPSIS
Automated unit test for MSFT_SqlServerSecureConnection DSC resource.
.NOTES
To run this script locally, please make sure to first run the bootstrap
script. Read more at
https://github.com/PowerShell/SqlServerDsc/blob/dev/CONTRIBUTING.md#bootstrap-script-assert-testenvironment
#>
Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')
if (Test-SkipContinuousIntegrationTask -Type 'Unit')
{
return
}
$script:dscModuleName = 'SqlServerDsc'
$script:dscResourceName = 'MSFT_SqlServerSecureConnection'
#region HEADER
# Unit Test Template Version: 1.2.0
$script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:dscModuleName `
-DSCResourceName $script:dscResourceName `
-TestType Unit
#endregion HEADER
function Invoke-TestSetup
{
# Importing SQLPS stubs
Import-Module -Name (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Stubs') -ChildPath 'SQLPSStub.psm1') -Force -Global
}
function Invoke-TestCleanup
{
Restore-TestEnvironment -TestEnvironment $TestEnvironment
}
# Begin Testing
try
{
Invoke-TestSetup
InModuleScope $script:dscResourceName {
class MockedAccessControl
{
[hashtable]$Access = @{
IdentityReference = 'Everyone'
FileSystemRights = @{
value__ = '131209'
}
}
[void] AddAccessRule([System.Security.AccessControl.FileSystemAccessRule] $object)
{
}
}
class MockedGetItem
{
[string] $Thumbprint = '12345678'
[string] $PSPath = 'PathToItem'
[string] $Path = 'PathToItem'
[MockedAccessControl]$ACL = [MockedAccessControl]::new()
[hashtable]$PrivateKey = @{
CspKeyContainerInfo = @{
UniqueKeyContainerName = 'key'
}
}
[MockedGetItem] GetAccessControl()
{
return $this
}
}
$mockNamedInstanceName = 'INSTANCE'
$mockDefaultInstanceName = 'MSSQLSERVER'
$mockThumbprint = '123456789'
$mockServiceAccount = 'SqlSvc'
Describe 'SqlServerSecureConnection\Get-TargetResource' -Tag 'Get' {
BeforeAll {
$mockDynamic_SqlBuildVersion = '13.0.4001.0'
$defaultParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
Context 'When the system is in the desired state and Ensure is Present' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $true
Certificate = $mockThumbprint
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the the state of present' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $true
$resultGetTargetResource.Ensure | Should -Be 'Present'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Present' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $false
Certificate = '987654321'
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
It "Should return the state of absent when certificate thumbprint and certificate permissions don't match." {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Not -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $false
$resultGetTargetResource.Ensure | Should -Be 'Absent'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Present' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $true
Certificate = '987654321'
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the state of absent when certificate permissions match but encryption settings dont' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Not -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $true
$resultGetTargetResource.Ensure | Should -Be 'Absent'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Present' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $true
Certificate = $mockThumbprint
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
It 'Should return the state of absent when certificate permissions dont match but encryption settings do' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $true
$resultGetTargetResource.Ensure | Should -Be 'Absent'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
$defaultParameters.Ensure = 'Absent'
Context 'When the system is in the desired state and Ensure is Absent' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $false
Certificate = ''
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the the state of absent' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -BeNullOrEmpty
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $false
$resultGetTargetResource.Ensure | Should -Be 'Absent'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Absent' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $true
Certificate = $mockThumbprint
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the the state of present' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $true
$resultGetTargetResource.Ensure | Should -Be 'Present'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Absent' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $false
Certificate = $mockThumbprint
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the the state of present when ForceEncryption is False but a thumbprint exist.' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -Be $mockThumbprint
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $false
$resultGetTargetResource.Ensure | Should -Be 'Present'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
Context 'When the system is not in the desired state and Ensure is Absent' {
Mock -CommandName Get-EncryptedConnectionSetting -MockWith {
return @{
ForceEncryption = $true
Certificate = ''
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should return the the state of present when Certificate is null but ForceEncryption is True.' {
$resultGetTargetResource = Get-TargetResource @defaultParameters
$resultGetTargetResource.InstanceName | Should -Be $mockNamedInstanceName
$resultGetTargetResource.Thumbprint | Should -BeNullOrEmpty
$resultGetTargetResource.ServiceAccount | Should -Be $mockServiceAccount
$resultGetTargetResource.ForceEncryption | Should -Be $true
$resultGetTargetResource.Ensure | Should -Be 'Present'
Assert-MockCalled -CommandName Get-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
}
}
}
Describe 'SqlServerSecureConnection\Set-TargetResource' -Tag 'Set' {
BeforeAll {
$defaultParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
$defaultAbsentParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Absent'
}
Mock -CommandName Set-EncryptedConnectionSetting -Verifiable
Mock -CommandName Set-CertificatePermission -Verifiable
Mock -CommandName Restart-SqlService -Verifiable
}
Context 'When the system is not in the desired state' {
Context 'When only certificate permissions are set' {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = '987654321'
ServiceAccount = $mockServiceAccount
ForceEncryption = $false
Ensure = 'Present'
}
}
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
It 'Should configure only ForceEncryption and Certificate thumbprint' {
{ Set-TargetResource @defaultParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Set-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Set-CertificatePermission -Exactly -Times 0 -Scope It
Assert-MockCalled -CommandName Restart-SqlService -Exactly -Times 1 -Scope It
}
}
Context 'When there is no certificate permissions set' {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
It 'Should configure only certificate permissions' {
{ Set-TargetResource @defaultParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Set-EncryptedConnectionSetting -Exactly -Times 0 -Scope It
Assert-MockCalled -CommandName Set-CertificatePermission -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Restart-SqlService -Exactly -Times 1 -Scope It
}
}
Context 'When no settings are configured' {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = '987654321'
ServiceAccount = $mockServiceAccount
ForceEncryption = $false
Ensure = 'Present'
}
}
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
It 'Should configure Encryption settings and certificate permissions' {
{ Set-TargetResource @defaultParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Set-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Set-CertificatePermission -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Restart-SqlService -Exactly -Times 1 -Scope It
}
}
Context 'When ensure is absent' {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Absent'
}
}
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
It 'Should configure Encryption settings setting certificate to empty string' {
{ Set-TargetResource @defaultAbsentParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Set-EncryptedConnectionSetting -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Set-CertificatePermission -Exactly -Times 0 -Scope It
Assert-MockCalled -CommandName Restart-SqlService -Exactly -Times 1 -Scope It
}
}
}
}
Describe 'SqlServerSecureConnection\Test-TargetResource' -Tag 'Test' {
Context 'When the system is not in the desired state' {
Context 'When ForceEncryption is not configured properly' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $false
Ensure = 'Absent'
}
} -Verifiable
$testParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
It 'Should return state as not in desired state' {
$resultTestTargetResource = Test-TargetResource @testParameters
$resultTestTargetResource | Should -Be $false
}
}
Context 'When Thumbprint is not configured properly' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = '987654321'
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Absent'
}
} -Verifiable
$testParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
It 'Should return state as not in desired state' {
$resultTestTargetResource = Test-TargetResource @testParameters
$resultTestTargetResource | Should -Be $false
}
}
Context 'When certificate permission is not set' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Absent'
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $false }
$testParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
It 'Should return state as not in desired state' {
$resultTestTargetResource = Test-TargetResource @testParameters
$resultTestTargetResource | Should -Be $false
}
}
Context 'When Ensure is Absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Absent'
}
} -Verifiable
$testParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
It 'Should return state as not in desired state' {
$resultTestTargetResource = Test-TargetResource @testParameters
$resultTestTargetResource | Should -Be $false
}
}
}
Context 'When the system is in the desired state' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
} -Verifiable
Mock -CommandName Test-CertificatePermission -MockWith { return $true }
$testParameters = @{
InstanceName = $mockNamedInstanceName
Thumbprint = $mockThumbprint
ServiceAccount = $mockServiceAccount
ForceEncryption = $true
Ensure = 'Present'
}
}
It 'Should return state as in desired state' {
$resultTestTargetResource = Test-TargetResource @testParameters
$resultTestTargetResource | Should -Be $true
}
}
}
Describe 'SqlServerSecureConnection\Get-EncryptedConnectionSetting' -Tag 'Helper' {
Mock -CommandName 'Get-ItemProperty' -MockWith {
return @{
ForceEncryption = '1'
}
} -ParameterFilter { $Name -eq 'ForceEncryption' } -Verifiable
Mock -CommandName 'Get-ItemProperty' -MockWith {
return @{
Certificate = '12345678'
}
} -ParameterFilter { $Name -eq 'Certificate' } -Verifiable
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-SqlEncryptionValue' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
}
It 'Should return hashtable with ForceEncryption and Certificate' {
$result = Get-EncryptedConnectionSetting -InstanceName 'NamedInstance'
$result.Certificate | Should -Be '12345678'
$result.ForceEncryption | Should -Be 1
$result | Should -BeOfType [Hashtable]
Assert-VerifiableMock
}
}
Context 'When calling a method that executes unsuccesfuly' {
BeforeAll {
Mock -CommandName 'Get-SqlEncryptionValue' -MockWith {
return $null
}
}
It 'Should return null' {
$result = Get-EncryptedConnectionSetting -InstanceName 'NamedInstance'
$result | Should -BeNullOrEmpty
Assert-VerifiableMock
}
}
}
Describe 'SqlServerSecureConnection\Set-EncryptedConnectionSetting' -Tag 'Helper' {
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-SqlEncryptionValue' -MockWith {
return [MockedGetItem]::new()
}
Mock -CommandName 'Set-ItemProperty' -Verifiable
}
It 'Should not throw' {
{ Set-EncryptedConnectionSetting -InstanceName 'NamedInstance' -Thumbprint '12345678' -ForceEncryption $true } | Should -Not -Throw
Assert-VerifiableMock
}
}
Context 'When calling a method that executes unsuccesfuly' {
BeforeAll {
Mock -CommandName 'Get-SqlEncryptionValue' -MockWith {
return $null
} -Verifiable
Mock -CommandName 'Set-ItemProperty'
}
It 'Should throw' {
{ Set-EncryptedConnectionSetting -InstanceName 'NamedInstance' -Thumbprint '12345678' -ForceEncryption $true } | Should -Throw
Assert-MockCalled -CommandName 'Set-ItemProperty' -Times 0
Assert-VerifiableMock
}
}
}
Describe 'SqlServerSecureConnection\Test-CertificatePermission' -Tag 'Helper' {
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-CertificateAcl' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
}
It 'Should return True' {
$result = Test-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone'
$result | Should -be $true
Assert-VerifiableMock
}
}
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-CertificateAcl' -MockWith {
$mockedItem = [MockedGetItem]::new()
$mockedItem.ACL = $null
return $mockedItem
} -Verifiable
}
It 'Should return False when no permissions were found' {
$result = Test-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone'
$result | Should -be $false
Assert-VerifiableMock
}
}
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-CertificateAcl' -MockWith {
$mockedItem = [MockedGetItem]::new()
$mockedItem.ACL.FileSystemRights.Value__ = 1
return $mockedItem
} -Verifiable
}
It 'Should return False when the wrong permissions are added' {
$result = Test-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone'
$result | Should -be $false
Assert-VerifiableMock
}
}
Context 'When calling a method that executes unsuccesfuly' {
BeforeAll {
Mock -CommandName 'Get-CertificateAcl' -MockWith {
return $null
} -Verifiable
}
It 'Should return False' {
$result = Test-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone'
$result | Should -be $false
Assert-VerifiableMock
}
}
}
Describe 'SqlServerSecureConnection\Set-CertificatePermission' -Tag 'Helper' {
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-CertificateAcl' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
Mock -CommandName 'Set-Acl' -Verifiable
}
It 'Should not throw' {
{ Set-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone' } | Should -Not -Throw
Assert-VerifiableMock
}
}
Context 'When calling a method that executes unsuccesfuly' {
BeforeAll {
Mock -CommandName 'Get-Item' -MockWith {
return $null
} -Verifiable
Mock -CommandName 'Get-ChildItem' -MockWith {
return $null
} -Verifiable
}
It 'Should throw' {
{ Set-CertificatePermission -Thumbprint '12345678' -ServiceAccount 'Everyone' } | Should -Throw
Assert-VerifiableMock
}
}
}
Describe 'SqlServerSecureConnection\Get-CertificateAcl' -Tag 'Helper' {
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-ChildItem' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
Mock -CommandName 'Get-Item' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
}
It 'Should not throw' {
{ Get-CertificateAcl -Thumbprint '12345678' } | Should -Not -Throw
Assert-VerifiableMock
}
}
}
Describe 'SqlServerSecureConnection\Get-SqlEncryptionValue' -Tag 'Helper' {
Context 'When calling a method that execute successfully' {
BeforeAll {
Mock -CommandName 'Get-ItemProperty' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
Mock -CommandName 'Get-Item' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
}
It 'Should not throw' {
{ Get-SqlEncryptionValue -InstanceName $mockNamedInstanceName } | Should -Not -Throw
Assert-VerifiableMock
}
}
Context 'When calling a method that execute unsuccessfully' {
BeforeAll {
Mock -CommandName 'Get-ItemProperty' -MockWith {
throw "Error"
} -Verifiable
Mock -CommandName 'Get-Item' -MockWith {
return [MockedGetItem]::new()
} -Verifiable
}
It 'Should throw with expected message' {
{ Get-SqlEncryptionValue -InstanceName $mockNamedInstanceName } | Should -Throw -ExpectedMessage "SQL instance '$mockNamedInstanceName' not found on SQL Server."
Assert-VerifiableMock
}
}
}
}
}
finally
{
Invoke-TestCleanup
}
| Java |
{
test.ok(
thrown instanceof axios.Cancel,
"Promise must be rejected with a Cancel obejct"
);
test.equal(thrown.message, "Operation has been canceled.");
test.done();
}
| Java |
using System;
namespace EasyNetQ
{
public class EasyNetQException : Exception
{
public EasyNetQException() {}
public EasyNetQException(string message) : base(message) {}
public EasyNetQException(string format, params string[] args) : base(string.Format(format, args)) {}
public EasyNetQException(string message, Exception inner) : base(message, inner) {}
}
public class EasyNetQResponderException : EasyNetQException
{
public EasyNetQResponderException() { }
public EasyNetQResponderException(string message) : base(message) { }
public EasyNetQResponderException(string format, params string[] args) : base(format, args) { }
public EasyNetQResponderException(string message, Exception inner) : base(message, inner) { }
}
} | Java |
# frozen_string_literal: true
module ReviewBot
class Notification
def initialize(pull_request:, suggested_reviewers:)
@pull_request = pull_request
@suggested_reviewers = suggested_reviewers
end
attr_reader :pull_request, :suggested_reviewers
def message
[
%(• ##{pull_request.number} <#{pull_request.html_url}|#{pull_request.title}> needs a *#{needed_review_type}* from),
suggested_reviewers.map(&:slack_emoji).join(' ')
].join(' ')
end
private
def needed_review_type
pull_request.needs_first_review? ? 'first review' : 'second review'
end
end
end
| Java |
function closeObject(id) {
document.getElementById(id).style.display = 'none';
}
function openObject(id) {
document.getElementById(id).style.display = 'block';
}
function openClose(id){
if (document.getElementById(id).style.display == 'block'){
console.log('intenta cerrar');
closeObject(id);
}else{
console.log('intenta abrir');
openObject(id);
}
}
$(document).ready(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$(".botonRectificarEvento").on("click", function () {
$.ajax({
type: 'POST',
data: { id: $(this).attr("data-id") },
url: Routing.generate('eventos_rectificacion_nueva',null,true),
context: document.body
})
.done(function (datos) {
if(datos.estado) {
$('#tituloPopUp').html('Rectificar Evento');
$("#contenidoPopUp").html(datos.vista);
$('.modal-dialog').removeClass('modal-lg');
$('#piePopUp').addClass('show');
$('#ventanaPopUp').modal('show');
}
});
});
$("#botonGuardarPopUp").on("click", function () {
var datosFormulario = $("#formularioRectificarEvento").serializeArray();
var urlFormulario = Routing.generate('eventos_rectificacion_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
if(datos.estado){
if(datos.rectificado){
$('#ventanaPopUp').modal('hide');
$( location ).attr("href", Routing.generate('eventos',null,true));
} else {
$("#contenidoPopUp").html(datos.html);
}
}
},
error: function() {
alert('error');
}
});
return false;
});
// Visualizar detalles
$('.botonMostrarDetallesEvento').on('click',function(){
$.ajax({
type: 'GET',
url: Routing.generate('eventos_detalle',{ id: $(this).attr('data-id') },true),
context: document.body
})
.done(function (html) {
$('#tituloPopUp').html('Detalle eventos');
$("#contenidoPopUp").html(html);
$('.modal-dialog').addClass('modal-lg');
$('#piePopUp').addClass('hide');
$('#piePopUp').removeClass('show');
$('#ventanaPopUp').modal('show');
});
});
//Agregar nuevo detalle
$('#ventanaPopUp').on("click",'#botonAgregarDetalle',function(){
var datosFormulario = $("#formularioAgregarDetalle").serializeArray();
var urlFormulario = Routing.generate('eventos_detalle_crear',null,true);
$.ajax(
{
url : urlFormulario,
type: "POST",
data : datosFormulario,
success: function(datos)
{
$("#contenidoPopUp").html(datos.html);
}
});
return false;
});
$('#ventanaPopUp').on('mouseover','#dp-detalle',function(){
$('#dp-detalle').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$('#ventanaPopUp').on('mouseover','#dp-rectificar',function(){
$('#dp-rectificar').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
$(".estado-switch").bootstrapSwitch();
$('#botonFormularioRegistro').on('click',function(){
if(! $('#botonFormularioRegistro').hasClass('active')) {
$(':input','#formularioBusqueda')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$('#formularioBusqueda').append('<input type="hidden" name="seccion" value="registro" />');
$('#formularioBusqueda').submit();
}
// $('#botonFormularioBusqueda').removeClass('active');
// $(this).addClass('active');
// $('#divFormularioRegistro').removeClass('hide');
// $('#divFormularioRegistro').addClass('show');
// $('#divFormularioBusqueda').removeClass('show');
// $('#divFormularioBusqueda').addClass('hide');
});
$('#botonFormularioBusqueda').on('click',function(){
$('#botonFormularioRegistro').removeClass('active');
$(this).addClass('active');
$('#divFormularioBusqueda').removeClass('hide');
$('#divFormularioBusqueda').addClass('show');
$('#divFormularioRegistro').removeClass('show');
$('#divFormularioRegistro').addClass('hide');
});
$('#dtp-fecha-desde').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
$('#dtp-fecha-hasta').datetimepicker({
format: 'DD/MM/YYYY HH:mm'
});
});
| Java |
<!DOCTYPE html>
<html lang='en' dir='auto'><head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta name='description' content='The last weekend my colleagues and I had a nice time moving an existing application from a bare-metal infrastructure to AWS. I would like to share some of the focal points involved in such process, in case you’d go through it and would like to know:
don’t expect everything to work as usual: you are changing the underlying hardware, moving to a virtualized environment. You can test every single part of the application but infrastructural side effects may occur in a second time relying on the provider: consider well which functionalities should be delegated to the cloud provider (AWS, in this case, offers a lot) or should be managed internally; for example S3 is not a distributed filesystem, and in some cases an RDS instance won’t have the same performance as database installed on an EC2 instance test application compliance, not hardware failure: instead of focusing on stress tests, you should focus first on functionality tests to ensure every part of te application is behaving as expected; hardware failure are easily handled in the cloud, that’s the primary purpose of IaaS.'>
<meta name='theme-color' content='#ffcd00'>
<meta property='og:title' content='A smooth migration to the cloud » INGE4PRES RATIONAL THOUGHTS'>
<meta property='og:description' content='The last weekend my colleagues and I had a nice time moving an existing application from a bare-metal infrastructure to AWS. I would like to share some of the focal points involved in such process, in case you’d go through it and would like to know:
don’t expect everything to work as usual: you are changing the underlying hardware, moving to a virtualized environment. You can test every single part of the application but infrastructural side effects may occur in a second time relying on the provider: consider well which functionalities should be delegated to the cloud provider (AWS, in this case, offers a lot) or should be managed internally; for example S3 is not a distributed filesystem, and in some cases an RDS instance won’t have the same performance as database installed on an EC2 instance test application compliance, not hardware failure: instead of focusing on stress tests, you should focus first on functionality tests to ensure every part of te application is behaving as expected; hardware failure are easily handled in the cloud, that’s the primary purpose of IaaS.'>
<meta property='og:url' content='http://inge.4pr.es/2014/10/15/2014-10-15-a-smooth-migration-to-the-cloud/'>
<meta property='og:site_name' content='INGE4PRES RATIONAL THOUGHTS'>
<meta property='og:type' content='article'><meta property='article:publisher' content='358809487873346'><meta property='article:section' content='post'><meta property='article:published_time' content='2014-10-15T18:15:28Z'/><meta property='article:modified_time' content='2014-10-15T18:15:28Z'/><meta property='fb:app_id' content='1845367892442473'><meta property='fb:admins' content='francesco.inge'><meta name='twitter:card' content='summary'><meta name='twitter:site' content='@inge4pres'>
<meta name="generator" content="Hugo 0.82.0" />
<title>A smooth migration to the cloud » INGE4PRES RATIONAL THOUGHTS</title>
<link rel='canonical' href='http://inge.4pr.es/2014/10/15/2014-10-15-a-smooth-migration-to-the-cloud/'>
<link rel='icon' href='/favicon.ico'>
<link rel='stylesheet' href='/assets/css/main.ab98e12b.css'><style>
:root{--color-accent:#ffcd00;}
</style>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-55252403-1', 'auto');
ga('send', 'pageview');
}
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
</head>
<body class='page type-post layout-post has-sidebar'>
<div class='site'><div id='sidebar' class='sidebar'>
<a class='screen-reader-text' href='#main-menu'>Skip to Main Menu</a>
<div class='container'><section class='widget widget-about sep-after'>
<header>
<div class='logo'>
<a href='/'>
<img src='/avatar.png'>
</a>
</div>
<h2 class='title site-title '>
<a href='/'>
Francesco Gualazzi
</a>
</h2>
<div class='desc'>
infrastructure-aware developer
</div>
</header>
</section>
</div>
<div class='sidebar-overlay'></div>
</div><div class='main'><nav id='main-menu' class='menu main-menu' aria-label='Main Menu'>
<div class='container'>
<a class='screen-reader-text' href='#content'>Skip to Content</a>
<button id='sidebar-toggler' class='sidebar-toggler' aria-controls='sidebar'>
<span class='screen-reader-text'>Toggle Sidebar</span>
<span class='open'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<line x1="3" y1="12" x2="21" y2="12" />
<line x1="3" y1="6" x2="21" y2="6" />
<line x1="3" y1="18" x2="21" y2="18" />
</svg>
</span>
<span class='close'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</span>
</button>
<ul><li class='item'>
<a href='/'>/</a>
</li><li class='item'>
<a href='/about'>/about</a>
</li><li class='item'>
<a href='/resume'>/resume</a>
</li></ul>
</div>
</nav><div class='header-widgets'>
<div class='container'></div>
</div>
<header id='header' class='header site-header'>
<div class='container sep-after'>
<div class='header-info'><p class='site-title title'>INGE4PRES RATIONAL THOUGHTS</p><p class='desc site-desc'>Growing knowledge one post at a time</p>
</div>
</div>
</header>
<main id='content'>
<article lang='en' class='entry'>
<header class='header entry-header'>
<div class='container sep-after'>
<div class='header-info'>
<h1 class='title'>A smooth migration to the cloud</h1>
</div>
<div class='entry-meta'>
<span class='posted-on'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
<line x1="16" y1="2" x2="16" y2="6"/>
<line x1="8" y1="2" x2="8" y2="6"/>
<line x1="3" y1="10" x2="21" y2="10"/>
</svg>
<span class='screen-reader-text'>Posted on </span>
<time class='entry-date' datetime='2014-10-15T18:15:28Z'>15 Oct 2014</time>
</span>
<span class='reading-time'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<circle cx="12" cy="12" r="10"/>
<polyline points="12 6 12 12 15 15"/>
</svg>
2 mins read
</span>
</div>
</div>
</header>
<div class='container entry-content'>
<p>The last weekend my colleagues and I had a nice time moving an existing application from a bare-metal infrastructure to AWS. I would like to share some of the focal points involved in such process, in case you’d go through it and would like to know:</p>
<ul>
<li><strong>don’t expect everything to work as usual</strong>: you are changing the underlying hardware, moving to a virtualized environment. You can test every single part of the application but infrastructural side effects may occur in a second time</li>
<li><strong>relying on the provider</strong>: consider well which functionalities should be delegated to the cloud provider (AWS, in this case, offers a lot) or should be managed internally; for example S3 is not a distributed filesystem, and in some cases an RDS instance won’t have the same performance as database installed on an EC2 instance</li>
<li><strong>test application compliance, not hardware failure</strong>: instead of focusing on stress tests, you should focus first on functionality tests to ensure every part of te application is behaving as expected; hardware failure are easily handled in the cloud, that’s the primary purpose of IaaS. What is not handled by the cloud is that the application’s features will work on it!</li>
<li><strong>use a checklist</strong>: this may seem obvious, but having a clear and well written to-do list with a time table and activities’ details will help you analyze if anything is missing or needs to be done in advance</li>
</ul>
<p>Aside of this technical considerations, having the support of your coworkers and managers it is what really makes the difference: it keeps you focused in every step and at the same time helps if any problem comes up. That’s why my boss decided to take several videos with his phone and produced a “movie”, hope you like it 😀</p>
</div>
<footer class='entry-footer'>
<div class='container sep-before'><div class='categories'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<path d="M22,19a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2V5A2,2,0,0,1,4,3H9l2,3h9a2,2,0,0,1,2,2Z"/>
</svg>
<span class='screen-reader-text'>Categories: </span><a class='category' href='/categories/tech/'>tech</a></div>
</div>
</footer>
</article>
<nav class='entry-nav'>
<div class='container'><div class='prev-entry sep-before'>
<a href='/2013/11/11/2013-11-11-backup-and-restore-crontabs/'>
<span aria-hidden='true'><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<line x1="20" y1="12" x2="4" y2="12"/>
<polyline points="10 18 4 12 10 6"/>
</svg>
Previous</span>
<span class='screen-reader-text'>Previous post: </span>Backup and restore crontabs</a>
</div><div class='next-entry sep-before'>
<a href='/2014/12/11/2014-12-11-happy-birthday-server/'>
<span class='screen-reader-text'>Next post: </span>Happy birthday server!<span aria-hidden='true'>Next <svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<line x1="4" y1="12" x2="20" y2="12"/>
<polyline points="14 6 20 12 14 18"/>
</svg>
</span>
</a>
</div></div>
</nav>
<section id='comments' class='comments'>
<div class='container sep-before'>
<div class='comments-area'><div id="disqus_thread"></div>
<script type="application/javascript">
var disqus_config = function () {
};
(function() {
if (["localhost", "127.0.0.1"].indexOf(window.location.hostname) != -1) {
document.getElementById('disqus_thread').innerHTML = 'Disqus comments not available by default when the website is previewed locally.';
return;
}
var d = document, s = d.createElement('script'); s.async = true;
s.src = '//' + "inge4pres" + '.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
</section>
</main>
<footer id='footer' class='footer'>
<div class='container sep-before'><section class='widget widget-social_menu sep-after'><header>
<h4 class='title widget-title'>Stay Tuned</h4>
</header><nav aria-label='Social Menu'>
<ul><li>
<a href='https://github.com/inge4pres' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Open Github account in new tab</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>
</svg>
</a>
</li><li>
<a href='https://gitlab.com/inge4pres' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Open Gitlab account in new tab</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<title>GitLab icon</title> <path d="M22.65 14.39L12 22.13 1.35 14.39a.84.84 0 0 1-.3-.94l1.22-3.78 2.44-7.51A.42.42 0 0 1 4.82 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.49h8.1l2.44-7.51A.42.42 0 0 1 18.6 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.51L23 13.45a.84.84 0 0 1-.35.94z"/>
</svg>
</a>
</li><li>
<a href='https://twitter.com/inge4pres' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Open Twitter account in new tab</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<title>Twitter icon</title>
<path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"></path>
</svg>
</a>
</li><li>
<a href='mailto:fgualazzi@gmail.com' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Contact via Email</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline>
</svg>
</a>
</li><li>
<a href='https://linkedin.com/in/francescogualazzi' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Open Linkedin account in new tab</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"></path><rect x="2" y="9" width="4" height="12"></rect><circle cx="4" cy="4" r="2"></circle>
</svg>
</a>
</li><li>
<a href='https://instagram.com/inge4pres' target='_blank' rel='noopener me'>
<span class='screen-reader-text'>Open Instagram account in new tab</span><svg class='icon' xmlns='http://www.w3.org/2000/svg' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>
<rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
</svg>
</a>
</li></ul>
</nav>
</section><div class='copyright'>
<p>inge4pres © 2012-2021 Francesco Gualazzi </p>
</div>
</div>
</footer>
</div>
</div><script>window.__assets_js_src="/assets/js/"</script>
<script src='/assets/js/main.c3bcf2df.js'></script>
</body>
</html>
| Java |
import {Component, OnInit, ElementRef,} from '@angular/core';
import {FileSelect} from './file.select';
import {NgIf} from '@angular/common';
import {NgForm} from '@angular/common';
import {CostImport, CostImportService} from '../../../services/cost-import-service';
import {FourcastService} from '../../../services/fourcast-service';
import {FileUploader} from './file-uploader';
import {FileItem} from './file-uploader';
const TEMPLATE: string = require('./simple.import.setup.html');
const URL = 'http://127.0.0.1:8081/rest/$upload';
@Component({
selector: 'simple-demo',
template: TEMPLATE,
directives: [FileSelect],
styles: [`
.active {
background-color: red;
}
.disabled {
color: gray;
border: medium solid gray;
}
`],
providers: [FileUploader, CostImportService, FourcastService]
})
export class SimpleCostImportSetup implements OnInit {
isOn = true;
isDisabled = false;
importId: string;
private _file: File;
public isUploaded: boolean = false;
constructor( uploader: FileUploader, public importService: CostImportService){}
public isFileSelected: boolean = false;
typeNames = CostImport.typeNames;
model: CostImport = new CostImport();
ngOnInit(){
this.model.division = ''
}
onFileSelected(event){
console.log('File selected', event);
this._file = event['file'];
this.isFileSelected = true
this.model.importFileName = this._file.name;
//console.log('File selected 2: ', this.model.importFileName)
}
updateCostImport(fileId:string){
console.log('FileId (update): ', fileId)
this.importService.updateCostImportHdr(this.model, fileId)
.subscribe((res) =>{
var temp = JSON.stringify(res);
console.log("Update cost import header result: ",res);
this.importId = res['id'];
this.isUploaded = true;
//console.log('File content: ', text);
});
}
processCostImport(importId:string){
}
onImportFileClicked(){
console.log("Button clicked");
let uploader = new FileUploader();
uploader.uploadFile(this._file);
uploader.emitter.subscribe((data) => {
console.log("Upload event: ", data);
let response = JSON.parse(data['response']);
let fileId = response['ID'];
console.log('FileId (clicked): ', fileId)
this.updateCostImport(fileId);
});
//this.uploadFile(this._file);
}
onImportTypeChange(event){
this.model.isSupplierInvoices = false;
this.model.isPayrollWeekly = false;
this.model.isPayrollMonthly = false;
switch (true){
case event.target[0].selected:
this.model.isSupplierInvoices = true;
break;
case event.target[1].selected:
this.model.isPayrollWeekly = true;
break;
case event.target[2].selected:
this.model.isPayrollMonthly = true;
break;
}
}
testUpdate(){
let url:string = "http://127.0.0.1:8081/processImport";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',this.importId);
xhr.addEventListener("load", function (evt) {
let responseStr = evt.currentTarget['response'];
let res = JSON.parse(responseStr);
let id = res['ID'];
console.log("Response: ", res['ID']);
nextStep(id);
})
xhr.open('POST', url, true);
xhr.send(formdata);
function nextStep(id: string){
let url:string = "http://127.0.0.1:8081/processData";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',id);
xhr.addEventListener("load", function (evt) {
console.log(evt);
})
xhr.open('POST', url, true);
xhr.send(formdata);
}
}
}
| Java |
#include <iostream>
#include <string>
#include<iomanip>
using namespace std;
int main()
{
string a;
double h,m,x;
while(cin>>a)
{
if(a=="0:00")break;
if(a[1]==':')
{
h=a[0]-'0';
m=(a[2]-'0')*10+(a[3]-'0');
}
else if(a[2]==':')
{
h=(a[0]-'0')*10+(a[1]-'0');
m=(a[3]-'0')*10+(a[4]-'0');
}
x=30*h+m/2-6*m;
if(x<0)
{
x=-x;
}
if(x>180)
{
x=360-x;
}
cout<<fixed<<setprecision(3)<<x<<endl;
}
}
| Java |
<?php
namespace HealthCareAbroad\LogBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* ErrorLogRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ErrorLogRepository extends EntityRepository
{
} | Java |
# SilkSlider
[](http://travis-ci.org/wwood/bioruby-SilkSlider)
A bioinformatic program for predicting whether proteins are 'silk-like' or not.
This program was developed by Carmel McDougall and Ben Woodcroft at the [Degnan Laboratory](http://www.biology.uq.edu.au/staff/bernie-degnan) at the University of Queensland.
## Installation
After installing Ruby (SilkSlider is tested on Ruby 2.1.2):
```sh
gem install SilkSlider
```
Also required is the [SignalP](http://www.cbs.dtu.dk/services/SignalP/) and [TMHMM](http://www.cbs.dtu.dk/services/TMHMM/) programs, which need to be installed separately and available to silk_slider on the `$PATH`. SilkSlider is only tested on linux systems.
## Usage
To run the program:
```sh
silk_slider my.fasta
```
The program outputs a FASTA file of all silk-like proteins.
To see the help:
```sh
silk_slider -h
```
## Project home page
Information on the source tree, documentation, examples, issues and
how to contribute, see
http://github.com/wwood/SilkSlider
## Cite
Currently unpublished - a journal article is in preparation.
## Biogems.info
This Biogem is published at (http://biogems.info/index.html#SilkSlider)
## Copyright
Copyright (c) 2014 Carmel McDougall, Ben Woodcroft, and Bernard Degnan. See LICENSE.txt for further details.
| Java |
<?php
/*
* This file is part of the MopaBootstrapBundle.
*
* (c) Philipp A. Mohrenweiser <phiamo@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mopa\Bundle\BootstrapBundle\Menu\Factory;
use Knp\Menu\Factory\ExtensionInterface;
use Knp\Menu\ItemInterface;
/**
* Extension for integrating Bootstrap Menus into KnpMenu.
*/
class MenuExtension implements ExtensionInterface
{
/**
* Builds a menu item based.
*
* @param ItemInterface $item
* @param array $options
*/
public function buildItem(ItemInterface $item, array $options)
{
if ($options['navbar']) {
$item->setChildrenAttribute('class', 'nav navbar-nav');
}
if ($options['pills']) {
$item->setChildrenAttribute('class', 'nav nav-pills');
}
if ($options['stacked']) {
$class = $item->getChildrenAttribute('class');
$item->setChildrenAttribute('class', $class . ' nav-stacked');
}
if ($options['dropdown-header']) {
$item
->setAttribute('role', 'presentation')
->setAttribute('class', 'dropdown-header')
->setUri(null);
}
if ($options['list-group']) {
$item->setChildrenAttribute('class', 'list-group');
$item->setAttribute('class', 'list-group-item');
}
if ($options['list-group-item']) {
$item->setAttribute('class', 'list-group-item');
}
if ($options['dropdown']) {
$item
->setUri('#')
->setAttribute('class', 'dropdown')
->setLinkAttribute('class', 'dropdown-toggle')
->setLinkAttribute('data-toggle', 'dropdown')
->setChildrenAttribute('class', 'dropdown-menu')
->setChildrenAttribute('role', 'menu');
if ($options['caret']) {
$item->setExtra('caret', 'true');
}
}
if ($options['divider']) {
$item
->setLabel('')
->setUri(null)
->setAttribute('role', 'presentation')
->setAttribute('class', 'divider');
}
if ($options['pull-right']) {
$className = $options['navbar'] ? 'navbar-right' : 'pull-right';
$class = $item->getChildrenAttribute('class', '');
$item->setChildrenAttribute('class', $class . ' ' . $className);
}
if ($options['icon']) {
$item->setExtra('icon', $options['icon']);
}
}
/**
* Builds the options for extension.
*
* @param array $options
*
* @return array $options
*/
public function buildOptions(array $options)
{
return array_merge(array(
'navbar' => false,
'pills' => false,
'stacked' => false,
'dropdown-header' => false,
'dropdown' => false,
'list-group' => false,
'list-group-item' => false,
'caret' => false,
'pull-right' => false,
'icon' => false,
'divider' => false,
), $options);
}
}
| Java |
<?php
require_once "class_db.php";
class qly_pages extends db{
public function LayTieuDeKD($idPa){
$sql="SELECT TieuDeKD FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['TieuDeKD'];
}
public function LayTieuDe($idPa){
$sql="SELECT TieuDe FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['TieuDe'];
}
public function LayID($TieuDeKD){
$sql="SELECT idPa FROM mk_pages WHERE TieuDeKD = '$TieuDeKD'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['idPa'];
}
public function LayIDGroup($idPa){
$sql="SELECT idGroup FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['idGroup'];
}
public function LayParent($idPa){
$sql="SELECT Parent FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Parent'];
}
public function LayNoiDung($idPa){
$sql="SELECT NoiDung FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['NoiDung'];
}
public function Pages($idPa){
$sql="SELECT *
FROM mk_pages
WHERE idPa = $idPa";
$kq = mysql_query($sql,$this->conn);
return $kq;
}
public function ListCauHoi(){
$sql="SELECT TomTat, NoiDung
FROM mk_pages
WHERE AnHien = 1 and idGroup = 2
ORDER BY idPa
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function DanhChoKhachHang($parent){
$sql="SELECT *
FROM mk_pages
WHERE Parent = $parent and AnHien = 1
Order By ThuTu ASC, idLoai DESC
";
$kq = mysql_query($sql,$this->conn);
return $sql;
}
public function ListPagesParent($idGroup, &$totalRows, $pageNum=1, $pageSize = 10, $Parent){
$startRow = ($pageNum-1)*$pageSize;
$sql="SELECT TieuDe, TieuDeKD, TomTat, NoiDung, UrlHinh
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and Parent = '$Parent'
ORDER BY idPa desc
LIMIT $startRow , $pageSize
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
$sql="SELECT count(*) FROM mk_pages WHERE AnHien = 1 and idGroup = $idGroup and Parent = '$Parent'
";
$rs= mysql_query($sql) or die(mysql_error());;
$row_rs = mysql_fetch_row($rs);
$totalRows = $row_rs[0];
return $kq;
}
public function ListPages($idGroup, &$totalRows, $pageNum=1, $pageSize = 10, $lang = 'vi'){
$startRow = ($pageNum-1)*$pageSize;
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang, NoiDung
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and Lang = '$lang'
ORDER BY idPa desc
LIMIT $startRow , $pageSize
";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
$sql="SELECT count(*) FROM mk_pages WHERE AnHien = 1 and idGroup = $idGroup and Lang = '$lang'
";
$rs= mysql_query($sql) or die(mysql_error());;
$row_rs = mysql_fetch_row($rs);
$totalRows = $row_rs[0];
return $kq;
}
public function ListTinTuc($sotin, $idGroup){
if($idGroup == -1){
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang
FROM mk_pages
WHERE AnHien = 1 and idGroup in (1, 2)
ORDER BY idPa desc
LIMIT 0 , $sotin
";
}else{
$sql="SELECT TieuDe, TomTat, TieuDeKD, UrlHinh, NgayDang
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup
ORDER BY idPa desc
LIMIT 0 , $sotin
";
}
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function ListMenu($idGroup){
$sql="SELECT TieuDe, TieuDeKD, idPa
FROM mk_pages
WHERE AnHien = 1 and idGroup = $idGroup and idPa <> 2 and idPa <> 109
ORDER BY ThuTu ASC";
$kq = mysql_query($sql,$this->conn) or die(mysql_error());
return $kq;
}
public function LayTitle($idPa){
$sql="SELECT Title FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Title'];
}
public function LayDes($idPa){
$sql="SELECT Des FROM mk_pages WHERE idPa = '$idPa'
";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Des'];
}
public function LayKeyword($idPa){
$sql="SELECT Keyword FROM mk_pages WHERE idPa = '$idPa'";
$kq = mysql_query($sql,$this->conn);
$row_trang = mysql_fetch_assoc($kq);
return $row_trang['Keyword'];
}
}
?> | Java |
---
layout: page
title: Rain Tech Award Ceremony
date: 2016-05-24
author: Harold Yang
tags: weekly links, java
status: published
summary: Quisque sit amet posuere eros. Ut malesuada pharetra.
banner: images/banner/leisure-03.jpg
booking:
startDate: 09/17/2017
endDate: 09/18/2017
ctyhocn: MBGINHX
groupCode: RTAC
published: true
---
Nulla pretium felis ultricies, laoreet tortor ut, porta nisi. Morbi in consectetur dui. Fusce non magna in nibh blandit fermentum sed at mauris. Aenean hendrerit facilisis eros, at molestie ligula luctus vel. Maecenas non condimentum quam. Aliquam dignissim metus sed urna cursus convallis. Cras vitae urna velit. Praesent scelerisque, orci vulputate varius congue, nisi elit commodo mauris, id dapibus nulla velit id nisl. Sed iaculis dui elementum feugiat imperdiet.
In tincidunt sem a metus vulputate, et posuere elit porttitor. Donec sed risus id orci blandit pulvinar. Nunc euismod vehicula egestas. Quisque sit amet nulla purus. Nullam ac felis turpis. Nulla iaculis lacinia justo at placerat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed imperdiet id metus sed ornare. Vestibulum ultrices nec enim at pulvinar. Fusce dictum leo in ultricies bibendum. Duis pharetra turpis et placerat placerat. Ut porta pulvinar felis, in vestibulum eros eleifend in. Aliquam et ante elit. In interdum nulla placerat aliquam sodales.
1 Sed placerat nibh eget massa pellentesque ullamcorper ac a odio
1 Etiam quis sapien fermentum, sagittis ligula in, blandit nibh.
Nam luctus laoreet hendrerit. Donec consequat pretium quam, et faucibus eros egestas a. Aenean tempus ultricies est sed mattis. Praesent blandit turpis sit amet dolor laoreet, at tincidunt ligula congue. Proin commodo lobortis purus nec laoreet. Donec nec suscipit urna, venenatis congue felis. Maecenas congue, justo sed accumsan viverra, mi neque fringilla nisi, a bibendum libero odio sit amet urna. Etiam vulputate nulla consectetur magna ornare, sit amet gravida quam semper. Phasellus laoreet mauris et sem dignissim vestibulum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla luctus aliquet nibh, vel vehicula ligula consequat vel. Mauris interdum viverra elementum. Donec mattis, nisi a placerat egestas, nunc libero convallis ante, sed ullamcorper orci nulla condimentum turpis. Praesent egestas dolor vitae porta vehicula.
| Java |
/* eslint-env node*/
var gutil = require('gulp-util')
var paths = {
layouts: {
componentsDir: './app/components/**/*.jade',
src: './app/views/**/*.jade',
dest: './app/public/assets/html/'
},
styles: {
componentsDir: './app/lib/stylesheets/**/*.styl',
src: './app/lib/stylesheets/styles.styl',
dest: './app/public/assets/css/'
},
scripts: {
entry: './app/lib/scripts/entry.jsx',
src: ['./app/lib/scripts/**/*.jsx', './app/lib/scripts/**/*.js'],
dest: './app/public/assets/js/'
}
}
var onError = function (error) {
gutil.log(gutil.colors.red(error))
this.emit('end')
}
module.exports = {
paths: paths,
onError: onError
}
| Java |
//***************************************************************************
// Copyright (C) 2009 Realmac Software Ltd
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information of Realmac Software Ltd
// and are protected by copyright law. They may not be disclosed
// to third parties or copied or duplicated in any form, in whole or
// in part, without the prior written consent of Realmac Software Ltd.
// Created by Keith Duncan on 26/03/2009
//***************************************************************************
#import <Cocoa/Cocoa.h>
// Model
#import "RMUploadKit/AFPropertyListProtocol.h"
#import "RMUploadKit/RMUploadPlugin.h"
#import "RMUploadKit/RMUploadPreset.h"
#import "RMUploadKit/RMUploadCredentials.h"
// Controller
#import "RMUploadKit/RMUploadPresetConfigurationViewController.h"
#import "RMUploadKit/RMUploadMetadataConfigurationViewController.h"
// Upload
#import "RMUploadKit/RMUploadTask.h"
#import "RMUploadKit/RMUploadURLConnection.h"
#import "RMUploadKit/NSURLRequest+RMUploadAdditions.h"
#import "RMUploadKit/RMUploadMultipartFormDocument.h"
// Other
#import "RMUploadKit/RMUploadConstants.h"
#import "RMUploadKit/RMUploadErrors.h"
| Java |
/* Copyright (c) 2012 Jess VanDerwalker <washu@sonic.net>
* All rights reserved.
*
* data.h
*
* 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.
*/
#ifndef _DATA_H_
#define _DATA_H_
#include <xcb/xcb.h>
#include <xcb/damage.h>
#define XTOQ_DAMAGE 0
#define XTOQ_EXPOSE 1
#define XTOQ_CREATE 2
#define XTOQ_DESTROY 3
typedef struct xtoq_context_t {
xcb_connection_t *conn;
xcb_drawable_t window;
xcb_window_t parent;
xcb_damage_damage_t damage;
int x;
int y;
int width;
int height;
int damaged_x;
int damaged_y;
int damaged_width;
int damaged_height;
char *name; /* The name of the window */
int wm_delete_set; /* Flag for WM_DELETE_WINDOW, 1 if set */
void *local_data; // Area for data client cares about
} xtoq_context_t;
typedef struct xtoq_event_t {
xtoq_context_t *context;
int event_type;
} xtoq_event_t;
typedef struct image_data_t {
uint8_t *data;
int length;
} image_data_t;
typedef struct xtoq_image_t {
xcb_image_t *image;
int x;
int y;
int width;
int height;
} xtoq_image_t;
typedef void (*xtoq_event_cb_t) (xtoq_event_t const *event);
extern int _damage_event;
#endif
| Java |
# Lecture 1: Mathematical background
This lecture aims at introducing the mathematical concepts we will be using throughout the course (linear algebra, calculus, statistics, numerical optimization).
Note that this does not serve as a mathematics course in itself.
The students interested in a more formal and academic approach can refer to the following links:
- [Pr. Strang's course on linear algebra](https://www.youtube.com/playlist?list=PLE7DDD91010BC51F8)
- [Pr. Strang's course on calculus](https://www.youtube.com/playlist?list=PLBE9407EA64E2C318)
- [Pr. Boyd's course on convex optimization](https://www.youtube.com/playlist?list=PL3940DD956CDF0622)
- [Leon Bottou's paper on SGD](https://www.microsoft.com/en-us/research/publication/stochastic-gradient-tricks/)
This folder contains the material related to the first lecture.
- [`build/slides.pdf`](build/slides.pdf) corresponds the slides
The rest is the (latex) source code used to generate the slides. | Java |
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
| Java |
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="es"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="distribution" content="global"/>
<title>Wallery — Murales gratuitos, contenidos valiosos</title>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<meta name="author" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link type="text/plain" rel="author" href="humans.txt" />
<!-- Open Graphs Tag's -->
<meta property="og:title" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:image" content="" />
<meta property="og:image:secure_url" content="" />
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />
<meta property="og:description" content=""/>
<meta property="og:url" content=""/>
<!--[if lte IE 8]><script src="css/ie/html5shiv.js"></script><![endif]-->
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<!-- Stylesheets -->
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/bootstrap.css"/>
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:300,400,700&subset=latin-ext" rel="stylesheet">
<link rel="stylesheet" href="css/croppic.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.min.css">
<link rel="stylesheet" type="text/less" href="css/main.less"/>
<script src="js/vendor/less.min.js"></script>
<!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->
<!--[if lte IE 9]><link rel="stylesheet" href="css/ie/v9.css" /><![endif]-->
<!--[if lt IE 10]><script src="js/old/respond.min.js"></script><![endif]-->
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>
<!--[if lt IE 9]>
<p class="browsehappy">La version de su navegador es demasiado antigua. <a href="http://browsehappy.com/">Actualicelo</a> y disfrute el sitio al maximo.</p>
<![endif]-->
<div class="container-fluid alpha">
<div class="container">
Alpha v0.1 - 18/04/2017 - <a href="https://github.com/agustinl/Wallery"><strong>GITHUB</strong></a>
</div>
</div>
<header class="container-fluid">
<div class="container">
<div class="col-lg-2">
<img src="images/logo.png" alt="Wallery">
</div>
<div class="col-lg-8 text-center">
<h1>Murales gratuitos, <strong>contenidos valiosos</strong></h1>
</div>
<div class="col-lg-2">
<a class="btn btn-default" href="#" role="button">Busqueda avanzada</a>
</div>
</div>
</header>
<section class="container">
<div id="uploadform" class="col-lg-8 col-lg-offset-2 row">
<div class="row">
<div class="col-lg-5 row">
<div id="cropContaineroutputUpload"></div>
<input type="text" name="tmp_img" id="cropOutput"/>
</div>
<div class="col-lg-7 white-form">
<div class="align-middle">
<div class="form-group row">
<div class="col-lg-6">
<input type="text" class="form-control" name="" placeholder="DNI / LC / LE" data-toggle="tooltip" data-placement="bottom" title="Solo para comprobar que no se haya cargado una solicitud previa.">
<span class="glyphicon glyphicon-question-sign form-control-feedback" aria-hidden="true"></span>
</div>
<div class="col-lg-6">
<select class="selectpicker" data-width="100%" title="Tipo de sangre">
<option>O negativo</option>
<option>O positivo</option>
<option data-divider="true"></option>
<option>A negativo</option>
<option>A positivo</option>
<option data-divider="true"></option>
<option>B negativo</option>
<option>B positivo</option>
<option data-divider="true"></option>
<option>AB negativo</option>
<option>AB positivo</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-lg-8">
<input type="text" class="form-control" name="" placeholder="Nombre y apellido">
</div>
<div class="col-lg-4">
<input type="text" class="form-control" name="" placeholder="Cantidad" data-toggle="tooltip" data-placement="bottom" title="Dejar en blanco si no hay un numero determinado.">
<span class="glyphicon glyphicon-user form-control-feedback" aria-hidden="true"></span>
</div>
</div>
<div class="form-group">
<p class="text-muted-info">¿Donde donar?</p>
<hr>
<input id="searchTextField" type="text" class="form-control input-mg" name="" placeholder="Centro medico">
<input id="searchTextFieldTwo" type="text" class="form-control input-mg" name="" placeholder="Direccion">
<input type="text" class="form-control input-mg" name="" placeholder="Dias y horarios">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Informacion adicional..."></textarea>
</div>
<div class="form-group row">
<div class="col-lg-6">
<input type="text" class="form-control" name="" placeholder="Telefono #1">
</div>
<div class="col-lg-6">
<input type="text" class="form-control" name="" placeholder="Referencia #1">
</div>
</div>
<div class="form-group row">
<div class="col-lg-6">
<input type="text" class="form-control" name="" placeholder="Telefono #2">
</div>
<div class="col-lg-6">
<input type="text" class="form-control" name="" placeholder="Referencia #2">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2 uploadform-buttons">
<div>
<button class="btn btn-primary" type="submit">Listo</button>
<button class="btn btn-link">Cancelar</button>
</div>
</div>
</section>
<footer class="container-fluid">
<div class="container">
<h6>2017 — Buenos Aires, Argentina — <a href="#">hola@wallery.com.ar</a></h6>
</div>
</footer>
<script src="js/vendor/jquery-1.12.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/croppic.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyALeJWJhFIFahkYfCEsPBL5dNMbGfABXRA "></script>
<script src="js/scripts.js"></script>
<script>
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;
ga('create','UA-XXXXX-Y','auto');ga('send','pageview')
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<!--[if lt IE 10]><script src="js/old/rem.min.js"></script><![endif]-->
</body>
</html>
| Java |
/**
*
* app.js
*
* This is the entry file for the application
*
*/
import FilmLocationSearchComponent from '../MovieSearchApp/Containers/FilmSearchContainer/FilmSearchComponent';
import AppComponent from '../CommonComponent/app.js';
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
console.log("current href",window.location.href);
const getAppRouter = () => {
return (
<Route component={AppComponent}>
<Route component={FilmLocationSearchComponent} path='/searchmovies' />
</Route>
);
}
export {
getAppRouter
}
| Java |
/* Accordion directive */
app.directive('vmfAccordionContainer', ['$compile', function($compile) {
return {
restrict: 'EA',
scope: {
type: '@',
headers: '=',
accData: '=',
selAcc: '=',
customClass:'='
},
link: function(scope, elem, attrs) {
var template;
if(scope.type === '1') {
template = '<table class="vmf-accordion-table1"><thead class="vmf-accordion-table-header"><tr><td class="col1"></td>';
var count = 1;
angular.forEach(scope.headers, function(item) {
// if(count === 1) {
// template += '<td colspan="2">' + item + '</td>';
// }
// else {
template += '<td class="col' + (count + 1) +'">' + item + '</td>';
// }
count += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td ><span class="vmf-arrow"></span></td><td colspan="3">' + item.header + '</td></tr>';
angular.forEach(item.contents, function(content) {
template += '<tr class="vmf-accordion-row" ng-show="activeIndex =='+ scope.accordionIndex + '"><td colspan="1"></td>';
angular.forEach(content, function(cellData) {
template += '<td colspan="1">' + cellData + '</td>';
});
template += '</tr>';
});
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row').hide();
}
else if(scope.type === '2') {
template = '<table class="vmf-accordion-table2"><thead class="vmf-accordion-table2-header" style="background-color: lightgray;"><tr><td class="col1"></td>';
var headerCount = 0;
angular.forEach(scope.headers, function(item) {
if(headerCount !== scope.headers.length - 1) {
template += '<td class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
else {
template += '<td colspan="2" class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
headerCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-table2-body">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="vmf-accordion-header2" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td><span class="vmf-arrow"></span></td>';
var accHeadersCount = 1;
angular.forEach(item.headers, function(header) {
if(accHeadersCount !== item.headers.length) {
template += '<td>' + header + '</td>';
}
else {
template += '<td class="vmf-acc-header-last-child">' + header + '</td>';
}
accHeadersCount += 1;
});
template += '</tr><tr class="vmf-accordion-row2"><td></td><td class="vmf-acc-header-last-child" colspan="' + item.headers.length + '"><table class="vmf-accordion-sub-table" ng-show="activeIndex =='+ scope.accordionIndex + '">';
var count = 0;
angular.forEach(item.contents, function(content) {
if(count !== 0) {
template += '<tr class="vmf-accordion-sub-table-row">';
angular.forEach(content, function(cellData) {
template += '<td>' + cellData + '</td>';
});
template += '</tr>';
}
else {
template += '<thead class="vmf-accordion-sub-table-header"><tr>';
var subHeaderCount = 1;
angular.forEach(content, function(cellData) {
template += '<td class="col' + subHeaderCount + '">' + cellData + '</td>';
subHeaderCount += 1;
});
template += '</tr></thead><tbody class="vmf-accordion-sub-table-body">';
}
count += 1;
});
template += '</tbody></table></td></tr>';
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
if(scope.customClass){
angular.forEach(scope.customClass, function(item) {
elem.find(item.selector).addClass(item.cusclass);
});
}
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row2').hide();
// elem.find('.vmf-accordion-row2').hide();
}
scope.toggleAccordion = function(index) {
scope.activeIndex = scope.activeIndex === index ? -1 : index;
var accordions, accordionRows;
if(scope.type === '1') {
elem.find('.vmf-accordion-row').hide();
accordions = elem.find('.vmf-accordion-header');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
// accordions = elem.find('.vmf-accordion-header');
// console.log(accordions[index]);
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header');
$(accordionRows).show();
}
}
else if(scope.type === '2') {
elem.find('.vmf-accordion-row2').hide();
accordions = elem.find('.vmf-accordion-header2');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.vmf-accordion-header2');
$(accordionRows).show();
}
}
};
scope.buttonClick = function($event, index) {
$event.stopPropagation();
scope.selAcc = index;
};
}
};
}]); | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.comci.bigbib;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bson.types.ObjectId;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jbibtex.BibTeXEntry;
import org.jbibtex.Key;
import org.jbibtex.StringValue;
import org.jbibtex.Value;
/**
*
* @author Sebastian
*/
@XmlRootElement()
@XmlAccessorType(XmlAccessType.NONE)
public class PeristentBibTexEntry extends BibTeXEntry {
private ObjectId id;
public PeristentBibTexEntry(Key type, Key key) {
super(type, key);
}
static Map<String, Key> keyMapping = new HashMap<String, Key>();
static {
keyMapping.put("address", BibTeXEntry.KEY_ADDRESS);
keyMapping.put("annote", BibTeXEntry.KEY_ANNOTE);
keyMapping.put("author", BibTeXEntry.KEY_AUTHOR);
keyMapping.put("booktitle", BibTeXEntry.KEY_BOOKTITLE);
keyMapping.put("chapter", BibTeXEntry.KEY_CHAPTER);
keyMapping.put("crossref", BibTeXEntry.KEY_CROSSREF);
keyMapping.put("doi", BibTeXEntry.KEY_DOI);
keyMapping.put("edition", BibTeXEntry.KEY_EDITION);
keyMapping.put("editor", BibTeXEntry.KEY_EDITOR);
keyMapping.put("eprint", BibTeXEntry.KEY_EPRINT);
keyMapping.put("howpublished", BibTeXEntry.KEY_HOWPUBLISHED);
keyMapping.put("institution", BibTeXEntry.KEY_INSTITUTION);
keyMapping.put("journal", BibTeXEntry.KEY_JOURNAL);
keyMapping.put("key", BibTeXEntry.KEY_KEY);
keyMapping.put("month", BibTeXEntry.KEY_MONTH);
keyMapping.put("note", BibTeXEntry.KEY_NOTE);
keyMapping.put("number", BibTeXEntry.KEY_NUMBER);
keyMapping.put("organization", BibTeXEntry.KEY_ORGANIZATION);
keyMapping.put("pages", BibTeXEntry.KEY_PAGES);
keyMapping.put("publisher", BibTeXEntry.KEY_PUBLISHER);
keyMapping.put("school", BibTeXEntry.KEY_SCHOOL);
keyMapping.put("series", BibTeXEntry.KEY_SERIES);
keyMapping.put("title", BibTeXEntry.KEY_TITLE);
keyMapping.put("type", BibTeXEntry.KEY_TYPE);
keyMapping.put("url", BibTeXEntry.KEY_URL);
keyMapping.put("volume", BibTeXEntry.KEY_VOLUME);
keyMapping.put("year", BibTeXEntry.KEY_YEAR);
}
public PeristentBibTexEntry(DBObject persistentObject) {
super(
new Key((String) persistentObject.get("type")),
new Key((String) persistentObject.get("key"))
);
BasicDBObject fields = (BasicDBObject) persistentObject.get("fields");
id = (ObjectId) persistentObject.get("_id");
for (String key : fields.keySet()) {
if (keyMapping.containsKey(key)) {
this.addField(keyMapping.get(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
} else {
this.addField(new Key(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
}
}
}
@JsonProperty("id")
@XmlElement(name="id")
public String getStringId() {
return id.toString();
}
@JsonProperty("key")
@XmlElement(name="key")
public String getStringKey() {
return super.getKey().getValue();
}
@JsonProperty("type")
@XmlElement(name="type")
public String getStringType() {
return super.getType().getValue();
}
@JsonProperty("fields")
@XmlElement(name="fields")
public Map<String, String> getStringFields() {
Map<String, String> fields = new HashMap<String, String>();
for (Entry<Key,Value> e : getFields().entrySet()) {
if (e.getKey() != null && e.getValue() != null) {
fields.put(e.getKey().getValue(), e.getValue().toUserString());
}
}
return fields;
}
@Override
public String toString() {
return String.format("[%s:%s] %s: %s (%s)",
this.getType(),
this.getKey(),
this.getField(KEY_AUTHOR).toUserString(),
this.getField(KEY_TITLE).toUserString(),
this.getField(KEY_YEAR).toUserString());
}
}
| Java |
module Admin::BaseHelper
include ActionView::Helpers::DateHelper
def subtabs_for(current_module)
output = []
AccessControl.project_module(current_user.profile.label, current_module).submenus.each_with_index do |m,i|
current = (m.url[:controller] == params[:controller] && m.url[:action] == params[:action]) ? "current" : ""
output << subtab(_(m.name), current, m.url)
end
content_for(:tasks) { output.join("\n") }
end
def subtab(label, style, options = {})
content_tag :li, link_to(label, options, { "class"=> style })
end
def show_page_heading
content_tag(:h2, @page_heading, :class => 'mb20') unless @page_heading.blank?
end
def cancel(url = {:action => 'index'})
link_to _("Cancel"), url
end
def save(val = _("Store"))
'<input type="submit" value="' + val + '" class="save" />'
end
def confirm_delete(val = _("Delete"))
'<input type="submit" value="' + val + '" />'
end
def link_to_show(record, controller = @controller.controller_name)
if record.published?
link_to image_tag('admin/show.png', :alt => _("show"), :title => _("Show content")),
{:controller => controller, :action => 'show', :id => record.id},
{:class => "lbOn"}
end
end
def link_to_edit(label, record, controller = @controller.controller_name)
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
def link_to_edit_with_profiles(label, record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
end
def link_to_destroy(record, controller = @controller.controller_name)
link_to image_tag('admin/delete.png', :alt => _("delete"), :title => _("Delete content")),
:controller => controller, :action => 'destroy', :id => record.id
end
def link_to_destroy_with_profiles(record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to(_("delete"),
{ :controller => controller, :action => 'destroy', :id => record.id }, :confirm => _("Are you sure?"), :method => :post, :title => _("Delete content"))
end
end
def text_filter_options
TextFilter.find(:all).collect do |filter|
[ filter.description, filter ]
end
end
def text_filter_options_with_id
TextFilter.find(:all).collect do |filter|
[ filter.description, filter.id ]
end
end
def alternate_class
@class = @class != '' ? '' : 'class="shade"'
end
def reset_alternation
@class = nil
end
def task_quickpost(title)
link_to_function(title, toggle_effect('quick-post', 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_overview
content_tag :li, link_to(_('Back to overview'), :action => 'index')
end
def task_add_resource_metadata(title,id)
link_to_function(title, toggle_effect('add-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_metadata(title,id)
link_to_function(title, toggle_effect('edit-resource-metadata-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_edit_resource_mime(title,id)
link_to_function(title, toggle_effect('edit-resource-mime-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def class_write
if controller.controller_name == "content" or controller.controller_name == "pages"
"current" if controller.action_name == "new"
end
end
def class_content
if controller.controller_name =~ /content|pages|categories|resources|feedback/
"current" if controller.action_name =~ /list|index|show/
end
end
def class_themes
"current" if controller.controller_name =~ /themes|sidebar/
end
def class_users
controller.controller_name =~ /users/ ? "current right" : "right"
end
def class_dashboard
controller.controller_name =~ /dashboard/ ? "current right" : "right"
end
def class_settings
controller.controller_name =~ /settings|textfilter/ ? "current right" : "right"
end
def class_profile
controller.controller_name =~ /profiles/ ? "current right" : "right"
end
def alternate_editor
return 'visual' if current_user.editor == 'simple'
return 'simple'
end
def collection_select_with_current(object, method, collection, value_method, text_method, current_value, prompt=false)
result = "<select name='#{object}[#{method}]'>\n"
if prompt == true
result << "<option value=''>" << _("Please select") << "</option>"
end
for element in collection
if current_value and current_value == element.send(value_method)
result << "<option value='#{element.send(value_method)}' selected='selected'>#{element.send(text_method)}</option>\n"
else
result << "<option value='#{element.send(value_method)}'>#{element.send(text_method)}</option>\n"
end
end
result << "</select>\n"
return result
end
def render_void_table(size, cols)
if size == 0
"<tr>\n<td colspan=#{cols}>" + _("There are no %s yet. Why don't you start and create one?", _(controller.controller_name)) + "</td>\n</tr>\n"
end
end
def cancel_or_save
result = '<p class="right">'
result << cancel
result << " "
result << _("or")
result << " "
result << save( _("Save") + " »")
result << '</p>'
return result
end
def link_to_published(item)
item.published? ? link_to_permalink(item, _("published"), '', 'published') : "<span class='unpublished'>#{_("unpublished")}</span>"
end
def macro_help_popup(macro, text)
unless current_user.editor == 'visual'
"<a rel='lightbox' href=\"#{url_for :controller => 'textfilters', :action => 'macro_help', :id => macro.short_name}\" onclick=\"return popup(this, 'Typo Macro Help')\">#{text}</a>"
end
end
def render_macros(macros)
result = link_to_function _("Show help on Typo macros") + " (+/-)",update_page { |page| page.visual_effect(:toggle_blind, "macros", :duration => 0.2) }
result << "<table id='macros' style='display: none;'>"
result << "<tr>"
result << "<th>#{_('Name')}</th>"
result << "<th>#{_('Description')}</th>"
result << "<th>#{_('Tag')}</th>"
result << "</tr>"
for macro in macros.sort_by { |f| f.short_name }
result << "<tr #{alternate_class}>"
result << "<td>#{macro_help_popup macro, macro.display_name}</td>"
result << "<td>#{h macro.description}</td>"
result << "<td><code><typo:#{h macro.short_name}></code></td>"
result << "</tr>"
end
result << "</table>"
end
def build_editor_link(label, action, id, update, editor)
link = link_to_remote(label,
:url => { :action => action, 'editor' => editor},
:loading => "new Element.show('update_spinner_#{id}')",
:success => "new Element.toggle('update_spinner_#{id}')",
:update => "#{update}")
link << image_tag("spinner-blue.gif", :id => "update_spinner_#{id}", :style => 'display:none;')
end
def display_pagination(collection, cols)
if WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1
return "<tr><td colspan=#{cols} class='paginate'>#{will_paginate(collection)}</td></tr>"
end
end
def show_thumbnail_for_editor(image)
thumb = "#{RAILS_ROOT}/public/files/thumb_#{image.filename}"
picture = "#{this_blog.base_url}/files/#{image.filename}"
image.create_thumbnail unless File.exists? thumb
# If something went wrong with thumbnail generation, we just display a place holder
thumbnail = (File.exists? thumb) ? "#{this_blog.base_url}/files/thumb_#{image.filename}" : "#{this_blog.base_url}/images/thumb_blank.jpg"
picture = "<img class='tumb' src='#{thumbnail}' "
picture << "alt='#{this_blog.base_url}/files/#{image.filename}' "
picture << " onclick=\"edInsertImageFromCarousel('article_body_and_extended', '#{this_blog.base_url}/files/#{image.filename}');\" />"
return picture
end
end
| Java |
<?php
namespace Editionista\WebsiteBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Controller;
use Editionista\WebsiteBundle\Entity\Tag;
/**
* Edition controller.
*
* @Route("/tags")
*/
class TagController extends Controller
{
/**
* @Route("/", name="tags")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
return array('tags' => $tags);
}
/**
* @Route("/{tag}", name="show_tag")
* @Template()
*/
public function showAction($tag)
{
$em = $this->getDoctrine()->getManager();
$tag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($tag);
$editions = $tag->getEditions();
return array('tag' => $tag, 'editions' => $editions);
}
/**
* @Route("/push", name="push_tags")
* @Method({"POST"})
*/
public function pushAction(Request $request)
{
$pushedTag = $request->request->get('tag');
$em = $this->getDoctrine()->getManager();
$storedTag = $em->getRepository('EditionistaWebsiteBundle:Tag')->findOneByName($pushedTag);
if($storedTag == null) {
$tag = new Tag();
$tag->setName($pushedTag);
$em = $this->getDoctrine()->getManager();
$em->persist($tag);
$em->flush();
}
$response = new Response(json_encode(array('tag' => $pushedTag)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/pull", name="pull_tags")
*/
public function pullAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EditionistaWebsiteBundle:Tag')->findAll();
$tags = array();
foreach($entities as $entity) {
$tags['tags'][] = array('tag' => $entity->getName());
}
$response = new Response(json_encode($tags));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
| Java |
package io.questions.model.questionnaire
import io.questions.model.questionnaire.Element.{ Parent, Primitive }
trait ElementValues {
implicit class ElementValuesSyntax(e: Element) {
def parent: Element.Parent = e match {
case p: Parent => p
case x => throw new IllegalArgumentException(s"Expected a Parent. Got $x")
}
def primitive: Element.Primitive = e match {
case p: Primitive => p
case x => throw new IllegalArgumentException(s"Expected a Primitive. Got $x")
}
}
}
| Java |
using System;
using System.Reflection;
namespace Light.DataCore
{
abstract class DynamicFieldMapping : FieldMapping
{
public static DynamicFieldMapping CreateDynmaicFieldMapping (PropertyInfo property, DynamicCustomMapping mapping)
{
DynamicFieldMapping fieldMapping;
Type type = property.PropertyType;
TypeInfo typeInfo = type.GetTypeInfo();
string fieldName = property.Name;
if (typeInfo.IsGenericType) {
Type frameType = type.GetGenericTypeDefinition ();
if (frameType.FullName == "System.Nullable`1") {
Type [] arguments = type.GetGenericArguments ();
type = arguments [0];
typeInfo = type.GetTypeInfo();
}
}
if (type.IsArray) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (type.IsGenericParameter || typeInfo.IsGenericTypeDefinition) {
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
}
else if (typeInfo.IsEnum) {
DynamicEnumFieldMapping enumFieldMapping = new DynamicEnumFieldMapping (type, fieldName, mapping);
fieldMapping = enumFieldMapping;
}
else {
TypeCode code = Type.GetTypeCode (type);
switch (code) {
case TypeCode.Empty:
case TypeCode.Object:
throw new LightDataException(string.Format(SR.DataMappingUnsupportFieldType, property.DeclaringType, property.Name, type));
default:
DynamicPrimitiveFieldMapping primitiveFieldMapping = new DynamicPrimitiveFieldMapping (type, fieldName, mapping);
fieldMapping = primitiveFieldMapping;
break;
}
}
return fieldMapping;
}
protected DynamicFieldMapping (Type type, string fieldName, DynamicCustomMapping mapping, bool isNullable)
: base (type, fieldName, fieldName, mapping, isNullable, null)
{
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.