code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* simple sliding menu using jQuery and Interface - http://www.getintothis.com
*
* note: this library depends on jquery (http://www.jquery.com) and
* interface (http://interface.eyecon.ro)
*
* Copyright (c) 2006 Ramin Bozorgzadeh
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LECENSE.txt) linceses.
*/
jQuery.fn.rb_menu = function(options) {
var self = this;
self.options = {
// transitions: easein, easeout, easeboth, bouncein, bounceout,
// bounceboth, elasticin, elasticout, elasticboth
transition: 'bounceout',
// trigger events: mouseover, mousedown, mouseup, click, dblclick
triggerEvent: 'mouseover',
// number of ms to delay before hiding menu (on page load)
loadHideDelay : 1000,
// number of ms to delay before hiding menu (on mouseout)
blurHideDelay: 500,
// number of ms for transition effect
effectDuration: 1000,
// hide the menu when the page loads
hideOnLoad: true,
// automatically hide menu when mouse leaves area
autoHide: true
}
// make sure to check if options are given!
if(options) {
jQuery.extend(self.options, options);
}
return this.each(function() {
var menu = jQuery(this).find('.rb_menu');
var toggle = jQuery(this).find('.rb_toggle span');
// add 'hover' class to trigger for css styling
toggle.hover( function() {
jQuery(this).addClass('hover');
}, function() {
jQuery(this).removeClass('hover');
});
if(self.options.hideOnLoad) {
if(self.options.loadHideDelay <= 0) {
menu.hide();
self.closed = true;
self.unbind();
} else {
// let's hide the menu when the page is loading
// after {loadHideDelay} milliseconds
setTimeout( function() {
menu.hideMenu();
}, self.options.loadHideDelay);
}
}
// bind event defined by {triggerEvent} to the trigger
// to open and close the menu
toggle.bind(self.options.triggerEvent, function() {
// if the trigger event is click or dblclick, we want
// to close the menu if its open
if((self.options.triggerEvent == 'click' || self.options.triggerEvent == 'dblclick') && !self.closed) {
menu.hideMenu();
} else {
menu.showMenu();
}
});
menu.hideMenu = function() {
if(this.css('display') == 'block' && !self.closed) {
this.SlideOutLeft(
self.options.effectDuration,
function() {
self.closed = true;
self.unbind();
},
self.options.transition
);
}
}
menu.showMenu = function() {
if(this.css('display') == 'none' && self.closed) {
this.SlideInLeft(
self.options.effectDuration,
function() {
self.closed = false;
if(self.options.autoHide) {
self.hover(function() {
clearTimeout(self.timeout);
}, function() {
self.timeout = setTimeout( function() {
menu.hideMenu();
}, self.options.blurHideDelay);
});
}
},
self.options.transition
);
}
}
});
};
|
boy-jer/santhathi-appointment
|
public/javascripts/rb_menu.js
|
JavaScript
|
mit
| 3,754
|
---
title: About
layout: course_about
---
<img src="{{site.baseurl}}{{site.data.course.image}}" class="img-responsive img-rounded span4 block-center">
##### A 3ª Revolução Industrial começou! Bem Vindo à era *maker*!
As impressoras 3D permitem aprodução de objetos que vão de vestidos a tecidos biológicos, de peças de espaçonaves a objetos educativos, revolucionando a maneira como nos relacionamos com os produtos. Entenda como essa inovação disruptiva está mudando o mundo dos negócios a partir da colaboração em rede!
Neste curso criado pela equipe da Metamáquina, primeira fabricante de impressoras 3D de baixo custo baseadas em hardware aberto e software livre, serão abordados os processos de criação de protótipos e objetos personalizados, desde sua concepção em softwares de modelagem e design até a realização física dos objetos projetados. As demonstrações práticas serão feitas na Metamáquina 2, segundo modelo projetado e comercializado pela empresa.
O curso **Introdução ao Universo da Impressão 3D**, voltado para jovens e adultos independente de conhecimento prévio no assunto, é dividido em dez módulos. Cada módulo parte de uma temática ou problema que motive o uso da impressão 3D e é dividido em três partes: **conceito**, **técnica** e **aplicação**.
Na primeira parte, vamos entender a motivação por trás dos diversos usos das impressoras 3D. Na segunda, vamos entender o funcionamento da máquina e as técnicas relacionadas ao processo de impressão. Na terceira, vamos desenvolver projetos e experimentos, na maioria das vezes usando a máquina, de modo a aplicar os conceitos e técnicas aprendidos anteriormente.
À esquerda desta página temos uma lista com cada módulo do curso. Os módulos serão publicados conforme o andamento das aulas presenciais, então fique atento! Alguns dias antes de cada aula o conteúdo já estará disponível!
-----
Seja muito bem vindo! A terceira revolução industrial já está aí, e a Metamáquina quer você conectado e empoderado para tirar suas ideias do papel - ou melhor, do monitor!
|
Metamaquina/metamaquina.github.io
|
index.md
|
Markdown
|
mit
| 2,115
|
import DS from 'ember-data';
import DomainResource from 'ember-fhir/models/domain-resource';
const { attr, belongsTo, hasMany } = DS;
export default DomainResource.extend({
identifier: hasMany('identifier', { async: true }),
basedOn: hasMany('reference', { async: true }),
status: attr('string'),
category: belongsTo('codeable-concept', { async: false }),
code: belongsTo('codeable-concept', { async: false }),
subject: belongsTo('reference', { async: false }),
context: belongsTo('reference', { async: false }),
effectiveDateTime: attr('date'),
effectivePeriod: belongsTo('period', { async: false }),
issued: attr('string'),
performer: hasMany('diagnostic-report-performer', { async: true }),
specimen: hasMany('reference', { async: true }),
result: hasMany('reference', { async: true }),
imagingStudy: hasMany('reference', { async: true }),
image: hasMany('diagnostic-report-image', { async: true }),
conclusion: attr('string'),
codedDiagnosis: hasMany('codeable-concept', { async: true }),
presentedForm: hasMany('attachment', { async: true })
});
|
davekago/ember-fhir
|
addon/models/diagnostic-report.js
|
JavaScript
|
mit
| 1,088
|
#!/bin/bash
. $(dirname "$0")/tg_vars.cfg
CURL_TG="${CURL} https://api.telegram.org/bot${TG_KEY}"
TMP_DIR="/tmp/${ZBX_TG_PREFIX}"
[ ! -d "${TMP_DIR}" ] && (mkdir -p ${TMP_DIR} || TMP_DIR="/tmp")
TMP_COOKIE="${TMP_DIR}/cookie.txt"
TMP_UIDS="${TMP_DIR}/uids.txt"
TS="`date +%s_%N`_$RANDOM"
LOG="/dev/null"
IS_DEBUG () {
if [ "${ISDEBUG}" == "TRUE" ]
then
return 0
else
return 1
fi
}
login() {
# grab cookie for downloading image
IS_DEBUG && echo "${CURL} --cookie-jar ${TMP_COOKIE} --request POST --data \"name=${ZBX_API_USER}&password=${ZBX_API_PASS}&enter=Sign%20in\" ${ZBX_SERVER}/" >>${LOG}
${CURL} --cookie-jar ${TMP_COOKIE} --request POST --data "name=${ZBX_API_USER}&password=${ZBX_API_PASS}&enter=Sign%20in" ${ZBX_SERVER}/
}
get_image() {
URL=$1
URL=$(echo "${URL}" | sed -e 's/\ /%20/g')
IMG_NAME=$2
# downloads png graph and saves it to temporary path
IS_DEBUG && echo "${CURL} --cookie ${TMP_COOKIE} --globoff \"${URL}\" -o ${IMG_NAME}" >>${LOG}
${CURL} --cookie ${TMP_COOKIE} --globoff "${URL}" -o ${IMG_NAME}
}
TO=$1
SUBJECT=$2
BODY=$3
TG_GROUP=0 # send message to chat or to private chat to user
TG_CHANNEL=0 # send message to channel
METHOD="txt" # sendMessage (simple text) or sendPhoto (attached image)
echo "${BODY}" | grep -q "${ZBX_TG_PREFIX};graphs" && METHOD="image"
echo "${BODY}" | grep -q "${ZBX_TG_PREFIX};chat" && TG_GROUP=1
echo "${BODY}" | grep -q "${ZBX_TG_PREFIX};group" && TG_GROUP=1
echo "${BODY}" | grep -q "${ZBX_TG_PREFIX};debug" && ISDEBUG="TRUE"
echo "${BODY}" | grep -q "${ZBX_TG_PREFIX};channel" && TG_CHANNEL=1
IS_DEBUG && LOG="${TMP_DIR}/debug.${TS}.log"
IS_DEBUG && echo -e "TMP_DIR=${TMP_DIR}\nTMP_COOKIE=${TMP_COOKIE}\nTMP_UIDS=${TMP_UIDS}" >>${LOG}
if [ "${TG_GROUP}" -eq 1 ]
then
TG_CONTACT_TYPE="group"
else
TG_CONTACT_TYPE="private"
fi
TG_CHAT_ID=$(cat ${TMP_UIDS} | awk -F ';' '{if ($1 == "'${TO}'" && $2 == "'${TG_CONTACT_TYPE}'") print $3}' | tail -1)
if [ "${TG_CHANNEL}" -eq 1 ]
then
TG_CHAT_ID="${TO}"
fi
if [ -z "${TG_CHAT_ID}" ]
then
TG_UPDATES=$(${CURL_TG}/getUpdates | sed -e 's/},{/\n/')
for (( idx=${#TG_UPDATES[@]}-1 ; idx>=0 ; idx-- ))
do
UPDATE="${TG_UPDATES[idx]}"
echo "${UPDATE}"
if [ "${TG_GROUP}" -eq 1 ]
then
TG_CHAT_ID=$(echo "${UPDATE}" | sed -e 's/["}{]//g' | awk -F ',' '{if ($8 == "type:group" && $7 == "title:'${TO}'") {gsub("chat:id:", "", $6); print $6}}' | tail -1)
if [ "$(echo ${TG_CHAT_ID} | grep -Eq '\-[0-9]+' && echo 1 || echo 0)" -eq 1 ]
then
break
fi
else
TG_CHAT_ID=$(echo "${UPDATE}" | sed -e 's/["}{]//g' | awk -F ',' '{if ($10 == "type:private" && $5 == "username:'${TO}'") {gsub("chat:id:", "", $6); print $6}}' | tail -1)
if [ "$(echo ${TG_CHAT_ID} | grep -Eq '[0-9]+' && echo 1 || echo 0)" -eq 1 ]
then
break
fi
fi
done
echo "${TO};${TG_CONTACT_TYPE};${TG_CHAT_ID}" >>${TMP_UIDS}
fi
IS_DEBUG && echo "TG_CHAT_ID: ${TG_CHAT_ID}" >>${LOG}
TG_TEXT=$(echo "${BODY}" | grep -vE "^${ZBX_TG_PREFIX};")
if [ "${ZBX_TG_SIGN}" != "FALSE" ]
then
TG_TEXT=$(echo ${TG_TEXT}; echo "--"; echo "${ZBX_SERVER}")
fi
case "${METHOD}" in
"txt")
TG_MESSAGE=$(echo -e "${SUBJECT}\n${TG_TEXT}")
IS_DEBUG && echo "${CURL_TG}/sendMessage -F \"chat_id=${TG_CHAT_ID}\" -F \"text=${TG_MESSAGE}\"" >>${LOG}
ANSWER=$(${CURL_TG}/sendMessage?chat_id=${TG_CHAT_ID} --form "text=${TG_MESSAGE}" 2>&1)
if [ "$(echo "${ANSWER}" | grep -Ec 'migrated.*supergroup')" -eq 1 ]
then
migrate_to_chat_id=$(echo "${ANSWER}" | sed -e 's/["}{]//g' | grep -Eo '\-[0-9]+$')
echo "${TO};${TG_CONTACT_TYPE};${migrate_to_chat_id}" >>${TMP_UIDS}
ANSWER=$(${CURL_TG}/sendMessage?chat_id=${migrate_to_chat_id} --form "text=${TG_MESSAGE}" 2>&1)
fi
;;
"image")
PERIOD=3600 # default period
echo "${BODY}" | grep -q "^${ZBX_TG_PREFIX};graphs_period" && PERIOD=$(echo "${BODY}" | awk -F "${ZBX_TG_PREFIX};graphs_period=" '{if ($2 != "") print $2}' | tail -1 | grep -Eo '[0-9]+' || echo 3600)
ZBX_ITEMID=$(echo "${BODY}" | awk -F "${ZBX_TG_PREFIX};itemid:" '{if ($2 != "") print $2}' | tail -1 | grep -Eo '[0-9]+')
ZBX_TITLE=$(echo "${BODY}" | awk -F "${ZBX_TG_PREFIX};title:" '{if ($2 != "") print $2}' | tail -1)
URL="${ZBX_SERVER}/chart3.php?period=${PERIOD}&name=${ZBX_TITLE}&width=900&height=200&graphtype=0&legend=1&items[0][itemid]=${ZBX_ITEMID}&items[0][sortorder]=0&items[0][drawtype]=5&items[0][color]=00CC00"
IS_DEBUG && echo "Zabbix graph URL: ${URL}" >> ${LOG}
login
CACHE_IMAGE="${TMP_DIR}/graph.${ZBX_ITEMID}.png"
IS_DEBUG && echo "Image cached to ${CACHE_IMAGE} and wasn't deleted" >> ${LOG}
get_image "${URL}" ${CACHE_IMAGE}
TG_CAPTION_ORIG=$(echo -e "${SUBJECT}\n${TG_TEXT}")
TG_CAPTION=$(echo -e $(echo "${TG_CAPTION_ORIG}" | sed ':a;N;$!ba;s/\n/\\n/g' | awk '{print substr( $0, 0, 200 )}'))
if [ "${TG_CAPTION}" != "${TG_CAPTION_ORIG}" ]
then
echo "${ZBX_TG_PREFIX}: probably you will see MEDIA_CAPTION_TOO_LONG error, the message has been cut to 200 symbols, https://github.com/ableev/Zabbix-in-Telegram/issues/9#issuecomment-166895044"
fi
IS_DEBUG && echo "${CURL_TG}/sendPhoto?chat_id=${TG_CHAT_ID}\" --form \"caption=${TG_CAPTION}\" -F \"photo=@${CACHE_IMAGE}\"" >>${LOG}
ANSWER=$(${CURL_TG}/sendPhoto?chat_id=${TG_CHAT_ID} --form "caption=${TG_CAPTION}" -F "photo=@${CACHE_IMAGE}")
IS_DEBUG || rm ${CACHE_IMAGE}
;;
esac
echo >>${LOG}
|
ableev/Zabbix-in-Telegram
|
bash-old-version/zbxtg.sh
|
Shell
|
mit
| 5,749
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.19-2-13
description: >
Array.prototype.map - applied to the Array-like object when
'length' is inherited accessor property without a get function
includes: [runTestCase.js]
---*/
function testcase() {
function callbackfn(val, idx, obj) {
return val > 10;
}
var proto = {};
Object.defineProperty(proto, "length", {
set: function () { },
configurable: true
});
var Con = function () { };
Con.prototype = proto;
var child = new Con();
child[0] = 11;
child[1] = 12;
var testResult = Array.prototype.map.call(child, callbackfn);
return 0 === testResult.length;
}
runTestCase(testcase);
|
PiotrDabkowski/Js2Py
|
tests/test_cases/built-ins/Array/prototype/map/15.4.4.19-2-13.js
|
JavaScript
|
mit
| 1,120
|
module.exports = {
__esModule: true,
default: {
plugins: ['esm-object']
}
}
|
novemberborn/hullabaloo-config-manager
|
test/fixtures/js/esm-object/.babelrc.js
|
JavaScript
|
mit
| 86
|
# -*- encoding : utf-8 -*-
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :postablr_entry_post, :class => 'Entry::Post' do
body ""
title "MyString"
body "MyText"
end
end
|
michelson/postablr
|
spec/factories/postablr_entry_posts.rb
|
Ruby
|
mit
| 239
|
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml">
<head>
<!-- ****** faviconit.com favicons ****** -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
<link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png">
<link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png">
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
<link rel="apple-touch-icon" href="/favicon-57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="/favicon-144.png">
<meta name="msapplication-config" content="/browserconfig.xml">
<!-- ****** faviconit.com favicons ****** -->
<title>Stage Four: Value Propositions - Nathan Harrington</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="/posts/stage-four-value-propositions.html">
<meta name="author" content="Nathan Harrington" />
<meta name="keywords" content="business model canvas" />
<meta name="description" content="Fourth Stage: Value Propositions Research of known effective materials: Udacity course: How to Build a Startup, Lesson 5: Value Propositions All sections 1 - 27 Strategyzer: 10 Characteristics of a great Value Proposition checklist Strategyzer: Sell Your Colleagues on Value Proposition Design Strategyzer: Value Proposition Design book Preview Incorporation: Card deck …" />
<meta property="og:site_name" content="Nathan Harrington" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="Stage Four: Value Propositions"/>
<meta property="og:url" content="/posts/stage-four-value-propositions.html"/>
<meta property="og:description" content="Fourth Stage: Value Propositions Research of known effective materials: Udacity course: How to Build a Startup, Lesson 5: Value Propositions All sections 1 - 27 Strategyzer: 10 Characteristics of a great Value Proposition checklist Strategyzer: Sell Your Colleagues on Value Proposition Design Strategyzer: Value Proposition Design book Preview Incorporation: Card deck …"/>
<meta property="article:published_time" content="2017-09-22" />
<meta property="article:section" content="articles" />
<meta property="article:tag" content="business model canvas" />
<meta property="article:author" content="Nathan Harrington" />
<!-- Bootstrap -->
<link rel="stylesheet" href="/theme/css/bootstrap.min.css" type="text/css"/>
<link href="/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="/theme/css/pygments/native.css" rel="stylesheet">
<link rel="stylesheet" href="/theme/css/style.css" type="text/css"/>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/" class="navbar-brand">
Nathan Harrington </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/pages/about.html">
About
</a></li>
<li><a href="/pages/standing-invitation.html">
Standing Invitation
</a></li>
<!-- custom link to blog roll/articles -->
<li><a href="/category/articles.html">Blog</a></li>
<!--
Don't display categories on menu
<li class="active">
<a href="/category/articles.html">Articles</a>
</li>
<li >
<a href="/category/patents.html">Patents</a>
</li>
-->
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<div class="entry-content">
<p>Fourth Stage: Value Propositions</p>
<p><strong>Research of known effective materials:</strong></p>
<p>Udacity course: How to Build a Startup, Lesson 5: <a href="https://classroom.udacity.com/courses/ep245/lessons/48745133/concepts/482999050923">Value Propositions</a></p>
<p>All sections 1 - 27</p>
<p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/10-characteristics-of-great-value-propositions-checklist.pdf">10 Characteristics of a great Value Proposition
checklist</a></p>
<p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/sell-your-colleagues-on-value-proposition-design.pdf">Sell Your Colleagues on Value Proposition
Design</a></p>
<p>Strategyzer: <a href="https://assets.strategyzer.com/assets/resources/value-proposition-design-book-preview-2014.pdf">Value Proposition Design book
Preview</a></p>
<hr>
<h4>Incorporation:</h4>
<p><strong>Card deck 1 of 6 INTRO</strong></p>
<pre>
Chapter 1. Value Proposition
What product or service are you building, for who, and what does it
solve for those people?
It's about satisfying a customer need, not just you thinking: "What a
great idea".
Chapter 4. COMPONENTS
1. The features of your products and services.
2. What gain are you creating for customers?
3. What pain are you solving for them?
The goal is the smallest possible feature set that solves these pains
and creates these gains for the customer.
That is the Minimally Viable Product.
Chapter 9. PRODUCT
Which are part of your value proposition?
-manufactured goods, commodity product...
Which intangible products are part?
-copyrights, licenses...
Which financial products?
-financial guarantees, insurance policies...
Which digital products?
-mp3 files, ebooks....
The product is the whole package of all the above
Chapter 10. SERVICES
Which core services are part of the value proposition?
-Consulting, a haircut, investment advice...
Which pre-sales or sales services?
-help finding right solution, financing, free-delivery
Which after-sales services?
-free maintenance, disposal...
What is it that your product features do?
</pre>
<p><a href="/images/learning/learning_value_proposition_intro_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_intro_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_intro_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_intro_card_deck_back.jpg"></a></p>
<hr>
<p><strong>Card deck 2 of 6 PAIN</strong>
<pre>
PAIN KILLERS
What are you going to reduce or eliminate for the customer?</p>
<p>Chapter 12. PAIN Questions:
Produce savings? Time, money, effort
Feel better? Frustration, annoyance, headaches
Fix solutions? New features, better, faster
End challenges? Easier, eliminate resistance?
Impact social consequences? wipe out negative social
consequences or add to social status?
Eliminate risk? Financial, social or technical risk </p>
<p>Chapter 14. PAIN Importance
Rank each pain according to its intensity and frequency</p>
<p></pre>
<a href="/images/learning/learning_value_proposition_pain_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_pain_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_pain_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_pain_card_deck_back.jpg"></a></p>
<hr>
<p><strong>Card deck 3 of 6 GAIN</strong>
<pre>
GAIN CREATORS
What are the benefits the customer expects, desires or is surprised by?</p>
<p>Chapter 15. GAIN Questions
Happy customers? Save time, save money, save effort
Better outcomes? Higher quality, more or less of something
Exceed current solutions? Features, performance, quality
Job or life easier?
Create positive consequences? Social (need), business (more sales)</p>
<p>Chapter 16. GAIN Importance
Rank each gain your product and services create according to its
relevance to the customer.
</pre>
<a href="/images/learning/learning_value_proposition_gain_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_gain_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_gain_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_gain_card_deck_back.jpg"></a></p>
<hr>
<p><strong>Card deck 4 of 6 MVP </strong>
<pre>
Chapter 19. MVP Definition
The first instance of your product or service that is delivered to
customers. </p>
<p>What is it that customers tell us that they will pay for or use
right now.</p>
<p>It is not a beta, tell customers it is the MVP.</p>
<p>Chapter 17. MVP Physical
Always invest a day or two building a physical product mockup.
Something that customers can see and touch.</p>
<p>Chapter 18. MVP Webmobile
Build a "low fidelity" app or website to test the problem. </p>
<p>This helps you avoid building products no one wants.</p>
<p>Chapter 21. The art of the MVP
It's based on interaction and iteration and understanding customers
jobs, pains and gains.</p>
<p>For new markets, don't ask about features, ask "How do they spend their
time?"
</pre>
<a href="/images/learning/learning_value_proposition_mvp_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_mvp_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_mvp_card_deck_back.jpg"></a></p>
<hr>
<p><strong>Card deck 5 of 6 META-Value Prop</strong>
<pre>
Chapter 22. COMMON MISTAKES</p>
<p>It's just a feature of someones else's product
"It's nice to have" instead of "got to have"
Not enough customers care</p>
<p>Chapter 23. QUESTIONS:</p>
<p>Competition:
What do customers do today? Make BMC's for the competition.</p>
<p>Technology / Market Insight:
Why is the problem so hard to solve?
Why is the service not being done by other people?</p>
<p>Market size:
How big is this problem? </p>
<p>Product:
How do you make it once you understand the customer needs?</p>
<p>Chapter 24: TWO FORMS:</p>
<p>Technology insight:
Typically applies to hardware, clean tech and biotech.</p>
<p>Market insight:
Changes in how people work, live, interact and what they expect.</p>
<p>Both forms need to solve pains and create gains for the customer.</p>
<p>Chapter 25: TYPES</p>
<p>Technology Market</p>
<p>More efficient lower cost better distribution
smaller simpler better bundling
faster better branding</p>
<p>combine technology and market insights for the sweet spot of value
propositions.
</pre>
<a href="/images/learning/learning_value_proposition_meta_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_meta_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_meta_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_meta_card_deck_back.jpg"></a></p>
<hr>
<p><strong>Card deck 6 of 6 Examples</strong>
<pre>
Technology Insights
Ayasdi - topological analysis, solved previously unapproachable problems
Inscopix - smaller fluorescence microscope - created new market</p>
<p>Market insights
Zynga - play more involved games - facebook distribution
Twitter - micro-blog more than blog - solved a need</p>
<p>JERSEYSQUARE
Pains: cheaper way to wear jersey, eliminate risk of owning traded player
Gain: provide alternative to purchasing counterfeit jersey
Features: single place to rent sports jerseys
MVP: website with rental and stock of jerseys </p>
<p>OmegaChem
Pain: non-renewable petroleum derived feedstock for surfactant industry
Gains: Sustainable, bio-based replacement.
Higher performance
Improved cold temperature tolerance of detergents
Features:
Bi-functional molecules
Flexibility in chain length
MVP: chem-mix blue feedstock in 50-gal drums
</pre>
<a href="/images/learning/learning_value_proposition_examples_card_deck_front.jpg"><img alt="Front of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_examples_card_deck_front.jpg"></a>
<a href="/images/learning/learning_value_proposition_examples_card_deck_back.jpg"><img alt="Back of Card
Deck" src="/images/learning/thumbnails/learning_value_proposition_examples_card_deck_back.jpg"></a></p>
<hr>
<h2>Execution:</h2>
<p>Lessons learned:</p>
<p>36 cards with about double the total content of any previous learning
stage. Still took linear amounts of time to memorize when grouped into
individual card decks. Re-merged with randomization for surprisingly no
impact to time required for memorization and incorporation.</p>
<p>Now making a new set of business model canvases for various problems I'm
working on with these better value proposition ideas.</p>
<p>The creation of these bmfiddles is showing many new frustrations and
lack of clarity. Especially around the value propositions and customer
segments - looking at others briefly from the udacity materials, then
will recreate full BMC's for practice. Excellent - that instantly shows
you were confused about what goes in the customer segment box. It's the
persona, not the matching pains and gains. So execute a series of
bmfiddles based on teh various ideas you are working on that include:</p>
<ol>
<li>A pain solved for customer</li>
<li>A gain created for customer</li>
<li>Features for pain solved and/or gain created</li>
<li>mvp</li>
</ol>
<p><a href="/images/learning/rain_bmc.png"><img alt="Example
BMC" src="/images/learning/thumbnails/rain_bmc.png"></a>
<a href="/images/learning/noise_machine_app.png"><img alt="Example
BMC" src="/images/learning/thumbnails/noise_machine_app.png"></a>
<a href="/images/learning/triangle_innovation.png"><img alt="Example
BMC" src="/images/learning/thumbnails/triangle_innovation.png"></a>
<a href="/images/learning/data_science_matcher.png"><img alt="Example
BMC" src="/images/learning/thumbnails/data_science_matcher.png"></a></p>
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2017-09-22T00:00:00-04:00"> Fri 22 September 2017</time>
</span>
<span class="label label-default">Tags</span>
<a href="/tag/business-model-canvas.html">business model canvas</a>
</footer><!-- /.post-info --> </div>
</div>
</div>
<!-- /.entry-content -->
</article>
</section>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4>
<ul class="list-group" id="social">
<li class="list-group-item"><a href="http://github.com/NathanHarrington"><i class="fa fa-github-square fa-lg"></i> github</a></li>
<li class="list-group-item"><a href="https://www.linkedin.com/in/harringtonnathan"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li>
<li class="list-group-item"><a href="https://plus.google.com/100412424991063551562"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2021 Nathan Harrington
· Powered by <a href="https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="/theme/js/respond.min.js"></script>
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-4602287-2']);
_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>
<!-- End Google Analytics Code -->
</body>
</html>
|
NathanHarrington/NathanHarrington.github.io
|
posts/stage-four-value-propositions.html
|
HTML
|
mit
| 19,127
|
# ♦️ 5 实操
分别申明类型为 ```Number``` ```String``` ```Array``` ```Object``` 的 4 个变量
## 栗子
### Number
```
var num = 2017
```
### String
```
var str = "晓程序公开课"
```
### Array
```
var arr = [num, str]
```
### Object
```
var obj = { x: num, y: str, z: arr }
```
## 小知识点
掌握了四大基本数据类型,便可以根据实际需求为数据选择一种最恰当的存储方式
|
joephon/open-lession
|
JavaScript/block/5.md
|
Markdown
|
mit
| 433
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>printf: 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 / printf - 1.0.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
printf
<small>
1.0.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-01-28 23:20:48 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-28 23:20:48 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 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.2 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "gmalecha@gmail.com"
homepage: "https://github.com/gmalecha/coq-printf"
dev-repo: "git+https://github.com/gmalecha/coq-printf"
bug-reports: "https://github.com/gmalecha/coq-printf/issues"
authors: ["Gregory Malecha"]
license: "MIT"
build: [
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.12~"}
]
tags: [
"date:2020-04-05"
"logpath:Printf"
]
synopsis:
"Implementation of sprintf for Coq"
description: "Library providing implementation of sprintf for Coq"
url {
src: "https://github.com/gmalecha/coq-printf/archive/v1.0.2.tar.gz"
checksum: "sha512=1c26cef48739674e5a286a4e2fd9a85b735c998e43c4c400719b0daaa9117a5f64657e7f6fb43149c3af064436ee4eba7ef79619623ef93af904ea833a84f396"
}
</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-printf.1.0.2 coq.8.7.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).
The following dependencies couldn't be met:
- coq-printf -> coq >= 8.9
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-printf.1.0.2</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>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1/printf/1.0.2.html
|
HTML
|
mit
| 6,658
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>dpdgraph: 15 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 / dpdgraph - 1.0+8.14</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
dpdgraph
<small>
1.0+8.14
<span class="label label-success">15 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-11-01 16:42:58 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-01 16:42:58 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 3 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.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.0 Official release 4.12.0
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: "palmskog@gmail.com"
homepage: "https://github.com/coq-community/coq-dpdgraph"
dev-repo: "git+https://github.com/coq-community/coq-dpdgraph.git"
bug-reports: "https://github.com/coq-community/coq-dpdgraph/issues"
license: "LGPL-2.1-only"
synopsis: "Compute dependencies between Coq objects (definitions, theorems) and produce graphs"
description: """
Coq plugin that extracts the dependencies between Coq objects,
and produces files with dependency information. Includes tools
to visualize dependency graphs and find unused definitions."""
build: [
["./configure"]
[make "-j%{jobs}%" "WARN_ERR="]
]
install: [make "install" "BINDIR=%{bin}%"]
depends: [
"ocaml" {>= "4.05.0"}
"coq" {>= "8.14" & < "8.15~"}
"ocamlgraph"
]
tags: [
"category:Miscellaneous/Coq Extensions"
"keyword:dependency graph"
"keyword:dependency analysis"
"logpath:dpdgraph"
"date:2021-10-07"
]
authors: [
"Anne Pacalet"
"Yves Bertot"
"Olivier Pons"
]
url {
src: "https://github.com/coq-community/coq-dpdgraph/releases/download/v1.0%2B8.14/coq-dpdgraph-1.0-8.14.tgz"
checksum: "sha512=e4f4258133f809852d88bdd757c22140f8f2a8c0148c50af0ba78d25b40e249261c6b6e719855ec78a4315abaf2410b4454d1ec0ff3db8349f0a26e83e344eeb"
}
</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-dpdgraph.1.0+8.14 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-dpdgraph.1.0+8.14 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>45 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-dpdgraph.1.0+8.14 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>15 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 7 M</p>
<ul>
<li>3 M <code>../ocaml-base-compiler.4.12.0/bin/dpdusage</code></li>
<li>3 M <code>../ocaml-base-compiler.4.12.0/bin/dpd2dot</code></li>
<li>89 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/dpdgraph.cmxs</code></li>
<li>23 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/graphdepend.cmi</code></li>
<li>13 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/graphdepend.cmx</code></li>
<li>11 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/dpdgraph.cmxa</code></li>
<li>7 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/searchdepend.cmi</code></li>
<li>6 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/searchdepend.cmx</code></li>
<li>2 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/dpdgraph.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/dpdgraph.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.12.0/lib/coq/user-contrib/dpdgraph/dpdgraph.v</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-dpdgraph.1.0+8.14</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.12.0-2.0.8/released/8.14.0/dpdgraph/1.0+8.14.html
|
HTML
|
mit
| 8,429
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bertrand: 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.14.1 / bertrand - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
bertrand
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-12-29 02:51:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-29 02:51:29 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 3 Virtual package relying on a GMP lib system installation
coq 8.14.1 Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler
ocamlfind 1.9.1 A library manager for OCaml
ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-community/bertrand"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Bertrand"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: Knuth's algorithm" "keyword: prime numbers" "keyword: Bertrand's postulate" "category: Mathematics/Arithmetic and Number Theory/Number theory" "category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs based on external tools" "category: Miscellaneous/Extracted Programs/Arithmetic" "date: 2002" ]
authors: [ "Laurent Théry" ]
bug-reports: "https://github.com/coq-community/bertrand/issues"
dev-repo: "git+https://github.com/coq-community/bertrand.git"
synopsis: "Correctness of Knuth's algorithm for prime numbers"
description: """
A proof of correctness of the algorithm as described in
`The Art of Computer Programming: Fundamental Algorithms'
by Knuth, pages 147-149"""
flags: light-uninstall
url {
src: "https://github.com/coq-community/bertrand/archive/v8.8.0.tar.gz"
checksum: "md5=7abe286c4e4f394cfb9401cd28b7b209"
}
</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-bertrand.8.8.0 coq.8.14.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.14.1).
The following dependencies couldn't be met:
- coq-bertrand -> coq < 8.9~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-bertrand.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.06.1-2.0.5/released/8.14.1/bertrand/8.8.0.html
|
HTML
|
mit
| 7,539
|
class AddApprovedToTouts < ActiveRecord::Migration
def change
add_column :touts, :approved, :boolean, default:false
add_index :touts, :approved
end
end
|
mpakus/toute
|
db/migrate/20130803082347_add_approved_to_touts.rb
|
Ruby
|
mit
| 164
|
all:
cd src; qmake; make
clean:
cd src; qmake; make clean
rm -f src/Makefile
rm -f bin/CQPixmapEd
|
colinw7/CQPixmapEd
|
Makefile
|
Makefile
|
mit
| 103
|
MIME-Version: 1.0
Server: CERN/3.0
Date: Tuesday, 07-Jan-97 15:55:05 GMT
Content-Type: text/html
Content-Length: 4987
Last-Modified: Friday, 01-Mar-96 21:21:33 GMT
<title> Network Security</title>
<H1> Network Security</H1>
<hr>
To enhance the security of networked systems, we proposed a security
architecture together with novel protocols for authentication,
called Texas Authentication Protocols (TAPs), and a new language
for authorization, called Generalized Access Control List (GACL).
A proof methodology for verifying authentication protocols based upon
state transition semantics has been developed. A high level abstraction
for secure network programming (SNP), designed to resemble a socket interface,
has been implemented.
<hr>
<H1> Recent papers </H1>
<ol>
<li> <b> SNP : An interface for secure network programming</b>
<br>
Thomas Y.C. Woo, Raghuram Bindignavle, Shaowen Su and Simon S. Lam
<br>
<cite> Proc. USENIX '94 Summer Technical Conference, </cite>
Boston, June 1994
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/usenix2.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Design, verification and implementation of an authentication
protocol </b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Proc. Int. Conference on Network Protocols, </cite>
Boston, October 1994
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/icnp94.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Authorization in distributed systems: A new approach</b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Journal of Computer Security, </cite> 1994
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/final-1.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> A lesson in authentication protocol design</b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> ACM Operating Systems Review, </cite> vol. 28, no. 3, 1994
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/osr.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> A framework for distributed authorization </b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Proc. ACM Conference on Computer and Communications Security, </cite>
Fairfax, Virginia, November 1993
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/acm-es.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Verifying authentication protocols: Methodology and example</b>
<br>
Thomas Y. C. Woo and Simon S. Lam
<br>
<cite> Proc. Int. Conference on Network Protocols,</cite>
San Francisco, October 1993
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/icnp.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b>A semantic model for authentication protocols</b>
<br>
Thomas Y. C. Woo and Simon S. Lam
<br>
<cite> Proc. IEEE Symposium on Research in Security and Privacy,</cite>
Oakland, May 1993
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/sec93.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Authorization in distributed systems: A formal approach</b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Proc. IEEE Symposium on Research in Security and Privacy, </cite>
Oakland, May 1992
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/sec92.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Applying a theory of modules and interfaces to security verification</b>
<br>
Simon S. Lam, A. Udaya Shankar, and Thomas Y. C. Woo
<br>
<cite> Proc. IEEE Symposium on Research in Security and Privacy, </cite>
Oakland, May 1991
<ul>
<li> <a href = "ftp://ftp.cs.utexas.edu/pub/lam/main.ps.Z">
<b>compressed postscript file</b></a>
</ul>
<li> <b> Authentication revisited</b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Computer, </cite> vol. 25, no. 3, page 10, March 1992
<br>
(first publication of authentication protocol implemented in SNP)
<p>
<li> <b> Authentication for distributed systems </b>
<br>
Thomas Y.C. Woo and Simon S. Lam
<br>
<cite> Computer, </cite> vol. 25, no. 1, pp. 39-52, January 1992
<ul>
<li> <a href = "comp1.html">
<b>more info</b></a>
</ul>
</ol>
|
ML-SWAT/Web2KnowledgeBase
|
webkb/other/texas/http:^^www.cs.utexas.edu^users^lam^NRL^network_security.html
|
HTML
|
mit
| 5,159
|
package main
import (
"time"
"bytes"
"fmt"
)
const FreshPeriod = time.Minute * 10
type Location struct {
id int
Time time.Time
Latitude float32
Longitude float32
}
type ValuePair struct {
loaded bool
value string
}
// TODO: Don't change a value (or add squawk etc) if it already exists with that value.
// Don't add that to the history. However add new changes. Always update LastSeen if after
type Plane struct {
Icao uint
CallSign string
CallSigns []ValuePair
Squawks []ValuePair
Locations []Location
Altitude int
Track float32
Speed float32
Vertical int
LastSeen time.Time
History []*message // won't contain duplicate messages such as "on ground" unless they change
// Various flags
SquawkCh bool
Emergency bool
Ident bool
OnGround bool
}
func (p *Plane) ToJson() string {
buf := bytes.Buffer{}
buf.WriteString("{")
buf.WriteString(fmt.Sprintf("\"icao\": \"%06X\", ", p.Icao))
buf.WriteString(fmt.Sprintf("\"callsign\": %q, ", p.CallSign))
buf.WriteString("\"callsigns\": [")
for i, cs := range p.CallSigns {
buf.WriteString(fmt.Sprintf("%q", cs.value))
if i != len(p.CallSigns) - 1 {
buf.WriteString(", ")
}
}
if len(p.Locations) > 0 {
lastLoc := p.Locations[len(p.Locations) - 1]
buf.WriteString(fmt.Sprintf("], \"location\": \"%f,%f\", ", lastLoc.Latitude, lastLoc.Longitude))
} else {
buf.WriteString("], ")
}
buf.WriteString("\"squawks\": [")
for i, sq := range p.Squawks {
buf.WriteString(fmt.Sprintf("%q", sq.value))
if i != len(p.Squawks) - 1 {
buf.WriteString(", ")
}
}
buf.WriteString(fmt.Sprintf("], \"altitude\": %d, ", p.Altitude))
buf.WriteString(fmt.Sprintf("\"track\": %.2f, ", p.Track))
buf.WriteString(fmt.Sprintf("\"speed\": %.2f, ", p.Speed))
buf.WriteString(fmt.Sprintf("\"vertical\": %d, ", p.Vertical))
buf.WriteString(fmt.Sprintf("\"lastSeen\": %q", p.LastSeen.String()))
buf.WriteString("}")
return buf.String()
}
// SetCallSign tries to add the call sign to the slice of CallSigns for the Plane.
// Returns true if it was added, false if the callsign was already in the slice.
func (p *Plane) SetCallSign(cs string) bool {
if cs == "" || p.CallSign == cs {
return false
}
p.CallSign = cs
// More likely to find a match at the end, so search backwards.
for i := len(p.CallSigns) - 1; i >= 0; i-- {
if cs == p.CallSigns[i].value {
// if it exists, don't add it again
return true // True because at the least the current callsign has been set.
}
}
p.CallSigns = append(p.CallSigns, ValuePair{value: cs})
return true
}
// SetSquawk tries to add the Squawk code to the slice of Squawks for the Plane.
// Returns true if it was added, false if the Squawk was already in the slice.
func (p *Plane) SetSquawk(s string) bool {
// Search backwards as more likely to find result at end.
if s == "" {
return false
}
for i := len(p.Squawks) - 1; i >= 0; i-- {
if s == p.Squawks[i].value {
return false
}
}
p.Squawks = append(p.Squawks, ValuePair{value: s})
return true
}
// SetLocation creates a location from the specified Lat/lon and time and appends it
// to the locations slice. Returns true if successful, and false if there are no values to add
func (p *Plane) SetLocation(lat, lon float32, t time.Time) bool {
if lat == 0.0 || lon == 0.0 {
return false
}
l := Location{Time: t, Latitude: lat, Longitude: lon}
p.Locations = append(p.Locations, l)
return true
}
// SetAltitude will update the altitude if different from existing altitude.
// Returns true if successful, false if there is no change.
func (p *Plane) SetAltitude(a int) bool {
if a != 0 && p.Altitude != a {
p.Altitude = a
return true
}
return false
}
// SetTrack sets the Plane's current track if different from existing value.
// Returns true if successful, and false if there is no change.
func (p *Plane) SetTrack(t float32) bool {
if p.Track != t {
p.Track = t
return true
}
return false
}
// SetSpeed sets the Plane's speed if different from existing value.
// Returns true if successful, and false if there is no change.
func (p *Plane) SetSpeed(s float32) bool {
if p.Speed != s && s != 0.0 {
p.Speed = s
return true
}
return false
}
// SetVertical sets the Plane's vertical speed, if different from existing value.
// Returns true if successful, and false if there was no change.
func (p *Plane) SetVertical(v int) bool {
if p.Vertical != v {
p.Vertical = v
return true
}
return false
}
// SetHistory appends the history message to the history slice.
func (p *Plane) SetHistory(m *message) {
p.History = append(p.History, m)
}
// SetSquawkCh sets the Plane's SquawkChange flag if different from existing value.
// Returns true on success, and false if there is no change.
func (p *Plane) SetSquawkCh(s bool) bool {
if p.SquawkCh != s {
p.SquawkCh = s
return true
}
return false
}
// SetEmergency sets the Plane's emergency flag if different from existing value.
// Returns true on success, and false if there is no change.
func (p *Plane) SetEmergency(e bool) bool {
if p.Emergency != e {
p.Emergency = e
return true
}
return false
}
// SetIdent sets the Plane's ident flag if different from existing value.
// Returns true on success, and false if there is no change.
func (p *Plane) SetIdent(i bool) bool {
if p.Ident != i {
p.Ident = i
return true
}
return false
}
// SetOnGround sets the Plane's onGround flag if different from existing value.
// Returns true on success, and false if there is no change.
func (p *Plane) SetOnGround(g bool) bool {
if p.OnGround != g {
p.OnGround = g
return true
}
return false
}
func updatePlane(m *message, pl *Plane) {
buf := bytes.Buffer{}
if m == nil {
return
}
if m.dGen.After(pl.LastSeen) {
pl.LastSeen = m.dGen
}
if verbose {
buf.WriteString(fmt.Sprintf("%s - %06X -", m.dGen.String(), m.icao))
}
var dataStr string
var written bool
switch m.tType {
case 1:
written = pl.SetCallSign(m.callSign)
if verbose {
dataStr = fmt.Sprintf(" Callsign: %q", m.callSign)
}
case 2:
written = pl.SetAltitude(m.altitude) || written
written = pl.SetSpeed(m.groundSpeed) || written
written = pl.SetTrack(m.track) || written
written = pl.SetLocation(m.latitude, m.longitude, m.dGen) || written
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" Altitude: %d, Speed: %.2f, Track: %.2f, Lat: %s, Lon: %s", m.altitude, m.groundSpeed, m.track, m.latitude, m.longitude)
}
case 3:
written = pl.SetAltitude(m.altitude) || written
written = pl.SetLocation(m.latitude, m.longitude, m.dGen) || written
written = pl.SetSquawkCh(m.squawkCh) || written
written = pl.SetEmergency(m.emergency) || written
written = pl.SetIdent(m.ident) || written
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" Altitude: %d, Lat: %f, Lon: %f", m.altitude, m.latitude, m.longitude)
}
case 4:
written = pl.SetSpeed(m.groundSpeed) || written
written = pl.SetTrack(m.track) || written
written = pl.SetVertical(m.vertical) || written
if verbose {
dataStr = fmt.Sprintf(" Speed: %.2f, Track: %.2f, Vertical Rate: %d", m.groundSpeed, m.track, m.vertical)
}
case 5:
written = pl.SetAltitude(m.altitude) || written
written = pl.SetSquawkCh(m.squawkCh) || written
written = pl.SetIdent(m.ident) || written
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" Altitude: %d", m.altitude)
}
case 6:
written = pl.SetAltitude(m.altitude) || written
written = pl.SetSquawk(m.squawk) || written
written = pl.SetSquawkCh(m.squawkCh) || written
written = pl.SetEmergency(m.emergency) || written
written = pl.SetIdent(m.ident) || written
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" Altitude: %d, SquawkCode: %q", m.altitude, m.squawk)
}
case 7:
written = pl.SetAltitude(m.altitude) || written
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" Altitude: %d", m.altitude)
}
case 8:
written = pl.SetOnGround(m.onGround) || written
if verbose {
dataStr = fmt.Sprintf(" OnGround: %v", m.onGround)
}
}
// Log message if it updated a value, or the last message was more than 10 minutes ago
if written || m.dGen.Sub(pl.LastSeen) > FreshPeriod {
pl.SetHistory(m)
}
if verbose {
buf.WriteString(dataStr)
fmt.Println(buf.String())
buf.Reset()
}
}
|
butlermatt/tamer
|
plane.go
|
GO
|
mit
| 8,477
|
$(document).ready(function() {
var loading = $('#loading');
['ceneo', 'allegro'].forEach(function(service) {
$('#' + service + '-form').submit(function(e) {
e.preventDefault();
var self = $(this);
var resultsUl = $('#' + service + '-results');
resultsUl.empty().hide();
loading.show();
$.post('/' + service, self.serialize(), function(data){
loading.hide();
resultsUl.show();
console.log(data.result);
data.result.forEach(function(row) {
products = [];
row.products.forEach(function(product) {
products.push(
'<a href="' + product.url + '">' + product.name + '</a> ' + product.price.toFixed(2)
);
});
$('<li><b><a href="' + row.url + '">' + row.shop + '</a> ' + row.price.toFixed(2) + ' ' + row.products.length + ' prod.</b> (' + products.join(', ') + ')</li>').appendTo(resultsUl);
});
}).fail(function(data){
loading.hide();
resultsUl.show();
$('<li class=\'error\'>Error occured!</li>').appendTo(resultsUl);
});
});
});
});
|
Alkemic/common_offers
|
static/main.js
|
JavaScript
|
mit
| 1,337
|
/* $Id: volume_wrap.h 454 2010-09-08 21:40:28Z anders.e.e.wallin $
*
* Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenCAMlib.
*
* OpenCAMlib 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 3 of the License, or
* (at your option) any later version.
*
* OpenCAMlib 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 OpenCAMlib. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef VOLUME_WRAP_H
#define VOLUME_WRAP_H
#include <boost/python.hpp>
#include "volume.h"
namespace ocl
{
/* required wrapper class for virtual functions in boost-python */
/// \brief a wrapper around OCTVolume required for boost-python
class OCTVolumeWrap : public OCTVolume, public boost::python::wrapper<OCTVolume> {
public:
bool isInside(Point &p) const {
return this->get_override("isInside")(p);
}
};
} // end namespace
#endif
// end file volume_wrap.h
|
play113/swer
|
opencamlib-read-only/src/cutsim/volume_wrap.h
|
C
|
mit
| 1,341
|
// Generated by CoffeeScript 1.4.0-beerscript
(function() {
var CoffeeScript, cakefileDirectory, existsSync, fatalError, fs, helpers, missingTask, oparse, options, optparse, path, printTasks, switches, tasks;
fs = require('fs');
path = require('path');
helpers = require('./helpers');
optparse = require('./optparse');
CoffeeScript = require('./coffee-script');
existsSync = fs.existsSync || path.existsSync;
tasks = {};
options = {};
switches = [];
oparse = null;
helpers.extend(global, {
task: function(name, description, action) {
var _ref;
if (!action) {
_ref = [description, action], action = _ref[0], description = _ref[1];
}
return tasks[name] = {
name: name,
description: description,
action: action
};
},
option: function(letter, flag, description) {
return switches.push([letter, flag, description]);
},
invoke: function(name) {
if (!tasks[name]) {
missingTask(name);
}
return tasks[name].action(options);
}
});
exports.run = function() {
var arg, args, _i, _len, _ref, _results;
global.__originalDirname = fs.realpathSync('.');
process.chdir(cakefileDirectory(__originalDirname));
args = process.argv.slice(2);
CoffeeScript.run(fs.readFileSync('Cakefile').toString(), {
filename: 'Cakefile'
});
oparse = new optparse.OptionParser(switches);
if (!args.length) {
return printTasks();
}
try {
options = oparse.parse(args);
} catch (e) {
return fatalError("" + e);
}
_ref = options["arguments"];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
_results.push(invoke(arg));
}
return _results;
};
printTasks = function() {
var cakefilePath, desc, name, relative, spaces, task;
relative = path.relative || path.resolve;
cakefilePath = path.join(relative(__originalDirname, process.cwd()), 'Cakefile');
console.log("" + cakefilePath + " defines the following tasks:\n");
for (name in tasks) {
task = tasks[name];
spaces = 20 - name.length;
spaces = spaces > 0 ? Array(spaces + 1).join(' ') : '';
desc = task.description ? "# " + task.description : '';
console.log("cake " + name + spaces + " " + desc);
}
if (switches.length) {
return console.log(oparse.help());
}
};
fatalError = function(message) {
console.error(message + '\n');
console.log('To see a list of all tasks/options, run "cake"');
return process.exit(1);
};
missingTask = function(task) {
return fatalError("No such task: " + task);
};
cakefileDirectory = function(dir) {
var parent;
if (existsSync(path.join(dir, 'Cakefile'))) {
return dir;
}
parent = path.normalize(path.join(dir, '..'));
if (parent !== dir) {
return cakefileDirectory(parent);
}
throw new Error("Cakefile not found in " + (process.cwd()));
};
}).call(this);
|
falsecz/beer-script
|
lib/coffee-script/cake.js
|
JavaScript
|
mit
| 3,039
|
<template name="layout">
<div class="container">
{{> header}}
{{> toasts}}
{{> yield}}
{{> footer}}
</div>
</template>
|
ImproveCoimbra/ceres
|
client/views/application/layout.html
|
HTML
|
mit
| 129
|
<head>
<title>Commerces</title>
</head>
<body></body>
|
Menesys/camille_vasseur_partiel_meteor
|
client/main.html
|
HTML
|
mit
| 56
|
<form action="<?php echo URL_PREFIX; ?>admin/user/view" method="post" class="notice_box">
<strong>Enter a username to search for</strong>
<label>Username</label>
<input type="text" name="username" />
<p class="buttons">
<input type="submit" value="Load User" />
</p>
</form>
|
mattbasta/Tinytape
|
views/v4/admin/user.php
|
PHP
|
mit
| 287
|
package org.magicnexus.classes.ui.cli.parser;
import java.text.ParseException;
import org.magicnexus.classes.ui.cli.MagicNexusCliApplication;
import org.magicnexus.classes.ui.cli.command.AddPlayerCommand;
import org.magicnexus.classes.ui.cli.command.BackToMainCommand;
import org.magicnexus.classes.ui.cli.command.ExitCommand;
import org.magicnexus.classes.ui.cli.command.NoOpCommand;
import org.magicnexus.classes.ui.cli.menu.item.AddPlayerMenuItem;
import org.magicnexus.classes.ui.cli.menu.item.BackMenuItem;
import org.magicnexus.classes.ui.cli.menu.item.ExitMenuItem;
import org.magicnexus.interfaces.ui.cli.IParser;
import org.magicnexus.interfaces.ui.cli.IUiCommand;
public class PlayGameSetupParser implements IParser
{
MagicNexusCliApplication application = null;
public PlayGameSetupParser(MagicNexusCliApplication application)
{
this.application = application;
}
@Override
public IUiCommand parseCommand(String nl) throws ParseException
{
if(nl == null || nl.length() == 0)
return new NoOpCommand();
nl = nl.trim().toLowerCase();
if((new ExitMenuItem()).getCommandName().equals(nl))
return new ExitCommand();
if((new BackMenuItem()).getCommandName().equals(nl))
return new BackToMainCommand(application);
if(nl.length() > 3 && (new AddPlayerMenuItem()).getCommandName().equals(nl.substring(0, 3)))
return new AddPlayerCommand(application, nl);
return new NoOpCommand();
}
}
|
Anastaszor/magic-nexus
|
src/org/magicnexus/classes/ui/cli/parser/PlayGameSetupParser.java
|
Java
|
mit
| 1,481
|
import App from './container';
export default App;
|
IanCStewart/my-records
|
src/components/app/index.js
|
JavaScript
|
mit
| 52
|
namespace RangeIt.Ranges
{
using RangeStrategies.Ints;
public static partial class Range
{
/// <summary>
/// Generates a range containing a given number of sequential and distinct integers,
/// starting with value 1.
/// </summary>
/// <param name="count">The number of integers, which will be generated.</param>
/// <returns>
/// A <see cref="Range{T}" /> of ints, containing the generated integers.
/// If <paramref name="count"/> is 0, the returned <see cref="Range{T}" /> will be empty.
/// </returns>
public static Range<int> Ints(uint count) => Ints(1, count);
/// <summary>
/// Generates a range containing a given number of sequential and distinct integers,
/// starting with value 1.
/// </summary>
/// <param name="count">The number of integers, which will be generated.</param>
/// <param name="step">The difference between two sequential values in the generated range.</param>
/// <returns>
/// A <see cref="Range{T}" /> of ints, containing the generated integers.
/// If <paramref name="count"/> is 0, the returned <see cref="Range{T}" /> will be empty.
/// </returns>
public static Range<int> IntsWithStep(uint count, int step) => Ints(1, count, step);
/// <summary>
/// Generates a range containing a given number of sequential and distinct integers,
/// starting with a given <paramref name="startValue" />.
/// </summary>
/// <param name="startValue">The start value, at which the generated range starts.</param>
/// <param name="count">The number of integers, which will be generated.</param>
/// <returns>
/// A <see cref="Range{T}" /> of ints, containing the generated integers.
/// If <paramref name="count"/> is 0, the returned <see cref="Range{T}" /> will be empty.
/// </returns>
public static Range<int> Ints(int startValue, uint count)
=> new Range<int>(new IntsStrategy(startValue, count));
/// <summary>
/// Generates a range containing a given number of sequential and distinct integers,
/// starting with a given <paramref name="startValue" />.
/// </summary>
/// <param name="startValue">The start value, at which the generated range starts.</param>
/// <param name="count">The number of integers, which will be generated.</param>
/// <param name="step">The difference between two sequential values in the generated range.</param>
/// <returns>
/// A <see cref="Range{T}" /> of ints, containing the generated integers.
/// If <paramref name="count"/> is 0, the returned <see cref="Range{T}" /> will be empty.
/// </returns>
public static Range<int> Ints(int startValue, uint count, int step)
=> new Range<int>(new IntsWithStepStrategy(startValue, count, step));
}
}
|
henrikfroehling/RangeIt
|
Source/Lib/RangeIt/Ranges/Extensions/Range_Ints.cs
|
C#
|
mit
| 2,996
|
<?
include "config.php";
include "lib/function.php";
?>
|
antonraharja/playvoip
|
web/init.php
|
PHP
|
mit
| 55
|
const path = require('path');
const { CheckerPlugin } = require('awesome-typescript-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const baseConfig = require('./webpack.base');
const baseDevConfig = {
...baseConfig,
devtool: 'source-map',
mode: 'development',
devServer: {
contentBase: baseConfig.output.path,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
},
compress: true,
port: 3000,
},
};
const viewerConfig = {
...baseDevConfig,
entry: {
index: path.join(__dirname, 'src', 'viewer', 'viewer.tsx'),
},
plugins: [
new CheckerPlugin(),
new HtmlWebpackPlugin({
title: 'CSpell Settings Viewer',
hash: true,
template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'),
inject: 'body',
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
const testConfig = {
...baseDevConfig,
entry: {
test: path.join(__dirname, 'src', 'viewer', 'vsCodeTestWrapper.tsx'),
},
plugins: [
new HtmlWebpackPlugin({
title: 'Tester CSpell Settings Viewer',
hash: true,
template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'),
inject: 'body',
filename: 'test.html',
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
module.exports = [viewerConfig, testConfig];
|
Jason-Rev/vscode-spell-checker
|
packages/_settingsViewer/webpack.dev.js
|
JavaScript
|
mit
| 1,972
|
/*global describe: false, it: false, expect: false */
'use strict';
var apiFactory = require('../controller/apiFactory.js');
describe('will this work', function () {
var method = apiFactory.get('session');
it('Default test case', function apiFactory1() {
expect(method.create).toBe(require('../controller/sessionManager.js').create);
});
});
|
stefanbrittain/central-bookmarks
|
services/spec/apiFactory-spec.js
|
JavaScript
|
mit
| 366
|
# This file contains bash aliases and functions. Sourcing this file doesn't
# change the behavior of the system and just loads a few more handy aliases and
# functions into the environment.
alias fig='find . | grep --color=always -i'
alias ll='ls -alrth'
alias lsg='ls | grep'
alias lsn="ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr(\$1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(\"%0o \",k);print}'"
alias l='ls -alrth'
alias lsa='ls -a'
alias lsdir='ls -d */'
alias rmf='sudo rm -rf'
alias dfh='df -h'
alias duh='du -sch'
alias psg='ps aux | grep -i --color=always'
alias gi='grep -i'
alias gri='grep -rinI --color=always --exclude-dir=.git --exclude-dir=.eggs --exclude-dir=.venv --exclude-dir=tags --exclude-dir=tests --exclude=tags'
alias griv='grep -rinI --color=always --exclude-dir=.git --exclude-dir=.venv --exclude-dir=tags'
# Grep no-ignore-case
alias grin='grep -rnI --color=always --exclude-dir=.git --exclude-dir=.venv --exclude-dir=tags'
alias fr='free -h'
alias ssh='ssh -X'
alias wchere='cat $(find .) 2>/dev/null | wc'
alias eg='env | grep -i'
alias egp='env | grep proxy'
alias less='less -R'
alias cdd='cd ..'
alias cddd='cd ../..'
alias cdddd='cd ../../..'
alias cddddd='cd ../../../..'
alias cdddddd='cd ../../../../..'
alias cddddddd='cd ../../../../../..'
alias cdp='cd -'
function cds() {
cd ~/src/$1
}
function cdn() {
cd ~/notes/$1
}
alias cdv='cd ~/vagrant'
alias cdw='cd ~/ws'
function cd() {
# Improved 'cd' command
# If I write 'cd /dir1/dir2/dir3/t', where I typed 't' accidentally, take
# me anyway to /dir1/dir2/dir3/.
# TODO(rushiagr): Add colourful message in green whenever we're doing an
# intelligent 'cd' :)
if [[ -z $1 ]]; then
builtin cd
return
fi
builtin cd "${1}" > /dev/null 2>&1
RETVAL=$?
if [[ $RETVAL != 0 ]]; then
# If there is exactly one directory which matches pattern *$1*,
# case-insensitively, where $1 is the first argument, then cd to that
# directory. E.g. If there are four directories 'one', 'two', 'three',
# 'four', and you do `cd hr`, then cd into 'three' directory.
matching_dir_count=$(ls | grep -i -c "${1}")
if [[ $matching_dir_count == 1 ]]; then
matching_dir=$(ls | grep -i "${1}")
builtin cd $matching_dir
return
fi
TRAILING_DIR_INPUT=$(echo $(pwd)/"${1}" | rev | cut -d'/' -f1 | rev)
# If exactly one directory pattern-matches $2, go to that directory
# e.g. if the command is 'cd a/t' and there are two directories
# 'a/one/' and 'a/two/', then cd the user to 'a/two/' directory
PENULTIMATE_PATH=$(echo $(pwd)/"${1}" | rev | cut -d'/' -f2- | rev)
# NOTE: I could have done:
# DIRS_IN_PENULTIMATE_PATH=$(ls -alrth $PENULTIMATE_PATH | grep ^d | grep [^.]$ | rev | cut -d ' ' -f 1 | rev)
# and used this variable below. Instead, I'm doing this work twice below
# The problem is that whenever I do a 'grep -c' on this variable
# won't ever return a value greater than 1. This is because once I put
# data from a command into a variable, the variable will put all the
# values from multiple line into a single line.
# TODO(rushiagr): make the above comment more readable :)
if [[ $(ls -alrth $PENULTIMATE_PATH | grep ^d | grep [^.]$ | rev | cut -d ':' -f1 | rev | cut -d ' ' -f2- | grep -ic ^$TRAILING_DIR_INPUT) == 1 ]]; then
MATCHED_DIR_IN_PENULTIMATE_PATH=$(ls -alrth $PENULTIMATE_PATH | grep ^d | grep [^.]$ | rev | cut -d ':' -f1 | rev | cut -d ' ' -f2- | grep -i ^$TRAILING_DIR_INPUT)
FINAL_DIR=$(echo $PENULTIMATE_PATH/$MATCHED_DIR_IN_PENULTIMATE_PATH)
builtin cd "${FINAL_DIR}"
else
# Either there are more than one matches, or no matches. In either
# case, just go to the penultimate path
builtin cd "${PENULTIMATE_PATH}"
fi
fi
}
function pingbg() {
ping -i 60 $1 >/dev/null 2>&1 &
}
alias fs='sudo chown stack:stack `readlink /proc/self/fd/0`'
# Usage: cat file | aw 2,3,4
function aw() {
awk "{print \$${1:-1}}" $2;
}
# Kill all the processes which matches specified pattern. Won't kill sudo
# processes
function pskill() {
kill -9 $(ps aux | grep -i $1 | awk '{print $2}')
}
# 'sudo pskill'
function spskill() {
sudo kill -9 $(ps aux | grep -i $1 | awk '{print $2}')
}
# Find common lines between two files
function common () {
comm -12 <(sort $1) <(sort $2)
}
alias venv='source ~/src/venvs/main/bin/activate'
alias quit='exit'
alias unproxy='unset http_proxy https_proxy no_proxy'
alias d='date'
alias ud='TZ=UTC date' # UTC date
# 'S'ou'R'ce aliasrc. Useful only while sourcing updated aliasrc. Won't be
# available for sourcing for the first time obviously
alias sr='source ~/.aliasrc'
alias cdl='cd -'
alias vv='vim Vagrantfile'
alias vim='if [[ $TERM == "xterm" ]]; then export TERM=xterm-256color; fi; vim'
alias svim='if [[ $TERM == "xterm" ]]; then export TERM=xterm-256color; fi; sudo vim'
alias sv='svim'
alias pp='sudo pm-suspend-hybrid'
alias pig='ping google.com'
#function dk() {
# wget -b -O dkdm$1\.mp4 http://media.startv.in/newstream/star/lifeok/mahadev/$1/lf_300.mp4
#}
#
#function dkl() {
# for (( c=$1; c<=$2; c++ )); do
# dk $c
# done
#}
alias mys='mysql --pager="less -SFX" -uroot -pnova -h $(ifconfig lo0 | grep "inet " | aw 2)'
alias sx='screen -x'
alias gow='\
export GOPATH=$HOME/src/go; \
export PATH=$PATH:$HOME/src/go:$HOME/src/go/bin;'
alias astp='sudo service apache2 stop'
alias arst='sudo service apache2 restart'
alias astr='sudo service apache2 start'
alias are='sudo service apache2 reload'
alias astt='sudo service apache2 status'
alias airkill="sudo kill -9 $(ps aux | grep -i airtel | awk '{print $2}' | grep -v auto)"
function f() {
for i in `seq 1 10`; do
$*
done
}
function fdelay() {
for i in `seq 1 10`; do
sleep 1
$*
done
}
alias q="exit"
alias cer='cat /etc/resolv.conf'
alias ceh='cat /etc/hosts'
alias teh='tail /etc/hosts'
alias veh='sudo vim /etc/hosts'
alias ver='sudo vim /etc/resolv.conf'
# Alias to convert all files and directories to normal permissions
function fixfileperms() {
find * -type d -print0 | xargs -0 chmod 0755 # for directories
find . -type f -print0 | xargs -0 chmod 0644 # for files
}
alias gcu='git commit -m "update $(date)"'
alias qr="python ~/src/myutils/otherfiles/quotesroll.py $USER"
function setupnewuser() {
# Creates a new user, and gives passwordless sudo privileges to that user.
# There's just one small problem: the user won't have colours for the
# terminal, and some basic bash shortcut aliases like 'll'
USER=$1
OLD_USER=$(users) # NOT a good way actually
sudo addgroup $USER
sudo /usr/sbin/adduser --system --home /home/$USER --shell /bin/bash --ingroup $USER --gecos "$USER" $USER
echo "$USER ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/21_$USER
sudo -u $USER -H bash -c "sudo mkdir -p ~/.ssh"
sudo -u $USER -H bash -c "pwd"
sudo -u $USER -H bash -c "sudo cp /home/$OLD_USER/.ssh/authorized_keys ~/.ssh"
sudo -u $USER -H bash -c "sudo chown $USER:$USER ~/.ssh/authorized_keys"
}
function hugo_new() {
if [[ -z $1 ]]; then
echo "usage: hugo_new blog-post-name.md"
return
fi
CURR_DIR=$(pwd | rev | cut -d '/' -f 1 | rev)
if [ $CURR_DIR != 'npf' ]; then
echo 'This command should be executed from inside "npf" directory'
return
fi
hugo new $1 2>&1 >> /dev/null
mv content/$1 content/blog/
sed -i s/menu\ \=\ \"main\"/type\ \=\ \"post\"/g content/blog/$1
echo "Blog file ready at content/blog/$1"
}
# TODO(rushiagr): make color more beautiful. Red is kind of dull..
man() {
env \
LESS_TERMCAP_mb=$(printf "\e[1;31m") \
LESS_TERMCAP_md=$(printf "\e[1;31m") \
LESS_TERMCAP_me=$(printf "\e[0m") \
LESS_TERMCAP_se=$(printf "\e[0m") \
LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
LESS_TERMCAP_ue=$(printf "\e[0m") \
LESS_TERMCAP_us=$(printf "\e[1;32m") \
man "$@"
}
alias cxp='curl -XPOST -H "Authorization: token $MYTOKEN" -H "Content-Type: application/json"'
alias cx='curl -H "Authorization: token $MYTOKEN" -H "Content-Type: application/json"'
alias his='history | awk '"'"'{$1="";print substr($0,2)}'"'"''
alias hisl='his | less'
alias pkgupload='python setup.py bdist_wheel && twine upload dist/$(ls -t dist/ | head -1)'
alias c6='chmod 600'
# Mac battery
function macbat() {
# TODO: Don't make call to 'ioreg' twice. It's too bulky a call.
currentcapacity=$(ioreg -l | grep CurrentCapacity | awk '{print $5}')
maxcapacity=$(ioreg -l | grep MaxCapacity | awk '{print $5}')
echo $(($currentcapacity*100 / $maxcapacity ))
}
# In Mac, htop needs to be run as sudo to see CPU and memory usage
alias htop='sudo htop'
alias dk='sudo docker'
alias afk="/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend"
alias chromemem="ps aux | grep 'Chrome' | awk '{vsz += $5; rss += $6} END { print \"vsz=\"vsz, \"rss=\"rss }'"
function dirmd5sum() {
# Works with only 'gmd5sum' for now. Expects directory name as arg
find -s $1 -type f -exec gmd5sum {} \; | gmd5sum
}
|
rushiagr/myutils
|
superutils/safe/etc.sh
|
Shell
|
mit
| 9,357
|
package com.surrattfamily.acsdash.action;
/**
* @author rsurratt
* @since 6/6/15
*/
public enum Format
{
HTML,
CSV,
DELTA_CSV
}
|
rsurratt/ACSDashboard
|
src/main/java/com/surrattfamily/acsdash/action/Format.java
|
Java
|
mit
| 144
|
namespace Cake.Docker
{
/// <summary>
/// Settings for docker build.
/// </summary>
public sealed class DockerComposeRmSettings: DockerComposeSettings
{
/// <summary>
/// Don't ask to confirm removal
/// </summary>
public bool Force { get; set; }
/// <summary>
/// Remove any anonymous volumes attached to containers
/// </summary>
[AutoProperty(Format = "-v", OnlyWhenTrue = true)]
public bool Volumes { get; set; }
/// <summary>
/// Stop the containers, if required, before removing
/// </summary>
public bool Stop { get; set; }
}
}
|
MihaMarkic/Cake.Docker
|
src/Cake.Docker/Compose/Rm/DockerComposeRmSettings.cs
|
C#
|
mit
| 666
|
---
layout: post
title: "Physical address validation on Python"
excerpt: "A small war between EasyPost and SmartyStreets"
cover_image: false
comments: true
---
Recently I and my pair had to implement a physical address validation functionality on our Python project at East Agile. We started off with [USPS Web Tool APIs](https://www.usps.com/business/web-tools-apis/welcome.htm) per client request, however their complicated registration process and slow customer supportation stopped us to go any further. In the search to overcome this hassle, we fortunately passed by two promising APIs: [*EasyPost*](https://www.easypost.com/docs) and [*SmartyStreets*](http://smartystreets.com/kb/liveaddress-api). Our findings led to another big question:
> Which service should we choose to fulfill our need?
And I'm writing to find out which one and why. I will evaluate each of them on the following categories:
- API documentation
- API tutorial and samples
- API integration and supports for Python
- API pricing
- Detailedness and usefulness of response object
## API documentation
**EasyPost:**
EasyPost has a very well-structured and detailed documentation.
|
tklarryonline/tklarryonline.github.io
|
_drafts/physical-address-validation-on-python.md
|
Markdown
|
mit
| 1,164
|
import functools
from common.tornado_cookies import get_secure_cookie, generate_secure_cookie
from core import cookies
class Perms(object):
NONE = None
READ = 'r'
WRITE = 'w'
def _permission_level(user, room):
"""
`user`'s permission level on `room`, ignoring cookies
"""
if not user.is_authenticated():
return Perms.READ
else:
return Perms.WRITE
def _get_cached_perm_level(request, cookie_name):
perm = get_secure_cookie(request, cookie_name)
if not perm:
return
assert perm in ('r', 'w')
return perm
def _set_cached_perm_level(response, cookie_name, perm_level):
assert perm_level in ('r', 'w')
cookie_val = generate_secure_cookie(cookie_name, perm_level)
response.set_cookie(cookie_name, cookie_val)
def _perm_level_satisfies(perm_val, perm_req):
"""
If a user has permission level `perm_val`,
and is requesting access level `perm_req`.
"""
if perm_req == perm_val:
return True
if (perm_val == Perms.WRITE) and (perm_req == Perms.READ):
return True
return False
def get_permission(request, response, room, perm_req):
"""
Returns True or False.
Sets a cookie on the response object to cache
the result, if necessary.
"""
assert perm_req in (Perms.READ, Perms.WRITE)
if cookies.has_cached_room_permission(
room.shortname,
perm_req,
functools.partial(get_secure_cookie, request),
session_key=request.session.session_key,
uid=getattr(request.user, 'id', None)):
return True
# Cached permission does not satisfy requirement.
perm_actual = _permission_level(request.user, room)
if perm_actual == Perms.NONE:
return False
assert perm_actual in (Perms.READ, Perms.WRITE)
result = _perm_level_satisfies(perm_actual, perm_req)
cookie_name = cookies.room_cookie_name(room.shortname, session_key=request.session.session_key, uid=getattr(request.user, 'id', None))
if result:
_set_cached_perm_level(response, cookie_name, perm_actual)
return result
|
reverie/seddit.com
|
redditchat/core/permissions.py
|
Python
|
mit
| 2,122
|
---
sitemap:
tags:
changefreq: monthly
priority: 0.4
---
Post which defines custom sitemap tags in YAML metadata.
|
kevinoid/jekyll-sitemap
|
spec/fixtures/_posts/2017-08-10-post-sitemap-tags.html
|
HTML
|
mit
| 125
|
require "rails_helper"
RSpec.describe ConsensusGenomeConcatService, type: :service do
let(:project) { create(:project) }
let(:sample) { create(:sample, project: project) }
let(:workflow_run_1) { create(:workflow_run, sample: sample, workflow: WorkflowRun::WORKFLOW[:consensus_genome]) }
let(:workflow_run_2) { create(:workflow_run, sample: sample, workflow: WorkflowRun::WORKFLOW[:consensus_genome]) }
let(:workflow_run_3) { create(:workflow_run, sample: sample, workflow: WorkflowRun::WORKFLOW[:consensus_genome]) }
let(:fasta_1) do
">sample1_A\nATTAAAGGTTTATACCTTCCCAGGTAACAAACCAACCAACTTTCGATCTCTTGTAGATCT\nGTTCTCTAAACGAACTTTAAAATCTGTGTGGCTGTCACTCGGCTGCATGCTTAGTGCACT\n"
end
let(:fasta_2) { ">sample1_B\nCACGCAGTATAATTAATAACTAATTACTGTCGTTGACAGGACACGAGTAACTCGTCTATC\nTTCTGCAGGCTGCTTACGGTTTCGTCCGTGTTGCAGCCGATCATCAGCACATCTAGGTTT\n" }
let(:fasta_3) { ">sample1_C\nCGTCCGGGTGTGACCGAAAGGTAAGATGGAGAGCCTTGTCCCTGGTTTCAACGAGAAAAC\nACACGTCCAACTCAGTTTGCCTGTTTTACAGGTTCGCGACGTGCTCGTACGTGGCTTTGG\n" }
subject { ConsensusGenomeConcatService.new([workflow_run_1.id, workflow_run_2.id, workflow_run_3.id]) }
describe "#call" do
it "calls the generate method" do
expect_any_instance_of(ConsensusGenomeConcatService).to receive(:generate_concatenated_fasta).and_return(fasta_1 + fasta_2)
expect(subject.call).to eq(fasta_1 + fasta_2)
end
end
describe "#generate_concatenated_fasta" do
context "when all consensus output files exist" do
it "appends the samples together correctly" do
allow_any_instance_of(WorkflowRun).to receive(:output_path).with(ConsensusGenomeWorkflowRun::OUTPUT_CONSENSUS)
expect(S3Util).to receive(:get_s3_file).and_return(fasta_1, fasta_2, fasta_3)
expect(subject.send(:generate_concatenated_fasta)).to eq(fasta_1 + fasta_2 + fasta_3)
end
end
context "when workflow runs are missing" do
it "raises an error" do
service = ConsensusGenomeConcatService.new([-1, -2])
expect { service.send(:generate_concatenated_fasta) }.to raise_error(ConsensusGenomeConcatService::WorkflowRunNotFoundError)
end
end
context "when a workflow run output is missing or empty" do
it "raises an error" do
expect_any_instance_of(WorkflowRun).to receive(:output_path).with(ConsensusGenomeWorkflowRun::OUTPUT_CONSENSUS)
expect(S3Util).to receive(:get_s3_file)
expect { subject.send(:generate_concatenated_fasta) }.to raise_error(ConsensusGenomeConcatService::EmptyS3FileError)
end
end
end
end
|
chanzuckerberg/idseq-web
|
spec/services/consensus_genome_concat_service_spec.rb
|
Ruby
|
mit
| 2,562
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TweetLib.Browser.Interfaces;
using TweetLib.Core.Features.Plugins.Config;
using TweetLib.Core.Features.Plugins.Enums;
using TweetLib.Core.Features.Plugins.Events;
using TweetLib.Core.Resources;
using TweetLib.Utils.Data;
namespace TweetLib.Core.Features.Plugins {
public sealed class PluginManager {
public IEnumerable<Plugin> Plugins => plugins;
public IEnumerable<InjectedString> NotificationInjections => bridge.NotificationInjections;
public PluginConfig Config { get; }
public string PluginFolder { get; }
public string PluginDataFolder { get; }
internal event EventHandler<PluginErrorEventArgs>? Reloaded;
internal event EventHandler<PluginErrorEventArgs>? Executed;
internal readonly PluginBridge bridge;
private IScriptExecutor? browserExecutor;
private readonly HashSet<Plugin> plugins = new ();
internal PluginManager(PluginConfig config, string pluginFolder, string pluginDataFolder) {
this.Config = config;
this.Config.PluginChangedState += Config_PluginChangedState;
this.PluginFolder = pluginFolder;
this.PluginDataFolder = pluginDataFolder;
this.bridge = new PluginBridge(this);
}
public string GetPluginFolder(PluginGroup group) {
return Path.Combine(PluginFolder, group.GetSubFolder());
}
internal void Register(PluginEnvironment environment, IBrowserComponent browserComponent) {
browserComponent.AttachBridgeObject("$TDP", bridge);
if (environment == PluginEnvironment.Browser) {
browserExecutor = browserComponent;
}
}
public void Reload() {
plugins.Clear();
var errors = new List<string>(1);
foreach (var result in PluginGroups.All.SelectMany(group => PluginLoader.AllInFolder(PluginFolder, PluginDataFolder, group))) {
if (result.HasValue) {
plugins.Add(result.Value);
}
else {
errors.Add(result.Exception.Message);
}
}
Reloaded?.Invoke(this, new PluginErrorEventArgs(errors));
}
internal void Execute(PluginEnvironment environment, IScriptExecutor executor) {
if (!plugins.Any(plugin => plugin.HasEnvironment(environment))) {
return;
}
executor.RunScript("gen:pluginstall", PluginScriptGenerator.GenerateInstaller());
bool includeDisabled = environment == PluginEnvironment.Browser;
if (includeDisabled) {
executor.RunScript("gen:pluginconfig", PluginScriptGenerator.GenerateConfig(Config));
}
var errors = new List<string>(1);
foreach (Plugin plugin in Plugins) {
string path = plugin.GetScriptPath(environment);
if (string.IsNullOrEmpty(path) || (!includeDisabled && !Config.IsEnabled(plugin)) || !plugin.CanRun) {
continue;
}
string script;
try {
script = File.ReadAllText(path);
} catch (Exception e) {
errors.Add($"{plugin.Identifier} ({Path.GetFileName(path)}): {e.Message}");
continue;
}
executor.RunScript($"plugin:{plugin}", PluginScriptGenerator.GeneratePlugin(plugin.Identifier, script, bridge.GetTokenFromPlugin(plugin), environment));
}
executor.RunBootstrap($"plugins/{environment.GetPluginScriptNamespace()}");
Executed?.Invoke(this, new PluginErrorEventArgs(errors));
}
private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e) {
browserExecutor?.RunFunction("TDPF_setPluginState", e.Plugin, e.IsEnabled);
}
public bool IsPluginConfigurable(Plugin plugin) {
return plugin.HasConfig || bridge.WithConfigureFunction.Contains(plugin);
}
public void ConfigurePlugin(Plugin plugin) {
if (bridge.WithConfigureFunction.Contains(plugin) && browserExecutor != null) {
browserExecutor.RunFunction("TDPF_configurePlugin", plugin);
}
else if (plugin.HasConfig) {
App.SystemHandler.OpenFileExplorer(File.Exists(plugin.ConfigPath) ? plugin.ConfigPath : plugin.GetPluginFolder(Enums.PluginFolder.Data));
}
}
}
}
|
chylex/TweetDuck
|
lib/TweetLib.Core/Features/Plugins/PluginManager.cs
|
C#
|
mit
| 3,929
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FclEx
{
public static class NullableExtensions
{
/// <summary>
/// Exactly same as GetValueOrDefault but with shorter name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T Get<T>(this T? t, T defaultValue = default) where T : struct
{
return t.GetValueOrDefault(defaultValue);
}
public static bool IsValid<T>(this T? t) where T : struct
{
return !t.IsNullOrDefault();
}
public static bool IsNullOrDefault<T>(this T? t) where T : struct
{
return EqualityComparer<T>.Default.Equals(t.Get(), default);
}
}
}
|
huoshan12345/FclEx
|
src/FclEx/FclEx/~Extensions/NullableExtensions.cs
|
C#
|
mit
| 877
|
require 'spec_helper'
describe User do
context "when is a contestant" do
before {
@contestant = Factory.create(:contestant)
@contestant_role = Role.find_by_name("contestant")
}
it "should have contestant role" do
@contestant.role.should == @contestant_role
@contestant.role?("contestant")
end
end
context "when is an administrator" do
before {
@administrator = Factory.create(:administrator)
@administrator_role = Role.find_by_name("administrator")
}
it "should have the administrator role" do
@administrator.role.should == @administrator_role
@administrator.role?("administrator")
end
end
end
|
kennym/Nejupy-Ruby
|
spec/models/user_spec.rb
|
Ruby
|
mit
| 689
|
<?php
/**
* Configuration file for routes.
*/
return [
// Load these routefiles in order specified and optionally mount them
// onto a base route.
"routeFiles" => [
[
// Routers for the user parts mounts on user/
"mount" => "user",
"file" => __DIR__ . "/route/comment/user.php",
],
[
// Routers for the user parts mounts on comment/
"mount" => "comment",
"file" => __DIR__ . "/route/comment/comment.php",
],
[
// Routers for the user parts mounts on admin/
"mount" => "admin",
"file" => __DIR__ . "/route/comment/admin.php",
],
],
];
|
oenstrom/anax-user
|
config/MockRoute.php
|
PHP
|
mit
| 708
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Tests
* @package Tests_Functional
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Mage\Catalog\Test\Handler\CatalogCategory;
use Magento\Mtf\Handler\HandlerInterface;
/**
* Interface CatalogCategoryInterface.
*/
interface CatalogCategoryInterface extends HandlerInterface
{
//
}
|
portchris/NaturalRemedyCompany
|
src/dev/tests/functional/tests/app/Mage/Catalog/Test/Handler/CatalogCategory/CatalogCategoryInterface.php
|
PHP
|
mit
| 1,164
|
package org.openforis.collect.android.gui.input;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.FragmentActivity;
import org.openforis.collect.R;
import org.openforis.collect.android.SurveyService;
import org.openforis.collect.android.gui.detail.NavigationDialogFragment;
import org.openforis.collect.android.gui.util.Activities;
import org.openforis.collect.android.gui.util.Attrs;
import org.openforis.collect.android.gui.util.Views;
import org.openforis.collect.android.util.CoordinateUtils;
import org.openforis.collect.android.viewmodel.UiAttribute;
import org.openforis.collect.android.viewmodel.UiCoordinateAttribute;
import org.openforis.collect.android.viewmodel.UiSpatialReferenceSystem;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import static android.text.InputType.TYPE_CLASS_NUMBER;
import static android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL;
import static android.text.InputType.TYPE_NUMBER_FLAG_SIGNED;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static org.apache.commons.lang3.ObjectUtils.notEqual;
/**
* @author Daniel Wiell
*/
public class CoordinateAttributeComponent extends AttributeComponent<UiCoordinateAttribute> {
private final LocationProvider locationProvider;
private ViewHolder vh;
private boolean requestingLocation;
CoordinateAttributeComponent(UiCoordinateAttribute attribute, SurveyService surveyService, final FragmentActivity context) {
super(attribute, surveyService, context);
vh = new ViewHolder();
locationProvider = new LocationProvider(new UpdateListener(context), context, true);
}
@Override
public boolean hasChanged() {
UiSpatialReferenceSystem srs = selectedSpatialReferenceSystem();
// srs always set in ui, while it can be null in the attribute: avoid unnecessary updates
boolean srsUpdated = attribute.getSpatialReferenceSystem() != null && notEqual(srs, attribute.getSpatialReferenceSystem());
Double x = toDouble(vh.xView);
Double y = toDouble(vh.yView);
Double altitude = attribute.getDefinition().includeAltitude ? toDouble(vh.altitudeView) : null;
Double accuracy = attribute.getDefinition().includeAccuracy ? toDouble(vh.accuracyView) : null;
return srsUpdated ||
notEqual(x, attribute.getX()) ||
notEqual(y, attribute.getY()) ||
notEqual(altitude, attribute.getAltitude()) ||
notEqual(accuracy, attribute.getAccuracy());
}
protected boolean updateAttributeIfChanged() {
stopLocationRequest();
if (hasChanged()) {
UiSpatialReferenceSystem srs = selectedSpatialReferenceSystem();
Double x = toDouble(vh.xView);
Double y = toDouble(vh.yView);
Double altitude = attribute.getDefinition().includeAltitude ? toDouble(vh.altitudeView) : null;
Double accuracy = attribute.getDefinition().includeAccuracy ? toDouble(vh.accuracyView) : null;
attribute.setSpatialReferenceSystem(srs);
attribute.setX(x);
attribute.setY(y);
attribute.setAltitude(altitude);
attribute.setAccuracy(accuracy);
return true;
} else {
return false;
}
}
@Override
protected void onAttributeChange(UiAttribute attribute) {
super.onAttributeChange(attribute);
// update show map button availability
vh.showMapButton.setEnabled(!attribute.isEmpty());
}
private UiSpatialReferenceSystem selectedSpatialReferenceSystem() {
return (UiSpatialReferenceSystem) vh.srsSpinner.getSelectedItem();
}
private Double toDouble(TextView textView) {
if (textView.getText().toString().isEmpty())
return null;
try {
return numberFormat().parse(textView.getText().toString()).doubleValue();
} catch (ParseException e) {
textView.setError(context.getResources().getString(R.string.message_not_a_number));
}
return null;
}
protected final View toInputView() {
return vh.view;
}
private void requestLocation() {
locationProvider.start();
requestingLocation = true;
Activities.keepScreenOn(context);
}
private void stopLocationRequest() {
locationProvider.stop();
vh.startStopButton.setChecked(false);
requestingLocation = false;
Activities.clearKeepScreenOn(context);
}
private double[] transformToSelectedSrs(Location location) {
double[] coord = new double[]{location.getLongitude(), location.getLatitude()};
UiSpatialReferenceSystem from = UiSpatialReferenceSystem.LAT_LNG_SRS;
UiSpatialReferenceSystem to = selectedSpatialReferenceSystem();
return CoordinateUtils.transform(from, coord, to);
}
private double[] transformToLonLat(double x, double y) {
return CoordinateUtils.transform(selectedSpatialReferenceSystem(),
new double[]{x, y},
UiSpatialReferenceSystem.LAT_LNG_SRS);
}
private NumberFormat numberFormat() {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setGroupingUsed(false);
numberFormat.setMaximumFractionDigits(10);
numberFormat.setMaximumIntegerDigits(Integer.MAX_VALUE);
return numberFormat;
}
@Override
protected void focusOnMessageContainerView() {
if (!(vh.xView.hasFocus() || vh.yView.hasFocus())) {
super.focusOnMessageContainerView();
}
}
private class ViewHolder {
LinearLayout view;
Spinner srsSpinner;
TextView xView;
TextView yView;
TextView altitudeView;
TextView accuracyView;
TextView accuracyViewReadonly;
ToggleButton startStopButton;
Button navigateButton;
Button showMapButton;
ArrayAdapter<UiSpatialReferenceSystem> adapter;
private ViewHolder() {
srsSpinner = createSrsSpinner();
LinearLayout srsLayout = createSrsLayout();
xView = createNumberField(attribute.getX());
yView = createNumberField(attribute.getY());
startStopButton = createStartStopButton();
showMapButton = createShowMapButton();
view = new LinearLayout(context);
view.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
view.setOrientation(LinearLayout.VERTICAL);
view.addView(srsLayout);
view.addView(createFormField("X", xView));
view.addView(createFormField("Y", yView));
if (attribute.getDefinition().includeAltitude) {
altitudeView = createNumberField(attribute.getAltitude());
view.addView(createFormField(getString(R.string.label_altitude), altitudeView));
}
if (attribute.getDefinition().includeAccuracy) {
accuracyView = createNumberField(attribute.getAccuracy());
view.addView(createFormField(getString(R.string.label_accuracy), accuracyView));
} else {
accuracyViewReadonly = new AppCompatTextView(context);
}
view.addView(startStopButton);
if (!attribute.getDefinition().includeAccuracy) {
view.addView(accuracyViewReadonly);
}
RelativeLayout belowBar = new RelativeLayout(context);
RelativeLayout.LayoutParams belowBarLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
belowBarLayoutParams.setMargins(0, Views.px(context, 30), 0, 0);
belowBar.setLayoutParams(belowBarLayoutParams);
view.addView(belowBar);
RelativeLayout.LayoutParams showMapBtnLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
showMapBtnLayoutParams.addRule(RelativeLayout.ALIGN_LEFT, showMapButton.getId());
showMapBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, showMapButton.getId());
belowBar.addView(showMapButton, showMapBtnLayoutParams);
if (attribute.getDefinition().destinationPointSpecified) {
navigateButton = createNavigationButton();
RelativeLayout.LayoutParams navBtnLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
navBtnLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT, navigateButton.getId());
navBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigateButton.getId());
navBtnLayoutParams.addRule(RelativeLayout.RIGHT_OF, showMapButton.getId());
belowBar.addView(navigateButton, navBtnLayoutParams);
}
}
private LinearLayout createFormField(String label, View inputView) {
LinearLayout formField = new LinearLayout(context);
formField.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
TextView labelView = new AppCompatTextView(context);
labelView.setWidth(Views.px(context, 50));
labelView.setText(label);
formField.addView(labelView);
formField.addView(inputView);
return formField;
}
private LinearLayout createSrsLayout() {
TextView srsLabel = new AppCompatTextView(context);
srsLabel.setText(getString(R.string.label_spatial_reference_system) + ":");
LinearLayout srsLine = new LinearLayout(context);
srsLine.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
srsLine.setOrientation(LinearLayout.HORIZONTAL);
srsLine.addView(srsLabel);
srsLine.addView(srsSpinner);
return srsLine;
}
private Spinner createSrsSpinner() {
final Spinner srsSpinner = new AppCompatSpinner(context);
adapter = new ArrayAdapter<UiSpatialReferenceSystem>(context,
android.R.layout.simple_spinner_dropdown_item,
attribute.getDefinition().spatialReferenceSystems);
srsSpinner.setAdapter(adapter);
selectCurrentSrsInSpinner(srsSpinner);
srsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
saveNode();
}
public void onNothingSelected(AdapterView<?> parent) {
saveNode();
}
});
return srsSpinner;
}
private Button createNavigationButton() {
Button button = new AppCompatButton(context);
button.setTextAppearance(context, android.R.style.TextAppearance_Small);
button.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
button.setText(getString(R.string.label_navigate));
button.setCompoundDrawablesWithIntrinsicBounds(
null, new Attrs(context).drawable(R.attr.navigateToLocationIcon), null, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
NavigationDialogFragment.show(context.getSupportFragmentManager());
}
});
return button;
}
private void selectCurrentSrsInSpinner(Spinner srsSpinner) {
UiSpatialReferenceSystem selectedSrs = attribute.getSpatialReferenceSystem();
if (selectedSrs != null) {
int position = attribute.getDefinition().spatialReferenceSystems.indexOf(selectedSrs);
srsSpinner.setSelection(position);
}
}
private TextView createNumberInput(Double value) {
final TextView input = new AppCompatEditText(context);
input.setSingleLine();
if (value != null)
input.setText(formatDouble(value));
input.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_SIGNED | TYPE_NUMBER_FLAG_DECIMAL);
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
saveNode();
}
});
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT)
saveNode();
return false;
}
});
input.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
if (!requestingLocation) {
input.setError(null);
delaySaveNode();
}
}
});
return input;
}
private TextView createNumberOutput(Double value) {
final TextView output = new AppCompatTextView(context);
output.setSingleLine();
if (value != null)
output.setText(formatDouble(value));
output.setInputType(TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_SIGNED | TYPE_NUMBER_FLAG_DECIMAL);
return output;
}
private TextView createNumberField(Double value) {
return attribute.getDefinition().onlyChangedByDevice
? createNumberOutput(value)
: createNumberInput(value);
}
private ToggleButton createStartStopButton() {
ToggleButton button = new ToggleButton(context);
button.setText(getString(R.string.label_start_gps));
button.setTextOn(getString(R.string.label_stop_gps));
button.setTextOff(getString(R.string.label_start_gps));
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
requestLocation();
else {
stopLocationRequest();
saveNode();
}
}
});
return button;
}
private Button createShowMapButton() {
Button button = new AppCompatButton(context);
button.setText(getString(R.string.label_show_map));
button.setGravity(Gravity.RIGHT);
button.setLayoutParams(new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
button.setCompoundDrawablesWithIntrinsicBounds(
null, new Attrs(context).drawable(R.attr.mapIcon), null, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (!attribute.isEmpty()) {
double[] lonLat = transformToLonLat(attribute.getX(), attribute.getY());
double lon = lonLat[0];
double lat = lonLat[1];
String uri = String.format(Locale.ENGLISH,
"geo:%f,%f?z=17&q=%f,%f(%s)", lat, lon, lat, lon, attribute.getDefinition().label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
}
}
});
button.setEnabled(!attribute.isEmpty());
return button;
}
private void updateCoordinate(double[] transformedCoord) {
xView.setText(formatDouble(transformedCoord[0]));
yView.setText(formatDouble(transformedCoord[1]));
}
private String formatDouble(Double value) {
return numberFormat().format(value);
}
private String getString(int resId) {
return context.getResources().getString(resId);
}
}
private class UpdateListener implements LocationProvider.LocationUpdateListener {
private final FragmentActivity context;
UpdateListener(FragmentActivity context) {
this.context = context;
}
public void onUpdate(Location location) {
double accuracy = roundTo2Decimals(location.getAccuracy());
if (attribute.getDefinition().includeAccuracy) {
vh.accuracyView.setText(Double.toString(accuracy));
} else {
vh.accuracyViewReadonly.setText(context.getResources().getString(R.string.label_accuracy) + ": " + accuracy + "m");
}
if (attribute.getDefinition().includeAltitude) {
vh.altitudeView.setText(Double.toString(roundTo2Decimals(location.getAltitude())));
}
double[] transformedCoord = transformToSelectedSrs(location);
vh.updateCoordinate(transformedCoord);
}
private double roundTo2Decimals(double value) {
return Math.round(value * 100.0) / 100.0;
}
}
}
|
openforis/collect-mobile
|
android/src/main/java/org/openforis/collect/android/gui/input/CoordinateAttributeComponent.java
|
Java
|
mit
| 18,793
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Networks</title>
<meta name="description"
content="">
<meta name="author" content="Emily Stamey">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/white.css">
<link rel="stylesheet" href="css/my-style.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="./node_modules/highlight.js/styles/zenburn.css">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<!--<link rel="stylesheet" href="plugin/accessibility/helper.css">-->
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class='footer'>
@elstamey
</div>
<div class="slides">
<div class="slides">
<section>
<header>
<h3 class="title">Networks</h3>
<p>Emily Stamey @elstamey</p>
</header>
<myRowBox>
<article>
<img src="img/networks/forest-trees-fog-foggy.jpg" class="single_right">
</article>
</myRowBox>
</section>
<section>
<myRowBox>
<article>
<myColBox>
<article>
<!--<h3>Emily</h3>-->
<img src="img/me/developer.png" alt="developer">
</article>
<article>
<p>I'm a PHP developer</p>
<p>Co-Organizer of Triangle PHP and Director of WWCode Raleigh/Durham</p>
<p>I work at a company that builds tools for network security threat assessment</p>
</article>
</myColBox>
</article>
<article>
<myColBox>
<article>
<img src="img/inquest.svg">
</article>
<article>
<img src="img/trianglePHP_sm.jpg">
</article>
<article>
<img src="img/wwcode.png">
</article>
</myColBox>
</article>
</myRowBox>
<aside class="notes">
<li>I am Emily. I'm a php developer</li>
<li>I love community, so I help to build them at home.</li>
<li>I work at Inquest, a network security company based in Washington, DC. </li>
<p>We are going to talk about Event Sourcing, but we will begin in a sort of roundabout way because
at State we have been adding Event Sourcing to many of our legacy projects. We have one project
that we are rewriting, and it's a good case study for an older approach with status flags and we are rewriting it to use
event sourcing.</p>
</aside>
</section>
<section>
<myRowBox>
<article>
<img src="img/networks/network_layers.png">
</article>
</myRowBox>
</section>
<section>
<footer>
<img src="img/networks/forest-trees-fog-foggy.jpg" class="single_right">
</footer>
</section>
<section>
<footer>
<img src="img/networks/tree_layers.png" class="single_right">
</footer>
</section>
<section>
<myColBox>
<article>
<img src="img/networks/plant-transportation.jpg" class="single_right">
</article>
</myColBox>
</section>
<section>
<footer>
<img src="img/networks/forest-trees-fog-foggy.jpg" class="single_right">
</footer>
</section>
<section>
<myRowBox>
<article>
<img src="img/networks/network_layers.png">
</article>
</myRowBox>
</section>
<section>
<myRowBox>
<img src="img/networks/OSI_layers.png">
</myRowBox>
</section>
</div>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
history: true,
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'node_modules/highlight.js/lib/highlight.js' },
// { src: 'plugin/accessibility/helper.js', async: true, condition: function() {
// return !!document.body.classList;
// }},
{
src: 'node_modules/reveal-code-focus/reveal-code-focus.js',
async: true,
callback: function() {
RevealCodeFocus();
}
},
{ src: 'plugin/elapsed-time-bar/elapsed-time-bar.js'}
],
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions. Can be
// specified using percentage units.
width: 1280,
height: 720,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.5,
// your allotted time for presentation
allottedTime: 50 * 60 * 1000, // 50 minutes
// - (optional) height of page/time progress bar
progressBarHeight: 3,
// - (optional) bar color
barColor: 'rgb(200,0,0)',
// - (optional) bar color when timer is paused
pausedBarColor: 'rgba(200,0,0,.6)',
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: true,
// Push each slide change to the browser history
history: true,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: false,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding
autoSlideMethod: Reveal.navigateNext,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Transition style
transition: 'none', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'none', // none/fade/slide/convex/concave/zoom
// Number of slides away from the current that are visible
viewDistance: 3,
// Parallax background image
parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px"
// Number of pixels to move the parallax background per slide
// - Calculated automatically unless specified
// - Set to 0 to disable movement along an axis
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
pdfMaxPagesPerSlide: 1,
// Value of the display CSS property applied to current slide to make it visible
display: 'flex',
keyboard: {
// pause/resume time when Enter is pressed
13: () => {
ElapsedTimeBar.isPaused ? ElapsedTimeBar.resume() : ElapsedTimeBar.pause();
},
// reset timer when 'r' is pressed
82: () => {
ElapsedTimeBar.reset();
}
}
})
</script>
</body>
</html>
|
elstamey/elstamey.github.io
|
networks.html
|
HTML
|
mit
| 10,910
|
using Telerik.TestingFramework.Controls.KendoUI;
using Telerik.WebAii.Controls.Html;
using Telerik.WebAii.Controls.Xaml;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ArtOfTest.Common.UnitTesting;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Controls.HtmlControls;
using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts;
using ArtOfTest.WebAii.Design;
using ArtOfTest.WebAii.Design.Execution;
using ArtOfTest.WebAii.ObjectModel;
using ArtOfTest.WebAii.Silverlight;
using ArtOfTest.WebAii.Silverlight.UI;
namespace MonkeyTests
{
public enum SearchOptionModel
{
ByXPath = 1,
}
}
|
VitalyaKvas/MonkeyHelper
|
MonkeyTests/MonkeyHelper/Code/SearchOptionModel.tstest.cs
|
C#
|
mit
| 654
|
---
layout: post
title: "Gsoc at Libreoffice : Week 1"
date: 2016-05-30 18:06:23
categories: [gsoc]
tags: [gsoc]
---
So the first week has finally concluded. It was a week of balancing. Balancing between my exams and my project. I promised myself that I would focus on my exams and start my work from 7th . I ended up breaking the promise I made to myself.
So the summary of the week is that I have Implemented Code for border Import. It hasn't been merged into the master not because the code wasn't working or I was just too lazy to do the work but because I had done some coding style mistakes like sandwitching operator between 2 tokens (eg: if (a==b)) . Multipple rejections by the code-reviewer to merge my code has left me very happy. Im a happy because I learnt something which I would have never learnt by myself. These are the things that neither competitive programming teaches you nor your proffessor.
Writing Code is like writing an essay. You have to be very clear with your thought and convey your thought with that much clarity to the reader. There were times when choosing a variable name seemed difficult task. I dedicated alot of time to things like these (which otherwise seem trivial) but would help someone else understand the source code.
I still have some exams left So would continue with the rest of the work from 7th June. I would go for number formatting and cell protection in the coming week. Thanks for reading. Have a nice day(or night).
|
jvsg/joke
|
_posts/2016-05-31-Week-1-Libo.markdown
|
Markdown
|
mit
| 1,479
|
---
layout: default
permalink: /long/index.html
length: long
---
<div class="grid grid-pad">
<div class="post">
{% for post in site.posts %}
{% if post.length contains 'long' %}
<div class="col-1-3 ">
<a class="tile_link" href="{{ site.baseurl }}{{ post.url }}" >
<div class="tile">
<h2><img src class="tool_icon" src="{{ site.baseurl }}/images/{{ post.icon }}">{{ post.title }}</h2>
<div class="category">{{ post.tags }} <span class="os_icon" style="display:{{ post.gnu }};"><i class="fa fa-linux"></i></span>
<span class="os_icon" style="display:{{ post.mac }};"> <i class="fa fa-apple"></i></span>
<span class="os_icon" style="display:{{ post.win }};"><i class="fa fa-windows"></i></span></div>
<br>
<p>{{ post.des }}</p>
</div>
</a>
</div>
{% endif %}{% endfor %}
</div>
|
mooniak/colombore
|
long.html
|
HTML
|
mit
| 1,081
|
#pragma once
#include <utility>
#include <archie/container/ring_iterator.hpp>
#include <archie/meta/model_of.hpp>
namespace archie {
template <typename Container>
struct ring_adapter {
private:
struct is_valid_container {
template <typename C>
auto requires(C) -> decltype(std::declval<C const>().begin(),
std::declval<C const>().end(),
std::declval<C const>().size(),
std::declval<C const>().capacity());
};
struct can_emplace {
template <typename C, typename... Args>
auto requires(C, Args...) -> decltype(std::declval<C>().emplace_back(std::declval<Args>()...),
typename C::value_type{std::declval<Args>()...});
};
static_assert(meta::model_of<is_valid_container(Container)>::value == true, "");
public:
using value_type = typename Container::value_type;
using size_type = typename Container::size_type;
using difference_type = typename Container::difference_type;
using iterator = ring_iterator<typename Container::iterator>;
using const_iterator = ring_iterator<typename Container::const_iterator>;
template <typename... Args>
explicit ring_adapter(Args&&... args)
: container_(std::forward<Args>(args)...), pos_(container_, 0) {}
iterator begin() { return pos_; }
const_iterator begin() const { return iterator{container_, 0}; }
iterator end() { return begin() + size(); }
const_iterator end() const { return begin() + size(); }
size_type size() const { return container_.size(); }
size_type capacity() const { return container_.capacity(); }
bool empty() const { return size() == 0; }
template <typename... Args>
void emplace_back(Args&&... args) {
static_assert(meta::model_of<can_emplace(Container, Args...)>::value, "");
if (size() != capacity()) {
container_.emplace_back(std::forward<Args>(args)...);
pos_ = iterator{container_, 0};
} else { *pos_++ = std::move(value_type{std::forward<Args>(args)...}); }
}
Container* operator->() { return &container_; }
Container const* operator->() const { return &container_; }
Container& operator*() { return container_; }
Container const& operator*() const { return container_; }
private:
Container container_;
iterator pos_;
};
}
|
attugit/sandbox
|
inc/archie/container/ring_adapter.hpp
|
C++
|
mit
| 2,334
|
<div>
<form ng-submit="todoCtrl.update()">
<label>
Title
<input type="text" ng-model="todoCtrl.todo.title"
placeholder="Input task">
</label>
<label>
Completed
<input type="checkbox" ng-model="todoCtrl.todo.completed">
</label>
<input type="submit" value="Update">
</form>
</div>
|
melihovv/todos-laravel-angularjs
|
resources/assets/templates/tasks/show.html
|
HTML
|
mit
| 343
|
import { randomInt32 } from '@provably-fair/core';
/**
* Shuffles an array based on the given seeds, using the given HMAC algorithm.
* @param {[]} arr Array to be shuffled.
* @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair.
* @param {string|Buffer} secretSeed Secret seed used as HMAC key.
* @param {string|Buffer} [publicSeed] Public seed used as HMAC data. To prove fairness of random
* outputs, the hash of `secretSeed` shall be known before revealing `publicSeed`.
* @param {function} [hmacBufferUIntParser] Function to be used for parsing a UInt from the
* generated HMAC buffer.
* @param {function} [fallbackProvider] Function to provide a fallback value in a given range
* whether no appropriate number can be parsed from the generated HMAC buffer.
* @returns {[]} A new array instance containing every element of the input.
*/
export const shuffle = (
arr,
hmacAlgorithm,
secretSeed,
publicSeed,
hmacBufferUIntParser,
fallbackProvider,
) => {
const result = [...arr];
for (let i = arr.length - 1; i > 0; i -= 1) {
// Generate a random integer within [0, i]
const j = randomInt32(
hmacAlgorithm,
secretSeed,
`${publicSeed}-${i}`,
0,
i + 1,
hmacBufferUIntParser,
fallbackProvider,
);
// Exchange `result[i]` and `result[j]`
[result[i], result[j]] = [result[j], result[i]];
}
return result;
};
export default shuffle;
|
kripod/provably-fair
|
packages/shuffle/src/index.js
|
JavaScript
|
mit
| 1,465
|
from difflib import get_close_matches
from thefuck.utils import sudo_support, get_all_executables, get_closest
@sudo_support
def match(command, settings):
return 'not found' in command.stderr and \
bool(get_close_matches(command.script.split(' ')[0],
get_all_executables()))
@sudo_support
def get_new_command(command, settings):
old_command = command.script.split(' ')[0]
new_command = get_closest(old_command, get_all_executables())
return ' '.join([new_command] + command.script.split(' ')[1:])
priority = 3000
|
mbbill/thefuck
|
thefuck/rules/no_command.py
|
Python
|
mit
| 580
|
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login.component';
import { LoggedInGuard } from './logged-in.guard';
import { TransactionComponent } from './transaction.component';
import { TransactionDetailComponent } from './transaction-detail.component';
import { DashboardComponent } from './dashboard.component';
import { AccountComponent } from './accounts.component';
const appRoutes: Routes = [
{
path: 'transactions',
component: TransactionComponent,
canActivate: [LoggedInGuard]
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [LoggedInGuard]
},
{
path: 'accounts',
component: AccountComponent,
canActivate: [LoggedInGuard]
},
{
path: 'login',
component: LoginComponent
},
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'detail/:id',
component: TransactionDetailComponent
},
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
|
dmkent/cattrack-client
|
src/client/app/app.routing.ts
|
TypeScript
|
mit
| 1,182
|
package ninja.academy.vertx.market.seller.alternative.endpoint;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import ninja.academy.vertx.market.seller.alternative.storage.GeneratedShapesStorage;
import javax.inject.Inject;
public class ShapeIdConfirmationEndpoint {
private static final String CHANNEL_SHAPE_ID_CHECK = "espeo.vertx.workshop.shape_id_confirmation";
@Inject
private EventBus eventBus;
@Inject
private GeneratedShapesStorage shapesStorage;
public void init(){
eventBus.consumer(CHANNEL_SHAPE_ID_CHECK, this::checkShapeIdValidity);
}
private void checkShapeIdValidity(Message<Object> message) {
shapesStorage.shapePresent(message.body().toString(), event
-> message.reply(Boolean.toString(event.booleanValue())));
}
}
|
espeo/shape-market-factory
|
src/main/java/ninja/academy/vertx/market/seller/alternative/endpoint/ShapeIdConfirmationEndpoint.java
|
Java
|
mit
| 842
|
@extends('layouts.default', ['nav_login' => 'active'])
@section('content')
<div class="auth-form-container">
<form role="form" method="POST" action="{{ url('/password/reset') }}">
{!! csrf_field() !!}
<input type="hidden" name="token" value="{{ $token }}">
<p>
<label>E-Mail Address</label>
<input type="email" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<div class='flash-error'>
{{ $errors->first('email') }}
</div>
@endif
</p>
<p>
<label>New Password</label>
<input type="password" name="password">
@if ($errors->has('password'))
<div class='flash-error'>
{{ $errors->first('password') }}
</div>
@endif
</p>
<p>
<label>Confirm New Password</label>
<input type="password" name="password_confirmation">
</p>
<p>
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</p>
</form>
</div>
@endsection
|
njovin/mapil-web
|
resources/views/auth/passwords/reset.blade.php
|
PHP
|
mit
| 1,237
|
{% from 'macro/__frame__.html' import base_menu_navigation %}
{% set article_navigation = [{'href':'article', 'caption':'Article'},
{'href':'new-article', 'caption':'New Article'},
{'href':'source', 'caption':'Source'},
{'href':'category', 'caption':'Category'},
{'href':'keyword', 'caption':'Keyword'}] %}
{% macro article_menu_navigation(current_active_item) %}
{{base_menu_navigation('Article Manage', article_navigation, current_active_item)}}
{% endmacro %}
|
DreamWFJ/Everyeye
|
app/templates/macro/__article__.html
|
HTML
|
mit
| 549
|
\input{/Users/Claudius/Documents/PhD/THESIS/kks32/LaTeX/Appendix1/sRADprotocol/sRADprotocol}
\input{/Users/Claudius/Documents/PhD/THESIS/kks32/LaTeX/Appendix1/RAD_double_dig_protocol}
|
claudiuskerth/PhDthesis
|
Appendix1/appendix1.tex
|
TeX
|
mit
| 184
|
package cu.rst.alg;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.log4j.Logger;
import cu.rst.graph.*;
import Jama.Matrix;
/**
* This version of ET takes a rep graph and outputs a rep graph
* @author partheinstein
*
*/
public class EigenTrustPart1 implements AlgorithmIntf
{
private double[][] cijMatrix;
private Hashtable<Integer, Integer> agentIdmapping;
static Logger logger = Logger.getLogger(EigenTrustPart1.class.getName());
public EigenTrustPart1()
{
this.agentIdmapping = new Hashtable<Integer, Integer>();
}
public Graph execute(Graph g) throws Exception
{
if(!(g instanceof FHG))
{
throw new Exception("Input graph must be a FHG.");
}
FHG fhg = (FHG) g;
int numVertices = fhg.vertexSet().size();
cijMatrix = new double[numVertices][numVertices];
Set<Agent> agents = fhg.vertexSet();
int internalId=0;
this.agentIdmapping.clear();
for(Agent a : agents)
{
this.agentIdmapping.put(a.id, internalId);
internalId++;
}
for(Agent source : agents)
{
Set<FeedbackHistoryGraphEdge> allOutgoingEdges = fhg.outgoingEdgesOf(source);
//fill up cij matrix
for(FeedbackHistoryGraphEdge edge : allOutgoingEdges)
{
ArrayList<Feedback> feedbacks = edge.feedbacks;
double sij=0;
for(Feedback feedback : feedbacks)
{
// if(feedback.value >= threshold2Satisfy) sij++;
// else sij--;
if(feedback.value == 1) sij++;
else sij--;
}
if(sij<1) sij=0;
Agent sinkTemp = (Agent)edge.sink;
if(this.agentIdmapping.get(source.id) > cijMatrix.length || this.agentIdmapping.get(sinkTemp.id) > cijMatrix.length)
throw new Exception("Array out of bounds exception will occur. Problem with internal id mapping.");
cijMatrix[this.agentIdmapping.get(source.id)][this.agentIdmapping.get(sinkTemp.id)] = sij;
}
}
logger.info("cijMatrix before normalization = " + this.printMatrix(cijMatrix));
//normalize cij matrix
for(int i=0;i<numVertices;i++)
{
//row by row normalization
double total = 0;
for(int j=0;j<numVertices;j++)
{
total = total + cijMatrix[i][j];
}
for(int j=0;j<numVertices;j++)
{
if(total>0) cijMatrix[i][j] = cijMatrix[i][j] / total;
//else cijMatrix[i][j]=0; //don't divide by 0
//agent i doesnt trust anyone. make it trust everyone equally.
else cijMatrix[i][j]=1.0/(double)numVertices;
}
}
logger.info("cijMatrix after normalization = " + this.printMatrix(cijMatrix));
Matrix trustScores = new Matrix(cijMatrix);
RG outputGraph = new RG();
//create all the reputation edges that needs to be added to RG. Its a complete graph
for(Agent src : (Set<Agent>)fhg.vertexSet())
{
for(Agent sink : (Set<Agent>)fhg.vertexSet())
{
double rep = trustScores.getArray()[this.agentIdmapping.get(src.id)][this.agentIdmapping.get(sink.id)];
outputGraph.addEdge(src, sink, rep);
}
}
return outputGraph;
}
public String printMatrix(double[][] mat)
{
String output = "\n";
output += "Internal id mapping:";
Set<Entry<Integer, Integer>> temp = this.agentIdmapping.entrySet();
for(Entry<Integer, Integer> e : temp)
{
output += "Agent.id: " + e.getKey() + ", Internal id: " + e.getValue() + "\n";
}
for(int i=0;i<mat.length;i++)
{
for(int j=0;j<mat[i].length;j++)
{
output = output + (mat[i][j] + " ");
}
output = output + "\n";
}
return output;
}
}
|
tahalukmanji/reputationsystestbed
|
src/main/java/cu/rst/alg/EigenTrustPart1.java
|
Java
|
mit
| 3,529
|
#include "utils.h"
// void timer_config(void){
// }
void delay(uint16_t period_ms){
struct tcc_config tcc_cfg;
tcc_get_config_defaults(&tcc_cfg, TCC1);
tcc_cfg.counter.clock_prescaler = TCC_CLOCK_PRESCALER_DIV8; // 8MHz
tcc_init(&tcc_instance, TCC1, &tcc_cfg);
tcc_enable(&tcc_instance);
uint32_t t;
do{
t = tcc_get_count_value(&tcc_instance)/1000;
} while (t < period_ms);
tcc_reset(&tcc_instance);
}
|
dalmago/embarcados
|
rgb_game_d21/rgb_game_d21/src/utils.c
|
C
|
mit
| 468
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SedcServer
{
public enum RequestKind
{
Action,
File,
Error,
}
public class RequestParser
{
public string RequestString { get; private set; }
public List<Header> Headers { get; private set; }
public string Method { get; private set; }
public string PathString { get; private set; }
public string Parameter { get; private set; }
public string Action { get; private set; }
public RequestKind Kind { get; private set; }
public string Extension { get; private set; }
public string FileName { get; private set; }
public RequestParser(string requestString)
{
RequestString = requestString;
Kind = RequestKind.Error;
//parsing the request string
Parse();
}
private void Parse()
{
var lines = RequestString.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0)
return;
Headers = new List<Header>();
for (int i = 1; i < lines.Length; i++)
{
Regex headerRegex = new Regex(@"^([a-zA-Z\-]*):\s(.*)$");
var match = headerRegex.Match(lines[i]);
Header header = new Header
{
Name = match.Groups[1].Value,
Value = match.Groups[2].Value,
};
Headers.Add(header);
}
ParseMethod(lines[0]);
}
private void ParseMethod(string methodLine)
{
//GET /asdfsdaf HTTP/1.1
Regex methodRegex = new Regex(@"^([A-Z]*)\s(\/.*) HTTP\/1.1$");
var match = methodRegex.Match(methodLine);
Method = match.Groups[1].Value;
PathString = match.Groups[2].Value;
ParsePathString();
}
private void ParsePathString()
{
Regex patRegex = new Regex(@"^\/([a-zA-Z-]*)\/?([a-zA-Z0-9-]*)$");
var match = patRegex.Match(PathString);
if (match.Success)
{
Kind = RequestKind.Action;
Action = match.Groups[1].Value;
Parameter = match.Groups[2].Value;
return;
}
patRegex = new Regex(@"^\/(\w+).(\w+)$");
match = patRegex.Match(PathString);
if (match.Success)
{
Kind = RequestKind.File;
FileName = string.Format("{0}.{1}", match.Groups[1].Value, match.Groups[2].Value);
Extension = match.Groups[2].Value;
return;
}
Kind = RequestKind.Error;
}
}
}
|
sweko/SEDC-DataServer
|
DataServer/SedcServer.Core/RequestParser.cs
|
C#
|
mit
| 2,911
|
@defstruct ChannelPoolingLayer Layer (
name :: String = "channel-pooling",
(bottoms :: Vector{Symbol} = Symbol[], length(bottoms) > 0),
(tops :: Vector{Symbol} = Symbol[], length(tops) == length(bottoms)),
(kernel :: Int = 1, kernel > 0),
(stride :: Int = 1, stride > 0),
(pad :: NTuple{2, Int} = (0,0), all([pad...] .>= 0)),
(channel_dim :: Int = -2, channel_dim != 0),
pooling :: PoolingFunction = Pooling.Max(),
)
@characterize_layer(ChannelPoolingLayer,
can_do_bp => true,
)
type ChannelPoolingLayerState <: LayerState
layer :: ChannelPoolingLayer
blobs :: Vector{Blob}
blobs_diff :: Vector{Blob}
op_dims :: Vector{Int}
etc :: Any
end
function setup_etc(backend::CPUBackend, layer::ChannelPoolingLayer, inputs, blobs)
if isa(layer.pooling, Pooling.Max)
masks = Array(Array, length(inputs))
for i = 1:length(inputs)
masks[i] = Array(Csize_t, size(blobs[i]))
end
etc = masks
elseif isa(layer.pooling, Pooling.Mean)
integrals = Array(Array, length(inputs))
for i = 1:length(inputs)
integrals[i] = Array(eltype(inputs[i]), size(inputs[i])[1:end-1])
end
etc = integrals
else
etc = nothing
end
return etc
end
function setup(backend::Backend, layer::ChannelPoolingLayer, inputs::Vector{Blob}, diffs::Vector{Blob})
pooled_chann_all = Array(Int, length(inputs))
blobs = Array(Blob, length(inputs))
blobs_diff = Array(Blob, length(inputs))
op_dims = Array(Int, length(inputs))
for i = 1:length(inputs)
dim_total = ndims(inputs[i])
op_dim = layer.channel_dim < 0 ? layer.channel_dim + dim_total+1 : layer.channel_dim
@assert 1 <= op_dim <= dim_total
@assert op_dim != dim_total
op_dims[i] = op_dim
dims = [size(inputs[i])...]
pool_dim = dims[op_dim]
pooled_dim = int(ceil(float(pool_dim + layer.pad[1]+layer.pad[2] - layer.kernel) / layer.stride)) + 1
# make sure the last pooling is not purely pooling padded area
if ((pooled_dim-1)*layer.stride >= pool_dim + layer.pad[1])
pooled_dim -= 1
end
pooled_chann_all[i] = pooled_dim
output_dims = copy(dims)
output_dims[op_dim] = pooled_dim
output_dims = tuple(output_dims...)
data_type = eltype(inputs[i])
blobs[i] = make_blob(backend, data_type, output_dims)
if isa(diffs[i], NullBlob)
blobs_diff[i] = NullBlob()
else
blobs_diff[i] = make_blob(backend, data_type, output_dims)
end
end
etc = setup_etc(backend, layer, inputs, blobs)
state = ChannelPoolingLayerState(layer, blobs, blobs_diff, op_dims, etc)
end
function shutdown_etc(backend::CPUBackend, state::ChannelPoolingLayerState)
end
function shutdown(backend::Backend, state::ChannelPoolingLayerState)
map(destroy, state.blobs)
map(destroy, state.blobs_diff)
shutdown_etc(backend, state)
end
function forward(backend::CPUBackend, state::ChannelPoolingLayerState, inputs::Vector{Blob})
forward(backend, state.layer.pooling, state, inputs)
end
function forward(backend::CPUBackend, pool::StdPoolingFunction,
state::ChannelPoolingLayerState, inputs::Vector{Blob})
for i = 1:length(inputs)
input = inputs[i].data
output = state.blobs[i].data
dims_in = split_dims(input, state.op_dims[i])
dims_out = split_dims(output, state.op_dims[i])
if isa(pool, Pooling.Max)
max_channel_pooling_forward(reshape(input,dims_in), reshape(output,dims_out), reshape(state.etc[i],dims_out), state.layer)
elseif isa(pool, Pooling.Mean)
mean_channel_pooling_forward(reshape(input,dims_in), reshape(output,dims_out), state.etc[i], state.layer)
end
end
end
function backward(backend::CPUBackend, state::ChannelPoolingLayerState, inputs::Vector{Blob}, diffs::Vector{Blob})
backward(backend, state.layer.pooling, state, inputs, diffs)
end
function backward(backend::CPUBackend, pool::StdPoolingFunction, state::ChannelPoolingLayerState,
inputs::Vector{Blob}, diffs::Vector{Blob})
for i = 1:length(inputs)
diff = diffs[i]
if !isa(diff, NullBlob)
dims_in = split_dims(inputs[i], state.op_dims[i])
dims_out = split_dims(state.blobs[i], state.op_dims[i])
if isa(pool, Pooling.Max)
max_channel_pooling_backward(reshape(diff.data,dims_in), reshape(state.blobs_diff[i].data,dims_out),
reshape(state.etc[i],dims_out), state.layer)
elseif isa(pool, Pooling.Mean)
mean_channel_pooling_backward(reshape(diff.data,dims_in), reshape(state.blobs_diff[i].data,dims_out), state.layer)
end
end
end
end
|
rened/Mocha.jl
|
src/layers/channel-pooling.jl
|
Julia
|
mit
| 4,529
|
/// =======================================================================
/// Class Definitions {messageName}
/// =======================================================================
class {messageName}Message : public ProtoIO
{{
public:
{messageName}Message();
~{messageName}Message(){{
if (has_decoded_data_){{
pb_release({messageName}_fields, &data);
}}
}};
bool Encode();
bool Decode(const uint8_t* buffer, unsigned int number_of_bytes);
static int GetType() {{return {messageType};}};
{messageName} data;
}};
|
ioants/pypi-packages
|
ioant/ioant/proto/templates/message_class.template.h
|
C
|
mit
| 646
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
/**
*
* @author Bram Gadeyne
*/
public class MorseCoder extends ICoder {
HashMap<Character, String> morsemap;
HashMap<String,Character> inversemap;
public MorseCoder()
{
morsemap=new HashMap<Character, String>();
inversemap=new HashMap<String, Character>();
initMorseMap();
}
private void initMorseMap()
{
morsemap.clear();
morsemap.put('a',".-");
morsemap.put('b',"-...");
morsemap.put('c',"-.-.");
morsemap.put('d',"-..");
morsemap.put('e',".");
morsemap.put('f',"..-.");
morsemap.put('g',"--.");
morsemap.put('h',"....");
morsemap.put('i',"..");
morsemap.put('j',".---");
morsemap.put('k',"-.-");
morsemap.put('l',".-..");
morsemap.put('m',"--");
morsemap.put('n',"-.");
morsemap.put('o',"---");
morsemap.put('p',".--.");
morsemap.put('q',"--.-");
morsemap.put('r',".-.");
morsemap.put('s',"...");
morsemap.put('t',"-");
morsemap.put('u',"..-");
morsemap.put('v',"...-");
morsemap.put('w',".--");
morsemap.put('x',"-..-");
morsemap.put('y',"-.--");
morsemap.put('z',"--..");
morsemap.put('0',"-----");
morsemap.put('1',".----");
morsemap.put('2',"..---");
morsemap.put('3',"...--");
morsemap.put('4',"....-");
morsemap.put('5',".....");
morsemap.put('6',"-....");
morsemap.put('7',"--...");
morsemap.put('8',"---..");
morsemap.put('9',"----.");
Iterator<Entry<Character,String> > it=morsemap.entrySet().iterator();
while(it.hasNext())
{
Entry<Character,String> entry=it.next();
inversemap.put(entry.getValue(), entry.getKey());
}
}
public String code(String s) {
char[] arr=s.toLowerCase().toCharArray();
String coded="";
for(int i=0;i<arr.length;i++)
{
if(morsemap.containsKey(arr[i]))
{
coded+=morsemap.get(arr[i])+"/";
}else{
coded+=arr[i]+"/";
}
}
return coded;
}
@Override
public String decode(String d) {
String[] arr=d.split("/");
String coded="";
for(int i=0;i<arr.length;i++)
{
if(inversemap.containsKey(arr[i]))
{
coded+=inversemap.get(arr[i]);
}else{
coded+=arr[i];
}
}
return coded;
}
}
|
gadeynebram/voetjeonline
|
tvoetje/src/model/MorseCoder.java
|
Java
|
mit
| 2,793
|
require 'mida/vocabulary'
module Mida
module SchemaOrg
autoload :Thing, 'mida/vocabularies/schemaorg/thing'
autoload :Event, 'mida/vocabularies/schemaorg/event'
# Event type: A social dance.
class DanceEvent < Mida::Vocabulary
itemtype %r{http://schema.org/DanceEvent}i
include_vocabulary Mida::SchemaOrg::Thing
include_vocabulary Mida::SchemaOrg::Event
end
end
end
|
LawrenceWoodman/mida
|
lib/mida/vocabularies/schemaorg/danceevent.rb
|
Ruby
|
mit
| 412
|
#!/usr/bin/env python
# File created on 09 Aug 2012
from __future__ import division
__author__ = "Jon Sanders"
__copyright__ = "Copyright 2014, Jon Sanders"
__credits__ = ["Jon Sanders"]
__license__ = "GPL"
__version__ = "1.9.1"
__maintainer__ = "Jon Sanders"
__email__ = "jonsan@gmail.com"
__status__ = "Development"
from qiime.util import load_qiime_config, parse_command_line_parameters,\
get_options_lookup, make_option
from qiime.parse import parse_qiime_parameters, parse_taxonomy, parse_mapping_file_to_dict
from qiime.filter import sample_ids_from_metadata_description
from bfillings.uclust import get_clusters_from_fasta_filepath
from bfillings.usearch import usearch_qf
from scipy.stats import spearmanr
import os.path
from biom import load_table
import numpy as np
options_lookup = get_options_lookup()
script_info = {}
script_info['brief_description'] = """
A script to filter sequences by potential contaminants"""
script_info['script_description'] = """
This script performs a series of filtering steps on a sequence file with the
intent of removing contaminant sequences. It requires input of an OTU table, a
sample map, an OTU map, a sequence FASTA file, and an output directory.
There are two primary approaches the script can take: (1) comparing sequence
abundances in blank control sequence libraries to those in sample libraries,
where sequences present in blanks are presumed to be contaminants, and (2)
comparing sequences in sample libraries to a database of known contaminants.
In approach (1), OTUs (or unique sequences, if OTU table and map are defined at
100% identity) are tested for their maximum and mean presence in blank and
sample libraries, and excluded if they satisfy the given criteria. For example,
if you want to exclude any sequences whose maximum abundance in a blank sample
is more than 10% the maximum abundance in a sample (maxB > 0.1 * maxS), you
would choose '--removal_stat_blank maxB --removal_stat_sample maxS
--removal_differential 0.1'. For this approach, you must also provide a column
in your mapping file that indicates which samples to use as blanks, and pass
this information to the script with the 'valid states' option (e.g.
'Blank:True')
In approach (2), you must provide a fasta library of putative contaminants.
These may be previously clustered OTUs from the blank samples, commonly
sequenced contaminants (if known), or another fasta file. Sequences will be
clustered against this fasta file using Uclust-Ref, and any that match within
a given percent similarity (using the '-c' or '--contaminant_similarity' option)
will be marked as putative contaminants.
When using approach (2), it is possible to remove 'real' sequences from samples
that just happen to be similar to contaminants. This may be detectable when
using unique sequence OTU tables/maps as input, if the 'real' sequences are
nonetheless slightly different from contaminants. In this case, it may be
desireable to reinstate those unique sequences that are present in samples but
not in blanks. You may do this using criteria of relative abundance (similar to
approach [1], where a sequence is reinstated if its max presence in a sample is
greater than its max presence in a blank, i.e. maxS > X * maxB) or of incidence
in non-blank samples (i.e. reinstated if present in two or more samples). If
both criteria are provided, you must choose to reinstate either the intersection
of the criteria (i.e. BOTH more abundant in samples AND present in 2 or more)
or the union (i.e. EITHER more abundant in samples OR present in 2 or more).
"""
script_info['script_usage'] = []
script_info['script_usage'].append(("""Example:""", """
The following steps are performed by the command below:
1. Calculate max relative abundance of each sequence in samples and blanks
2. Identify sequences whose maximum abunance in blanks is more than 10% their
maximum abundance in samples.
3. Output OTU maps of sequences for which above is true, and for which above is
false.
""", """
decontaminate.py -i unique_seqs_otu_table.biom -o filter_out_dir
-m metadata_mapping_file.txt -f unique_seqs_rep_set.fna
-M unique_seqs_otus.txt -s 'Blank:True' --removal_stat_blank maxB
--removal_stat_sample maxS --removal_differential 0.1
"""))
script_info['output_description'] = """
This script will output a tab-delimited summary table, indicating the relative
abundance stats for each sequence considered, along with its fate at each step
of the process.
It will also output an OTU map for each category of sequences identified (e.g.
those never identified as contaminants, those identified as reference-based
contaminants, those identified as abundance-based contaminants, and those
reinstated). These OTU maps can then be used to filter in the input FASTA file.
Output file naming:
contamination_summary.txt -- tab-delimited per-sequence summary file
assed_otu_map.txt -- OTU map of non-contaminant sequences
ref_contaminants_otu_map.txt -- OTU map of reference contaminant sequences
abund_contaminants_otu_map.txt -- OTU map of abundance contaminant sequences
reinstated_contaminants_otu_map.txt -- OTU map of reinstated sequences
"""
script_info['required_options'] = [
options_lookup["output_dir"]
]
script_info['optional_options'] = [
options_lookup["otu_table_as_primary_input"],
make_option('--mothur_counts_fp',
type='existing_filepath',
help='path to mothur counts table as input'),
options_lookup["mapping_fp"],
make_option('-M', '--otu_map_fp', type="existing_filepath",
help='the input OTU map file'),
make_option('-s',
'--valid_states', type='string',
help="Column header:value pair in mapping file identifying blank samples"),
make_option('--blank_id_fp',
type='existing_filepath',
help='path to file listing blank sample ids'),
options_lookup["input_fasta"],
make_option('--contaminant_db_fp', type="existing_filepath",
help='A FASTA file of potential contaminant sequences'),
make_option('-c', '--contaminant_similarity', type='float', default=0.97,
help=('Sequence similarity threshold for contaminant matches')),
make_option('-r', '--max_correlation', type='float',
help=('Maximum Spearman correlation for contaminant identification')),
make_option('--correlate_header', type='string',
help=('Column header in mapping file with correlation data')),
make_option('--min_relabund_threshold', type="float",
help='discard sequences below this relative abundance threshold'),
make_option('--prescreen_threshold', type="float",
help='prescreen libraries that lose more than this proportion of sequences'),
make_option('--removal_stat_blank', type="choice", choices=["maxB", "avgB"],
help='blank statistic to be used for removal (maxB, avgB)'),
make_option('--removal_stat_sample', type="choice", choices=["maxS", "avgS"],
help='sample statistic to be used for removal (maxS, avgS)'),
make_option('--removal_differential', type="float",
help='differential proportion for removal (maxB > X * maxS)'),
make_option('--reinstatement_stat_blank', type="choice", choices=["maxB", "avgB"],
help='blank statistic to be used for reinstatement (maxB, avgB)'),
make_option('--reinstatement_stat_sample', type="choice", choices=["maxS", "avgS"],
help='sample statistic to be used for reinstatement (maxS, avgS)'),
make_option('--reinstatement_differential', type="float",
help='differential proportion for reinstatement (maxS > X * maxB)'),
make_option('--reinstatement_sample_number', type="int",
help='minimum number of samples necessary for reinstatement'),
make_option('--reinstatement_method', type="choice", choices=["union", "intersection"],
help='method to rectify reinstatement criteria'),
make_option('--drop_lib_threshold', type="float",
help='read loss threshold to drop libraries from output table'),
make_option('--write_filtered_output', action="store_true",
help='write an output table filtered of contaminants'),
make_option('--write_per_library_stats', action="store_true",
help='write a per-library decontamination summary'),
make_option('--write_per_seq_stats', action="store_true",
help='write a per-sequence decontamination summary'),
make_option('--write_per_seq_disposition', action="store_true",
help='write a per-sequence disposition file'),
make_option('--write_output_seq_lists', action="store_true",
help='write separate sequence name lists for each contaminant category')
]
script_info['version'] = __version__
def pick_ref_contaminants(queries, ref_db_fp, input_fasta_fp, contaminant_similarity, output_dir):
# Blast against contaminant DB
clusters, failures, seeds = get_clusters_from_fasta_filepath(
input_fasta_fp,
input_fasta_fp,
percent_ID=contaminant_similarity,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
output_dir=output_dir,
enable_rev_strand_matching=False,
subject_fasta_filepath=ref_db_fp,
suppress_new_clusters=True,
return_cluster_maps=True,
stable_sort=False,
save_uc_files=True,
HALT_EXEC=False)
# Pick seqs that fail the similarity to contaminants rule
ref_contaminants = set(queries) - set(failures)
return(ref_contaminants)
def pick_corr_contaminants(sample_biom,
corr_data_dict,
max_r):
# Filter biom to only samples for which correlate data available
sample_biom_filt = sample_biom.filter(
lambda val, id_, metadata: id_ in corr_data_dict,
invert=False,
inplace=False)
otus = sample_biom_filt.ids(axis='observation')
samples = sample_biom_filt.ids(axis='sample')
# Make array of correlate data in same order as biom file
correlate = [corr_data_dict[x] for x in samples]
obs_corr_dict = {}
# Make a 2D array of normalized biom table values
norm_array = sample_biom_filt.norm(inplace=False).matrix_data.toarray()
t = 0
for otu in otus:
obs_corr_dict[otu] = spearmanr(norm_array[t], correlate)
t += 1
# get keys (otu names) for OTUs with less than minimum correlation
obs_corr_contaminants = [x for x in obs_corr_dict if obs_corr_dict[x][0] < max_r]
return(set(obs_corr_contaminants), obs_corr_dict)
def reinstate_abund_seqs(putative_contaminants,
contamination_stats_dict,
contamination_stats_header,
reinstatement_stat_sample,
reinstatement_stat_blank,
reinstatement_differential):
abund_reinstated_seqs = compare_blank_abundances(contamination_stats_dict,
contamination_stats_header,
reinstatement_stat_sample,
reinstatement_stat_blank,
reinstatement_differential,
negate=False)
# Only consider seqs as reinstated if previously identified as contaminants
abund_reinstated_seqs = set(putative_contaminants) & set(abund_reinstated_seqs)
return(abund_reinstated_seqs)
def reinstate_incidence_seqs(putative_contaminants,
unique_seq_biom,
blank_sample_ids,
reinstatement_sample_number):
sample_biom = unique_seq_biom.filter(lambda val, id_, metadata:
id_ in blank_sample_ids, invert=True, inplace=False)
incidence_reinstated_seqs = sample_biom.pa().filter(
lambda val, id_, metadata: val.sum() >= reinstatement_sample_number,
axis='observation', inplace=False).ids(
axis='observation')
# Only consider seqs as reinstated if previously identified as contaminants
incidence_reinstated_seqs = set(putative_contaminants) & set(incidence_reinstated_seqs)
return(incidence_reinstated_seqs)
def mothur_counts_to_biom(mothur_fp):
mothur_biom = load_table(mothur_fp)
mothur_biom.type = u'OTU table'
filter_biom = mothur_biom.filter(
lambda val, id_, metadata: id_ in 'total', invert=True)
return(filter_biom)
def biom_to_mothur_counts(biom_obj):
sample_ids = biom_obj.ids(axis='sample')
otu_ids = biom_obj.ids(axis='observation')
otu_totals = biom_obj.sum(axis='observation')
outstring = 'Representative_Sequence\ttotal\t' + '\t'.join(sample_ids) + '\n'
for otu in otu_ids:
otu_data = biom_obj.data(id = otu, axis = 'observation')
outstring += '{0}\t{1}\t{2}\n'.format(otu,
int(otu_data.sum()),
'\t'.join(str(x) for x in otu_data.astype('int')))
return(outstring)
def prescreen_libraries(unique_seq_biom,
blank_sample_ids,
removal_stat_sample,
removal_stat_blank,
removal_differential,
prescreen_threshold):
contamination_stats_header, contamination_stats_dict = \
get_contamination_stats(unique_seq_biom, blank_sample_ids)
abund_contaminants = compare_blank_abundances(contamination_stats_dict,
contamination_stats_header,
removal_stat_sample,
removal_stat_blank,
removal_differential,
negate=True)
# make relabund table
norm_biom = unique_seq_biom.norm(inplace = False)
# filter out sequences marked as contaminants
norm_biom.filter(lambda val, id_, metadata: id_ in abund_contaminants,
axis='observation', invert=True, inplace=True)
# filter out samples above threshold
norm_biom.filter(lambda val, id_, metadata: sum(val) > prescreen_threshold,
axis='sample', invert=False, inplace=True)
# Now only have samples failing the prescreening
above_threshold_samples = norm_biom.ids(axis='sample')
return above_threshold_samples
def get_contamination_stats(biom_file, blank_sample_ids=None, exp_sample_ids=[], proportional=False):
if not proportional:
biom_file = biom_file.norm(inplace=False)
header = ['maxS','avgS']
# Calculate blank stats if blank sample names are provided
if blank_sample_ids:
blanks = True
blank_data = biom_file.filter(blank_sample_ids, axis='sample',
invert=False, inplace=False).matrix_data
maxB = blank_data.max(axis=1).todense().tolist()
avgB = blank_data.mean(axis=1).tolist()
header.append('maxB')
header.append('avgB')
else:
# Otherwise, set the 'blanks' to an empty list
blank_sample_ids = []
blanks = False
# If specific list of experimental sample IDs aren't provided,
# assume everything not marked blank is an experimental sample
if len(exp_sample_ids) == 0:
exp_sample_ids = set(biom_file.ids(axis='sample')) - set(blank_sample_ids)
sample_data = biom_file.filter(exp_sample_ids, axis='sample',
invert=False, inplace=False).matrix_data
maxS = sample_data.max(axis=1).todense().tolist()
avgS = sample_data.mean(axis=1).tolist()
stats_dict = {}
i = 0
if blanks:
for otu in biom_file.ids(axis='observation'):
stats_dict[otu] = [maxS[i][0], avgS[i][0], maxB[i][0], avgB[i][0]]
i += 1
else:
for otu in biom_file.ids(axis='observation'):
stats_dict[otu] = [maxS[i][0], avgS[i][0]]
i += 1
return(header, stats_dict)
def pick_min_relabund_threshold(stats_dict, stats_header, min_relabund, sample_stat='maxS'):
i_s = stats_header.index(sample_stat)
passed_otus = set()
for otu in stats_dict:
if(float(stats_dict[otu][i_s]) < float(min_relabund)):
passed_otus.add(otu)
return(passed_otus)
def compare_blank_abundances(stats_dict, stats_header,
sample_stat, blank_stat, scalar=1, negate=False):
"""Note that this method will default to returning sequences for which
the criteria sample_stat > blank_stat * scalar are TRUE, i.e. non-contam
sequences. To return contaminants (sequences that FAIL the inequality),
set negate to True."""
i_s = stats_header.index(sample_stat)
i_b = stats_header.index(blank_stat)
passed_otus = set()
for otu in stats_dict:
if((float(stats_dict[otu][i_s]) > (float(scalar) * float(stats_dict[otu][i_b]))) != negate):
passed_otus.add(otu)
# print passed_otus
return(passed_otus)
def calc_per_category_decontam_stats(biom_obj, filter_otus):
reads = biom_obj.filter(lambda val, id_, metadata: id_ in filter_otus,
axis='observation', invert=False, inplace=False).sum(axis = 'sample')
otus = biom_obj.pa(inplace = False).filter(lambda val, id_, metadata: id_ in filter_otus,
axis='observation', invert=False, inplace=False).sum(axis = 'sample')
return(reads.tolist(),otus.tolist())
def calc_per_library_decontam_stats(start_biom, output_dict):
# calculate starting number of sequences and unique sequences per library
steps = ['below_relabund_threshold','putative_contaminants','ever_good_seqs','reinstated_seqs','all_good_seqs']
results_dict = {}
results_dict['starting'] = calc_per_category_decontam_stats(start_biom, start_biom.ids(axis='observation'))
results_header = ['starting']
for step in steps:
if step in output_dict:
results_dict[step] = calc_per_category_decontam_stats(start_biom, output_dict[step])
results_header.append(step)
return(results_dict, results_header)
def filter_contaminated_libraries(unique_seq_biom, contaminant_otus, contam_threshold):
# make relabund table
norm_biom = unique_seq_biom.norm(inplace = False)
# filter out sequences marked as contaminants
norm_biom.filter(lambda val, id_, metadata: id_ in contaminant_otus,
axis='observation', invert=True, inplace=True)
# filter out samples above threshold
norm_biom.filter(lambda val, id_, metadata: sum(val) > contam_threshold,
axis='sample', invert=False, inplace=True)
# filter contam sequences from original biom
filtered_biom = unique_seq_biom.filter(lambda val, id_, metadata: id_ in contaminant_otus,
axis='observation', invert=True, inplace=False)
# filter samples that lost too much relative to starting from original biom
filtered_biom = filtered_biom.filter(lambda val, id_, metadata: id_ in norm_biom.ids(axis='sample'),
axis='sample', invert=False, inplace=True)
return(filtered_biom)
def print_filtered_otu_map(input_otu_map_fp, output_otu_map_fp, filter_set):
output_otu_map_f = open(output_otu_map_fp, 'w')
for line in open(input_otu_map_fp, 'U'):
seq_identifier = line.strip().split('\t')[0]
# write OTU line if present in the filter set
if seq_identifier in filter_set:
output_otu_map_f.write(line)
output_otu_map_f.close()
return
def print_filtered_mothur_counts(mothur_counts_fp, output_counts_fp, filter_set):
output_counts_f = open(output_counts_fp, 'w')
t = 0
for line in open(mothur_counts_fp, 'U'):
seq_identifier = line.strip().split('\t')[0]
# only write this line if the otu has more than n sequences (so
# greater than n tab-separated fields including the otu identifier)
# or if it's the header (first) line
if seq_identifier in filter_set or t == 0:
output_counts_f.write(line)
t += 1
output_counts_f.close()
return
def print_per_library_stats(per_library_stats, per_library_stats_header, lib_ids, dropped_libs=[]):
outline = 'Library\t'
outline += '_reads\t'.join(per_library_stats_header) + '_reads\t'
outline += '_otus\t'.join(per_library_stats_header) + '_otus'
if len(dropped_libs) > 0:
outline += '\tlibrary_discarded'
discard = True
else:
discard = False
outline += '\n'
t = 0
for lib in lib_ids:
outline += lib
for category in per_library_stats_header:
outline += '\t' + str(int(per_library_stats[category][0][t]))
for category in per_library_stats_header:
outline += '\t' + str(int(per_library_stats[category][1][t]))
if discard:
if lib in dropped_libs:
outline += '\tTrue'
else:
outline += '\tFalse'
outline += '\n'
t += 1
return(outline)
def print_otu_disposition(input_seqs, output_dict, hierarchy=[]):
outline = ''
if hierarchy == []:
hierarchy = ['below_relabund_threshold', 'putative_contaminants','reinstated_seqs','ever_good_seqs']
# Subset hierarchy to levels also in output dict:
hierarchy = [x for x in hierarchy if x in output_dict]
# Check that the levels of the hierarchy are non-overlapping:
for x in range(len(hierarchy) - 1):
for y in range(x + 1,len(hierarchy)):
if not output_dict[hierarchy[x]].isdisjoint(output_dict[hierarchy[y]]):
print('warning: non-disjoint sets in the disposition hierarchy')
seqs_left = set(input_seqs)
for seq in input_seqs:
for level in hierarchy:
if seq in output_dict[level]:
outline += '{0}\t{1}\n'.format(seq,level)
break
return(outline)
def print_filtered_seq_headers(seq_headers, output_headers_fp, filter_set):
output_headers_f = open(output_headers_fp, 'w')
for x in seq_headers:
if x in filter_set:
output_headers_f.write('{0}\n'.format(x))
output_headers_f.close()
return
def print_filtered_output(output_method, unfiltered_input, output_dir, output_dict, output_categories=None):
output_fn = 'print_filtered_' + output_method
if not output_categories:
output_categories = output_dict.keys()
if output_method == 'seq_headers':
output_fn = print_filtered_seq_headers
elif output_method == 'mothur_counts':
output_fn = print_filtered_mothur_counts
elif output_method == 'otu_map':
output_fn = print_filtered_otu_map
for category in output_categories:
output_fn(unfiltered_input,
os.path.join(output_dir,
'{0}_{1}.txt'.format(category, output_method)),
output_dict[category])
return
def print_results_file(seq_ids,
output_dict,
output_fp,
stats_header=None,
stats_dict=None,
corr_data_dict=None):
output_f = open(output_fp, 'w')
header = "SeqID"
sorted_categories = sorted(output_dict.keys())
for category in sorted_categories:
header += '\t{0}'.format(category)
if stats_header:
for x in stats_header:
header += '\t{0}'.format(x)
if corr_data_dict:
header += '\t{0}\t{1}'.format('spearman_r','spearman_p')
output_f.write(header + '\n')
for otu in seq_ids:
outline = str(otu)
for category in sorted_categories:
outline += '\t{0}'.format(1 if otu in output_dict[category] else 0)
if stats_header:
t = 0
for x in stats_header:
outline += '\t{0:.3f}'.format(stats_dict[otu][t])
t += 1
if corr_data_dict:
outline += '\t{0:.3f}\t{1:.3f}'.format(
corr_data_dict[otu][0],
corr_data_dict[otu][1])
output_f.write(outline + '\n')
return
def main():
option_parser, opts, args = parse_command_line_parameters(**script_info)
otu_table_fp = opts.otu_table_fp
mothur_counts_fp = opts.mothur_counts_fp
mapping_fp = opts.mapping_fp
valid_states = opts.valid_states
blank_id_fp = opts.blank_id_fp
contaminant_db_fp = opts.contaminant_db_fp
contaminant_similarity = opts.contaminant_similarity
max_correlation = opts.max_correlation
correlate_header = opts.correlate_header
input_fasta_fp = opts.input_fasta_fp
otu_map_fp = opts.otu_map_fp
output_dir = opts.output_dir
min_relabund_threshold = opts.min_relabund_threshold
prescreen_threshold = opts.prescreen_threshold
removal_stat_blank = opts.removal_stat_blank
removal_stat_sample = opts.removal_stat_sample
removal_differential = opts.removal_differential
reinstatement_stat_sample = opts.reinstatement_stat_sample
reinstatement_stat_blank = opts.reinstatement_stat_blank
reinstatement_differential = opts.reinstatement_differential
reinstatement_sample_number = opts.reinstatement_sample_number
reinstatement_method = opts.reinstatement_method
write_output_seq_lists = opts.write_output_seq_lists
write_filtered_output = opts.write_filtered_output
drop_lib_threshold = opts.drop_lib_threshold
write_per_seq_stats = opts.write_per_seq_stats
write_per_library_stats = opts.write_per_library_stats
write_per_seq_disposition = opts.write_per_seq_disposition
# Make unique seq OTU table (biom file)
# Compute unique seq stats
# output biom file with unique seq stats
# Optionally: make candidate contaminant DB
# remove sequences present at higher abundance in samples
# cluster blanks
# remove low-abundance contaminant OTUs
# Filter by similarity against candidate contaminant DB
# annotate unique seq OTU table with top hit (OTU#, rep seq, ID%)
# make list of seqs @ threshold
# Calculate reinstatement rule for filtered sequences
# Generate lists of seqs failing:
# - unique seq rule
# - hit to contaminant
# - reinstatement after hit
# Make sure passed at least one of an OTU biom or mothur counts table file
input_file_counter = 0
if mothur_counts_fp:
input_file_counter += 1
unique_seq_biom = mothur_counts_to_biom(mothur_counts_fp)
mothur_output = True
print "mothur input"
if otu_table_fp:
input_file_counter += 1
unique_seq_biom = load_table(otu_table_fp)
mothur_output = False
print "BIOM input"
if input_file_counter != 1:
option_parser.error("must provide ONLY ONE of an OTU table biom file or"
"mothur counts table")
# Check to make sure that if blank-based contamination filtering requested,
# all necessary options are specified:
removal_options_counter = 0
if removal_stat_blank:
removal_options_counter += 1
if removal_stat_sample:
removal_options_counter += 1
if removal_differential:
removal_options_counter += 1
if ((removal_options_counter > 0) and (removal_options_counter < 3)):
option_parser.error("Must provide all of "
"removal_stats_blank, "
"removal_stat_sample, and "
"removal_differential, or none.")
elif removal_options_counter == 0:
blank_stats_removal = False
elif removal_options_counter == 3:
blank_stats_removal = True
# If reference-based filtering requested, make sure all necessary options
# have been specified:
if contaminant_db_fp and not input_fasta_fp:
option_parser.error("If specifying ref-based contaminant ID, must "
"also specify path to input sequence fasta")
# If correlation-based filtering requested, make sure correlate data
# are specified
if max_correlation and not correlate_header:
option_parser.error("If specifying maximum Spearman correlation, must "
"also provide map column header for correlate data")
# If sequence reinstatement is requested, make sure all necessary options
# are specified
reinstatement_options_counter = 0
if reinstatement_stat_blank:
reinstatement_options_counter += 1
if reinstatement_stat_sample:
reinstatement_options_counter += 1
if reinstatement_differential:
reinstatement_options_counter += 1
if ((reinstatement_options_counter > 0) and
(reinstatement_options_counter < 3)):
option_parser.error("Must provide all of "
"reinstatement_stats_blank, "
"reinstatement_stat_sample, and "
"reinstatement_differential, or none.")
if ((reinstatement_options_counter == 3 and reinstatement_sample_number)
and not reinstatement_method):
option_parser.error("If providing sample number AND abundance criteria "
"for sequence reinstatement, must also provide "
"a method for combining results.")
if reinstatement_options_counter == 3 or reinstatement_sample_number:
reinstatement = True
else:
reinstatement = False
# get blank sample IDs from mapping file or sample ID list
if mapping_fp and valid_states:
blank_sample_ids = sample_ids_from_metadata_description(
open(mapping_fp, 'U'), valid_states)
blanks = True
elif blank_id_fp is not None:
blank_id_f = open(blank_id_fp, 'Ur')
blank_sample_ids = set([line.strip().split()[0]
for line in blank_id_f
if not line.startswith('#')])
blank_id_f.close()
blanks = True
else:
blanks = False
# Initialize output objets
output_dict = {}
contaminant_types = []
contamination_stats_dict = None
contamination_stats_header = None
corr_data_dict = None
# Do blank-based stats calculations, if not there check to make sure no
# blank-dependent methods are requested:
if blanks:
if prescreen_threshold:
low_contam_libraries = prescreen_libraries(unique_seq_biom,
blank_sample_ids,
removal_stat_sample,
removal_stat_blank,
removal_differential,
prescreen_threshold)
contamination_stats_header, contamination_stats_dict = \
get_contamination_stats(unique_seq_biom,
blank_sample_ids,
exp_sample_ids=low_contam_libraries)
else:
contamination_stats_header, contamination_stats_dict = \
get_contamination_stats(unique_seq_biom, blank_sample_ids)
elif (blank_stats_removal or reinstatement or prescreen_threshold):
option_parser.error("Blank-based filtering requested but no blank"
"samples indicated in mapping file or ID file.")
else:
contamination_stats_header, contamination_stats_dict = \
get_contamination_stats(unique_seq_biom)
seq_ids = unique_seq_biom.ids(axis='observation')
# Do blank-based contaminant identification
if min_relabund_threshold:
output_dict['below_relabund_threshold'] = pick_min_relabund_threshold(
contamination_stats_dict,
contamination_stats_header,
min_relabund_threshold)
if blank_stats_removal:
output_dict['abund_contaminants'] = compare_blank_abundances(contamination_stats_dict,
contamination_stats_header,
removal_stat_sample,
removal_stat_blank,
removal_differential,
negate=True)
contaminant_types.append('abund_contaminants')
# Do reference-based contaminant identification
if contaminant_db_fp:
output_dict['ref_contaminants'] = pick_ref_contaminants(seq_ids, contaminant_db_fp, input_fasta_fp, contaminant_similarity, output_dir)
contaminant_types.append('ref_contaminants')
# Do spearman correlation based contaminant identification
if max_correlation:
metadata_dict = parse_mapping_file_to_dict(open(mapping_fp, 'U'))[0]
corr_data_dict = {x: float(metadata_dict[x][correlate_header]) for x in metadata_dict}
output_dict['corr_contaminants'], corr_contaminant_dict = pick_corr_contaminants(unique_seq_biom,
corr_data_dict,
max_correlation)
contaminant_types.append('corr_contaminants')
else:
corr_contaminant_dict = None
# Putative contaminants are those that have been identified by any method
output_dict['putative_contaminants'] = set.union(*map(set, [output_dict[x] for x in contaminant_types]))
# If considering low abundance sequences, remove those from consideration as potential contaminants
if 'below_relabund_threshold' in output_dict:
output_dict['putative_contaminants'] = output_dict['putative_contaminants'] - set(output_dict['below_relabund_threshold'])
# Pick abundance-criterion seqs to reinstate
if (reinstatement_stat_blank and reinstatement_stat_sample and reinstatement_differential):
output_dict['abund_reinstated_seqs'] = reinstate_abund_seqs(output_dict['putative_contaminants'],
contamination_stats_dict,
contamination_stats_header,
reinstatement_stat_sample,
reinstatement_stat_blank,
reinstatement_differential)
output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs']
# Pick incidence-criterion seqs to reinstate
if reinstatement_sample_number:
output_dict['incidence_reinstated_seqs'] = reinstate_incidence_seqs(
output_dict['putative_contaminants'],
unique_seq_biom,
blank_sample_ids,
reinstatement_sample_number)
output_dict['reinstated_seqs'] = output_dict['incidence_reinstated_seqs']
# combine incidence and abundance reinstatements
if reinstatement_sample_number and reinstatement_stat_blank:
if reinstatement_method == "union":
output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs'] | output_dict['incidence_reinstated_seqs']
elif reinstatement_method == "intersection":
output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs'] & output_dict['incidence_reinstated_seqs']
# make sets for sequence _never_ identified as contaminants:
output_dict['ever_good_seqs'] = set(seq_ids) - output_dict['putative_contaminants']
# If considering low abundance sequences, remove those from consideration as potential contaminants
if 'below_relabund_threshold' in output_dict:
output_dict['ever_good_seqs'] = output_dict['ever_good_seqs'] - set(output_dict['below_relabund_threshold'])
# Make set of good seqs for final filtering
final_good_seqs = output_dict['ever_good_seqs']
# ...and those either never ID'd as contaminants or reinstated:
if reinstatement:
output_dict['all_good_seqs'] = set(output_dict['ever_good_seqs'] | output_dict['reinstated_seqs'])
final_good_seqs = output_dict['all_good_seqs']
# ...and those who remain contaminants after reinstatement:
output_dict['never_good_seqs'] = set(output_dict['putative_contaminants'] - output_dict['reinstated_seqs'])
# print filtered OTU maps if given a QIIME OTU map input
if otu_map_fp:
print_filtered_output('otu_map', otu_map_fp, output_dir, output_dict)
# print filtered Mothur counts tables if given a Mothur counts table input
if mothur_output:
print_filtered_output('mothur_counts', mothur_counts_fp, output_dir, output_dict)
# print filtered seq header files if requested
if write_output_seq_lists:
print_filtered_output('seq_headers', seq_ids, output_dir, output_dict)
# filter final biom file to just good seqs
filtered_biom = unique_seq_biom.filter(lambda val, id_, metadata: id_ in final_good_seqs,
axis='observation', invert=False, inplace=False)
# drop heavily contaminated libraries if requested
if drop_lib_threshold:
dropped_libs = unique_seq_biom.norm(inplace=False).filter(lambda val, id_, metadata: id_ in final_good_seqs,
axis='observation', invert=False, inplace=False).filter(lambda val, id_, metadata: sum(val) >= drop_lib_threshold,
axis='sample', invert=True, inplace=False).ids(axis='sample')
filtered_biom.filter(lambda val, id_, metadata: id_ in dropped_libs,
axis='sample', invert=True, inplace=True)
else:
dropped_libs = []
# print filtered biom/mothur_output if library filtering is requested
if write_filtered_output:
if mothur_output:
output_counts_string = biom_to_mothur_counts(filtered_biom)
with open(os.path.join(output_dir,'decontaminated_table.counts'), "w") as output_counts_file:
output_counts_file.write(output_counts_string)
else:
output_biom_string = filtered_biom.to_json('Filtered by decontaminate.py')
output_biom_string
with open(os.path.join(output_dir,'decontaminated_otu_table.biom'), "w") as output_biom_file:
output_biom_file.write(output_biom_string)
# print per-library stats if requested
if write_per_library_stats:
per_library_stats, per_library_stats_header = calc_per_library_decontam_stats(unique_seq_biom, output_dict)
library_stats_string = print_per_library_stats(per_library_stats, per_library_stats_header, unique_seq_biom.ids(axis='sample'), dropped_libs=dropped_libs)
with open(os.path.join(output_dir,'decontamination_per_library_stats.txt'), "w") as output_stats_file:
output_stats_file.write(library_stats_string)
# print otu by disposition file if requested
if write_per_seq_disposition:
per_seq_disposition = print_otu_disposition(seq_ids, output_dict)
with open(os.path.join(output_dir,'decontamination_per_otu_disposition.txt'), "w") as output_stats_file:
output_stats_file.write(per_seq_disposition)
# print log file / per-seq info
if write_per_seq_stats:
print_results_file(seq_ids,
output_dict,
os.path.join(output_dir,'contamination_summary.txt'),
contamination_stats_header,
contamination_stats_dict,
corr_contaminant_dict)
if __name__ == "__main__":
main()
|
tanaes/decontaminate
|
decontaminate_unitary.py
|
Python
|
mit
| 40,011
|
<?php
namespace PUGX\Godfather;
interface StrategistInterface
{
/**
* Add a strategy into the container.
*
* @param string $contextName the serviceId of the context
* @param string $contextKey the key
* @param string $strategyServiceId the service to obtain
*
* @return
*/
public function addStrategy($contextName, $contextKey, $strategyServiceId);
/**
* Given the object and a context, get the correct strategy service from the container.
*
* @param $contextName
* @param $object
*
* @return mixed the service
*/
public function getStrategy($contextName, $object);
}
|
PUGX/godfather
|
lib/PUGX/Godfather/StrategistInterface.php
|
PHP
|
mit
| 676
|
"""
Load the CCGOIS datasets into a CKAN instance
"""
import dc
import json
import slugify
import ffs
def make_name_from_title(title):
# For some reason, we're finding duplicate names
name = slugify.slugify(title).lower()[:99]
if not name.startswith('ccgois-'):
name = u"ccgois-{}".format(name)
return name
def load_ccgois(datasets):
for metadata in datasets:
resources = [
dict(
description=r['description'],
name=r['name'],
format=r['filetype'],
url=r['url']
)
for r in metadata['resources']
]
print [r['name'] for r in metadata['resources']]
metadata['title'] = u'CCGOIS - {}'.format(metadata['title'])
metadata['name'] = make_name_from_title(metadata['title'])
print u'Creating {}'.format(metadata['name'])
dc.Dataset.create_or_update(
name=metadata['name'],
title=metadata['title'],
state='active',
license_id='uk-ogl',
notes=metadata['description'],
origin='https://indicators.ic.nhs.uk/webview/',
tags=dc.tags(*metadata['keyword(s)']),
resources=resources,
#frequency=[metadata['frequency'], ],
owner_org='hscic',
extras=[
dict(key='frequency', value=metadata.get('frequency', '')),
dict(key='coverage_start_date', value=metadata['coverage_start_date']),
dict(key='coverage_end_date', value=metadata['coverage_end_date']),
dict(key='domain', value=metadata['domain']),
dict(key='origin', value='HSCIC'),
dict(key='next_version_due', value=metadata['next version due']),
dict(key='nhs_OF_indicators', value=metadata['nhs_of_indicators']),
dict(key='HSCIC_unique_id', value=metadata['unique identifier']),
dict(key='homepage', value=metadata['homepage']),
dict(key='status', value=metadata['status']),
dict(key='language', value=metadata['language']),
dict(key='assurance_level', value=metadata['assurance_level']),
dict(key='release_date', value=metadata['current version uploaded'])
]
)
return
def group_ccgois(datasets):
for metadata in datasets:
dataset_name = make_name_from_title(metadata['title'])
try:
dataset = dc.ckan.action.package_show(id=dataset_name)
except:
print "Failed to find dataset: {}".format(dataset_name)
print "Can't add to group"
continue
if [g for g in dataset.get('groups', []) if g['name'] == 'ccgois']:
print 'Already in group', g['name']
else:
dc.ckan.action.member_create(
id='ccgois',
object=dataset_name,
object_type='package',
capacity='member'
)
return
def main(workspace):
DATA_DIR = ffs.Path(workspace)
datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))
dc.ensure_publisher('hscic')
dc.ensure_group('ccgois')
load_ccgois(datasets)
group_ccgois(datasets)
|
nhsengland/publish-o-matic
|
datasets/ccgois/load.py
|
Python
|
mit
| 3,287
|
package macaca.client.common;
public enum Keycode implements CharSequence {
NULL('\uE000'),
CANCEL('\uE001'),
HELP('\uE002'),
BACK_SPACE('\uE003'),
TAB('\uE004'),
CLEAR('\uE005'),
RETURN('\uE006'),
ENTER('\uE007'), SHIFT('\uE008'),
CONTROL('\uE009'), ALT('\uE00A'),
PAUSE('\uE00B'),
ESCAPE('\uE00C'),
SPACE('\uE00D'),
PAGE_UP('\uE00E'),
PAGE_DOWN('\uE00F'),
END('\uE010'),
HOME('\uE011'), ARROW_LEFT('\uE012'),
ARROW_UP('\uE013'),
ARROW_RIGHT('\uE014'),
ARROW_DOWN('\uE015'),
INSERT('\uE016'),
DELETE('\uE017'),
SEMICOLON('\uE018'),
EQUALS('\uE019'),
// Number pad keys
NUMPAD0('\uE01A'),
NUMPAD1('\uE01B'),
NUMPAD2('\uE01C'),
NUMPAD3('\uE01D'),
NUMPAD4('\uE01E'),
NUMPAD5('\uE01F'),
NUMPAD6('\uE020'),
NUMPAD7('\uE021'),
NUMPAD8('\uE022'),
NUMPAD9('\uE023'),
MULTIPLY('\uE024'),
ADD('\uE025'),
SEPARATOR('\uE026'),
SUBTRACT('\uE027'),
DECIMAL('\uE028'),
DIVIDE('\uE029'),
// Function keys
F1('\uE031'),
F2('\uE032'),
F3('\uE033'),
F4('\uE034'),
F5('\uE035'),
F6('\uE036'),
F7('\uE037'),
F8('\uE038'),
F9('\uE039'),
F10('\uE03A'),
F11('\uE03B'),
F12('\uE03C'),
META('\uE03D'),
COMMAND(Keycode.META),
ZENKAKU_HANKAKU('\uE040');
private final char keyCode;
Keycode(Keycode key) {
this(key.charAt(0));
}
Keycode(char keyCode) {
this.keyCode = keyCode;
}
public char charAt(int index) {
if (index == 0) {
return keyCode;
}
return 0;
}
public int length() {
return 1;
}
public CharSequence subSequence(int start, int end) {
if (start == 0 && end == 1) {
return String.valueOf(keyCode);
}
throw new IndexOutOfBoundsException();
}
@Override
public String toString() {
return String.valueOf(keyCode);
}
public static Keycode getKeyFromUnicode(char key) {
for (Keycode unicodeKey : values()) {
if (unicodeKey.charAt(0) == key) {
return unicodeKey;
}
}
return null;
}
}
|
Yinxl/wd.java
|
src/main/java/macaca/client/common/Keycode.java
|
Java
|
mit
| 1,891
|
package PJC.hash;
import PJC.map.hashMap.HashFunctions;
import PJC.map.hashMap.TPrimitiveHash;
abstract public class TDoubleIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of #k#s */
public transient double[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected double no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**object used to synchronize the methods used in put*/
//private Object objectPut = new Object();
/**
* Creates a new <code>TIntHash</code> instance with the default
* capacity and load factor.
*/
public TDoubleIntHash() {
super();
no_entry_key = (double) 0;
no_entry_value = (int) 0;
}
/**
* Creates a new <code>TIntHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TDoubleIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = (double) 0;
no_entry_value = (int) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TDoubleIntHash (int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
no_entry_key = (double) 0;
no_entry_value = (int) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TDoubleIntHash( int initialCapacity, float loadFactor,
double no_entry_key, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns true if the map contains a mapping for the specified key
* @param key the key whose presence in this map is to be tested
* @return true if this map contains a mapping for the specified key
*/
public boolean contains (double key) {
return index(key) >= 0;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the key that represents null
*/
public double getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt (int index) {
_set[index] = no_entry_key;
super.removeAt (index);
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp (int initialCapacity) {
int capacity;
capacity = super.setUp(initialCapacity);
_set = new double[capacity];
return capacity;
}
/**
* Locates the index of <tt>value</tt>.
*
* @param key an <code>byte</code> value
* @return the index of <tt>value</tt> or -1 if it isn't in the set.
*/
protected int index (double key) {
int hash, index, length;
final byte[] states = _states;
final double[] set = _set;
length = states.length;
hash = HashFunctions.hash(key) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed (key, index, hash, state);
}
int indexRehashed (double key, int index, int hash, byte state) {
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
if (state == FREE)
return -1;
if (key == _set[index] && state != REMOVED)
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>value</tt> can be inserted. if
* there is already a value equal()ing <tt>value</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>byte</code> value
* @return an <code>int</code> value
*/
protected int insertKeyPar (double key) {
int hash, index = 0;
hash = HashFunctions.hash(key) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
synchronized ((Object)this._states[index]) {
//synchronized ((Object) (_set[index])) {
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, key);
return index;
}
}
if (state == FULL && _set[index] == key) {
return -index - 1;
}
return insertKeyRehash(key, index, hash, state);
}
protected int insertKeyParAll (double key) {
int hash, index = 0;
hash = HashFunctions.hash(key) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
//consumeFreeSlot = false;
/**synchronized ((Object)this._states[index]) {
//synchronized ((Object) (_set[index])) {
if (state == FREE) {
//consumeFreeSlot = true;
insertKeyAt(index, val);
//System.out.println ("Posición " + index + " : " + val + " " + _set[index]);
return index; // empty, all done
}
}*/
boolean empty = false;
//synchronized ((Object)this._states[index]) {
if (state == FREE) {
empty = true;
_states[index] = FULL;
}
//}
if (empty) {
_set[index] = key;
return index;
}
if (state == FULL && _set[index] == key) {
return -index - 1;
}
return insertKeyRehash(key, index, hash, state);
}
protected int insertKey (double key) {
int hash, index;
hash = HashFunctions.hash(key) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, key);
return index;
}
if (state == FULL && _set[index] == key) {
return -index - 1;
}
return insertKeyRehash2(key, index, hash, state);
}
int insertKeyRehash(double key, int index, int hash, byte state) {
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
synchronized ((Object)this._states[index]) {
if (state == REMOVED && (!this.contains(key))) {
insertKeyAt (index, key);
return index;
}
}
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
synchronized ((Object)this._states[index]) {
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt (index,key);
return index;
}
}
/**if ((state == FREE) && (firstRemoved != -1)) {
insertKeyAt (firstRemoved, val);
return firstRemoved;
}*/
/** if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}*/
if (state == FULL && _set[index] == key) {
//unreserves the position of the first removed
_states[firstRemoved] = REMOVED;
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, key);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
int insertKeyRehash2(double key, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, key);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, key);
return index;
}
}
if (state == FULL && _set[index] == key) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, key);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, double key) {
_set[index] = key; // insert value
_states[index] = FULL;
}
protected int XinsertKey (double key ) {
int hash, probe, index, length;
final byte[] states = _states;
final double[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
else if ( state == FULL && set[index] == key ) {
return -index -1;
}
else {
probe = 1 + ( hash % ( length - 2 ) );
if ( state != REMOVED ) {
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
/**public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
}*/
/** {@inheritDoc} */
/**public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
}*/
} // TByteIntHash
|
mariaacha/PJC
|
hash/TDoubleIntHash.java
|
Java
|
mit
| 15,844
|
using System;
using Leak.Common;
using Leak.Events;
using Leak.Extensions;
using Leak.Networking.Core;
using Leak.Peer.Coordinator.Core;
using Leak.Peer.Receiver.Events;
namespace Leak.Peer.Coordinator
{
public class CoordinatorService
{
private readonly CoordinatorContext context;
public CoordinatorService(CoordinatorParameters parameters, CoordinatorDependencies dependencies, CoordinatorHooks hooks, CoordinatorConfiguration configuration)
{
context = new CoordinatorContext(parameters, dependencies, hooks, configuration);
}
public FileHash Hash
{
get { return context.Parameters.Hash; }
}
public CoordinatorParameters Parameters
{
get { return context.Parameters; }
}
public CoordinatorDependencies Dependencies
{
get { return context.Dependencies; }
}
public CoordinatorHooks Hooks
{
get { return context.Hooks; }
}
public CoordinatorConfiguration Configuration
{
get { return context.Configuration; }
}
public void Start()
{
context.Facts.Install(context.Configuration.Plugins);
context.Dependencies.Pipeline.Register(TimeSpan.FromSeconds(15), OnTick);
}
private void OnTick()
{
foreach (CoordinatorEntry entry in context.Collection.All())
{
context.Hooks.SendKeepAlive(entry.Peer);
}
}
public void Connect(NetworkConnection connection, Handshake handshake)
{
CoordinatorEntry entry = context.Collection.Add(connection, handshake);
if (entry != null)
{
entry.More = new MoreContainer();
entry.Extensions = handshake.Options.HasFlag(HandshakeOptions.Extended);
context.Hooks.CallPeerConnected(entry.Peer, connection);
SendBitfieldIfNeeded(entry);
SendActiveHandshakeWithExtensionsIfNeeded(entry);
}
else
{
connection.Terminate();
}
}
private void SendBitfieldIfNeeded(CoordinatorEntry entry)
{
if (context.Configuration.AnnounceBitfield && context.Facts.Bitfield != null)
{
context.Hooks.SendBitfield(entry.Peer, context.Facts.Bitfield);
}
}
private void SendActiveHandshakeWithExtensionsIfNeeded(CoordinatorEntry entry)
{
bool supportExtensions = entry.Extensions;
bool isOutgoing = entry.Direction == NetworkDirection.Outgoing;
if (supportExtensions && isOutgoing)
{
context.Hooks.SendExtended(entry.Peer, context.Facts.GetHandshake());
context.Hooks.CallExtensionListSent(entry.Peer, context.Facts.GetExtensions());
}
}
public void Disconnect(NetworkConnection connection)
{
CoordinatorEntry entry = context.Collection.Remove(connection);
if (entry != null)
{
context.Hooks.CallPeerDisconnected(entry.Peer, entry.Remote);
}
}
public void Handle(MetafileVerified data)
{
context.Facts.Handle(data);
}
public void Handle(DataVerified data)
{
context.Facts.Handle(data);
}
public void Choke(PeerHash peer, bool value)
{
CoordinatorEntry entry = context.Collection.Find(peer);
if (entry != null)
{
context.Hooks.SendChoke(entry.Peer, value);
entry.State.IsLocalChokingRemote = value;
context.Hooks.CallStatusChanged(entry.Peer, entry.State);
}
}
public void Interested(PeerHash peer)
{
CoordinatorEntry entry = context.Collection.Find(peer);
if (entry != null)
{
context.Hooks.SendInterested(entry.Peer);
entry.State.IsLocalInterestedInRemote = true;
context.Hooks.CallStatusChanged(entry.Peer, entry.State);
}
}
public void SendRequest(PeerHash peer, BlockIndex block)
{
CoordinatorEntry entry = context.Collection.Find(peer);
Request request = new Request(block);
if (entry != null)
{
context.Hooks.SendRequest(entry.Peer, request);
}
}
public void SendPiece(PeerHash peer, BlockIndex block, DataBlock payload)
{
CoordinatorEntry entry = context.Collection.Find(peer);
Piece piece = new Piece(block, payload);
if (entry != null)
{
context.Hooks.SendPiece(entry.Peer, piece);
}
}
public void SendHave(PeerHash peer, int piece)
{
CoordinatorEntry entry = context.Collection.Find(peer);
if (entry != null)
{
context.Hooks.SendHave(entry.Peer, new PieceInfo(piece));
}
}
public void SendExtension(PeerHash peer, string extension, byte[] payload)
{
CoordinatorEntry entry = context.Collection.Find(peer);
if (entry != null)
{
byte identifier = entry.More.Translate(extension);
Extended extended = new Extended(identifier, payload);
MoreHandler handler = context.Facts.GetHandler(extension);
context.Hooks.SendExtended(entry.Peer, extended);
context.Hooks.CallExtensionDataSent(entry.Peer, extension, payload.Length);
handler.OnMessageSent(context.Parameters.Hash, entry.Peer, payload);
}
}
public bool IsSupported(PeerHash peer, string extension)
{
return context.Collection.Find(peer)?.More.Supports(extension) == true;
}
public void ForEachPeer(Action<PeerHash> callback)
{
foreach (CoordinatorEntry entry in context.Collection.All())
{
callback.Invoke(entry.Peer);
}
}
public void ForEachPeer(Action<PeerHash, NetworkAddress> callback)
{
foreach (CoordinatorEntry entry in context.Collection.All())
{
callback.Invoke(entry.Peer, entry.Remote);
}
}
public void ForEachPeer(Action<PeerHash, NetworkAddress, NetworkDirection> callback)
{
foreach (CoordinatorEntry entry in context.Collection.All())
{
callback.Invoke(entry.Peer, entry.Remote, entry.Direction);
}
}
public void Handle(MessageReceived data)
{
CoordinatorEntry entry = context.Collection.Find(data.Peer);
if (entry != null)
{
switch (data.Type)
{
case "choke":
entry.State.IsRemoteChokingLocal = true;
context.Hooks.CallStatusChanged(entry.Peer, entry.State);
break;
case "unchoke":
entry.State.IsRemoteChokingLocal = false;
context.Hooks.CallStatusChanged(entry.Peer, entry.State);
break;
case "interested":
entry.State.IsRemoteInterestedInLocal = true;
context.Hooks.CallStatusChanged(entry.Peer, entry.State);
break;
case "have":
entry.Bitfield = context.Facts.ApplyHave(entry.Bitfield, data.Payload.GetInt32(0));
context.Hooks.CallBitfieldChanged(entry.Peer, entry.Bitfield, new PieceInfo(data.Payload.GetInt32(0)));
break;
case "bitfield":
entry.Bitfield = context.Facts.ApplyBitfield(entry.Bitfield, data.Payload.GetBitfield());
context.Hooks.CallBitfieldChanged(entry.Peer, entry.Bitfield);
break;
case "request":
context.Hooks.CallBlockRequested(context.Parameters.Hash, entry.Peer, data.Payload.GetRequest());
break;
case "piece":
context.Hooks.CallBlockReceived(context.Parameters.Hash, entry.Peer, data.Payload.GetPiece(context.Dependencies.Blocks));
break;
case "extended":
HandleHandshakeWithExtensionsIfNeeded(entry, data);
SendPassiveHandshakeWithExtensionsIfNeeded(entry, data);
HandleExtensionIfNeeded(entry, data);
break;
}
}
}
private void HandleHandshakeWithExtensionsIfNeeded(CoordinatorEntry entry, MessageReceived data)
{
if (data.Payload.IsExtensionHandshake())
{
entry.More = new MoreContainer(data.Payload.GetBencoded());
context.Hooks.CallExtensionListReceived(entry.Peer, entry.More.ToArray());
}
}
private void SendPassiveHandshakeWithExtensionsIfNeeded(CoordinatorEntry entry, MessageReceived data)
{
if (data.Payload.IsExtensionHandshake())
{
bool supportExtensions = entry.Extensions;
bool isIncoming = entry.Direction == NetworkDirection.Incoming;
if (supportExtensions && isIncoming)
{
context.Hooks.SendExtended(entry.Peer, context.Facts.GetHandshake());
context.Hooks.CallExtensionListSent(entry.Peer, context.Facts.GetExtensions());
}
}
}
private void HandleExtensionIfNeeded(CoordinatorEntry entry, MessageReceived data)
{
if (data.Payload.IsExtensionHandshake())
{
foreach (MoreHandler handler in context.Facts.AllHandlers())
{
handler.OnHandshake(context.Parameters.Hash, entry.Peer, data.Payload.GetExtensionData());
}
}
if (data.Payload.IsExtensionHandshake() == false)
{
MoreHandler handler;
byte id = data.Payload.GetExtensionIdentifier();
string code = context.Facts.Translate(id, out handler);
context.Hooks.CallExtensionDataReceived(entry.Peer, code, data.Payload.GetExtensionSize());
handler.OnMessageReceived(context.Parameters.Hash, entry.Peer, data.Payload.GetExtensionData());
}
}
}
}
|
amacal/leak
|
sources/Leak.Glue/CoordinatorService.cs
|
C#
|
mit
| 10,983
|
<?php
/**
* This source file is proprietary and part of Rebilly.
*
* (c) Rebilly SRL
* Rebilly Ltd.
* Rebilly Inc.
*
* @see https://www.rebilly.com
*/
namespace Rebilly\Tests\Api;
use DomainException;
use Rebilly\Entities\Session;
use Rebilly\Tests\TestCase as BaseTestCase;
/**
* Class SessionTest.
*/
class SessionTest extends BaseTestCase
{
/**
* @test
* @dataProvider provideInvalidData
*
* @param $data
*/
public function exceptionOnWrongPermissions($data)
{
$session = new Session();
$this->expectException(DomainException::class);
$session->setPermissions($data);
}
/**
* @return array
*/
public function provideInvalidData()
{
return [
'Not an array' => [
'wrong',
],
'Single rule is not an array' => [
[
'wrong',
],
],
'Wrong resourceName' => [
[
[
'resourceName' => 'wrong',
'resourceIds' => ['id123'],
'methods' => ['POST', 'GET'],
],
],
],
'Wrong resourceIds' => [
[
[
'resourceName' => 'customers',
'resourceIds' => 'wrong',
'methods' => ['POST', 'GET'],
],
],
],
'Wrong method' => [
[
[
'resourceName' => 'customers',
'resourceIds' => ['id123'],
'methods' => ['wrong'],
],
],
],
'Wrong methods' => [
[
[
'resourceName' => 'customers',
'resourceIds' => ['id123'],
'methods' => 'wrong',
],
],
],
];
}
}
|
Rebilly/rebilly-php
|
tests/Api/SessionTest.php
|
PHP
|
mit
| 2,133
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- This file documents the GNU C Library.
This is
The GNU C Library Reference Manual, for version
2.21.
Copyright (C) 1993-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version
1.3 or any later version published by the Free
Software Foundation; with the Invariant Sections being "Free Software
Needs Free Documentation" and "GNU Lesser General Public License",
the Front-Cover texts being "A GNU Manual", and with the Back-Cover
Texts as in (a) below. A copy of the license is included in the
section entitled "GNU Free Documentation License".
(a) The FSF's Back-Cover Text is: "You have the freedom to
copy and modify this GNU manual. Buying copies from the FSF
supports it in developing GNU and promoting software freedom." -->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>The GNU C Library: File Position Primitive</title>
<meta name="description" content="The GNU C Library: File Position Primitive">
<meta name="keywords" content="The GNU C Library: File Position Primitive">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Low_002dLevel-I_002fO.html#Low_002dLevel-I_002fO" rel="up" title="Low-Level I/O">
<link href="Descriptors-and-Streams.html#Descriptors-and-Streams" rel="next" title="Descriptors and Streams">
<link href="I_002fO-Primitives.html#I_002fO-Primitives" rel="prev" title="I/O Primitives">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="File-Position-Primitive"></a>
<div class="header">
<p>
Next: <a href="Descriptors-and-Streams.html#Descriptors-and-Streams" accesskey="n" rel="next">Descriptors and Streams</a>, Previous: <a href="I_002fO-Primitives.html#I_002fO-Primitives" accesskey="p" rel="prev">I/O Primitives</a>, Up: <a href="Low_002dLevel-I_002fO.html#Low_002dLevel-I_002fO" accesskey="u" rel="up">Low-Level I/O</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Setting-the-File-Position-of-a-Descriptor"></a>
<h3 class="section">13.3 Setting the File Position of a Descriptor</h3>
<p>Just as you can set the file position of a stream with <code>fseek</code>, you
can set the file position of a descriptor with <code>lseek</code>. This
specifies the position in the file for the next <code>read</code> or
<code>write</code> operation. See <a href="File-Positioning.html#File-Positioning">File Positioning</a>, for more information
on the file position and what it means.
</p>
<p>To read the current file position value from a descriptor, use
<code>lseek (<var>desc</var>, 0, SEEK_CUR)</code>.
</p>
<a name="index-file-positioning-on-a-file-descriptor"></a>
<a name="index-positioning-a-file-descriptor"></a>
<a name="index-seeking-on-a-file-descriptor"></a>
<dl>
<dt><a name="index-lseek"></a>Function: <em>off_t</em> <strong>lseek</strong> <em>(int <var>filedes</var>, off_t <var>offset</var>, int <var>whence</var>)</em></dt>
<dd><p>Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See <a href="POSIX-Safety-Concepts.html#POSIX-Safety-Concepts">POSIX Safety Concepts</a>.
</p>
<p>The <code>lseek</code> function is used to change the file position of the
file with descriptor <var>filedes</var>.
</p>
<p>The <var>whence</var> argument specifies how the <var>offset</var> should be
interpreted, in the same way as for the <code>fseek</code> function, and it must
be one of the symbolic constants <code>SEEK_SET</code>, <code>SEEK_CUR</code>, or
<code>SEEK_END</code>.
</p>
<dl compact="compact">
<dt><code>SEEK_SET</code></dt>
<dd><p>Specifies that <var>offset</var> is a count of characters from the beginning
of the file.
</p>
</dd>
<dt><code>SEEK_CUR</code></dt>
<dd><p>Specifies that <var>offset</var> is a count of characters from the current
file position. This count may be positive or negative.
</p>
</dd>
<dt><code>SEEK_END</code></dt>
<dd><p>Specifies that <var>offset</var> is a count of characters from the end of
the file. A negative count specifies a position within the current
extent of the file; a positive count specifies a position past the
current end. If you set the position past the current end, and
actually write data, you will extend the file with zeros up to that
position.
</p></dd>
</dl>
<p>The return value from <code>lseek</code> is normally the resulting file
position, measured in bytes from the beginning of the file.
You can use this feature together with <code>SEEK_CUR</code> to read the
current file position.
</p>
<p>If you want to append to the file, setting the file position to the
current end of file with <code>SEEK_END</code> is not sufficient. Another
process may write more data after you seek but before you write,
extending the file so the position you write onto clobbers their data.
Instead, use the <code>O_APPEND</code> operating mode; see <a href="Operating-Modes.html#Operating-Modes">Operating Modes</a>.
</p>
<p>You can set the file position past the current end of the file. This
does not by itself make the file longer; <code>lseek</code> never changes the
file. But subsequent output at that position will extend the file.
Characters between the previous end of file and the new position are
filled with zeros. Extending the file in this way can create a
“hole”: the blocks of zeros are not actually allocated on disk, so the
file takes up less space than it appears to; it is then called a
“sparse file”.
<a name="index-sparse-files"></a>
<a name="index-holes-in-files"></a>
</p>
<p>If the file position cannot be changed, or the operation is in some way
invalid, <code>lseek</code> returns a value of <em>-1</em>. The following
<code>errno</code> error conditions are defined for this function:
</p>
<dl compact="compact">
<dt><code>EBADF</code></dt>
<dd><p>The <var>filedes</var> is not a valid file descriptor.
</p>
</dd>
<dt><code>EINVAL</code></dt>
<dd><p>The <var>whence</var> argument value is not valid, or the resulting
file offset is not valid. A file offset is invalid.
</p>
</dd>
<dt><code>ESPIPE</code></dt>
<dd><p>The <var>filedes</var> corresponds to an object that cannot be positioned,
such as a pipe, FIFO or terminal device. (POSIX.1 specifies this error
only for pipes and FIFOs, but on GNU systems, you always get
<code>ESPIPE</code> if the object is not seekable.)
</p></dd>
</dl>
<p>When the source file is compiled with <code>_FILE_OFFSET_BITS == 64</code> the
<code>lseek</code> function is in fact <code>lseek64</code> and the type
<code>off_t</code> has 64 bits which makes it possible to handle files up to
<em>2^63</em> bytes in length.
</p>
<p>This function is a cancellation point in multi-threaded programs. This
is a problem if the thread allocates some resources (like memory, file
descriptors, semaphores or whatever) at the time <code>lseek</code> is
called. If the thread gets canceled these resources stay allocated
until the program ends. To avoid this calls to <code>lseek</code> should be
protected using cancellation handlers.
</p>
<p>The <code>lseek</code> function is the underlying primitive for the
<code>fseek</code>, <code>fseeko</code>, <code>ftell</code>, <code>ftello</code> and
<code>rewind</code> functions, which operate on streams instead of file
descriptors.
</p></dd></dl>
<dl>
<dt><a name="index-lseek64"></a>Function: <em>off64_t</em> <strong>lseek64</strong> <em>(int <var>filedes</var>, off64_t <var>offset</var>, int <var>whence</var>)</em></dt>
<dd><p>Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See <a href="POSIX-Safety-Concepts.html#POSIX-Safety-Concepts">POSIX Safety Concepts</a>.
</p>
<p>This function is similar to the <code>lseek</code> function. The difference
is that the <var>offset</var> parameter is of type <code>off64_t</code> instead of
<code>off_t</code> which makes it possible on 32 bit machines to address
files larger than <em>2^31</em> bytes and up to <em>2^63</em> bytes. The
file descriptor <code>filedes</code> must be opened using <code>open64</code> since
otherwise the large offsets possible with <code>off64_t</code> will lead to
errors with a descriptor in small file mode.
</p>
<p>When the source file is compiled with <code>_FILE_OFFSET_BITS == 64</code> on a
32 bits machine this function is actually available under the name
<code>lseek</code> and so transparently replaces the 32 bit interface.
</p></dd></dl>
<p>You can have multiple descriptors for the same file if you open the file
more than once, or if you duplicate a descriptor with <code>dup</code>.
Descriptors that come from separate calls to <code>open</code> have independent
file positions; using <code>lseek</code> on one descriptor has no effect on the
other. For example,
</p>
<div class="smallexample">
<pre class="smallexample">{
int d1, d2;
char buf[4];
d1 = open ("foo", O_RDONLY);
d2 = open ("foo", O_RDONLY);
lseek (d1, 1024, SEEK_SET);
read (d2, buf, 4);
}
</pre></div>
<p>will read the first four characters of the file <samp>foo</samp>. (The
error-checking code necessary for a real program has been omitted here
for brevity.)
</p>
<p>By contrast, descriptors made by duplication share a common file
position with the original descriptor that was duplicated. Anything
which alters the file position of one of the duplicates, including
reading or writing data, affects all of them alike. Thus, for example,
</p>
<div class="smallexample">
<pre class="smallexample">{
int d1, d2, d3;
char buf1[4], buf2[4];
d1 = open ("foo", O_RDONLY);
d2 = dup (d1);
d3 = dup (d2);
lseek (d3, 1024, SEEK_SET);
read (d1, buf1, 4);
read (d2, buf2, 4);
}
</pre></div>
<p>will read four characters starting with the 1024’th character of
<samp>foo</samp>, and then four more characters starting with the 1028’th
character.
</p>
<dl>
<dt><a name="index-off_005ft"></a>Data Type: <strong>off_t</strong></dt>
<dd><p>This is a signed integer type used to represent file sizes. In
the GNU C Library, this type is no narrower than <code>int</code>.
</p>
<p>If the source is compiled with <code>_FILE_OFFSET_BITS == 64</code> this type
is transparently replaced by <code>off64_t</code>.
</p></dd></dl>
<dl>
<dt><a name="index-off64_005ft"></a>Data Type: <strong>off64_t</strong></dt>
<dd><p>This type is used similar to <code>off_t</code>. The difference is that even
on 32 bit machines, where the <code>off_t</code> type would have 32 bits,
<code>off64_t</code> has 64 bits and so is able to address files up to
<em>2^63</em> bytes in length.
</p>
<p>When compiling with <code>_FILE_OFFSET_BITS == 64</code> this type is
available under the name <code>off_t</code>.
</p></dd></dl>
<p>These aliases for the ‘<samp>SEEK_…</samp>’ constants exist for the sake
of compatibility with older BSD systems. They are defined in two
different header files: <samp>fcntl.h</samp> and <samp>sys/file.h</samp>.
</p>
<dl compact="compact">
<dt><code>L_SET</code></dt>
<dd><p>An alias for <code>SEEK_SET</code>.
</p>
</dd>
<dt><code>L_INCR</code></dt>
<dd><p>An alias for <code>SEEK_CUR</code>.
</p>
</dd>
<dt><code>L_XTND</code></dt>
<dd><p>An alias for <code>SEEK_END</code>.
</p></dd>
</dl>
<hr>
<div class="header">
<p>
Next: <a href="Descriptors-and-Streams.html#Descriptors-and-Streams" accesskey="n" rel="next">Descriptors and Streams</a>, Previous: <a href="I_002fO-Primitives.html#I_002fO-Primitives" accesskey="p" rel="prev">I/O Primitives</a>, Up: <a href="Low_002dLevel-I_002fO.html#Low_002dLevel-I_002fO" accesskey="u" rel="up">Low-Level I/O</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|
elmerland/elmerland
|
gnu/File-Position-Primitive.html
|
HTML
|
mit
| 13,448
|
protoman 0.1a
=================
Simple django app to help with prototyping.
Running `newprototype` will set up a new TemplateView, and Url mapping along with a django template file for your prototype. This allows you to keep your prototypes inside of the django engine thus giving you all the django goodies, while keeping your code highly re-usable. Also allows your front end 'devs' to stay the heck out of your python code. As a nice bonus to your devs, it creates a usuable list of views that they will need to bang out.
Installation
-----------
1. Download/clone/fetch this repo into your app directory
2. Include `protoman` in your `INSTALLED_APPS`
3. Include url file into app
`url(r'^protoman/', include('protoman.urls')),`
Usage
-------
`manage.py newprototype <name of prototype>`
Required Folders
------------------
1. <root>/raw/tpl/ (currently set up to generate jade files in the project root)
Todo
----
1. Ability to create folders if necessary (see above)
2. Create some variables so you can pass in template names & directories
3. Create a method to turn off/on jade creation
4. Flesh out ability to pass in a dictionary to be returned as context (simple integration complete)
|
ScottBarkman/django_protoman
|
README.md
|
Markdown
|
mit
| 1,204
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SmoONE.DTOs
{
/// <summary>
/// 统计项的信息
/// </summary>
public class ALStatisticsItems
{
/// <summary>
/// 统计类型
/// </summary>
public StatisticsType AL_Status { get; set; }
/// <summary>
/// 人数
/// </summary>
public int Count { get; set; }
}
}
|
comsmobiler/SmoONE
|
Source/SmoONE.DTOs/OutputDTO/ALStatisticsItems.cs
|
C#
|
mit
| 455
|
## Go
These settings apply only when `--go` is specified on the command line.
``` yaml $(go)
go:
license-header: MICROSOFT_APACHE_NO_VERSION
namespace: appconfiguration
clear-output-folder: true
```
### Go multi-api
``` yaml $(go) && $(multiapi)
batch:
- tag: package-2019-10-01
- tag: package-2019-02-01-preview
```
### Tag: package-2019-10-01 and go
These settings apply only when `--tag=package-2019-10-01 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.
``` yaml $(tag) == 'package-2019-10-01' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2019-10-01/$(namespace)
```
### Tag: package-2019-02-01-preview and go
These settings apply only when `--tag=package-2019-02-01-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.
``` yaml $(tag) == 'package-2019-02-01-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2019-02-01-preview/$(namespace)
```
|
AppPlatPerf/azure-rest-api-specs
|
specification/appconfiguration/resource-manager/readme.go.md
|
Markdown
|
mit
| 1,111
|
'use strict';
const Flag = require('../src/Flag');
const expect = require('chai').expect;
describe('flag.isShort', function () {
it('(empty)', function () {
const input = '';
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-f', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('--', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('-F', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('---', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('aa', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('a', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-1', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-2', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
});
|
zlargon/node-commander
|
test/flag.isShort.js
|
JavaScript
|
mit
| 1,374
|
/* normalize.css v3.0.2 | MIT License | git.io/normalize */
html {
font-family: sans-serif; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
mark {
background: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
::selection {
background: #262a30;
color: #fff;
}
body {
position: relative;
font-family: 'Lato', "PingFang SC", "Microsoft YaHei", sans-serif;
font-size: 14px;
line-height: 2;
color: #555;
background: #fff;
}
@media (max-width: 767px) {
body {
padding-right: 0 !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
body {
padding-right: 0 !important;
}
}
@media (min-width: 1600px) {
body {
font-size: 16px;
}
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
padding: 0;
font-weight: bold;
line-height: 1.5;
font-family: 'Lato', "PingFang SC", "Microsoft YaHei", sans-serif;
}
h2,
h3,
h4,
h5,
h6 {
margin: 20px 0 15px;
}
h1 {
font-size: 22px;
}
@media (max-width: 767px) {
h1 {
font-size: 18px;
}
}
h2 {
font-size: 20px;
}
@media (max-width: 767px) {
h2 {
font-size: 16px;
}
}
h3 {
font-size: 18px;
}
@media (max-width: 767px) {
h3 {
font-size: 14px;
}
}
h4 {
font-size: 16px;
}
@media (max-width: 767px) {
h4 {
font-size: 12px;
}
}
h5 {
font-size: 14px;
}
@media (max-width: 767px) {
h5 {
font-size: 10px;
}
}
h6 {
font-size: 12px;
}
@media (max-width: 767px) {
h6 {
font-size: 8px;
}
}
p {
margin: 0 0 25px 0;
}
a {
color: #555;
text-decoration: none;
border-bottom: 1px solid #999;
word-wrap: break-word;
}
a:hover {
color: #222;
border-bottom-color: #222;
}
ul {
list-style: none;
}
blockquote {
margin: 0;
padding: 0;
}
img {
display: block;
margin: auto;
max-width: 100%;
height: auto;
}
hr {
margin: 40px 0;
height: 3px;
border: none;
background-color: #ddd;
background-image: repeating-linear-gradient(-45deg, #fff, #fff 4px, transparent 4px, transparent 8px);
}
blockquote {
padding: 0 15px;
color: #666;
border-left: 4px solid #ddd;
}
blockquote cite::before {
content: "-";
padding: 0 5px;
}
dt {
font-weight: 700;
}
dd {
margin: 0;
padding: 0;
}
.text-left {
text-align: left;
}
.text-center {
text-align: center;
}
.text-right {
text-align: right;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
.pullquote {
width: 45%;
}
.pullquote.left {
float: left;
margin-left: 5px;
margin-right: 10px;
}
.pullquote.right {
float: right;
margin-left: 10px;
margin-right: 5px;
}
.affix.affix.affix {
position: fixed;
}
.translation {
margin-top: -20px;
font-size: 14px;
color: #999;
}
.scrollbar-measure {
width: 100px;
height: 100px;
overflow: scroll;
position: absolute;
top: -9999px;
}
.use-motion .motion-element {
opacity: 0;
}
#local-search-input {
padding: 5px;
border: none;
font-size: 1.5em;
font-weight: 800;
line-height: 1.5em;
text-indent: 1.5em;
border-radius: 0;
width: 140px;
outline: none;
border-bottom: 1px solid #999;
background: inherit;
opacity: 0.5;
transition-duration: 200ms;
}
#local-search-input:focus {
opacity: 1;
}
#local-search-input:focus + .search-icon {
opacity: 1;
}
.search-icon {
position: absolute;
top: 16px;
left: 15px;
font-size: 1.5em;
font-weight: 800;
color: #333;
opacity: 0.5;
transition-duration: 200ms;
}
table {
margin: 20px 0;
width: 100%;
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #ddd;
font-size: 14px;
table-layout: fixed;
word-wrap: break-all;
}
table>tbody>tr:nth-of-type(odd) {
background-color: #f9f9f9;
}
table>tbody>tr:hover {
background-color: #f5f5f5;
}
caption,
th,
td {
padding: 8px;
text-align: left;
vertical-align: middle;
font-weight: normal;
}
th,
td {
border-bottom: 3px solid #ddd;
border-right: 1px solid #eee;
}
th {
padding-bottom: 10px;
font-weight: 700;
}
td {
border-bottom-width: 1px;
}
html,
body {
height: 100%;
}
.container {
position: relative;
min-height: 100%;
}
.header-inner {
margin: 0 auto;
padding: 100px 0 70px;
width: 700px;
}
.main {
padding-bottom: 150px;
}
.main-inner {
margin: 0 auto;
width: 700px;
}
@media (min-width: 1600px) {
.container .main-inner {
width: 900px;
}
}
.footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
min-height: 50px;
}
.footer-inner {
box-sizing: border-box;
margin: 20px auto;
width: 700px;
}
@media (min-width: 1600px) {
.container .footer-inner {
width: 900px;
}
}
pre,
.highlight {
overflow: auto;
margin: 20px 0;
padding: 15px;
font-size: 13px;
color: #eaeaea;
background: #000;
line-height: 1.6;
}
pre,
code {
font-family: consolas, Menlo, "PingFang SC", "Microsoft YaHei", monospace;
}
code {
padding: 2px 4px;
word-break: break-all;
color: #555;
background: #eee;
border-radius: 4px;
font-size: 13px;
}
pre code {
padding: 0;
color: #eaeaea;
background: none;
text-shadow: none;
}
.highlight pre {
border: none;
margin: 0;
padding: 1px;
}
.highlight table {
margin: 0;
width: auto;
border: none;
}
.highlight td {
border: none;
padding: 0;
}
.highlight figcaption {
font-size: 1em;
color: #eaeaea;
line-height: 1em;
margin-bottom: 1em;
}
.highlight figcaption:before,
.highlight figcaption:after {
content: " ";
display: table;
}
.highlight figcaption:after {
clear: both;
}
.highlight figcaption a {
float: right;
color: #eaeaea;
}
.highlight figcaption a:hover {
border-bottom-color: #eaeaea;
}
.highlight .gutter pre {
color: #666;
text-align: right;
padding-right: 20px;
}
.highlight .line {
height: 20px;
}
.gist table {
width: auto;
}
.gist table td {
border: none;
}
pre .comment {
color: #969896;
}
pre .variable,
pre .attribute,
pre .tag,
pre .regexp,
pre .ruby .constant,
pre .xml .tag .title,
pre .xml .pi,
pre .xml .doctype,
pre .html .doctype,
pre .css .id,
pre .css .class,
pre .css .pseudo {
color: #d54e53;
}
pre .number,
pre .preprocessor,
pre .built_in,
pre .literal,
pre .params,
pre .constant,
pre .command {
color: #e78c45;
}
pre .ruby .class .title,
pre .css .rules .attribute,
pre .string,
pre .value,
pre .inheritance,
pre .header,
pre .ruby .symbol,
pre .xml .cdata,
pre .special,
pre .number,
pre .formula {
color: #b9ca4a;
}
pre .title,
pre .css .hexcolor {
color: #70c0b1;
}
pre .function,
pre .python .decorator,
pre .python .title,
pre .ruby .function .title,
pre .ruby .title .keyword,
pre .perl .sub,
pre .javascript .title,
pre .coffeescript .title {
color: #7aa6da;
}
pre .keyword,
pre .javascript .function {
color: #c397d8;
}
.full-image.full-image.full-image {
border: none;
max-width: 100%;
width: auto;
margin: 20px auto;
}
@media (min-width: 992px) {
.full-image.full-image.full-image {
max-width: none;
width: 118%;
margin: 0 -9%;
}
}
.blockquote-center,
.page-home .post-type-quote blockquote,
.page-post-detail .post-type-quote blockquote {
position: relative;
margin: 40px 0;
padding: 0;
border-left: none;
text-align: center;
}
.blockquote-center::before,
.page-home .post-type-quote blockquote::before,
.page-post-detail .post-type-quote blockquote::before,
.blockquote-center::after,
.page-home .post-type-quote blockquote::after,
.page-post-detail .post-type-quote blockquote::after {
position: absolute;
content: ' ';
display: block;
width: 100%;
height: 24px;
opacity: 0.2;
background-repeat: no-repeat;
background-position: 0 -6px;
background-size: 22px 22px;
}
.blockquote-center::before,
.page-home .post-type-quote blockquote::before,
.page-post-detail .post-type-quote blockquote::before {
top: -20px;
background-image: url("../images/quote-l.svg");
border-top: 1px solid #ccc;
}
.blockquote-center::after,
.page-home .post-type-quote blockquote::after,
.page-post-detail .post-type-quote blockquote::after {
bottom: -20px;
background-image: url("../images/quote-r.svg");
border-bottom: 1px solid #ccc;
background-position: 100% 8px;
}
.blockquote-center p,
.page-home .post-type-quote blockquote p,
.page-post-detail .post-type-quote blockquote p,
.blockquote-center div,
.page-home .post-type-quote blockquote div,
.page-post-detail .post-type-quote blockquote div {
text-align: center;
}
.post .post-body .group-picture img {
box-sizing: border-box;
padding: 0 3px;
border: none;
}
.post .group-picture-row {
overflow: hidden;
margin-top: 6px;
}
.post .group-picture-row:first-child {
margin-top: 0;
}
.post .group-picture-column {
float: left;
}
.page-post-detail .post-body .group-picture-column {
float: none;
margin-top: 10px;
width: auto !important;
}
.page-post-detail .post-body .group-picture-column img {
margin: 0 auto;
}
.page-archive .group-picture-container {
overflow: hidden;
}
.page-archive .group-picture-row {
float: left;
}
.page-archive .group-picture-row:first-child {
margin-top: 6px;
}
.page-archive .group-picture-column {
max-width: 150px;
max-height: 150px;
}
.btn {
display: inline-block;
padding: 0 20px;
font-size: 14px;
color: #fff;
background: #222;
border: 2px solid #555;
text-decoration: none;
border-radius: 0;
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
.btn:hover,
.post-more-link .btn:hover {
border-color: #222;
color: #fff;
background: #222;
}
.btn-bar {
display: block;
width: 22px;
height: 2px;
background: #555;
border-radius: 1px;
}
.btn-bar+.btn-bar {
margin-top: 4px;
}
.pagination {
margin: 120px 0 40px;
text-align: center;
border-top: 1px solid #eee;
}
.page-number-basic,
.pagination .prev,
.pagination .next,
.pagination .page-number,
.pagination .space {
display: inline-block;
position: relative;
top: -1px;
margin: 0 10px;
padding: 0 10px;
line-height: 30px;
}
@media (max-width: 767px) {
.page-number-basic,
.pagination .prev,
.pagination .next,
.pagination .page-number,
.pagination .space {
margin: 0 5px;
}
}
.pagination .prev,
.pagination .next,
.pagination .page-number {
border-bottom: 0;
border-top: 1px solid #eee;
transition-property: border-color;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
.pagination .prev:hover,
.pagination .next:hover,
.pagination .page-number:hover {
border-top-color: #222;
}
.pagination .space {
padding: 0;
margin: 0;
}
.pagination .prev {
margin-left: 0;
}
.pagination .next {
margin-right: 0;
}
.pagination .page-number.current {
color: #fff;
background: #ccc;
border-top-color: #ccc;
}
@media (max-width: 767px) {
.pagination {
border-top: none;
}
.pagination .prev,
.pagination .next,
.pagination .page-number {
margin-bottom: 10px;
border-top: 0;
border-bottom: 1px solid #eee;
}
.pagination .prev:hover,
.pagination .next:hover,
.pagination .page-number:hover {
border-bottom-color: #222;
}
}
.comments {
margin: 60px 20px 0;
}
.tag-cloud {
text-align: center;
}
.tag-cloud a {
display: inline-block;
margin: 10px;
}
.back-to-top {
box-sizing: border-box;
position: fixed;
bottom: -100px;
right: 50px;
z-index: 1050;
padding: 0 6px;
width: 25px;
background: #222;
font-size: 12px;
opacity: 0.6;
color: #fff;
cursor: pointer;
text-align: center;
-webkit-transform: translateZ(0);
transition-property: bottom;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
@media (max-width: 767px) {
.back-to-top {
display: none;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.back-to-top {
display: none;
}
}
.back-to-top.back-to-top-on {
bottom: 40px;
}
.header {
background: #fff;
}
.header-inner {
position: relative;
}
.headband {
display: none;
height: 3px;
background: #222;
}
.site-home {
position: relative;
top: 0;
display: inline-block;
color: #fff;
font-size: 18px;
font-weight: bolder;
margin: 5px 20px;
border: none;
opacity: 0;
}
@media (min-width: 768px) and (max-width: 991px) {
.site-home {
font-size: 50px;
line-height: 110px;
}
}
.site-home:after {
content: '';
display: block;
border-bottom: #fff 1px solid;
-webkit-transform: scaleX(0);
-moz-transform: scaleX(0);
-ms-transform: scaleX(0);
-o-transform: scaleX(0);
transform: scaleX(0);
transition-duration: 200ms;
}
.site-home:hover {
color: #fff;
}
.site-home:hover:after {
-webkit-transform: scaleX(1);
-moz-transform: scaleX(1);
-ms-transform: scaleX(1);
-o-transform: scaleX(1);
transform: scaleX(1);
}
.site-meta {
margin: 80px 0 0;
text-align: center;
}
@media (max-width: 767px) {
.site-meta {
text-align: center;
}
}
.brand {
position: relative;
display: inline-block;
padding: 0 40px;
color: #fff;
background: #222;
border-bottom: none;
}
.brand:hover {
color: #fff;
}
.logo {
display: inline-block;
margin-right: 5px;
line-height: 36px;
vertical-align: top;
}
.site-title {
display: inline-block;
vertical-align: top;
font-size: 80px;
font-weight: 700;
font-family: 'Lato', "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 100px;
}
.site-title:before,
.site-title:after {
content: '';
width: 100%;
border-top: 5px solid #fff;
display: block;
transform-origin: left;
transition-duration: 500ms;
transition-timing-function: ease;
-webkit-transform: scaleX(0);
-moz-transform: scaleX(0);
-ms-transform: scaleX(0);
-o-transform: scaleX(0);
transform: scaleX(0);
}
.site-title:after {
transform-origin: right;
}
.site-title.show:before,
.site-title.show:after {
-webkit-transform: scaleX(1);
-moz-transform: scaleX(1);
-ms-transform: scaleX(1);
-o-transform: scaleX(1);
transform: scaleX(1);
}
@media (max-width: 767px) {
.site-title {
font-size: 60px;
}
.site-title:before,
.site-title:after {
border-width: 3px;
}
}
.site-subtitle {
margin-top: 10px;
font-size: 18px;
font-weight: 300;
color: #fff;
}
@media (max-width: 767px) {
.site-subtitle {
font-size: 16px;
}
}
.use-motion .brand {
opacity: 0;
}
.use-motion .logo,
.use-motion .site-title,
.use-motion .site-subtitle {
opacity: 0;
position: relative;
top: -10px;
}
.site-nav-toggle {
display: none;
position: absolute;
top: 10px;
left: 10px;
opacity: 0;
}
@media (max-width: 767px) {
.site-nav-toggle {
display: block;
z-index: 10;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.site-nav-toggle {
display: none;
}
}
.site-nav-toggle button {
margin-top: 2px;
padding: 9px 10px;
background: transparent;
border: none;
}
.site-nav {
position: absolute;
top: 0;
right: 20px;
}
@media (max-width: 767px) {
.site-nav {
right: 16px;
top: 40px;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.site-nav {
top: 5px;
display: block !important;
}
}
@media (min-width: 992px) {
.site-nav {
display: block !important;
}
}
.menu {
margin-top: 20px;
padding-left: 0;
text-align: center;
}
.menu .menu-item {
display: inline-block;
margin: 0 10px;
}
@media screen and (max-width: 767px) {
.menu .menu-item {
margin-top: 10px;
}
}
.menu .menu-item a {
display: block;
font-size: 13px;
text-transform: capitalize;
line-height: inherit;
border-bottom: 1px solid transparent;
transition-property: border-color;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
.menu .menu-item a:hover,
.menu-item-active a {
border-bottom-color: #222;
}
@media (max-width: 767px) {
.menu .menu-item a {
text-align: right !important;
}
}
.menu .menu-item .fa {
margin-right: 5px;
}
@media (max-width: 767px) {
.menu .menu-item .fa {
margin: 0 0 0 5px;
line-height: 27px;
float: right;
}
}
.use-motion .menu-item {
opacity: 0;
}
.post-body {
font-family: 'Lato', "PingFang SC", "Microsoft YaHei", sans-serif;
}
@media (max-width: 767px) {
.post-body {
word-break: break-word;
}
}
.post-body .fancybox img {
display: block !important;
margin: 0 auto;
cursor: pointer;
cursor: zoom-in;
cursor: -webkit-zoom-in;
}
.post-body .image-caption,
.post-body .figure .caption {
margin: 10px auto 15px;
text-align: center;
font-size: 14px;
color: #999;
font-weight: bold;
line-height: 1;
}
.post-sticky-flag {
display: inline-block;
font-size: 16px;
-ms-transform: rotate(30deg);
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}
@media (max-width: 767px) {
.post-body pre,
.post-body .highlight {
padding: 10px;
}
.post-body pre .gutter pre,
.post-body .highlight .gutter pre {
padding-right: 10px;
}
}
@media (min-width: 992px) {
.posts-expand .post-body {
text-align: justify;
}
}
.posts-expand .post-body h2,
.posts-expand .post-body h3,
.posts-expand .post-body h4,
.posts-expand .post-body h5,
.posts-expand .post-body h6 {
padding-top: 10px;
}
.posts-expand .post-body h2 .header-anchor,
.posts-expand .post-body h3 .header-anchor,
.posts-expand .post-body h4 .header-anchor,
.posts-expand .post-body h5 .header-anchor,
.posts-expand .post-body h6 .header-anchor {
float: right;
margin-left: 10px;
color: #ccc;
border-bottom-style: none;
visibility: hidden;
}
.posts-expand .post-body h2 .header-anchor:hover,
.posts-expand .post-body h3 .header-anchor:hover,
.posts-expand .post-body h4 .header-anchor:hover,
.posts-expand .post-body h5 .header-anchor:hover,
.posts-expand .post-body h6 .header-anchor:hover {
color: inherit;
}
.posts-expand .post-body h2:hover .header-anchor,
.posts-expand .post-body h3:hover .header-anchor,
.posts-expand .post-body h4:hover .header-anchor,
.posts-expand .post-body h5:hover .header-anchor,
.posts-expand .post-body h6:hover .header-anchor {
visibility: visible;
}
.posts-expand .post-body ul li {
list-style: circle;
}
.posts-expand .post-body img {
box-sizing: border-box;
margin: auto;
padding: 3px;
}
.posts-expand .fancybox img {
margin: 0 auto;
}
@media (max-width: 767px) {
.posts-collapse {
margin: 0 20px;
}
.posts-collapse .post-title,
.posts-collapse .post-meta {
display: block;
width: auto;
text-align: left;
}
}
.posts-collapse {
position: relative;
z-index: 1010;
margin-left: 55px;
}
.posts-collapse::after {
content: " ";
position: absolute;
top: 20px;
left: 0;
margin-left: -2px;
width: 4px;
height: 100%;
background: #f5f5f5;
z-index: -1;
}
@media (max-width: 767px) {
.posts-collapse {
margin: 0 20px;
}
}
.posts-collapse .collection-title {
position: relative;
margin: 60px 0;
}
.posts-collapse .collection-title h2 {
margin-left: 20px;
}
.posts-collapse .collection-title small {
color: #bbb;
}
.posts-collapse .collection-title::before {
content: " ";
position: absolute;
left: 0;
top: 50%;
margin-left: -4px;
margin-top: -4px;
width: 8px;
height: 8px;
background: #bbb;
border-radius: 50%;
}
.posts-collapse .post {
margin: 30px 0;
}
.posts-collapse .post-header {
position: relative;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
transition-property: border;
border-bottom: 1px dashed #ccc;
}
.posts-collapse .post-header::before {
content: " ";
position: absolute;
left: 0;
top: 12px;
width: 6px;
height: 6px;
margin-left: -4px;
background: #bbb;
border-radius: 50%;
border: 1px solid #fff;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
transition-property: background;
}
.posts-collapse .post-header:hover {
border-bottom-color: #666;
}
.posts-collapse .post-header:hover::before {
background: #222;
}
.posts-collapse .post-meta {
position: absolute;
font-size: 12px;
left: 20px;
top: 5px;
}
.posts-collapse .post-comments-count {
display: none;
}
.posts-collapse .post-title {
margin-left: 60px;
font-size: 16px;
font-weight: normal;
line-height: inherit;
}
.posts-collapse .post-title::after {
margin-left: 3px;
opacity: 0.6;
}
.posts-collapse .post-title a {
color: #666;
border-bottom: none;
}
.page-home .post-type-quote .post-header,
.page-post-detail .post-type-quote .post-header,
.page-home .post-type-quote .post-tags,
.page-post-detail .post-type-quote .post-tags {
display: none;
}
.posts-expand .post-title {
font-size: 26px;
text-align: center;
word-break: break-word;
font-weight: 300;
}
@media (max-width: 767px) {
.posts-expand .post-title {
font-size: 22px;
}
}
.posts-expand .post-title-link {
display: inline-block;
position: relative;
color: #555;
border-bottom: none;
line-height: 1.2;
vertical-align: top;
}
.posts-expand .post-title-link::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: #000;
visibility: hidden;
-webkit-transform: scaleX(0);
-moz-transform: scaleX(0);
-ms-transform: scaleX(0);
-o-transform: scaleX(0);
transform: scaleX(0);
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
.posts-expand .post-title-link:hover::before {
visibility: visible;
-webkit-transform: scaleX(1);
-moz-transform: scaleX(1);
-ms-transform: scaleX(1);
-o-transform: scaleX(1);
transform: scaleX(1);
}
.posts-expand .post-title-link .fa {
font-size: 16px;
}
.posts-expand .post-meta {
margin: 3px 0 10px 0;
color: #999;
font-family: 'Lato', "PingFang SC", "Microsoft YaHei", sans-serif;
font-size: 12px;
text-align: center;
}
.posts-expand .post-meta .post-category-list {
display: inline-block;
margin: 0;
padding: 3px;
}
.posts-expand .post-meta .post-category-list-link {
color: #999;
}
.post-meta-item-icon {
display: none;
margin-right: 3px;
}
@media (min-width: 768px) and (max-width: 991px) {
.post-meta-item-icon {
display: inline-block;
}
}
@media (max-width: 767px) {
.post-meta-item-icon {
display: inline-block;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.post-meta-item-text {
display: none;
}
}
@media (max-width: 767px) {
.post-meta-item-text {
display: none;
}
}
@media (max-width: 767px) {
.posts-expand .post-comments-count {
display: none;
}
}
.post-more-link {
margin-top: 50px;
}
.post-more-link .btn {
color: #555;
font-size: 14px;
background: #fff;
border-radius: 2px;
line-height: 2;
margin: 0 4px 8px 4px;
}
.post-more-link .fa-fw {
width: 1.285714285714286em;
text-align: left;
}
.posts-expand .post-tags {
margin-top: 40px;
text-align: center;
}
.posts-expand .post-tags a {
display: inline-block;
margin-right: 10px;
font-size: 13px;
}
.post-nav {
overflow: hidden;
margin-top: 60px;
padding: 10px;
white-space: nowrap;
border-top: 1px solid #eee;
}
.post-nav-item {
display: inline-block;
width: 50%;
white-space: normal;
}
.post-nav-item a {
position: relative;
display: inline-block;
line-height: 25px;
font-size: 14px;
color: #555;
border-bottom: none;
}
.post-nav-item a:hover {
color: #222;
border-bottom: none;
}
.post-nav-item a:active {
top: 2px;
}
.post-nav-item a i {
font-size: 12px;
}
.post-nav-prev {
text-align: right;
}
.posts-expand .post-eof {
display: block;
margin: 80px auto 60px;
width: 8%;
height: 1px;
background: #ccc;
text-align: center;
}
.post:last-child .post-eof.post-eof.post-eof {
display: none;
}
.post-gallery {
display: table;
table-layout: fixed;
width: 100%;
border-collapse: separate;
}
.post-gallery-row {
display: table-row;
}
.post-gallery .post-gallery-img {
display: table-cell;
text-align: center;
vertical-align: middle;
border: none;
}
.post-gallery .post-gallery-img img {
max-width: 100%;
max-height: 100%;
border: none;
}
.fancybox-close,
.fancybox-close:hover {
border: none;
}
.page-post-detail .header-inner {
overflow: visible !important;
}
.page-post-detail .site-meta,
.page-post-detail article header.post-header {
display: none;
}
.page-post-detail .header-post {
width: 100%;
}
.page-post-detail .post-header {
position: relative;
top: -10px;
width: 960px;
margin: 80px auto 0;
color: #fff;
opacity: 0;
}
@media (max-width: 767px) {
.page-post-detail .post-header {
width: auto;
padding: 0 1em;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.page-post-detail .post-header {
width: auto;
padding: 0 1em;
}
}
.page-post-detail .post-header .tags a {
display: inline-block;
border: 1px solid rgba(255,255,255,0.8);
border-radius: 999em;
padding: 0 10px;
line-height: 24px;
color: inherit;
font-size: 12px;
margin: 0 1px;
margin-bottom: 6px;
transition-duration: 300ms;
transition-delay: 50ms;
}
.page-post-detail .post-header .tags a:hover {
border-color: #fff;
background-color: rgba(255,255,255,0.4);
}
.page-post-detail .post-header h1 {
font-size: 49px;
}
.page-post-detail .post-header time,
.page-post-detail .post-header .post-meta-item-text {
font-family: Lora, 'Times New Roman', serif;
font-style: italic;
font-weight: 300;
font-size: 20px;
}
.sidebar {
position: fixed;
right: 0;
top: 0;
bottom: 0;
width: 0;
z-index: 1040;
box-shadow: inset 0 2px 6px #000;
background: #222;
-webkit-transform: translateZ(0);
}
.sidebar a {
color: #999;
border-bottom-color: #555;
}
.sidebar a:hover {
color: #eee;
}
@media (min-width: 768px) and (max-width: 991px) {
.sidebar {
display: none !important;
}
}
@media (max-width: 767px) {
.sidebar {
display: none !important;
}
}
.sidebar-inner {
position: relative;
padding: 20px 10px;
color: #999;
text-align: center;
}
.sidebar-toggle {
position: fixed;
right: 50px;
bottom: 45px;
width: 15px;
height: 15px;
padding: 5px;
background: #222;
line-height: 0;
z-index: 1050;
cursor: pointer;
-webkit-transform: translateZ(0);
}
@media (min-width: 768px) and (max-width: 991px) {
.sidebar-toggle {
display: none;
}
}
@media (max-width: 767px) {
.sidebar-toggle {
display: none;
}
}
.sidebar-toggle-line {
position: relative;
display: inline-block;
vertical-align: top;
height: 2px;
width: 100%;
background: #fff;
margin-top: 3px;
}
.sidebar-toggle-line:first-child {
margin-top: 0;
}
.site-author-image {
display: block;
margin: 0 auto;
padding: 2px;
max-width: 120px;
height: auto;
border: 1px solid #eee;
}
.site-author-name {
margin: 0;
text-align: center;
color: #222;
font-weight: 600;
}
.site-description {
margin-top: 0;
text-align: center;
font-size: 13px;
color: #999;
}
.site-state {
overflow: hidden;
line-height: 1.4;
white-space: nowrap;
text-align: center;
}
.site-state-item {
display: inline-block;
padding: 0 15px;
border-left: 1px solid #eee;
}
.site-state-item:first-child {
border-left: none;
}
.site-state-item a {
border-bottom: none;
}
.site-state-item-count {
display: block;
text-align: center;
color: inherit;
font-weight: 600;
font-size: 16px;
}
.site-state-item-name {
font-size: 13px;
color: #999;
}
.feed-link {
margin-top: 20px;
}
.feed-link a {
display: inline-block;
padding: 0 15px;
color: #fc6423;
border: 1px solid #fc6423;
border-radius: 4px;
}
.feed-link a i {
color: #fc6423;
font-size: 14px;
}
.feed-link a:hover {
color: #fff;
background: #fc6423;
}
.feed-link a:hover i {
color: #fff;
}
.links-of-author {
margin-top: 20px;
}
.links-of-author a {
display: inline-block;
vertical-align: middle;
margin-right: 10px;
margin-bottom: 10px;
border-bottom-color: #555;
font-size: 13px;
}
.links-of-author a:before {
display: inline-block;
vertical-align: middle;
margin-right: 3px;
content: " ";
width: 4px;
height: 4px;
border-radius: 50%;
background: #ece38b;
}
.links-of-blogroll {
font-size: 13px;
}
.links-of-blogroll-title {
margin-top: 20px;
font-size: 14px;
font-weight: 600;
}
.links-of-blogroll-list {
margin: 0;
padding: 0;
}
.links-of-blogroll-item {
padding: 2px 10px;
}
.sidebar-nav {
margin: 0 0 20px;
padding-left: 0;
}
.sidebar-nav li {
display: inline-block;
cursor: pointer;
border-bottom: 1px solid transparent;
font-size: 14px;
color: #555;
}
.sidebar-nav li:hover {
color: #fc6423;
}
.page-post-detail .sidebar-nav-toc {
padding: 0 5px;
}
.page-post-detail .sidebar-nav-overview {
margin-left: 10px;
}
.sidebar-nav .sidebar-nav-active {
color: #fc6423;
border-bottom-color: #fc6423;
}
.sidebar-nav .sidebar-nav-active:hover {
color: #fc6423;
}
.sidebar-panel {
display: none;
}
.sidebar-panel-active {
display: block;
}
.post-toc-empty {
font-size: 14px;
color: #666;
}
.post-toc-wrap {
overflow: hidden;
}
.post-toc {
overflow: auto;
}
.post-toc ol {
margin: 0;
padding: 0 2px 5px 10px;
text-align: left;
list-style: none;
font-size: 14px;
}
.post-toc ol > ol {
padding-left: 0;
}
.post-toc ol a {
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
transition-property: all;
color: #666;
border-bottom-color: #ccc;
}
.post-toc ol a:hover {
color: #000;
border-bottom-color: #000;
}
.post-toc .nav-item {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.8;
}
.post-toc .nav .nav-child {
display: none;
}
.post-toc .nav .active > .nav-child {
display: block;
}
.post-toc .nav .active-current > .nav-child {
display: block;
}
.post-toc .nav .active-current > .nav-child > .nav-item {
display: block;
}
.post-toc .nav .active > a {
color: #fc6423;
border-bottom-color: #fc6423;
}
.post-toc .nav .active-current > a {
color: #fc6423;
}
.post-toc .nav .active-current > a:hover {
color: #fc6423;
}
.footer {
font-size: 14px;
color: #999;
}
.footer img {
border: none;
}
.footer-inner {
text-align: center;
}
.with-love {
display: inline-block;
margin: 0 5px;
}
.powered-by,
.theme-info {
display: inline-block;
}
.powered-by {
margin-right: 10px;
}
.powered-by::after {
content: "|";
padding-left: 10px;
}
.cc-license {
margin-top: 10px;
text-align: center;
}
.cc-license .cc-opacity {
opacity: 0.7;
border-bottom: none;
}
.cc-license .cc-opacity:hover {
opacity: 0.9;
}
.cc-license img {
display: inline-block;
}
.theme-next #ds-thread #ds-reset {
color: #555;
}
.theme-next #ds-thread #ds-reset .ds-replybox {
margin-bottom: 30px;
}
.theme-next #ds-thread #ds-reset .ds-replybox .ds-avatar,
.theme-next #ds-reset .ds-avatar img {
box-shadow: none;
}
.theme-next #ds-thread #ds-reset .ds-textarea-wrapper {
border-color: #c7d4e1;
background: none;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.theme-next #ds-thread #ds-reset .ds-textarea-wrapper textarea {
height: 60px;
}
.theme-next #ds-reset .ds-rounded-top {
border-radius: 0;
}
.theme-next #ds-thread #ds-reset .ds-post-toolbar {
box-sizing: border-box;
border: 1px solid #c7d4e1;
background: #f6f8fa;
}
.theme-next #ds-thread #ds-reset .ds-post-options {
height: 40px;
border: none;
background: none;
}
.theme-next #ds-thread #ds-reset .ds-toolbar-buttons {
top: 11px;
}
.theme-next #ds-thread #ds-reset .ds-sync {
top: 5px;
}
.theme-next #ds-thread #ds-reset .ds-post-button {
top: 4px;
right: 5px;
width: 90px;
height: 30px;
border: 1px solid #c5ced7;
border-radius: 3px;
background-image: linear-gradient(#fbfbfc, #f5f7f9);
color: #60676d;
}
.theme-next #ds-thread #ds-reset .ds-post-button:hover {
background-position: 0 -30px;
color: #60676d;
}
.theme-next #ds-thread #ds-reset .ds-comments-info {
padding: 10px 0;
}
.theme-next #ds-thread #ds-reset .ds-sort {
display: none;
}
.theme-next #ds-thread #ds-reset li.ds-tab a.ds-current {
border: none;
background: #f6f8fa;
color: #60676d;
}
.theme-next #ds-thread #ds-reset li.ds-tab a.ds-current:hover {
background-color: #e9f0f7;
color: #60676d;
}
.theme-next #ds-thread #ds-reset li.ds-tab a {
border-radius: 2px;
padding: 5px;
}
.theme-next #ds-thread #ds-reset .ds-login-buttons p {
color: #999;
line-height: 36px;
}
.theme-next #ds-thread #ds-reset .ds-login-buttons .ds-service-list li {
height: 28px;
}
.theme-next #ds-thread #ds-reset .ds-service-list a {
background: none;
padding: 5px;
border: 1px solid;
border-radius: 3px;
text-align: center;
}
.theme-next #ds-thread #ds-reset .ds-service-list a:hover {
color: #fff;
background: #666;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-weibo {
color: #fc9b00;
border-color: #fc9b00;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-weibo:hover {
background: #fc9b00;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-qq {
color: #60a3ec;
border-color: #60a3ec;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-qq:hover {
background: #60a3ec;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-renren {
color: #2e7ac4;
border-color: #2e7ac4;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-renren:hover {
background: #2e7ac4;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-douban {
color: #37994c;
border-color: #37994c;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-douban:hover {
background: #37994c;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-kaixin {
color: #fef20d;
border-color: #fef20d;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-kaixin:hover {
background: #fef20d;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-netease {
color: #f00;
border-color: #f00;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-netease:hover {
background: #f00;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-sohu {
color: #ffcb05;
border-color: #ffcb05;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-sohu:hover {
background: #ffcb05;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-baidu {
color: #2831e0;
border-color: #2831e0;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-baidu:hover {
background: #2831e0;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-google {
color: #166bec;
border-color: #166bec;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-google:hover {
background: #166bec;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-weixin {
color: #00ce0d;
border-color: #00ce0d;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-weixin:hover {
background: #00ce0d;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-more-services {
border: none;
}
.theme-next #ds-thread #ds-reset .ds-service-list .ds-more-services:hover {
background: none;
}
.theme-next #ds-reset .duoshuo-ua-admin {
display: inline-block;
color: #f00;
}
.theme-next #ds-reset .duoshuo-ua-platform,
.theme-next #ds-reset .duoshuo-ua-browser {
color: #ccc;
}
.theme-next #ds-reset .duoshuo-ua-platform .fa,
.theme-next #ds-reset .duoshuo-ua-browser .fa {
display: inline-block;
margin-right: 3px;
}
.theme-next #ds-reset .duoshuo-ua-separator {
display: inline-block;
margin-left: 5px;
}
.theme-next .this_ua {
background-color: #ccc !important;
border-radius: 4px;
padding: 0 5px !important;
margin: 1px 1px !important;
border: 1px solid #bbb !important;
color: #fff;
display: inline-block !important;
}
.theme-next .this_ua.admin {
background-color: #d9534f !important;
border-color: #d9534f !important;
}
.theme-next .this_ua.platform.iOS,
.theme-next .this_ua.platform.Mac,
.theme-next .this_ua.platform.Windows {
background-color: #39b3d7 !important;
border-color: #46b8da !important;
}
.theme-next .this_ua.platform.Linux {
background-color: #3a3a3a !important;
border-color: #1f1f1f !important;
}
.theme-next .this_ua.platform.Android {
background-color: #00c47d !important;
border-color: #01b171 !important;
}
.theme-next .this_ua.browser.Mobile,
.theme-next .this_ua.browser.Chrome {
background-color: #5cb85c !important;
border-color: #4cae4c !important;
}
.theme-next .this_ua.browser.Firefox {
background-color: #f0ad4e !important;
border-color: #eea236 !important;
}
.theme-next .this_ua.browser.Maxthon,
.theme-next .this_ua.browser.IE {
background-color: #428bca !important;
border-color: #357ebd !important;
}
.theme-next .this_ua.browser.baidu,
.theme-next .this_ua.browser.UCBrowser,
.theme-next .this_ua.browser.Opera {
background-color: #d9534f !important;
border-color: #d43f3a !important;
}
.theme-next .this_ua.browser.Android,
.theme-next .this_ua.browser.QQBrowser {
background-color: #78ace9 !important;
border-color: #4cae4c !important;
}
.post-spread {
margin-top: 20px;
text-align: center;
}
.jiathis_style {
display: inline-block;
}
.jiathis_style a {
border: none;
}
.post-spread {
margin-top: 20px;
text-align: center;
}
.bdshare-slide-button-box a {
border: none;
}
.bdsharebuttonbox {
display: inline-block;
}
.bdsharebuttonbox a {
border: none;
}
ul.search-result-list {
padding-left: 0px;
margin: 0px 5px 0px 8px;
}
p.search-result {
border-bottom: 1px dashed #ccc;
padding: 5px 0;
}
a.search-result-title {
font-weight: bold;
}
a.search-result {
border-bottom: transparent;
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.search-keyword {
border-bottom: 1px dashed #4088b8;
font-weight: bold;
}
#local-search-result {
height: 90%;
overflow: auto;
}
.popup {
display: none;
position: fixed;
top: 10%;
left: 50%;
width: 700px;
height: 80%;
margin-left: -350px;
padding: 3px 10px 0;
background: #fff;
color: #333;
z-index: 9999;
border-radius: 5px;
}
@media (max-width: 767px) {
.popup {
padding: 3px;
top: 0;
left: 0;
margin: 0;
width: 100%;
height: 100%;
border-radius: 0px;
}
}
.popoverlay {
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
z-index: 2080;
background-color: rgba(0,0,0,0.3);
}
#local-search-input {
margin-bottom: 10px;
width: calc(100% - 10px);
}
.popup-btn-close {
position: absolute;
top: 10px;
right: 14px;
color: #4ebd79;
font-size: 14px;
font-weight: bold;
text-transform: uppercase;
cursor: pointer;
transition-duration: 200ms;
}
.popup-btn-close:hover {
color: #9cce28;
}
#no-result {
position: absolute;
left: 44%;
top: 42%;
color: #ccc;
}
.busuanzi-count:before {
content: " ";
float: right;
width: 194px;
min-height: 25px;
}
@media (min-width: 768px) and (max-width: 991px) {
.busuanzi-count {
width: auto;
}
.busuanzi-count:before {
display: none;
}
}
@media (max-width: 767px) {
.busuanzi-count {
width: auto;
}
.busuanzi-count:before {
display: none;
}
}
.site-uv,
.site-pv,
.page-pv {
display: inline-block;
}
.site-uv .busuanzi-value,
.site-pv .busuanzi-value,
.page-pv .busuanzi-value {
margin: 0 5px;
}
.site-uv {
margin-right: 10px;
}
.site-uv::after {
content: "|";
padding-left: 10px;
}
.use-motion .post {
opacity: 0;
}
.page-archive .archive-page-counter {
position: relative;
top: 3px;
left: 20px;
}
@media (max-width: 767px) {
.page-archive .archive-page-counter {
top: 5px;
}
}
.page-archive .posts-collapse .archive-move-on {
position: absolute;
top: 11px;
left: 0;
margin-left: -6px;
width: 10px;
height: 10px;
opacity: 0.5;
background: #555;
border: 1px solid #fff;
border-radius: 50%;
}
.category-all-page .category-all-title {
text-align: center;
}
.category-all-page .category-all {
margin-top: 20px;
}
.category-all-page .category-list {
margin: 0;
padding: 0;
list-style: none;
}
.category-all-page .category-list-item {
margin: 5px 10px;
}
.category-all-page .category-list-count {
color: #bbb;
}
.category-all-page .category-list-count:before {
display: inline;
content: " (";
}
.category-all-page .category-list-count:after {
display: inline;
content: ") ";
}
.category-all-page .category-list-child {
padding-left: 10px;
}
.page-post-detail .sidebar-toggle-line {
background: #fc6423;
}
.page-post-detail .comments {
overflow: hidden;
}
.header {
position: relative;
margin: 0 auto;
width: 100%;
background: no-repeat center center;
background-color: #808080;
background-attachment: scroll;
background-size: cover;
min-height: 400px;
}
@media (min-width: 768px) and (max-width: 991px) {
.header {
width: auto;
min-height: 130px;
}
}
@media (max-width: 767px) {
.header {
width: auto;
min-height: 80px;
}
}
.header-inner {
top: 0;
overflow: hidden;
padding: 0;
width: inherit;
}
@media (min-width: 768px) and (max-width: 991px) {
.header-inner {
position: relative;
width: auto;
}
}
@media (max-width: 767px) {
.header-inner {
position: relative;
width: auto;
overflow: visible;
}
}
.main:before,
.main:after {
content: " ";
display: table;
}
.main:after {
clear: both;
}
@media (min-width: 768px) and (max-width: 991px) {
.main {
padding-bottom: 100px;
}
}
@media (max-width: 767px) {
.main {
padding-bottom: 100px;
}
}
.container .main-inner {
width: 960px;
}
@media (min-width: 768px) and (max-width: 991px) {
.container .main-inner {
width: auto;
}
}
@media (max-width: 767px) {
.container .main-inner {
width: auto;
}
}
.content-wrap {
float: right;
box-sizing: border-box;
padding: 40px;
width: 700px;
background: #fff;
min-height: 700px;
}
@media (min-width: 768px) and (max-width: 991px) {
.content-wrap {
width: 100%;
padding: 1em;
}
}
@media (max-width: 767px) {
.content-wrap {
width: 100%;
padding: 1em;
min-height: auto;
}
}
.sidebar {
position: static;
float: left;
margin-top: 300px;
width: 240px;
background: #fff;
box-shadow: none;
}
@media (min-width: 768px) and (max-width: 991px) {
.sidebar {
display: none;
}
}
@media (max-width: 767px) {
.sidebar {
display: none;
}
}
.sidebar-toggle {
display: none;
}
.footer-inner {
width: 960px;
}
.footer-inner:before {
content: " ";
float: left;
width: 260px;
min-height: 50px;
}
@media (min-width: 768px) and (max-width: 991px) {
.footer-inner {
width: auto;
}
.footer-inner:before {
display: none;
}
}
@media (max-width: 767px) {
.footer-inner {
width: auto;
}
.footer-inner:before {
display: none;
}
}
.sidebar-position-right .header-inner {
right: 0;
}
.sidebar-position-right .content-wrap {
float: left;
}
.sidebar-position-right .sidebar {
float: right;
}
.sidebar-position-right .footer-inner:before {
float: right;
}
.site-meta {
padding: 20px 0;
color: #fff;
/* background: $black-deep; */
}
@media (min-width: 768px) and (max-width: 991px) {
.site-meta {
display: none;
}
}
.brand {
display: block;
padding: 0;
background: none;
}
.brand:hover {
color: #fff;
}
.site-subtitle {
margin: 0;
}
.site-search form {
display: none;
}
.site-nav {
border-top: none;
}
@media (max-width: 767px) {
.site-nav {
display: none;
z-index: 9;
overflow: visible !important;
}
.site-nav:before {
content: '';
position: absolute;
top: -41px;
right: -16px;
width: calc(100% + 16px);
height: calc(100% + 35px);
background: #000;
opacity: 0.5;
pointer-events: none;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.site-nav-on {
display: block !important;
}
}
.menu {
margin-top: 5px;
}
.menu .menu-item {
display: block;
margin: 0;
list-style: none;
}
.menu .menu-item a {
position: relative;
box-sizing: border-box;
padding: 5px;
text-align: left;
line-height: inherit;
color: #fff;
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
border: none;
}
@media (max-width: 767px) {
.menu .menu-item a {
padding: 0 5px;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.menu .menu-item a {
padding: 0 5px;
}
}
.menu .menu-item a:after {
content: '';
display: block;
border-bottom: #fff 1px solid;
-webkit-transform: scaleX(0);
-moz-transform: scaleX(0);
-ms-transform: scaleX(0);
-o-transform: scaleX(0);
transform: scaleX(0);
transition-delay: 50ms;
transition-duration: 200ms;
}
.menu .menu-item a:hover,
.menu-item-active a {
color: #fff;
}
.menu .menu-item a:hover:after,
.menu-item-active a:after {
-webkit-transform: scaleX(1);
-moz-transform: scaleX(1);
-ms-transform: scaleX(1);
-o-transform: scaleX(1);
transform: scaleX(1);
}
.menu .menu-item br {
display: none;
}
.menu-item-active a:after {
content: " ";
position: absolute;
top: 50%;
margin-top: -3px;
right: 15px;
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #bbb;
}
.btn-bar {
background-color: #fff;
}
.site-nav-toggle {
top: 7px;
right: 10px;
left: auto;
}
.use-motion .sidebar .motion-element {
opacity: 1;
}
.sidebar {
display: none;
right: auto;
bottom: auto;
-webkit-transform: none;
}
.sidebar-inner {
box-sizing: border-box;
width: 240px;
color: #555;
background: #fff;
}
.sidebar-inner.affix {
position: fixed;
top: 0;
}
.site-overview {
margin: 0 2px;
text-align: left;
}
.site-author:before,
.site-author:after {
content: " ";
display: table;
}
.site-author:after {
clear: both;
}
.sidebar a {
color: #555;
}
.sidebar a:hover {
color: #222;
}
.links-of-author-item a:before {
display: none;
}
.links-of-author-item a {
border-bottom: none;
text-decoration: underline;
}
.feed-link {
border-top: 1px dotted #ccc;
border-bottom: 1px dotted #ccc;
text-align: center;
}
.feed-link a {
display: block;
color: #fc6423;
border: none;
}
.feed-link a:hover {
background: none;
color: #e34603;
}
.feed-link a:hover i {
color: #e34603;
}
.links-of-author:before,
.links-of-author:after {
content: " ";
display: table;
}
.links-of-author:after {
clear: both;
}
.links-of-author-item {
float: left;
margin: 5px 0 0;
width: 50%;
}
.links-of-author-item a {
box-sizing: border-box;
display: inline-block;
margin-right: 0;
margin-bottom: 0;
padding: 0 5px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.links-of-author-item a {
display: block;
text-decoration: none;
}
.links-of-author-item a:hover {
border-radius: 4px;
background: #eee;
}
.links-of-author-item .fa {
margin-right: 2px;
font-size: 16px;
}
.links-of-author-item .fa-globe {
font-size: 15px;
}
.links-of-blogroll {
margin-top: 20px;
padding: 3px 0 0;
border-top: 1px dotted #ccc;
}
.links-of-blogroll-title {
margin-top: 0;
}
.links-of-blogroll-item {
padding: 0;
}
.links-of-blogroll-inline:before,
.links-of-blogroll-inline:after {
content: " ";
display: table;
}
.links-of-blogroll-inline:after {
clear: both;
}
.links-of-blogroll-inline .links-of-blogroll-item {
float: left;
margin: 5px 0 0;
width: 50%;
}
.links-of-blogroll-inline .links-of-blogroll-item a {
box-sizing: border-box;
display: inline-block;
margin-right: 0;
margin-bottom: 0;
padding: 0 5px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
@media (max-width: 767px) {
.post-body {
text-align: justify;
}
}
|
susers/susers.github.io
|
css/main.css
|
CSS
|
mit
| 50,087
|
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Instagram Fancybox</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:image" content="route.png" />
<link rel="stylesheet" href="lib/leaflet/leaflet.css" />
<link rel="stylesheet" href="lib/fancybox/jquery.fancybox.css" />
<link rel="stylesheet" href="../dist/Leaflet.Instagram.css" />
<link rel="stylesheet" href="css/map.css" />
</head>
<body>
<div id="map"></div>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="lib/fancybox/jquery.fancybox.pack.js"></script>
<script src="lib/reqwest.min.js"></script>
<script src="lib/leaflet/leaflet.js"></script>
<script src="../dist/Leaflet.Instagram.Fancybox.js"></script>
<script>
var map = L.map('map', {
maxZoom: 15
}).fitBounds([[59.22, 5.78], [59.28,5.89]]);
L.tileLayer('http://opencache.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=norges_grunnkart&zoom={z}&x={x}&y={y}', {
attribution: '© <a href="http://kartverket.no/">Kartverket</a>'
}).addTo(map);
L.instagram.fancybox('http://turban.cartodb.com/api/v2/sql?q=SELECT * FROM instagram WHERE the_geom %26%26 ST_SetSRID(ST_MakeBox2D(ST_Point(5.727, 59.124), ST_Point(5.924, 59.305)), 4326)'
).addTo(map);
</script>
</body>
</html>
|
turban/Leaflet.Instagram
|
examples/fancybox.html
|
HTML
|
mit
| 1,321
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
namespace Common
{
public static class Function
{
#region 改动后的MD5
/// <summary>
/// 改动后的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetMd5(string str)
{
string cl = "&8e(t)ed" + str;
//string cl = "&8eed" + DateTime.Now.Month + str + DateTime.Now.Day;//将真实验证码加上前缀与后缀后再加密;
string pwd = "";
MD5 md5 = MD5.Create();//实例化一个md5对像
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
s.Reverse(); //翻转生成的MD5码
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 6; i < s.Length - 1; i++) //只取MD5码的一部分;恶意访问者无法知道我取的是哪几位。
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
pwd = pwd + (s[i] < 198 ? s[i] + 28 : s[i]).ToString("X"); // 进一步对生成的MD5码做一些改造。
}
return pwd;
}
#endregion
#region 过滤非法字符
/// <summary>
/// SQL过滤敏感字符
/// </summary>
/// <param name="inText">要特殊过滤的字符串</param>
/// <returns>过滤后的字符串</returns>
public static string SqlFilter(string inText = "")
{
if (string.IsNullOrEmpty(inText)) //如果字符串为空,直接返回。
{
return "";
}
inText = inText.Replace("\" ", " ");
inText = inText.Replace("or ", " ");
inText = inText.Replace("* ", " ");
inText = inText.Replace("count( ", " ");
inText = inText.Replace("drop table ", " ");
inText = inText.Replace("update ", " ");
inText = inText.Replace("truncate ", " ");
inText = inText.Replace("asc( ", " ");
inText = inText.Replace("mid( ", " ");
inText = inText.Replace("char( ", " ");
inText = inText.Replace("xp_cmdshell ", " ");
inText = inText.Replace("exec master ", " ");
inText = inText.Replace("net localgroup administrators ", " ");
inText = inText.Replace(" and ", " ");
inText = inText.Replace("net user ", " ");
inText = inText.Replace(" or ", " ");
inText = inText.Replace("and ", "");
inText = inText.Replace("exec ", "");
inText = inText.Replace("insert ", "");
inText = inText.Replace("select ", "");
inText = inText.Replace("delete ", "");
inText = inText.Replace("update ", "");
inText = inText.Replace(" and", "");
inText = inText.Replace(" exec", "");
inText = inText.Replace(" insert", "");
inText = inText.Replace(" select", "");
inText = inText.Replace(" delete", "");
inText = inText.Replace(" update ", "");
inText = inText.Replace("chr ", "");
inText = inText.Replace("mid ", "");
inText = inText.Replace(" chr", "");
inText = inText.Replace(" mid", "");
inText = inText.Replace("master ", "");
inText = inText.Replace(" master", "");
inText = inText.Replace("or ", "");
inText = inText.Replace(" or", "");
inText = inText.Replace("truncate ", "");
inText = inText.Replace("char ", "");
inText = inText.Replace("declare ", "");
inText = inText.Replace("join ", "");
inText = inText.Replace("union ", "");
inText = inText.Replace("truncate ", "");
inText = inText.Replace(" char", "");
inText = inText.Replace(" declare", "");
inText = inText.Replace(" join", "");
inText = inText.Replace(" union", "");
inText = inText.Replace("'", "");
inText = inText.Replace("<", "");
inText = inText.Replace(">", "");
inText = inText.Replace("%", "");
inText = inText.Replace("'delete", "");
inText = inText.Replace("''", "");
inText = inText.Replace("\"\"", "");
inText = inText.Replace(",", "");
inText = inText.Replace(">=", "");
inText = inText.Replace("=<", "");
inText = inText.Replace("--", "");
inText = inText.Replace(";", "");
inText = inText.Replace("||", "");
inText = inText.Replace("[", "");
inText = inText.Replace("]", "");
inText = inText.Replace("&", "");
inText = inText.Replace("/", "");
inText = inText.Replace("?", "");
inText = inText.Replace(">?", "");
inText = inText.Replace("?<", "");
inText = inText.Replace(" ", "");
return inText;
}
#endregion
/// <summary>
/// 加密数据
/// </summary>
/// <param name="text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Encrypt(string text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(text);
MD5 md5Hash = MD5.Create();
des.Key = Encoding.ASCII.GetBytes(md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sKey)).ToString().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sKey)).ToString().Substring(0, 8));
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string Decrypt(string text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
int len;
len = text.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
MD5 md5Hash = MD5.Create();
des.Key = Encoding.ASCII.GetBytes(md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sKey)).ToString().Substring(0, 8));
des.IV = Encoding.ASCII.GetBytes(md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sKey)).ToString().Substring(0, 8));
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
/// <summary>
/// sql过滤
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public static T EntityFilter<T>(T entity)
{
foreach (var property in entity.GetType().GetProperties())
{
if (property.PropertyType == typeof(string))
{
var value = property.GetValue(entity)?.ToString().Trim();
if (!string.IsNullOrEmpty(value))
property.SetValue(entity, SqlFilter(value));
}
}
return entity;
}
public static void ExceptionThrow(string errorName, string errormsg)
{
throw new Exception("{" + $"\"ErrorName\":\"{errorName}\",\"ErrorMsg\":\"{errormsg}\"" + "}");
}
}
}
|
Dasiys/mvcDapper
|
MobileSmw/Common/Function.cs
|
C#
|
mit
| 8,807
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }}</title>
<meta name="author" content="{{ site.name }}" />
<meta name="description" content="{{ site.description }}">
<link rel="shortcut icon" href="{{ site.baseurl }}/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="{{ site.baseurl }}/images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="{{ site.baseurl }}/css/pure-min.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="{{ site.baseurl }}/css/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="{{ site.baseurl }}/css/grids-responsive-min.css">
<!--<![endif]-->
<!--[if lte IE 8]>
<link rel="stylesheet" href="{{ site.baseurl }}/css/blog-old-ie.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="{{ site.baseurl }}/css/blog.css">
<!--<![endif]-->
<link rel="alternate" type="application/rss+xml" title="{{ site.name }} - {{ site.description }}" href="{{ site.baseurl }}/feed.xml" />
</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header">
<h1 class="brand-title">{{ site.name }}</h1>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a href="{{ site.baseurl }}/" class="pure-button">Home</a>
</li>
<li class="nav-item">
<a href="{{ site.baseurl }}/about/" class="pure-button">About</a>
</li>
<li class="nav-item">
<a href="{{ site.baseurl }}/archive/" class="pure-button">Archive</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="content pure-u-1 pure-u-md-3-4">
{{ content }}
</div>
</div>
{% include analytics.html %}
</body>
</html>
|
fernandocortez/fernandocortez.github.io
|
_layouts/default.html
|
HTML
|
mit
| 2,159
|
/**
* Created by Jairo Martinez on 8/15/15.
*/
var five = require("johnny-five");
var board = {};
var lcd = {};
var rly1 = {};
var rly2 = {};
var btnBack = {};
var btnMenu = {};
var btnHome = {};
var btnEntr = {};
var btnNvUp = {};
var btnNvDn = {};
var btnNvLt = {};
var btnNvRt = {};
function _btnsSetup() {
btnEntr = new five.Button({
pin: 2,
isPullup: true
});
btnHome = new five.Button({
pin: 3,
isPullup: true
});
btnBack = new five.Button({
pin: 8,
isPullup: true
});
btnMenu = new five.Button({
pin: 9,
isPullup: true
});
btnNvRt = new five.Button({
pin: 5, //
isPullup: true
});
btnNvDn = new five.Button({
pin: 4, //
isPullup: true
});
btnNvUp = new five.Button({
pin: 7, //
isPullup: true
});
btnNvLt = new five.Button({
pin: 6,
isPullup: true
});
}
function _btns() {
_btnsSetup();
btnMenu.on("down", function () {
console.log("Btn Menu");
lcd.print("Menu");
});
btnHome.on("down", function () {
console.log("Btn Home");
});
btnEntr.on("down", function () {
console.log("Btn Enter");
});
btnBack.on("down", function () {
console.log("Btn Back");
});
btnNvUp.on("down", function () {
console.log("Btn Up");
});
btnNvDn.on("down", function () {
console.log("Btn Down");
});
btnNvLt.on("down", function () {
console.log("Btn Left");
});
btnNvRt.on("down", function () {
console.log("Btn Right");
});
}
function _lcd() {
lcd = new five.LCD({
controller: "PCF8574",
address: 0x20,
rows: 4,
cols: 20
});
lcd.clear();
lcd.home();
}
/**
* Setup Relays
* @private
*/
function _relays() {
rly1 = new five.Relay(10);
rly2 = new five.Relay(11);
setTimeout(function () {
rly1.on();
rly2.on();
}, 1000);
}
/**
* Initialize
* @private
*/
function _init() {
_btns();
_lcd();
_relays();
}
///////////////////////////////////////////////////
//
var j5 = function (){
};
/**
* Initialize Module
* @param opts
* @param cb
*/
j5.prototype.init = function (opts, cb) {
cb = (typeof cb === 'function') ? cb : function () {};
opts = opts || { port: "/dev/ttyAMA0" };
board = new five.Board(opts);
try {
board.on("ready", function () {
_init();
this.repl.inject({
lcd: lcd
});
cb(null);
});
}
catch(ex){
cb(ex,null);
}
};
/**
* Send Message To The LCD
* @param msg
* @param row
* @param col
*/
j5.prototype.message = function(msg,row,col){
row = row || 0;
col = col || 0;
lcd.cursor(row, col).print(msg);
};
module.exports = new j5();
|
Zenitram-Oriaj/RaspLinx
|
services/j5.js
|
JavaScript
|
mit
| 2,567
|
#ifndef GE_MESH_SETTINGS_ASSET_HPP
#define GE_MESH_SETTINGS_ASSET_HPP
#pragma once
#include "ge/concept/asset.hpp"
#include "ge/material_asset.hpp"
#include "ge/mesh_asset.hpp"
#include "ge/mesh_settings.hpp"
namespace ge
{
/// Asset loader for mesh settings objects
/// [asset.json
/// spec](https://lbovet.github.io/docson/index.html#https://raw.githubusercontent.com/gentlemans/gentlemanly_engine/master/doc/json_spec/mesh_settings_asset.json)
struct mesh_settings_asset {
/// Loads mesh_settings objects
using loaded_type = mesh_settings;
/// Asset loader function
static std::shared_ptr<mesh_settings> load_asset(asset_manager& manager, const char* asset_name,
const char* filepath, const nlohmann::json& json_data)
{
std::string mat = json_data["material"];
std::string mesh = json_data["mesh"];
return std::make_shared<mesh_settings>(manager.get_asset<mesh_asset>(mesh.c_str()),
*manager.get_asset<material_asset>(mat.c_str()));
}
/// Require the assets to have "asset_type": "mesh_settings_asset"
static const char* asset_type() { return "mesh_settings"; }
// make sure it qualifies as an asset
BOOST_CONCEPT_ASSERT((concept::Asset<mesh_settings_asset>));
};
}
#endif // GE_MESH_SETTINGS_ASSET_HPP
|
gentlemans/gentlemanly_engine
|
modules/renderer/include/ge/mesh_settings_asset.hpp
|
C++
|
mit
| 1,235
|
using System;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Extensibility;
using Access = NetOffice.AccessApi;
using Office = NetOffice.OfficeApi;
namespace COMAddinRibbonExampleCS4
{
[Guid("44665894-708B-45B2-B2D8-6D2C8D2CA0A6"), ProgId("AccessAddinCS4.RibbonAddin"), ComVisible(true)]
public class Addin : IDTExtensibility2, Office.Native.IRibbonExtensibility
{
private static readonly string _addinOfficeRegistryKey = "Software\\Microsoft\\Office\\Access\\AddIns\\";
private static readonly string _progId = "AccessAddinCS4.RibbonAddin";
private static readonly string _addinFriendlyName = "NetOffice Sample Addin in C#";
private static readonly string _addinDescription = "NetOffice Sample Addin with custom Ribbon UI";
private Access.Application _accessApplication;
#region IDTExtensibility2 Members
void IDTExtensibility2.OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
try
{
_accessApplication = new Access.Application(null, Application);
}
catch (Exception exception)
{
string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, exception.Message);
MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void IDTExtensibility2.OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom)
{
try
{
if (null != _accessApplication)
_accessApplication.Dispose();
}
catch (Exception exception)
{
string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, exception.Message);
MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void IDTExtensibility2.OnStartupComplete(ref Array custom)
{
}
void IDTExtensibility2.OnAddInsUpdate(ref Array custom)
{
}
void IDTExtensibility2.OnBeginShutdown(ref Array custom)
{
}
#endregion
#region IRibbonExtensibility Members
public string GetCustomUI(string RibbonID)
{
try
{
return ReadString("RibbonUI.xml");
}
catch (Exception throwedException)
{
string details = string.Format("{1}{1}Details:{1}{1}{0}", throwedException.Message, Environment.NewLine);
MessageBox.Show("An error occured in GetCustomUI." + details, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return "";
}
}
#endregion
#region Ribbon UI Trigger
public void OnAction(Office.IRibbonControl control)
{
try
{
switch (control.Id)
{
case "customButton1":
MessageBox.Show("This is the first sample button.", _progId);
break;
case "customButton2":
MessageBox.Show("This is the second sample button.", _progId);
break;
default:
MessageBox.Show("Unkown Control Id: " + control.Id, _progId);
break;
}
}
catch (Exception throwedException)
{
string details = string.Format("{1}{1}Details:{1}{1}{0}", throwedException.Message, Environment.NewLine);
MessageBox.Show("An error occured in OnAction." + details, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region COM Register Functions
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type type)
{
try
{
// add codebase value
Assembly thisAssembly = Assembly.GetAssembly(typeof(Addin));
RegistryKey key = Registry.ClassesRoot.CreateSubKey("CLSID\\{" + type.GUID.ToString().ToUpper() + "}\\InprocServer32\\1.0.0.0");
key.SetValue("CodeBase", thisAssembly.CodeBase);
key.Close();
Registry.ClassesRoot.CreateSubKey(@"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable");
// add bypass key
// http://support.microsoft.com/kb/948461
key = Registry.ClassesRoot.CreateSubKey("Interface\\{000C0601-0000-0000-C000-000000000046}");
string defaultValue = key.GetValue("") as string;
if (null == defaultValue)
key.SetValue("", "Office .NET Framework Lockback Bypass Key");
key.Close();
// add excel addin key
RegistryKey rk = Registry.CurrentUser.CreateSubKey(_addinOfficeRegistryKey + _progId);
rk.SetValue("LoadBehavior", Convert.ToInt32(3));
rk.SetValue("FriendlyName", _addinFriendlyName);
rk.SetValue("Description", _addinDescription);
rk.Close();
}
catch (Exception ex)
{
string details = string.Format("{1}{1}Details:{1}{1}{0}", ex.Message, Environment.NewLine);
MessageBox.Show("An error occured." + details, "Register " + _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type type)
{
try
{
Registry.ClassesRoot.DeleteSubKey(@"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable", false);
Registry.CurrentUser.DeleteSubKey(_addinOfficeRegistryKey + _progId, false);
}
catch (Exception throwedException)
{
string details = string.Format("{1}{1}Details:{1}{1}{0}", throwedException.Message, Environment.NewLine);
MessageBox.Show("An error occured." + details, "Unregister " + _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Private Helper
/// <summary>
/// reads text from ressource
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string ReadString(string fileName)
{
Assembly assembly = typeof(Addin).Assembly;
System.IO.Stream ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + fileName);
if (ressourceStream == null)
throw (new System.IO.IOException("Error accessing resource Stream."));
System.IO.StreamReader textStreamReader = new System.IO.StreamReader(ressourceStream);
if (textStreamReader == null)
throw (new System.IO.IOException("Error accessing resource File."));
string text = textStreamReader.ReadToEnd();
ressourceStream.Close();
textStreamReader.Close();
return text;
}
#endregion
}
}
|
NetOfficeFw/Samples
|
Access/03 IDTExtensibility2 Access Sample/RibbonUI/Addin.cs
|
C#
|
mit
| 7,461
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-22a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sink: w32_execv
* BadSink : execute command with wexecv
* Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#include <process.h>
#define EXECV _wexecv
#ifndef OMITBAD
/* The global variable below is used to drive control flow in the source function */
int CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_badGlobal = 0;
wchar_t * CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_badSource(wchar_t * data);
void CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_badGlobal = 1; /* true */
data = CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_badSource(data);
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wexecv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECV(COMMAND_INT_PATH, args);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The global variables below are used to drive control flow in the source functions. */
int CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B1Global = 0;
int CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B2Global = 0;
/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
wchar_t * CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B1Source(wchar_t * data);
static void goodG2B1()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B1Global = 0; /* false */
data = CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B1Source(data);
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wexecv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECV(COMMAND_INT_PATH, args);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
wchar_t * CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B2Source(wchar_t * data);
static void goodG2B2()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B2Global = 1; /* true */
data = CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_goodG2B2Source(data);
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wexecv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECV(COMMAND_INT_PATH, args);
}
}
void CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
maurer/tiamat
|
samples/Juliet/testcases/CWE78_OS_Command_Injection/s08/CWE78_OS_Command_Injection__wchar_t_file_w32_execv_22a.c
|
C
|
mit
| 4,849
|
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main()
#include "catch.hpp"
#include <memory>
#include <utility>
#include "LadderQueue.hpp"
#include "Event.hpp"
#include "mocks.hpp"
TEST_CASE("Ladder Queue operations") {
warped::LadderQueue q;
std::shared_ptr<warped::Event> e;
REQUIRE(q.begin() == nullptr);
SECTION("Insert, read and erase event on a Laddder Queue") {
// Basic check for insert(), begin() and erase()
q.insert(std::shared_ptr<warped::Event>(new test_Event {"r1", 10}));
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r1");
CHECK(e->timestamp() == 10);
q.erase(e);
e = q.begin();
REQUIRE(e == nullptr);
// Check for algorithmic accuracy
// Add events in decreasing order
q.insert(std::shared_ptr<warped::Event>(new test_Event {"r1", 10}));
q.insert(std::shared_ptr<warped::Event>(new test_Event {"r2", 5}));
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r2");
CHECK(e->timestamp() == 5);
q.erase(e);
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r1");
CHECK(e->timestamp() == 10);
// Add event with a larger timestamp
q.insert(std::shared_ptr<warped::Event>(new test_Event {"r1", 15}));
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r1");
CHECK(e->timestamp() == 10);
// Add event with a smaller timestamp
q.insert(std::shared_ptr<warped::Event>(new test_Event {"r3", 8}));
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r3");
CHECK(e->timestamp() == 8);
// Delete the 3 events
q.erase(e);
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r1");
CHECK(e->timestamp() == 10);
q.erase(e);
e = q.begin();
REQUIRE(e != nullptr);
CHECK(e->receiverName() == "r1");
CHECK(e->timestamp() == 15);
q.erase(e);
e = q.begin();
REQUIRE(e == nullptr);
}
}
|
wilseypa/warped2
|
test/test_LadderQueue.cpp
|
C++
|
mit
| 2,199
|
package com.maddog05.demoeasysqlite.application;
import android.app.Application;
import com.maddog05.demoeasysqlite.utils.DatabaseUtils;
import com.maddog05.easysqlite.EasySQLite;
/*
* Created by maddog05 on 22/04/16.
*/
public class MaddogApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
EasySQLite.getInstance().init(this, DatabaseUtils.DATABASE_NAME, DatabaseUtils.DATABASE_VERSION, DatabaseUtils.getTables());
}
}
|
maddog05/EasySQLite
|
DemoEasySQLite/app/src/main/java/com/maddog05/demoeasysqlite/application/MaddogApplication.java
|
Java
|
mit
| 489
|
{% if results %}
<p>
Mostrando <b>{{ results.items|length }}</b> de <b>{{ results.total }}</b> presupuestos{% if year != -1 %} del año {{ year }}{% endif %}{% if query %} con "<i>{{ query }}</i>"{% endif %}
{% if results.pages > 1 %}
{% if results.has_prev %}
<a href="#" class="aimg" onclick="loadDoc('{{ url_for('search_budgets', query=query, page=results.prev_num) }}');">
<img class="textcentered" src="{{ url_for('static', filename='images/201-previous.png') }}" alt="Anterior" height="40" width="40">
</a>
{% else %}
<img class="grayscale textcentered" src="{{ url_for('static', filename='images/201-previous.png') }}" alt="Anterior" height="40" width="40">
{% endif %}
Página <b>{{ results.page }}</b> de <b>{{ results.pages }}</b>
{% if results.has_next %}
<a href="#" class="aimg" onclick="loadDoc('{{ url_for('search_budgets', query=query, page=results.next_num) }}');">
<img class="textcentered" src="{{ url_for('static', filename='images/201-next-1.png') }}" alt="Siguiente" height="40" width="40">
</a>
{% else %}
<img class="grayscale textcentered" src="{{ url_for('static', filename='images/201-next-1.png') }}" alt="Siguiente" height="40" width="40">
{% endif %}
{% endif %}
</p>
{% set load = 0 %}
{% include 'budgets_search_table.html' %}
{% else %}
<p class="fmerror">No se han encontrado presupuestos{% if query %} con "<i>{{ query }}</i>"{% endif %}</p>
{% endif %}
|
dsloop/FranERP
|
app/templates/budgets_search_results.html
|
HTML
|
mit
| 1,654
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from .base import FunctionalTest
class RecipeEditTest(FunctionalTest):
def test_can_add_a_recipe(self):
# Ben goes to the recipe website homepage
self.browser.get(self.server_url)
# He notices the page title mention cookbook
self.assertIn('cookbook', self.browser.title)
# He is invited to enter his name to create his own cookbook or
# view other user's cookbook's
# Ben wants to create his own right now, so he enters his name
# and then clicks the 'get started button'
# TODO -- duplication here. consider refactoring if there is a third instance
username_input = self.browser.find_element_by_id('id_username')
username_input.send_keys('ben')
username_input.send_keys(Keys.ENTER)
# Ben goes to a unique URL which includes his name
ben_url = self.browser.current_url
self.assertRegex(ben_url, '/users/ben.+')
# He is invited to click on a link to add a new recipe
add_recipe_button = self.browser.find_element_by_id('id_add_recipe_button')
self.assertIn('Add recipe', add_recipe_button.text)
# He clicks on the link and new page appears
add_recipe_button.click()
# When he adds a new recipe, he is taken to a new URL
self.assertRegex(self.browser.current_url, '/users/.*/add_recipe')
# He sees a form with a textbox for name, ingredients, directions and servings
# along with a 'cancel' and 'add' button
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('Add Recipe', header_text)
name_textbox = self.browser.find_element_by_id('id_title')
self.assertEqual(name_textbox.get_attribute('placeholder'),
'Enter the title of the recipe')
ingredients_textbox = self.browser.find_element_by_id('id_ingredients')
directions_textbox = self.browser.find_element_by_id('id_directions')
servings_textbox = self.browser.find_element_by_id('id_servings')
add_button = self.browser.find_element_by_id('id_add_button')
# He types in Grilled Halibut with Mango-Avocado Salsa into the textbox for name
name_textbox.send_keys('Grilled Halibut with Mango-Avocado Salsa')
# He types in ingredients:
ingredients_textbox.send_keys('1 medium ripe avocado, peeled and cut into 1/2" dice')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('1 medium ripe mango, peeled and cut into 1/2" dice')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('1 cup cherry tomatoes, quartered')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('4 large fresh basil leaves, thinly sliced')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('3 tablespoons extra-virgin olive oil, divided, plus more for brushing')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('3 tablespoons fresh lime juice, divided')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('Kosher salt and freshly ground black pepper')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('4 6-ounce halibut or mahi-mahi fillets')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('4 lime wedges')
# He then types in the following for directions:
directions_textbox.send_keys('Prepare a grill to medium-high heat. Gently combine the avocado, mango, '
'tomatoes, basil, 1 tablespoon oil, and 1 tablespoon lime juice in a large mixing '
'bowl. Season salsa to taste with salt and pepper and set aside at room '
'temperature, gently tossing occasionally.')
directions_textbox.send_keys(Keys.ENTER)
directions_textbox.send_keys('Place fish fillets in a 13x9x2" glass baking dish. Drizzle remaining 2 '
'tablespoon oil and 2 tablespoon lime juice over. Season fish with salt and '
'pepper. Let marinate at room temperature for 10 minutes, turning fish '
'occasionally.')
directions_textbox.send_keys(Keys.ENTER)
directions_textbox.send_keys('Brush grill rack with oil. Grill fish until just opaque in center, about 5 '
'minutes per side. Transfer to plates. Spoon mango-avocado salsa over fish. '
'Squeeze a lime wedge over each and serve.')
# He then types in the servings
servings_textbox.send_keys('7')
# Finally, he clicks the add button
add_button.click()
# He is returned to the main page
# He sees that the recipe appears in the list of recipes
self.check_for_row_in_list_table('Grilled Halibut with Mango-Avocado Salsa')
# Ben then clicks on a recipe to get the full info
recipe_link = self.browser.find_element_by_link_text('Grilled Halibut with Mango-Avocado Salsa')
recipe_link.click()
# He is taken to a new page which has the title in the url
self.assertRegex(self.browser.current_url, '/users/(\S+)/recipe/grilled-halibut-with-mango-avocado-salsa')
# The new page lists all of the ingredients and directions
page_text = self.browser.find_element_by_tag_name('body').text
self.assertIn('1 medium ripe avocado, peeled and cut into 1/2" dice', page_text)
self.assertIn('Prepare a grill to medium-high heat. Gently combine the avocado, mango, ', page_text)
# He then remembers that the servings are for 8 people and a chili pepper is needed. He clicks
# on the edit button to start editing
edit_button = self.browser.find_element_by_id('id_edit_button')
self.assertIn('Edit', edit_button.text)
edit_button.click()
# The edit page shows the same text as before
page_text = self.browser.find_element_by_tag_name('body').text
self.assertIn('1 medium ripe avocado, peeled and cut into 1/2" dice', page_text)
self.assertIn('Prepare a grill to medium-high heat. Gently combine the avocado, mango, ', page_text)
# He changes the number of servings from 7 to 8
servings_textbox = self.browser.find_element_by_id('id_servings')
servings_textbox.send_keys(Keys.BACKSPACE)
servings_textbox.send_keys('8')
# He adds chili pepper to the list of ingredients
ingredients_textbox = self.browser.find_element_by_id('id_ingredients')
ingredients_textbox.send_keys(Keys.ENTER)
ingredients_textbox.send_keys('1 chili pepper')
# He adds a note for next time
notes_textbox = self.browser.find_element_by_id('id_notes')
notes_textbox.send_keys("Wasn't that spicy, added a pepper")
# He then clicks the save button
save_button = self.browser.find_element_by_id('id_save_button')
self.assertIn('Save', save_button.text)
save_button.click()
# He is returned to the recipe page
self.assertRegex(self.browser.current_url, '/users/(\S+)/recipe/grilled-halibut-with-mango-avocado-salsa')
# He can see his changes reflected on the page
page_text = self.browser.find_element_by_tag_name('body').text
self.assertIn('8', page_text)
self.assertNotIn('7', page_text)
self.assertIn('1 chili pepper', page_text)
self.assertIn('added a pepper', page_text)
#self.fail('Finish the test')
# He changes his mind and cancels
# cancel_button = self.browser.find_element_by_name('id_cancel_button')
#cancel_button.click()
# He is returned to the main page
# The number of recipes is still 1
# table = self.browser.find_element_by_id('id_recipe_table')
# rows = table.find_element_by_tag_name('tr')
#self.assertEqual(len(rows), 1)
|
benosment/recipes
|
functional_tests/test_edit_recipe.py
|
Python
|
mit
| 8,273
|
<!DOCTYPE html>
<html>
<head>
<title>Classe KFadeWidgetEffect</title>
</head>
<body>
<p>Classe <b>KFadeWidgetEffect</b></p><p>Derivada de <a href='QWidget.html'>QWidget</a></p><p>Classes derivadas: <a href='.html'></a></p><p>Módulo <b>kdeui</b></p><p>Construtor: KFadeWidgetEffect():new(QWidget * )</p><p>Método: KFadeWidgetEffect():start(int=250 ) -> void</p>
</body>
</html>
|
marcosgambeta/KDE4xHb
|
doc/classes/KFadeWidgetEffect.html
|
HTML
|
mit
| 388
|
// Dependencies
var Enny = require("enny")
, Deffy = require("deffy")
;
/**
* lineType
* Returns the line type for given input.
*
* @name lineType
* @function
* @param {Element|SubElement} source The source (sub)element.
* @param {Element|SubElement} target The target (sub)element.
* @param {} target
* @return {String} The line type.
*/
module.exports = function (source, target) {
if (!Deffy(source.id.parentId, {}, true).isServer && Deffy(target.id.parentId, {}, true).isServer) {
return "link-in";
}
// * -> error
if (Enny.TYPES(target.type, Enny.TYPES.errorHandler)) {
// "line-"
// <path class="line-error-in"...>
return "error-in";
}
// error -> *
if (Enny.TYPES(source.type, Enny.TYPES.errorHandler)) {
return "error-out";
}
// data -> *
if (Enny.TYPES(source.type, Enny.TYPES.dataHandler)) {
return "data-out";
}
return "normal";
};
|
jillix/engine-parser
|
lib/parsers/line-type.js
|
JavaScript
|
mit
| 959
|
package org.robolectric;
import android.app.Application;
import org.junit.Test;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import android.content.res.Resources;
import android.content.res.Configuration;
import org.robolectric.internal.ParallelUniverse;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(TestRunners.WithDefaults.class)
public class ParallelUniverseTest {
private ParallelUniverse pu;
@Before
public void setUp() {
pu = new ParallelUniverse(mock(RobolectricTestRunner.class));
pu.setSdkConfig(new SdkConfig(18));
}
@Test
public void setUpApplicationState_setsVersionQualifierFromSdkConfig() {
String givenQualifiers = "";
Config c = new Config.Implementation(-1, Config.DEFAULT, givenQualifiers, "res", -1, new Class[0], Application.class, new String[0]);
pu.setUpApplicationState(null, new DefaultTestLifecycle(), false, null, null, c);
assertThat(getQualifiersfromSystemResources()).isEqualTo("v18");
assertThat(getQualifiersFromAppAssetManager()).isEqualTo("v18");
assertThat(getQualifiersFromSystemAssetManager()).isEqualTo("v18");
}
@Test
public void setUpApplicationState_setsVersionQualifierFromConfigQualifiers() {
String givenQualifiers = "land-v17";
Config c = new Config.Implementation(-1, Config.DEFAULT, givenQualifiers, "res", -1, new Class[0], Application.class, new String[0]);
pu.setUpApplicationState(null, new DefaultTestLifecycle(), false, null, null, c);
assertThat(getQualifiersfromSystemResources()).isEqualTo("land-v17");
assertThat(getQualifiersFromAppAssetManager()).isEqualTo("land-v17");
assertThat(getQualifiersFromSystemAssetManager()).isEqualTo("land-v17");
}
@Test
public void setUpApplicationState_setsVersionQualifierFromSdkConfigWithOtherQualifiers() {
String givenQualifiers = "large-land";
Config c = new Config.Implementation(-1, Config.DEFAULT, givenQualifiers, "res", -1, new Class[0], Application.class, new String[0]);
pu.setUpApplicationState(null, new DefaultTestLifecycle(), false, null, null, c);
assertThat(getQualifiersfromSystemResources()).isEqualTo("large-land-v18");
assertThat(getQualifiersFromAppAssetManager()).isEqualTo("large-land-v18");
assertThat(getQualifiersFromSystemAssetManager()).isEqualTo("large-land-v18");
}
private String getQualifiersfromSystemResources() {
Resources systemResources = Resources.getSystem();
Configuration configuration = systemResources.getConfiguration();
return Robolectric.shadowOf(configuration).getQualifiers();
}
private String getQualifiersFromAppAssetManager() {
return Robolectric.shadowOf(Robolectric.application.getResources().getAssets()).getQualifiers();
}
private String getQualifiersFromSystemAssetManager() {
return Robolectric.shadowOf(Resources.getSystem().getAssets()).getQualifiers();
}
}
|
gabrielduque/robolectric
|
robolectric/src/test/java/org/robolectric/ParallelUniverseTest.java
|
Java
|
mit
| 2,981
|
<?php
class ErrorIndexAction extends CAction {
public $view = 'index';
public function run() {
Yii::app()->errorHandler->errorAction = 'error/index';
if ($error = Yii::app()->errorHandler->error) {
if (Yii::app()->request->isAjaxRequest) {
echo $error['message'];
} else {
$this->controller->render($this->view, $error);
}
}
}
}
|
nek-v/yii-min-app
|
protected/actions/ErrorIndexAction.php
|
PHP
|
mit
| 437
|
package com.github.acc15.glob.matchers;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Vyacheslav Mayorov
* @since 2016-12-01
*/
public class MatchersTest {
@Test
public void testPattern() throws Exception {
// pattern "abc?{xyz,yui}.zip"
final GlobPattern pattern = new GlobPattern(
Matchers.text("abc"),
Matchers.zeroOrMore(),
Matchers.variants(Matchers.text("xyz"), Matchers.text("yui")),
Matchers.any(),
Matchers.text(".zip"));
assertThat(pattern.test("abcxyzl.zip")).isTrue();
assertThat(pattern.test("abcdyuia.zip")).isTrue();
assertThat(pattern.test("abceyuid.zip")).isTrue();
assertThat(pattern.test("abceyuid.zi")).isFalse(); // ".zip" not matches
assertThat(pattern.test("abcddkokk.zip")).isFalse(); // "{xyz,yui}" not matches
assertThat(pattern.test("abdcyui2.zip")).isFalse(); // "abc" not matches
}
@Test
public void testVariantMatcher() throws Exception {
final GlobPattern pattern = new GlobPattern(
Matchers.variants(Matchers.text("abc"), Matchers.text("xyz")),
Matchers.text("ddd"));
assertThat(pattern.test("abcddd")).isTrue();
assertThat(pattern.test("xyzddd")).isTrue();
assertThat(pattern.test("abcxyzddd")).isFalse();
assertThat(pattern.test("xyzabcddd")).isFalse();
}
@Test
public void testVariantWithSequence() throws Exception {
final GlobPattern pattern = new GlobPattern(
Matchers.variants(Matchers.sequence(Matchers.any(), Matchers.text("yz")), Matchers.text("yui")));
assertThat(pattern.test("ayz")).isTrue();
assertThat(pattern.test("byz")).isTrue();
assertThat(pattern.test("zyz")).isTrue();
assertThat(pattern.test("yui")).isTrue();
assertThat(pattern.test("abc")).isFalse();
assertThat(pattern.test("cde")).isFalse();
assertThat(pattern.test("fdkj")).isFalse();
}
}
|
acc15/glob
|
src/test/java/com/github/acc15/glob/matchers/MatchersTest.java
|
Java
|
mit
| 2,078
|
package com.shdwlf.boom.listeners;
import com.shdwlf.boom.Boom;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class InteractListener implements Listener {
private final Boom plugin;
public InteractListener(Boom plugin) {
this.plugin = plugin;
}
/**
* Listen for player to shift click on TNT with a block
*/
@EventHandler
public void onInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().isSneaking()) {
Block clickedBlock = event.getClickedBlock();
if (clickedBlock != null && clickedBlock.getType() == Material.TNT) {
event.setCancelled(true);
ItemStack inHand = event.getPlayer().getItemInHand();
if (!event.getPlayer().hasPermission("boom.use")) {
event.getPlayer().sendMessage(ChatColor.RED + "You do not have permission.");
return;
}
if (inHand != null && inHand.getType().isBlock() && inHand.getType() != Material.TNT && inHand.getType().isOccluding() && checkEconomy(event.getPlayer())) {
clickedBlock.setType(inHand.getType());
clickedBlock.setData((byte) inHand.getDurability());
clickedBlock.getState().update();
if (event.getPlayer().getGameMode() != GameMode.CREATIVE) {
//Remove item from player
if (inHand.getAmount() > 1) {
inHand.setAmount(inHand.getAmount() - 1);
event.getPlayer().setItemInHand(inHand);
event.getPlayer().updateInventory();
} else {
event.getPlayer().setItemInHand(null);
event.getPlayer().updateInventory();
}
}
plugin.getBlockManager().registerBlock(clickedBlock);
if (plugin.economy != null)
plugin.economy.withdrawPlayer(event.getPlayer(), plugin.getConfig().getDouble("economy.create-cost", 1000));
event.getPlayer().getLocation().getWorld().playSound(event.getPlayer().getLocation(), Sound.LEVEL_UP, 1F, 1F);
}
}
}
}
private boolean checkEconomy(Player player) {
if (plugin.economy == null)
return true;
else {
double cost = plugin.getConfig().getDouble("economy.create-cost", 1000);
if (plugin.economy.has(player, cost)) {
return true;
} else {
String formatted = plugin.economy.format(cost);
String message = plugin.getConfig().getString("lang.not-enough-money", "You do not have enough money &8(&c%cost%&8)&c.").replace("%cost", formatted);
player.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("lang.prefix", "&7[&cBoom&7] &r")) + ChatColor.translateAlternateColorCodes('&', message));
return false;
}
}
}
}
|
dfanara/Boom
|
src/main/java/com/shdwlf/boom/listeners/InteractListener.java
|
Java
|
mit
| 3,529
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
namespace System.Net.NetworkInformation.Tests
{
internal static class FileUtil
{
public static void NormalizeLineEndings(string source, string normalizedDest)
{
// I'm storing the test text assets with their original line endings ('\n').
// The parsing logic depends on Environment.NewLine, so we normalize beforehand.
string contents = File.ReadAllText(source);
if (Environment.NewLine == "\r\n")
{
if (!contents.Contains(Environment.NewLine))
{
contents = contents.Replace("\n", "\r\n");
}
}
else if (Environment.NewLine == "\n")
{
if (contents.Contains("\r\n"))
{
contents = contents.Replace("\r\n", "\n");
}
}
File.WriteAllText(normalizedDest, contents);
}
}
}
|
mafiya69/corefx
|
src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs
|
C#
|
mit
| 1,218
|
var decode = require('base64-decode');
var crypto = require('crypto');
var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z';
var SALT = 'af0ik392jrmt0nsfdghy0';
function parse(save) {
if (save.indexOf(ANTI_CHEAT_CODE) > -1) {
var result = save.split(ANTI_CHEAT_CODE);
save = '';
for (var i = 0; i < result[0].length; i += 2) {
save += result[0].charAt(i);
}
var md5 = crypto.createHash('md5');
md5.update(save + SALT, 'ascii');
if (md5.digest('hex') !== result[1]) {
throw new Error('Bad hash');
}
}
else {
throw new Error('Anti-cheat code not found');
}
var data = JSON.parse(decode(save));
return data;
}
module.exports = parse;
|
KenanY/clickerheroes-save
|
index.js
|
JavaScript
|
mit
| 683
|
from flask import render_template
from app import app, host, port, user, passwd, db
from app.helpers.database import con_db, query_db
from app.helpers.filters import *
from app.helpers.filters import format_currency
import jinja2
from flask import request, url_for
# To create a database connection, add the following
# within your view functions:
# con = con_db(host, port, user, passwd, db)
# ROUTING/VIEW FUNCTIONS
@app.route('/', methods=['GET'])
def index():
# Create database connection
con = con_db(host, port, user, passwd, db)
# Add custom filter to jinja2 env
jinja2.filters.FILTERS['format_currency'] = format_currency
var_dict = {
"home": request.args.get("home"),
"year_built": request.args.get("year_built", '0'),
"zip_code": request.args.get("zip_code", '0'),
"list_price": request.args.get("list_price", '0'),
"min_list_price": request.args.get("min_list_price", '0'),
"max_list_price": request.args.get("max_list_price", '0'),
"beds": request.args.get("beds", '0'),
"baths": request.args.get("baths", '0'),
"sqft": request.args.get("sqft", '0'),
"dom": request.args.get("dom", '0'),
"parking": request.args.get("parking", '0'),
"prediction": request.args.get("prediction", '0'),
"bike_score": request.args.get("bike_score", '0'),
"transit_score": request.args.get("transit_score", '0'),
"walk_score": request.args.get("walk_score", '0'),
"order_by": request.args.get("order_by", "difference"),
"sort": request.args.get("sort", "ASC")
}
# Query the database
data = query_db(con, var_dict)
# Add data to dictionary
var_dict["data"] = data
return render_template('homes.html', settings=var_dict)
@app.route('/home')
def home():
# Create database connection
con = con_db(host, port, user, passwd, db)
# Add custom filter to jinja2 env
jinja2.filters.FILTERS['format_currency'] = format_currency
var_dict = {
"home": request.args.get("home"),
"year_built": request.args.get("year_built", '0'),
"zip_code": request.args.get("zip_code", '0'),
"list_price": request.args.get("list_price", '0'),
"min_list_price": request.args.get("min_list_price", '0'),
"max_list_price": request.args.get("max_list_price", '0'),
"beds": request.args.get("beds", '0'),
"baths": request.args.get("baths", '0'),
"sqft": request.args.get("sqft", '0'),
"dom": request.args.get("dom", '0'),
"parking": request.args.get("parking", '0'),
"prediction": request.args.get("prediction", '0'),
"bike_score": request.args.get("bike_score", '0'),
"transit_score": request.args.get("transit_score", '0'),
"walk_score": request.args.get("walk_score", '0'),
"order_by": request.args.get("order_by", "difference"),
"sort": request.args.get("sort", "ASC")
}
# Query the database
data = query_db(con, var_dict)
# Add data to dictionary
var_dict["data"] = data # Renders home.html.
return render_template('splash.html', settings=var_dict)
@app.route('/slides')
def about():
# Renders slides.html.
return render_template('slides.html')
@app.route('/author')
def contact():
# Renders author.html.
return render_template('author.html')
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('500.html'), 500
|
MonicaHsu/truvaluation
|
app/static/temp.html
|
HTML
|
mit
| 3,588
|
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
///
/// LOGIN WITHOUT PASSWORD
///
// Method called by a user to request a password reset email. This is
// the start of the reset process.
Meteor.methods({
loginWithoutPassword: function ({ email, username = null }) {
if (username !== null) {
check(username, String);
var user = Meteor.users.findOne({ $or: [{
"username": username, "emails.address": { $exists: 1 }
}, {
"emails.address": email
}]
});
if (!user)
throw new Meteor.Error(403, "User not found");
email = user.emails[0].address;
}
else {
check(email, String);
var user = Meteor.users.findOne({ "emails.address": email });
if (!user)
throw new Meteor.Error(403, "User not found");
}
if (Accounts.ui._options.requireEmailVerification) {
if (!user.emails[0].verified) {
throw new Meteor.Error(403, "Email not verified");
}
}
Accounts.sendLoginEmail(user._id, email);
},
});
/**
* @summary Send an email with a link the user can use verify their email address.
* @locus Server
* @param {String} userId The id of the user to send email to.
* @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first unverified email in the list.
*/
Accounts.sendLoginEmail = function (userId, address) {
// XXX Also generate a link using which someone can delete this
// account if they own said address but weren't those who created
// this account.
// Make sure the user exists, and address is one of their addresses.
var user = Meteor.users.findOne(userId);
if (!user)
throw new Error("Can't find user");
// pick the first unverified address if we weren't passed an address.
if (!address) {
var email = (user.emails || []).find(({ verified }) => !verified);
address = (email || {}).address;
}
// make sure we have a valid address
if (!address || !(user.emails || []).map(({ address }) => address).includes(address))
throw new Error("No such email address for user.");
var tokenRecord = {
token: Random.secret(),
address: address,
when: new Date()};
Meteor.users.update(
{_id: userId},
{$push: {'services.email.verificationTokens': tokenRecord}});
// before passing to template, update user object with new token
Meteor._ensure(user, 'services', 'email');
if (!user.services.email.verificationTokens) {
user.services.email.verificationTokens = [];
}
user.services.email.verificationTokens.push(tokenRecord);
var loginUrl = Accounts.urls.verifyEmail(tokenRecord.token);
var options = {
to: address,
from: Accounts.emailTemplates.loginNoPassword.from
? Accounts.emailTemplates.loginNoPassword.from(user)
: Accounts.emailTemplates.from,
subject: Accounts.emailTemplates.loginNoPassword.subject(user)
};
if (typeof Accounts.emailTemplates.loginNoPassword.text === 'function') {
options.text =
Accounts.emailTemplates.loginNoPassword.text(user, loginUrl);
}
if (typeof Accounts.emailTemplates.loginNoPassword.html === 'function')
options.html =
Accounts.emailTemplates.loginNoPassword.html(user, loginUrl);
if (typeof Accounts.emailTemplates.headers === 'object') {
options.headers = Accounts.emailTemplates.headers;
}
Email.send(options);
};
// Check for installed accounts-password dependency.
if (Accounts.emailTemplates) {
Accounts.emailTemplates.loginNoPassword = {
subject: function(user) {
return "Login on " + Accounts.emailTemplates.siteName;
},
text: function(user, url) {
var greeting = (user.profile && user.profile.name) ?
("Hello " + user.profile.name + ",") : "Hello,";
return `${greeting}
To login, simply click the link below.
${url}
Thanks.
`;
}
};
}
|
studiointeract/accounts-ui
|
imports/api/server/loginWithoutPassword.js
|
JavaScript
|
mit
| 3,963
|
# SUS_3D
Simulating thin film growth with 3-D Rod like particles: Using the Successive umbrella sampling Algorithm
|
Aieener/SUS_3D
|
README.md
|
Markdown
|
mit
| 115
|
//
// ProductFilterResultTableAdapter.h
// TianJiCloud
//
// Created by 朱鹏 on 2017/8/10.
// Copyright © 2017年 TianJiMoney. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ProductFilterResultConfigurateProtocol.h"
@interface ProductFilterResultTableAdapter : NSObject<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,weak) id<ProductFilterResultInteractor> interactor;
//@property (nonatomic,weak) id<TJSProductFilterResultCellDelegate> cellDelegate;
- (instancetype)initWithTableView:(UITableView *)tableView;
@end
|
BaoSeed/TianFuYun
|
ios/TianJiCloud/Sections/ProductFilter/Result/Disaggregate/ProductFilterResultTableAdapter.h
|
C
|
mit
| 570
|
<!DOCTYPE html>
<html>
<head>
<title>Flashcards</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="js/checkLoggedIn.js" type="text/javascript"></script>
</head>
<body class="main">
<nav class="navbar navbar-custom">
<div class="navbar-header">
<a class="navbar-brand" href="#">Flashcards</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="logout">Sign out</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<p class="welcome">Welcome, {{NAME}}</p>
<!-- <p class="user-score">50%</p>-->
<p><a href="cards.html">View Score</a> for each card</p>
<div class="controls text-center">
<button class="btn btn-lg btn-custom"><a href="reviewcard.html">Review Cards</a></button>
<p><a href="addcard.html">Add New Cards</a></p>
</div>
</div>
</div>
</div>
</body>
</html>
|
ryanwcraig/INFSCI-1025-Flashcards
|
Flashcards/web/home.html
|
HTML
|
mit
| 1,699
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>IRC: Ircbot Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">IRC
 <span id="projectnumber">0.1</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Macros</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-attribs">Public Attributes</a> |
<a href="struct_ircbot-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">Ircbot Struct Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a578e1b551365a0cfae1988a08cd44338"><td class="memItemLeft" align="right" valign="top">string </td><td class="memItemRight" valign="bottom"><a class="el" href="struct_ircbot.html#a578e1b551365a0cfae1988a08cd44338">name</a></td></tr>
<tr class="separator:a578e1b551365a0cfae1988a08cd44338"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1792738fa95166d28cbb44e6e2b4b02a"><td class="memItemLeft" align="right" valign="top">string </td><td class="memItemRight" valign="bottom"><a class="el" href="struct_ircbot.html#a1792738fa95166d28cbb44e6e2b4b02a">port</a></td></tr>
<tr class="separator:a1792738fa95166d28cbb44e6e2b4b02a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0a4c331476d0cfc4450626ae053432f7"><td class="memItemLeft" align="right" valign="top">string </td><td class="memItemRight" valign="bottom"><a class="el" href="struct_ircbot.html#a0a4c331476d0cfc4450626ae053432f7">server</a></td></tr>
<tr class="separator:a0a4c331476d0cfc4450626ae053432f7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac0b9a9e243989a264d5a4a0a09457be1"><td class="memItemLeft" align="right" valign="top">string </td><td class="memItemRight" valign="bottom"><a class="el" href="struct_ircbot.html#ac0b9a9e243989a264d5a4a0a09457be1">channel</a></td></tr>
<tr class="separator:ac0b9a9e243989a264d5a4a0a09457be1"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="ac0b9a9e243989a264d5a4a0a09457be1"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">string Ircbot::channel</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a578e1b551365a0cfae1988a08cd44338"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">string Ircbot::name</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a1792738fa95166d28cbb44e6e2b4b02a"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">string Ircbot::port</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a0a4c331476d0cfc4450626ae053432f7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">string Ircbot::server</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this struct was generated from the following file:<ul>
<li>src/<a class="el" href="main_8cpp.html">main.cpp</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Jun 12 2013 16:07:21 for IRC by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
|
m1001243/Linux_Projekt
|
html/struct_ircbot.html
|
HTML
|
mit
| 7,750
|
<?php
namespace LSI\OrderBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class TaxRate
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=5, unique=true)
*/
protected $zip;
/**
* @ORM\Column(type="decimal", precision=6, scale=5)
*/
protected $rate;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getZip()
{
return $this->zip;
}
public function setZip($zip)
{
$this->zip = $zip;
return $this;
}
public function getRate()
{
return $this->rate;
}
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
}
|
Storyitr8/LivingScripturesWS
|
src/LSI/OrderBundle/Entity/TaxRate.php
|
PHP
|
mit
| 987
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.