repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
delamoe/fcc-tic-tac-toe | ttt.css | 911 | body {
font-family: 'Rancho', cursive;
font-weight: bold;
margin: auto;
padding: 5%;
background-color: #F49D37;
}
.score,
.game {
color: #0A1128;
font-size: 28px;
}
#board {
width: 450px;
height: 450px;
}
#board .square {
width: 33.333333333%;
height: 33.333333333%;
background-color: #496DDB;
float: left;
text-align: center;
line-height: 155px;
}
.square {
font-size: 170px;
color: #2E4052;
border: 2px dashed #F49D37;
}
.topRow {
border-top: none;
}
.right {
border-right: none;
}
.botRow {
border-bottom: none;
}
.left {
border-left: none;
}
.topRow.right {
border-radius: 0 10% 0 0;
}
.topRow.left {
border-radius: 10% 0 0 0;
}
.botRow.right {
border-radius: 0 0 10% 0;
}
.botRow.left {
border-radius: 0 0 0 10%;
}
#data-bottom,
#data-top {
width: 450px;
}
.btnText {
color: #0A1128;
font-size: 50px;
}
| mit |
couchbaselabs/touchbase | TouchbaseModular/public/deprecated/pictureUpload.html | 3981 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Couch411 | Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="/semantic-ui/dist/semantic.min.css">
<script src="semantic-ui/dist/semantic.min.js"></script>
<link href="./ng-cropper/dist/ngCropper.all.css" rel="stylesheet">
<script src="./ng-cropper/dist/ngCropper.all.js"></script>
<script src="./js/picture.js"></script>
<!--<script src="ng-flow-standalone.js"></script>
<script src="ng-img-crop.js"></script>
<link rel="stylesheet" type="text/css" href="ng-img-crop.css"/>-->
</head>
<body ng-app="picture" ng-controller="pictureController" ng-init="printSessionStorage()">
<h4 class = "text-center"> My Profile </h4>
<button class="ui button">Follow</button>
<script type="text/javascript">
$(window).load(function(){
$('#myModal').modal('show');
});
var closemodal = function() { $('#myModal').modal('hide'); };
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id = "uploadForm" action="/api/uploadAttempt" method="post" enctype="multipart/form-data">
<div class="modal-header">
<!--<button type="button" class="close" data-dismiss="modal"><span
aria-hidden="true">×</span><span class="sr-only">Close</span></button>-->
<h4 class="modal-title" id="myModalLabel">Upload Profile Picture</h4>
</div>
<div class="modal-body">
<input type="file" onchange="angular.element(this).scope().onFile(this.files[0])" name="userPhoto" accept="image/*">
<button class="btn btn-default" ng-click="preview()">Show preview</button>
<button class="btn btn-default" ng-click="scale(200)">Scale to 200px width</button>
<label>Disabled <input type="checkbox" ng-model="options.disabled"></label>
<br />
<div ng-if="dataUrl" class="img-container">
<img ng-if="dataUrl" ng-src="{{dataUrl}}" width="300"
ng-cropper
ng-cropper-show="showEvent"
ng-cropper-hide="hideEvent"
ng-cropper-options="options">
</div>
<div class="preview-container">
<img ng-if="preview.dataUrl" ng-src="{{preview.dataUrl}}">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No Thanks</button>
<input type="hidden" value="{{session.sessionID}}" name="sessionID" >
<input type="hidden" value="{{cropDim}}" name="cropDim" >
<input ng-click="finalCropCheck();" onclick="closemodal();" type="submit" value="Upload Picture" name="submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<button class="btn btn-default" ng-click="publishTry()">Make Post</button>
<button class = "btn btn-primary" ng-click="getMyProfile()"> Get My Profile </button>
<span>{{myData.changed}}</span>
<img width="100" height="100" ng-src="{{myData.changed.users.picSRC}}"></img>
</body> | mit |
qq137712630/MeiZiNews | app/src/main/java/com/ms/meizinewsapplication/features/meizi/model/DbGroupBreastModel.java | 1004 | package com.ms.meizinewsapplication.features.meizi.model;
import android.content.Context;
import com.ms.meizinewsapplication.features.base.pojo.ImgItem;
import com.ms.retrofitlibrary.web.MyOkHttpClient;
import org.loader.model.OnModelListener;
import java.util.List;
import rx.Observable;
import rx.Subscription;
/**
* Created by 啟成 on 2016/3/15.
*/
public class DbGroupBreastModel extends DbGroupModel {
private String pager_offset;
public Subscription loadWeb(Context context, OnModelListener<List<ImgItem>> listener, String pager_offset) {
this.pager_offset = pager_offset;
return loadWeb(context, listener);
}
@Override
protected Subscription reSubscription(Context context, OnModelListener<List<ImgItem>> listener) {
Observable<String> dbGroupBreast = getDbGroup().RxDbGroupBreast(
MyOkHttpClient.getCacheControl(context),
pager_offset
);
return rxDbGroup(dbGroupBreast, listener);
}
}
| mit |
nellypeneva/SoftUniProjects | 01_ProgrFundamentalsMay/11_Data-Types-Exercises/12_RectangleProperties/Properties/AssemblyInfo.cs | 1420 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("12_RectangleProperties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12_RectangleProperties")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efacbe98-13fb-4c4d-b368-04e2f314a249")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
KevinJMcGrath/Symphony-Ares | modules/plugins/PABot/logging.py | 796 | import logging.handlers
import os
_pabotlog = logging.getLogger('PABot')
_pabotlog.setLevel(logging.DEBUG)
_logPath = os.path.abspath("./logging/pabot.log")
_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
_consoleStreamHandler = logging.StreamHandler()
_consoleStreamHandler.setLevel(logging.DEBUG)
_consoleStreamHandler.setFormatter(_formatter)
_symLogRotFileHandler = logging.handlers.RotatingFileHandler(_logPath, maxBytes=2000000, backupCount=5)
_symLogRotFileHandler.setLevel(logging.DEBUG)
_symLogRotFileHandler.setFormatter(_formatter)
_pabotlog.addHandler(_consoleStreamHandler)
_pabotlog.addHandler(_symLogRotFileHandler)
def LogPABotMessage(message):
_pabotlog.info(message)
def LogPABotError(message):
_pabotlog.error(message)
| mit |
ericwebster/project-crayfish | templates/storycontributor/individual.html | 4116 | {# ------------------------------------------------------- #}
{# INDIVIDUAL VIEW FOR EACH storycontributor #}
{# This page can use any data from http:localhost:2000/cms/#/form/storycontributor/ #}
{# Webhook uses the SWIG.js (like Djagno/Twig) templating system. Their documentation is here: #}
{# http://paularmstrong.github.io/swig/docs/tags/ #}
{# Learn about calling data into Webhook pages here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/ #}
{# ------------------------------------------------------- #}
{# Confused what extends and blocks do? Watch a primer: #}
{# http://www.webhook.com/docs/template-inheritance-blocks/ #}
{% extends "templates/partials/base.html" %}
{# This sets our page <title>. It will append this storycontributor's name to the site title defined in base.html #}
{% block title %}{% parent %} - {{ item.name }}{% endblock %}
{% block content %}
<p><a href="{{ url('storycontributor') }}">View a list of all storycontributor</a></p>
<h1>{{ item.name }}</h1>
<ul>
<li>
<strong>Name: </strong>
{{ item.name }}
</li>
<li>
<strong>Create Date: </strong>
{# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
{{ item.create_date|date('F d Y') }}
</li>
<li>
<strong>Last Updated: </strong>
{# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
{{ item.last_updated|date('F d Y') }}
</li>
<li>
<strong>Publish Date: </strong>
{# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
{{ item.publish_date|date('F d Y') }}
</li>
<li>
<strong>First Name: </strong>
{{ item.first_name }}
</li>
<li>
<strong>Last Name: </strong>
{{ item.last_name }}
</li>
<li>
<strong>Title: </strong>
{{ item.title }}
</li>
<li>
<strong>Company: </strong>
{{ item.company }}
</li>
<li>
<strong>Bio - Short: </strong>
{{ item.bio__short }}
</li>
<li>
<strong>Bio - Full: </strong>
{{ item.bio__full|safe }}
</li>
<li>
<strong>Avatar: </strong>
{# You can pull out a lot more information from the image property. Info here: #}
{# http://www.webhook.com/docs/widget-template-reference/#image #}
<img src="{{ item.avatar|imageSize(200) }}" />
</li>
<li>
<strong>Website: </strong>
{{ item.website }}
</li>
<li>
<strong>Twitter: </strong>
{{ item.twitter }}
</li>
<li>
<strong>LinkedIn: </strong>
{{ item.linkedin }}
</li>
<li>
<strong>Preview URL: </strong>
{{ item.preview_url }}
</li>
<li>
<strong>Slug: </strong>
{{ item.slug }}
</li>
<li>
<strong>Story (Contributor - Primary): </strong>
{# Relations require some special code. More info about relations here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/#getitem #}
{% for relation in item.story_contributor__primary %}
{# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
<a href="{{ url(relation) }}">{{ relation.name }}</a>{% if not loop.last %},{% endif %}
{% endfor %}
</li>
<li>
<strong>Story (Contributor - Additional): </strong>
{# Relations require some special code. More info about relations here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/#getitem #}
{% for relation in item.story_contributor__additional %}
{# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
<a href="{{ url(relation) }}">{{ relation.name }}</a>{% if not loop.last %},{% endif %}
{% endfor %}
</li>
</ul>
{% endblock %}
| mit |
0bin/Project-collection | BBBLayer/BBBLayer/BBBClockViewController.h | 224 | //
// BBBClockViewController.h
// BBBLayer
//
// Created by LinBin on 16/7/23.
// Copyright © 2016年 LinBin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BBBClockViewController : UIViewController
@end
| mit |
frjf14/Projekt | vendor/phpmvc/comment/src/Comment/CommentController.php | 3878 | <?php
namespace Phpmvc\Comment;
/**
* To attach comments-flow to a page or some content.
*
*/
class CommentController implements \Anax\DI\IInjectionAware
{
use \Anax\DI\TInjectable;
/**
* View all comments.
*
* @return void
*/
public function viewAction($page)
{
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$all = $comments->findAll($page);
$this->views->add('comment/comments', [
'comments' => $all,
]);
}
/**
* Add a comment.
*
* @return void
*/
public function addAction()
{
$isPosted = $this->request->getPost('doCreate');
if (!$isPosted) {
$this->response->redirect($this->request->getPost('redirect'));
}
$comment = [
'page' => $this->request->getPost('page'),
'content' => $this->request->getPost('content'),
'name' => $this->request->getPost('name'),
'web' => $this->request->getPost('web'),
'mail' => $this->request->getPost('mail'),
'timestamp' => time(),
'ip' => $this->request->getServer('REMOTE_ADDR'),
];
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$comments->add($comment);
$this->response->redirect($this->request->getPost('redirect'));
}
/**
* Remove all comments.
*
* @return void
*/
public function removeAllAction()
{
$isPosted = $this->request->getPost('doRemoveAll');
if (!$isPosted) {
$this->response->redirect($this->request->getPost('redirect'));
}
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$comments->deleteAll();
$this->response->redirect($this->request->getPost('redirect'));
}
public function removeAction($id)
{
// $isPosted = $this->request->getPost('doRemove'); //doRemove måste lägga till i formulär i tpl.
// if (!$isPosted) {
// $this->response->redirect($this->request->getPost('redirect'));
// }
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$comments->delete($id);
$this->response->redirect($this->request->getPost('redirect'));
}
public function editFormAction($id)
{
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$all = $comments->findAll();
$i = 0;
foreach($all as $comment){
if($comment['id'] == $id){
break;
}
$i++;
}
$this->views->add('comment/editComment', [
'comment' => $all[$i],
]);
}
public function editAction($id)
{
$isPosted = $this->request->getPost('doEdit');
if (!$isPosted) {
$this->response->redirect($this->request->getPost('redirect'));
}
$comment = [
'page' => $this->request->getPost('page'),
'content' => $this->request->getPost('content'),
'name' => $this->request->getPost('name'),
'web' => $this->request->getPost('web'),
'mail' => $this->request->getPost('mail'),
'timestamp' => $this->request->getPost('timestamp'),
'ip' => $this->request->getServer('REMOTE_ADDR'),
'id' => $id,
'edited' => time(),
];
$comments = new \Phpmvc\Comment\CommentsInSession();
$comments->setDI($this->di);
$comments->edit($comment, $id);
$this->response->redirect($this->request->getPost('redirect'));
}
}
| mit |
AusDTO/citizenship-appointment-server | bin/cideploy.sh | 886 | #!/bin/bash
# Exit immediately if any commands return non-zero
set -e
# Output the commands we run
set -x
# This is a modified version of the Cloud Foundry Blue/Green deployment guide:
# https://docs.pivotal.io/pivotalcf/devguide/deploy-apps/blue-green.html
test $URL
# Update the blue app
cf unmap-route citizenship-appointment-blue $URL
cf push citizenship-appointment-blue -b https://github.com/AusDTO/java-buildpack.git --no-hostname --no-manifest --no-route -p build/libs/citizenship-appointments-0.0.1.jar -i 1 -m 512M
cf map-route citizenship-appointment-blue $URL
# Update the green app
cf unmap-route citizenship-appointment-green $URL
cf push citizenship-appointment-green -b https://github.com/AusDTO/java-buildpack.git --no-hostname --no-manifest --no-route -p build/libs/citizenship-appointments-0.0.1.jar -i 1 -m 512M
cf map-route citizenship-appointment-green $URL
| mit |
vdods/heisenberg | heisenberg/plot/__main__.py | 4283 | import ast
import heisenberg.library.heisenberg_dynamics_context
import heisenberg.library.orbit_plot
import heisenberg.option_parser
import heisenberg.plot
import heisenberg.util
import matplotlib
import numpy as np
import sys
# https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell block limit" problems
matplotlib.rcParams['agg.path.chunksize'] = 10000
dynamics_context = heisenberg.library.heisenberg_dynamics_context.Numeric()
op = heisenberg.option_parser.OptionParser(module=heisenberg.plot)
# Add the subprogram-specific options here.
op.add_option(
'--initial-preimage',
dest='initial_preimage',
type='string',
help='Specifies the preimage of the initial conditions with respect to the embedding map specified by the --embedding-dimension and --embedding-solution-sheet-index option values. Should have the form [x_1,...,x_n], where n is the embedding dimension and x_i is a floating point literal for each i.'
)
op.add_option(
'--initial',
dest='initial',
type='string',
help='Specifies the initial conditions [x,y,z,p_x,p_y,p_z], where each of x,y,z,p_x,p_y,p_z are floating point literals.'
)
op.add_option(
'--optimization-iterations',
dest='optimization_iterations',
default=1000,
type='int',
help='Specifies the number of iterations to run the optimization for (if applicable). Default is 1000.'
)
op.add_option(
'--optimize-initial',
dest='optimize_initial',
action='store_true',
default=False,
help='Indicates that the specified initial condition (via whichever of the --initial... options) should be used as the starting point for an optimization to attempt to close the orbit. Default value is False.'
)
op.add_option(
'--output-dir',
dest='output_dir',
default='.',
help='Specifies the directory to write plot images and data files to. Default is current directory.'
)
op.add_option(
'--disable-plot-initial',
dest='disable_plot_initial',
action='store_true',
default=False,
help='Disables plotting the initial curve; only has effect if --optimize-initial is specified.'
)
options,args = op.parse_argv_and_validate()
if options is None:
sys.exit(-1)
num_initial_conditions_specified = sum([
options.initial_preimage is not None,
options.initial is not None,
])
if num_initial_conditions_specified != 1:
print('Some initial condition option must be specified; --initial-preimage, --initial. However, {0} of those were specified.'.format(num_initial_conditions_specified))
op.print_help()
sys.exit(-1)
# Validate subprogram-specific options here.
# Attempt to parse initial conditions. Upon success, the attribute options.qp_0 should exist.
if options.initial_preimage is not None:
try:
options.initial_preimage = np.array(ast.literal_eval(options.initial_preimage))
expected_shape = (options.embedding_dimension,)
if options.initial_preimage.shape != expected_shape:
raise ValueError('--initial-preimage value had the wrong number of components (got {0} but expected {1}).'.format(options.initial_preimage.shape, expected_shape))
options.qp_0 = dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)(options.initial_preimage)
except Exception as e:
print('error parsing --initial-preimage value; error was {0}'.format(e))
op.print_help()
sys.exit(-1)
elif options.initial is not None:
try:
options.initial = heisenberg.util.csv_as_ndarray(heisenberg.util.pop_brackets_off_of(options.initial), float)
expected_shape = (6,)
if options.initial.shape != expected_shape:
raise ValueError('--initial value had the wrong number of components (got {0} but expected {1}).'.format(options.initial.shape, expected_shape))
options.qp_0 = options.initial.reshape(2,3)
except ValueError as e:
print('error parsing --initial value: {0}'.format(str(e)))
op.print_help()
sys.exit(-1)
else:
assert False, 'this should never happen because of the check with num_initial_conditions_specified'
rng = np.random.RandomState(options.seed)
heisenberg.plot.plot(dynamics_context, options, rng=rng)
| mit |
nicorellius/pdxpixel | pdxpixel/core/mailgun.py | 1073 | def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <[email protected]>",
"to": "nick <[email protected]>",
"subject": "Hello nick",
"text": "Congratulations nick, you just sent an email with Mailgun! You are truly awesome! You can see a record of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this sandbox server. Next, you should add your own domain so you can send 10,000 emails/month for free."})
# cURL command to send mail aith API key
# curl -s --user 'api:key-679dc79b890e700f11f001a6bf86f4a1' \
# https://api.mailgun.net/v3/mail.pdxpixel.com/messages \
# -F from='Excited User <[email protected]>' \
# -F [email protected] \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'
| mit |
ooxif/laravel-spec-schema | src/Ooxif/LaravelSpecSchema/SqlServer/BlueprintTrait.php | 77 | <?php
namespace Ooxif\LaravelSpecSchema\SqlServer;
trait BlueprintTrait
{
} | mit |
nhatbui/LebronCoin | lebroncoin/key_loader.py | 654 | def load_keys(filepath):
"""
Loads the Twitter API keys into a dict.
:param filepath: file path to config file with Twitter API keys.
:return: keys_dict
:raise: IOError
"""
try:
keys_file = open(filepath, 'rb')
keys = {}
for line in keys_file:
key, value = line.split('=')
keys[key.strip()] = value.strip()
except IOError:
message = ('File {} cannot be opened.'
' Check that it exists and is binary.')
print message.format(filepath)
raise
except:
print "Error opening or unpickling file."
raise
return keys
| mit |
originalbitcoin/original-bitcoin-client-0.1.0 | base58.h | 5438 | // Copyright (c) 2009 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Doubleclicking selects the whole number as one word if it's all alphanumeric.
//
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
inline string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to string
string str;
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian string to big endian
reverse(str.begin(), str.end());
return str;
}
inline string EncodeBase58(const vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
inline bool DecodeBase58(const char* psz, vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
inline bool DecodeBase58(const string& str, vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
inline string EncodeBase58Check(const vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
inline bool DecodeBase58Check(const char* psz, vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
inline bool DecodeBase58Check(const string& str, vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
static const unsigned char ADDRESSVERSION = 0;
inline string Hash160ToAddress(uint160 hash160)
{
// add 1-byte version number to the front
vector<unsigned char> vch(1, ADDRESSVERSION);
vch.insert(vch.end(), UBEGIN(hash160), UEND(hash160));
return EncodeBase58Check(vch);
}
inline bool AddressToHash160(const char* psz, uint160& hash160Ret)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(psz, vch))
return false;
if (vch.empty())
return false;
unsigned char nVersion = vch[0];
if (vch.size() != sizeof(hash160Ret) + 1)
return false;
memcpy(&hash160Ret, &vch[1], sizeof(hash160Ret));
return (nVersion <= ADDRESSVERSION);
}
inline bool AddressToHash160(const string& str, uint160& hash160Ret)
{
return AddressToHash160(str.c_str(), hash160Ret);
}
inline bool IsValidBitcoinAddress(const char* psz)
{
uint160 hash160;
return AddressToHash160(psz, hash160);
}
inline bool IsValidBitcoinAddress(const string& str)
{
return IsValidBitcoinAddress(str.c_str());
}
inline string PubKeyToAddress(const vector<unsigned char>& vchPubKey)
{
return Hash160ToAddress(Hash160(vchPubKey));
}
| mit |
snfactory/cubefit | cubefit/main.py | 26267 | """Main entry points for scripts."""
from __future__ import print_function, division
from argparse import ArgumentParser
from collections import OrderedDict
from copy import copy
from datetime import datetime
import glob
import json
import logging
import math
import os
import scipy.stats
import numpy as np
from .version import __version__
from .psffuncs import gaussian_moffat_psf
from .psf import TabularPSF, GaussianMoffatPSF
from .io import read_datacube, write_results, read_results
from .fitting import (guess_sky, fit_galaxy_single, fit_galaxy_sky_multi,
fit_position_sky, fit_position_sky_sn_multi,
RegularizationPenalty)
from .utils import yxbounds
from .extern import ADR, Hyper_PSF3D_PL
__all__ = ["cubefit", "cubefit_subtract", "cubefit_plot"]
MODEL_SHAPE = (32, 32)
SPAXEL_SIZE = 0.43
MIN_NMAD = 2.5 # Minimum Number of Median Absolute Deviations above
# the minimum spaxel value in fit_position
LBFGSB_FACTOR = 1e10
REFWAVE = 5000. # reference wavelength in Angstroms for PSF params and ADR
POSITION_BOUND = 3. # Bound on fitted positions relative in initial positions
def snfpsf(wave, psfparams, header, psftype):
"""Create a 3-d PSF based on SNFactory-specific parameterization of
Gaussian + Moffat PSF parameters and ADR."""
# Get Gaussian+Moffat parameters at each wavelength.
relwave = wave / REFWAVE - 1.0
ellipticity = abs(psfparams[0]) * np.ones_like(wave)
alpha = np.abs(psfparams[1] +
psfparams[2] * relwave +
psfparams[3] * relwave**2)
# correlated parameters (coefficients determined externally)
sigma = 0.545 + 0.215 * alpha # Gaussian parameter
beta = 1.685 + 0.345 * alpha # Moffat parameter
eta = 1.040 + 0.0 * alpha # gaussian ampl. / moffat ampl.
# Atmospheric differential refraction (ADR): Because of ADR,
# the center of the PSF will be different at each wavelength,
# by an amount that we can determine (pretty well) from the
# atmospheric conditions and the pointing and angle of the
# instrument. We calculate the offsets here as a function of
# observation and wavelength and input these to the model.
# Correction to parallactic angle and airmass for 2nd-order effects
# such as MLA rotation, mechanical flexures or finite-exposure
# corrections. These values have been trained on faint-std star
# exposures.
#
# `predict_adr_params` uses 'AIRMASS', 'PARANG' and 'CHANNEL' keys
# in input dictionary.
delta, theta = Hyper_PSF3D_PL.predict_adr_params(header)
# check for crazy values of pressure and temperature, and assign default
# values.
pressure = header.get('PRESSURE', 617.)
if not 550. < pressure < 650.:
pressure = 617.
temp = header.get('TEMP', 2.)
if not -20. < temp < 20.:
temp = 2.
adr = ADR(pressure, temp, lref=REFWAVE, delta=delta, theta=theta)
adr_refract = adr.refract(0, 0, wave, unit=SPAXEL_SIZE)
# adr_refract[0, :] corresponds to x, adr_refract[1, :] => y
xctr, yctr = adr_refract
if psftype == 'gaussian-moffat':
return GaussianMoffatPSF(sigma, alpha, beta, ellipticity, eta,
yctr, xctr, MODEL_SHAPE, subpix=3)
elif psftype == 'tabular':
A = gaussian_moffat_psf(sigma, alpha, beta, ellipticity, eta,
yctr, xctr, MODEL_SHAPE, subpix=3)
return TabularPSF(A)
else:
raise ValueError("unknown psf type: " + repr(psftype))
def setup_logging(loglevel, logfname=None):
# if loglevel isn't an integer, parse it as "debug", "info", etc:
if not isinstance(loglevel, int):
loglevel = getattr(logging, loglevel.upper(), None)
if not isinstance(loglevel, int):
print('Invalid log level: %s' % loglevel)
exit(1)
# remove logfile if it already exists
if logfname is not None and os.path.exists(logfname):
os.remove(logfname)
logging.basicConfig(filename=logfname, format="%(levelname)s %(message)s",
level=loglevel)
def cubefit(argv=None):
DESCRIPTION = "Fit SN + galaxy model to SNFactory data cubes."
parser = ArgumentParser(prog="cubefit", description=DESCRIPTION)
parser.add_argument("configfile",
help="configuration file name (JSON format)")
parser.add_argument("outfile", help="Output file name (FITS format)")
parser.add_argument("--dataprefix", default="",
help="path prepended to data file names; default is "
"empty string")
parser.add_argument("--logfile", help="Write log to this file "
"(default: print to stdout)", default=None)
parser.add_argument("--loglevel", default="info",
help="one of: debug, info, warning (default is info)")
parser.add_argument("--diagdir", default=None,
help="If given, write intermediate diagnostic results "
"to this directory")
parser.add_argument("--refitgal", default=False, action="store_true",
help="Add an iteration where galaxy model is fit "
"using all epochs and then data/SN positions are "
"refit")
parser.add_argument("--mu_wave", default=0.07, type=float,
help="Wavelength regularization parameter. "
"Default is 0.07.")
parser.add_argument("--mu_xy", default=0.001, type=float,
help="Spatial regularization parameter. "
"Default is 0.001.")
parser.add_argument("--psftype", default="gaussian-moffat",
help="Type of PSF: 'gaussian-moffat' or 'tabular'. "
"Currently, tabular means generate a tabular PSF from "
"gaussian-moffat parameters.")
args = parser.parse_args(argv)
setup_logging(args.loglevel, logfname=args.logfile)
# record start time
tstart = datetime.now()
logging.info("cubefit v%s started at %s", __version__,
tstart.strftime("%Y-%m-%d %H:%M:%S"))
tsteps = OrderedDict() # finish time of each step.
logging.info("parameters: mu_wave={:.3g} mu_xy={:.3g} refitgal={}"
.format(args.mu_wave, args.mu_xy, args.refitgal))
logging.info(" psftype={}".format(args.psftype))
logging.info("reading config file")
with open(args.configfile) as f:
cfg = json.load(f)
# basic checks on config contents.
assert (len(cfg["filenames"]) == len(cfg["xcenters"]) ==
len(cfg["ycenters"]) == len(cfg["psf_params"]))
# -------------------------------------------------------------------------
# Load data cubes from the list of FITS files.
nt = len(cfg["filenames"])
logging.info("reading %d data cubes", nt)
cubes = []
for fname in cfg["filenames"]:
logging.debug(" reading %s", fname)
cubes.append(read_datacube(os.path.join(args.dataprefix, fname)))
wave = cubes[0].wave
nw = len(wave)
# assign some local variables for convenience
refs = cfg["refs"]
master_ref = cfg["master_ref"]
if master_ref not in refs:
raise ValueError("master ref choice must be one of the final refs (" +
" ".join(refs.astype(str)) + ")")
nonmaster_refs = [i for i in refs if i != master_ref]
nonrefs = [i for i in range(nt) if i not in refs]
# Ensure that all cubes have the same wavelengths.
if not all(np.all(cubes[i].wave == wave) for i in range(1, nt)):
raise ValueError("all data must have same wavelengths")
# -------------------------------------------------------------------------
# PSF for each observation
logging.info("setting up PSF for all %d epochs", nt)
psfs = [snfpsf(wave, cfg["psf_params"][i], cubes[i].header, args.psftype)
for i in range(nt)]
# -------------------------------------------------------------------------
# Initialize all model parameters to be fit
yctr0 = np.array(cfg["ycenters"])
xctr0 = np.array(cfg["xcenters"])
galaxy = np.zeros((nw, MODEL_SHAPE[0], MODEL_SHAPE[1]), dtype=np.float64)
sn = np.zeros((nt, nw), dtype=np.float64) # SN spectrum at each epoch
skys = np.zeros((nt, nw), dtype=np.float64) # Sky spectrum at each epoch
yctr = yctr0.copy()
xctr = xctr0.copy()
snctr = (0., 0.)
# For writing out to FITS
modelwcs = {"CRVAL1": -SPAXEL_SIZE * (MODEL_SHAPE[0] - 1) / 2.,
"CRPIX1": 1,
"CDELT1": SPAXEL_SIZE,
"CRVAL2": -SPAXEL_SIZE * (MODEL_SHAPE[1] - 1) / 2.,
"CRPIX2": 1,
"CDELT2": SPAXEL_SIZE,
"CRVAL3": cubes[0].header["CRVAL3"],
"CRPIX3": cubes[0].header["CRPIX3"],
"CDELT3": cubes[0].header["CDELT3"]}
# -------------------------------------------------------------------------
# Position bounds
# Bounds on data position: shape=(nt, 2)
xctrbounds = np.vstack((xctr - POSITION_BOUND, xctr + POSITION_BOUND)).T
yctrbounds = np.vstack((yctr - POSITION_BOUND, yctr + POSITION_BOUND)).T
snctrbounds = (-POSITION_BOUND, POSITION_BOUND)
# For data positions, check that bounds do not extend
# past the edge of the model and adjust the minbound and maxbound.
# This doesn't apply to SN position.
gshape = galaxy.shape[1:3] # model shape
for i in range(nt):
dshape = cubes[i].data.shape[1:3]
(yminabs, ymaxabs), (xminabs, xmaxabs) = yxbounds(gshape, dshape)
yctrbounds[i, 0] = max(yctrbounds[i, 0], yminabs)
yctrbounds[i, 1] = min(yctrbounds[i, 1], ymaxabs)
xctrbounds[i, 0] = max(xctrbounds[i, 0], xminabs)
xctrbounds[i, 1] = min(xctrbounds[i, 1], xmaxabs)
# -------------------------------------------------------------------------
# Guess sky
logging.info("guessing sky for all %d epochs", nt)
for i, cube in enumerate(cubes):
skys[i, :] = guess_sky(cube, npix=30)
# -------------------------------------------------------------------------
# Regularization penalty parameters
# Calculate rough average galaxy spectrum from all final refs.
spectra = np.zeros((len(refs), len(wave)), dtype=np.float64)
for j, i in enumerate(refs):
avg_spec = np.average(cubes[i].data, axis=(1, 2)) - skys[i]
mean_spec, bins, bn = scipy.stats.binned_statistic(wave, avg_spec,
bins=len(wave)/10)
spectra[j] = np.interp(wave, bins[:-1] + np.diff(bins)[0]/2.,
mean_spec)
mean_gal_spec = np.average(spectra, axis=0)
# Ensure that there won't be any negative or tiny values in mean:
mean_floor = 0.1 * np.median(mean_gal_spec)
mean_gal_spec[mean_gal_spec < mean_floor] = mean_floor
galprior = np.zeros((nw, MODEL_SHAPE[0], MODEL_SHAPE[1]), dtype=np.float64)
regpenalty = RegularizationPenalty(galprior, mean_gal_spec, args.mu_xy,
args.mu_wave)
tsteps["setup"] = datetime.now()
# -------------------------------------------------------------------------
# Fit just the galaxy model to just the master ref.
data = cubes[master_ref].data - skys[master_ref, :, None, None]
weight = cubes[master_ref].weight
logging.info("fitting galaxy to master ref [%d]", master_ref)
galaxy = fit_galaxy_single(galaxy, data, weight,
(yctr[master_ref], xctr[master_ref]),
psfs[master_ref], regpenalty, LBFGSB_FACTOR)
if args.diagdir:
fname = os.path.join(args.diagdir, 'step1.fits')
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname)
tsteps["fit galaxy to master ref"] = datetime.now()
# -------------------------------------------------------------------------
# Fit the positions of the other final refs
#
# Here we only use spaxels where the *model* has significant flux.
# We define "significant" as some number of median absolute deviations
# (MAD) above the minimum flux in the model. We (temporarily) set the
# weight of "insignificant" spaxels to zero during this process, then
# restore the original weight after we're done.
#
# If there are less than 20 "significant" spaxels, we do not attempt to
# fit the position, but simply leave it as is.
logging.info("fitting position of non-master refs %s", nonmaster_refs)
for i in nonmaster_refs:
cube = cubes[i]
# Evaluate galaxy on this epoch for purpose of masking spaxels.
gal = psfs[i].evaluate_galaxy(galaxy, (cube.ny, cube.nx),
(yctr[i], xctr[i]))
# Set weight of low-valued spaxels to zero.
gal2d = gal.sum(axis=0) # Sum of gal over wavelengths
mad = np.median(np.abs(gal2d - np.median(gal2d)))
mask = gal2d > np.min(gal2d) + MIN_NMAD * mad
if mask.sum() < 20:
continue
weight = cube.weight * mask[None, :, :]
fctr, fsky = fit_position_sky(galaxy, cube.data, weight,
(yctr[i], xctr[i]), psfs[i],
(yctrbounds[i], xctrbounds[i]))
yctr[i], xctr[i] = fctr
skys[i, :] = fsky
tsteps["fit positions of other refs"] = datetime.now()
# -------------------------------------------------------------------------
# Redo model fit, this time including all final refs.
datas = [cubes[i].data for i in refs]
weights = [cubes[i].weight for i in refs]
ctrs = [(yctr[i], xctr[i]) for i in refs]
psfs_refs = [psfs[i] for i in refs]
logging.info("fitting galaxy to all refs %s", refs)
galaxy, fskys = fit_galaxy_sky_multi(galaxy, datas, weights, ctrs,
psfs_refs, regpenalty, LBFGSB_FACTOR)
# put fitted skys back in `skys`
for i,j in enumerate(refs):
skys[j, :] = fskys[i]
if args.diagdir:
fname = os.path.join(args.diagdir, 'step2.fits')
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname)
tsteps["fit galaxy to all refs"] = datetime.now()
# -------------------------------------------------------------------------
# Fit position of data and SN in non-references
#
# Now we think we have a good galaxy model. We fix this and fit
# the relative position of the remaining epochs (which presumably
# all have some SN light). We simultaneously fit the position of
# the SN itself.
logging.info("fitting position of all %d non-refs and SN position",
len(nonrefs))
if len(nonrefs) > 0:
datas = [cubes[i].data for i in nonrefs]
weights = [cubes[i].weight for i in nonrefs]
psfs_nonrefs = [psfs[i] for i in nonrefs]
fyctr, fxctr, snctr, fskys, fsne = fit_position_sky_sn_multi(
galaxy, datas, weights, yctr[nonrefs], xctr[nonrefs],
snctr, psfs_nonrefs, LBFGSB_FACTOR, yctrbounds[nonrefs],
xctrbounds[nonrefs], snctrbounds)
# put fitted results back in parameter lists.
yctr[nonrefs] = fyctr
xctr[nonrefs] = fxctr
for i,j in enumerate(nonrefs):
skys[j, :] = fskys[i]
sn[j, :] = fsne[i]
tsteps["fit positions of nonrefs & SN"] = datetime.now()
# -------------------------------------------------------------------------
# optional step(s)
if args.refitgal and len(nonrefs) > 0:
if args.diagdir:
fname = os.path.join(args.diagdir, 'step3.fits')
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname)
# ---------------------------------------------------------------------
# Redo fit of galaxy, using ALL epochs, including ones with SN
# light. We hold the SN "fixed" simply by subtracting it from the
# data and fitting the remainder.
#
# This is slightly dangerous: any errors in the original SN
# determination, whether due to an incorrect PSF or ADR model
# or errors in the galaxy model will result in residuals. The
# galaxy model will then try to compensate for these.
#
# We should look at the galaxy model at the position of the SN
# before and after this step to see if there is a bias towards
# the galaxy flux increasing.
logging.info("fitting galaxy using all %d epochs", nt)
datas = [cube.data for cube in cubes]
weights = [cube.weight for cube in cubes]
ctrs = [(yctr[i], xctr[i]) for i in range(nt)]
# subtract SN from non-ref cubes.
for i in nonrefs:
s = psfs[i].point_source(snctr, datas[i].shape[1:3], ctrs[i])
# do *not* use in-place operation (-=) here!
datas[i] = cubes[i].data - sn[i, :, None, None] * s
galaxy, fskys = fit_galaxy_sky_multi(galaxy, datas, weights, ctrs,
psfs, regpenalty, LBFGSB_FACTOR)
for i in range(nt):
skys[i, :] = fskys[i] # put fitted skys back in skys
if args.diagdir:
fname = os.path.join(args.diagdir, 'step4.fits')
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname)
# ---------------------------------------------------------------------
# Repeat step before last: fit position of data and SN in
# non-references
logging.info("re-fitting position of all %d non-refs and SN position",
len(nonrefs))
if len(nonrefs) > 0:
datas = [cubes[i].data for i in nonrefs]
weights = [cubes[i].weight for i in nonrefs]
psfs_nonrefs = [psfs[i] for i in nonrefs]
fyctr, fxctr, snctr, fskys, fsne = fit_position_sky_sn_multi(
galaxy, datas, weights, yctr[nonrefs], xctr[nonrefs],
snctr, psfs_nonrefs, LBFGSB_FACTOR, yctrbounds[nonrefs],
xctrbounds[nonrefs], snctrbounds)
# put fitted results back in parameter lists.
yctr[nonrefs] = fyctr
xctr[nonrefs] = fxctr
for i, j in enumerate(nonrefs):
skys[j, :] = fskys[i]
sn[j, :] = fsne[i]
# -------------------------------------------------------------------------
# Write results
logging.info("writing results to %s", args.outfile)
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, args.outfile)
# time info
logging.info("step times:")
maxlen = max(len(key) for key in tsteps)
fmtstr = " %2dm%02ds - %-" + str(maxlen) + "s"
tprev = tstart
for key, tstep in tsteps.items():
t = (tstep - tprev).seconds
logging.info(fmtstr, t//60, t%60, key)
tprev = tstep
tfinish = datetime.now()
logging.info("finished at %s", tfinish.strftime("%Y-%m-%d %H:%M:%S"))
t = (tfinish - tstart).seconds
logging.info("took %3dm%2ds", t // 60, t % 60)
return 0
def cubefit_subtract(argv=None):
DESCRIPTION = \
"""Subtract model determined by cubefit from the original data.
The "outnames" key in the supplied configuration file is used to
determine the output FITS file names. The input FITS header is passed
unaltered to the output file, with the following additions:
(1) A `HISTORY` entry. (2) `CBFT_SNX` and `CBFT_SNY` records giving
the cubefit-determined position of the SN relative to the center of
the data array (at the reference wavelength).
This script also writes fitted SN spectra to individual FITS files.
The "sn_outnames" configuration field determines the output filenames.
"""
import shutil
import fitsio
prog_name = "cubefit-subtract"
prog_name_ver = "{} v{}".format(prog_name, __version__)
parser = ArgumentParser(prog=prog_name, description=DESCRIPTION)
parser.add_argument("configfile", help="configuration file name "
"(JSON format), same as cubefit input.")
parser.add_argument("resultfile", help="Result FITS file from cubefit")
parser.add_argument("--dataprefix", default="",
help="path prepended to data file names; default is "
"empty string")
parser.add_argument("--outprefix", default="",
help="path prepended to output file names; default is "
"empty string")
args = parser.parse_args(argv)
setup_logging("info")
# get input & output filenames
with open(args.configfile) as f:
cfg = json.load(f)
fnames = [os.path.join(args.dataprefix, fname)
for fname in cfg["filenames"]]
outfnames = [os.path.join(args.outprefix, fname)
for fname in cfg["outnames"]]
# load results
results = read_results(args.resultfile)
epochs = results["epochs"]
sny, snx = results["snctr"]
if not len(epochs) == len(fnames) == len(outfnames):
raise RuntimeError("number of epochs in result file not equal to "
"number of input and output files in config file")
# subtract and write out.
for fname, outfname, epoch in zip(fnames, outfnames, epochs):
logging.info("writing %s", outfname)
shutil.copy(fname, outfname)
f = fitsio.FITS(outfname, "rw")
data = f[0].read()
data -= epoch["galeval"]
f[0].write(data)
f[0].write_history("galaxy subtracted by " + prog_name_ver)
f[0].write_key("CBFT_SNX", snx - epoch['xctr'],
comment="SN x offset from center at {:.0f} A [spaxels]"
.format(REFWAVE))
f[0].write_key("CBFT_SNY", sny - epoch['yctr'],
comment="SN y offset from center at {:.0f} A [spaxels]"
.format(REFWAVE))
f.close()
# output SN spectra to separate files.
sn_outnames = [os.path.join(args.outprefix, fname)
for fname in cfg["sn_outnames"]]
header = {"CRVAL1": results["header"]["CRVAL3"],
"CRPIX1": results["header"]["CRPIX3"],
"CDELT1": results["header"]["CDELT3"]}
for outfname, epoch in zip(sn_outnames, epochs):
logging.info("writing %s", outfname)
if os.path.exists(outfname): # avoid warning from clobber=True
os.remove(outfname)
with fitsio.FITS(outfname, "rw") as f:
f.write(epoch["sn"], extname="sn", header=header)
f[0].write_history("created by " + prog_name_ver)
return 0
def cubefit_plot(argv=None):
DESCRIPTION = """Plot results and diagnostics from cubefit"""
from .plotting import plot_timeseries, plot_epoch, plot_sn, plot_adr
# arguments are the same as cubefit except an output
parser = ArgumentParser(prog="cubefit-plot", description=DESCRIPTION)
parser.add_argument("configfile", help="configuration filename")
parser.add_argument("resultfile", help="Result filename from cubefit")
parser.add_argument("outprefix", help="output prefix")
parser.add_argument("--dataprefix", default="",
help="path prepended to data file names; default is "
"empty string")
parser.add_argument('-b', '--band', help='timeseries band (U, B, V). '
'Default is a 1000 A wide band in middle of cube.',
default=None, dest='band')
parser.add_argument('--idrfiles', nargs='+', default=None,
help='Prefix of IDR. If given, the cubefit SN '
'spectra are plotted against the production values.')
parser.add_argument("--diagdir", default=None,
help="If given, read intermediate diagnostic "
"results from this directory and include in plot(s)")
parser.add_argument("--plotepochs", default=False, action="store_true",
help="Make diagnostic plots for each epoch")
args = parser.parse_args(argv)
# Read in data
with open(args.configfile) as f:
cfg = json.load(f)
cubes = [read_datacube(os.path.join(args.dataprefix, fname), scale=False)
for fname in cfg["filenames"]]
results = OrderedDict()
# Diagnostic results at each step
if args.diagdir is not None:
fnames = sorted(glob.glob(os.path.join(args.diagdir, "step*.fits")))
for fname in fnames:
name = os.path.basename(fname).split(".")[0]
results[name] = read_results(fname)
# Final result (don't fail if not available)
if os.path.exists(args.resultfile):
results["final"] = read_results(args.resultfile)
# plot time series
plot_timeseries(cubes, results, band=args.band,
fname=(args.outprefix + '_timeseries.png'))
# Plot wave slices and sn, galaxy and sky spectra for all epochs.
if 'final' in results and args.plotepochs:
for i_t in range(len(cubes)):
plot_epoch(cubes[i_t], results['final']['epochs'][i_t],
fname=(args.outprefix + '_epoch%02d.png' % i_t))
# Plot result spectra against IDR spectra.
if 'final' in results and args.idrfiles is not None:
plot_sn(cfg['filenames'], results['final']['epochs']['sn'],
results['final']['wave'], args.idrfiles,
args.outprefix + '_sn.png')
# Plot the x-y coordinates of the adr versus wavelength
# (Skip this for now; contains no interesting information)
#plot_adr(cubes, cubes[0].wave, fname=(args.outprefix + '_adr.png'))
return 0
| mit |
sensu/sensu-docs | archived/sensu-core/1.8/reference/aggregates.md | 5864 | ---
title: "Aggregates"
description: "Reference documentation for Sensu Named Aggregates."
product: "Sensu Core"
version: "1.8"
weight: 4
menu:
sensu-core-1.8:
parent: reference
---
## Reference documentation
- [What is a Sensu named aggregate?](#what-is-a-check-aggregate)
- [When should named aggregates be used?](#when-should-check-aggregates-be-used)
- [How do named aggregates work?](#how-do-check-aggregates-work)
- [Example aggregated check result](#example-aggregated-check-result)
- [Aggregate configuration](#aggregate-configuration)
- [Example aggregate definition](#example-aggregate-definition)
- [Aggregate definition specification](#aggregate-definition-specification)
- [Aggregate `check` attributes](#aggregate-check-attributes)
## What is a Sensu named aggregate? {#what-is-a-check-aggregate}
Sensu named aggregates are collections of [check results][1], accessible via
the [Aggregates API][2]. Check aggregates make it possible to treat the results
of multiple disparate check results – executed across multiple disparate
systems – as a single result.
### When should named aggregates be used? {#when-should-check-aggregates-be-used}
Check aggregates are extremely useful in dynamic environments and/or
environments that have a reasonable tolerance for failure. Check aggregates
should be used when a service can be considered healthy as long as a minimum
threshold is satisfied (e.g. are at least 5 healthy web servers? are at least
70% of N processes healthy?).
## How do named aggregates work? {#how-do-check-aggregates-work}
Check results are included in an aggregate when a check definition includes the
[`aggregate` definition attribute][3]. Check results that provide an
`"aggregate": "example_aggregate"` are aggregated under the corresponding name
(e.g. `example_aggregate`), effectively capturing multiple check results as a
single aggregate.
### Example aggregated check result
Aggregated check results are available from the [Aggregates API][2], via the
`/aggregates/:name` API endpoint. An aggregate check result provides a
set of counters indicating the total number of client members, checks, and
check results collected, with a breakdown of how many results were recorded per
status (i.e. `ok`, `warning`, `critical`, and `unknown`).
{{< code json >}}
{
"clients": 15,
"checks": 2,
"results": {
"ok": 18,
"warning": 0,
"critical": 1,
"unknown": 0,
"total": 19,
"stale": 0
}
}
{{< /code >}}
Additional aggregate data is available from the Aggregates API, including Sensu
client members of a named aggregate, and the corresponding checks which are
included in the aggregate:
{{< code shell >}}
$ curl -s http://localhost:4567/aggregates/elasticsearch/clients | jq .
[
{
"name": "i-424242",
"checks": [
"elasticsearch_service",
"elasticsearch_cluster_health"
]
},
{
"name": "1-424243",
"checks": [
"elasticsearch_service"
]
},
]
{{< /code >}}
Aggregate data may also be fetched per check that is a member of the named
aggregate, along with the corresponding clients that are producing results for
said check:
{{< code shell >}}
$ curl -s http://localhost:4567/aggregates/elasticsearch/checks | jq .
[
{
"name": "elasticsearch_service",
"clients": [
"i-424242",
"i-424243"
]
},
{
"name": "elasticsearch_cluster_health",
"clients": [
"i-424242"
]
}
]
{{< /code >}}
## Aggregate configuration
### Example aggregate definition
The following is an example [check definition][6], a JSON configuration file located at `/etc/sensu/conf.d/check_aggregate_example.json`.
{{< code shell >}}
{
"checks": {
"example_check_aggregate": {
"command": "do_something.rb -o option",
"aggregate": "example_aggregate",
"interval": 60,
"subscribers": [
"my_aggregate"
],
"handle": false
}
}
}{{< /code >}}
### Aggregate definition specification
_NOTE: aggregates are created via the [`aggregate` Sensu `check` definition
attribute][4]. The configuration example(s) provided above, and the
"specification" provided here are for clarification and convenience only (i.e.
this "specification" is just a subset of the [check definition
specification][5], and not a definition of a distinct Sensu primitive)._
#### Aggregate `check` attributes
aggregate |
-------------|------
description | Create a named aggregate for the check. Check result data will be aggregated and exposed via the [Sensu Aggregates API][2].
required | false
type | String
example | {{< code shell >}}"aggregate": "elasticsearch"{{< /code >}}
aggregates |
-------------|------
description | An array of strings defining one or more named aggregates (described above).
required | false
type | Array
example | {{< code shell >}}"aggregates": [ "webservers", "production" ]{{< /code >}}
handle |
-------------|------
description | If events created by the check should be handled.
required | false
type | Boolean
default | true
example | {{< code shell >}}"handle": false{{< /code >}}_NOTE: although there are cases when it may be helpful to aggregate check results **and** handle individual check results, it is typically recommended to set `"handle": false` when aggregating check results, as the [purpose of the aggregation][8] should be to act on the state of the aggregated result(s) rather than the individual check result(s)._
[1]: ../checks#check-results
[2]: ../../api/aggregates
[3]: ../checks#check-definition-specification
[4]: ../checks#check-attributes
[5]: ../checks#check-definition-specification
[6]: ../checks#check-configuration
[7]: ../checks#standalone-checks
[8]: #when-should-check-aggregates-be-used
[9]: ../checks#how-are-checks-scheduled
| mit |
askl56/income-tax | lib/income_tax/countries/morocco.rb | 310 | module IncomeTax
module Countries
class Morocco < Models::Progressive
register 'Morocco', 'MA', 'MAR'
currency 'MAD'
level 30_000, '0%'
level 50_000, '10%'
level 60_000, '20%'
level 80_000, '30%'
level 180_000, '34%'
remainder '38%'
end
end
end
| mit |
racerx2000/ne_stenka | application/demo/profile.html | 69361 | <!DOCTYPE html>
<html>
<head lang="ru">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Template</title>
<link href="http://themesanytime.com/startui/demo/img/favicon.144x144.png" rel="apple-touch-icon" type="image/png" sizes="144x144">
<link href="http://themesanytime.com/startui/demo/img/favicon.114x114.png" rel="apple-touch-icon" type="image/png" sizes="114x114">
<link href="http://themesanytime.com/startui/demo/img/favicon.72x72.png" rel="apple-touch-icon" type="image/png" sizes="72x72">
<link href="http://themesanytime.com/startui/demo/img/favicon.57x57.png" rel="apple-touch-icon" type="image/png">
<link href="http://themesanytime.com/startui/demo/img/favicon.png" rel="icon" type="image/png">
<link href="http://themesanytime.com/startui/demo/img/favicon.ico" rel="shortcut icon">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[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]-->
<script src="js/plugins.js"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/lib/font-awesome/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header class="site-header">
<div class="container-fluid">
<a href="profile.html#" class="site-logo">
<img class="hidden-md-down" src="img/logo-2.png" alt="">
<img class="hidden-lg-up" src="img/logo-2-mob.png" alt="">
</a>
<button class="hamburger hamburger--htla">
<span>toggle menu</span>
</button>
<div class="site-header-content">
<div class="site-header-content-in">
<div class="site-header-shown">
<div class="dropdown dropdown-notification notif">
<a href="profile.html#"
class="header-alarm dropdown-toggle active"
id="dd-notification"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false">
<i class="font-icon-alarm"></i>
</a>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-notif" aria-labelledby="dd-notification">
<div class="dropdown-menu-notif-header">
Notifications
<span class="label label-pill label-danger">4</span>
</div>
<div class="dropdown-menu-notif-list">
<div class="dropdown-menu-notif-item">
<div class="photo">
<img src="img/photo-64-1.jpg" alt="">
</div>
<div class="dot"></div>
<a href="profile.html#">Morgan</a> was bothering about something
<div class="color-blue-grey-lighter">7 hours ago</div>
</div>
<div class="dropdown-menu-notif-item">
<div class="photo">
<img src="img/photo-64-2.jpg" alt="">
</div>
<div class="dot"></div>
<a href="profile.html#">Lioneli</a> had commented on this <a href="profile.html#">Super Important Thing</a>
<div class="color-blue-grey-lighter">7 hours ago</div>
</div>
<div class="dropdown-menu-notif-item">
<div class="photo">
<img src="img/photo-64-3.jpg" alt="">
</div>
<div class="dot"></div>
<a href="profile.html#">Xavier</a> had commented on the <a href="profile.html#">Movie title</a>
<div class="color-blue-grey-lighter">7 hours ago</div>
</div>
<div class="dropdown-menu-notif-item">
<div class="photo">
<img src="img/photo-64-4.jpg" alt="">
</div>
<a href="profile.html#">Lionely</a> wants to go to <a href="profile.html#">Cinema</a> with you to see <a href="profile.html#">This Movie</a>
<div class="color-blue-grey-lighter">7 hours ago</div>
</div>
</div>
<div class="dropdown-menu-notif-more">
<a href="profile.html#">See more</a>
</div>
</div>
</div>
<div class="dropdown dropdown-notification messages">
<a href="profile.html#"
class="header-alarm dropdown-toggle active"
id="dd-messages"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false">
<i class="font-icon-mail"></i>
</a>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-messages" aria-labelledby="dd-messages">
<div class="dropdown-menu-messages-header">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active"
data-toggle="tab"
href="profile.html#tab-incoming"
role="tab">
Inbox
<span class="label label-pill label-danger">8</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link"
data-toggle="tab"
href="profile.html#tab-outgoing"
role="tab">Outbox</a>
</li>
</ul>
<!--<button type="button" class="create">
<i class="font-icon font-icon-pen-square"></i>
</button>-->
</div>
<div class="tab-content">
<div class="tab-pane active" id="tab-incoming" role="tabpanel">
<div class="dropdown-menu-messages-list">
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span>
<span class="mess-item-name">Tim Collins</span>
<span class="mess-item-txt">Morgan was bothering about something!</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span>
<span class="mess-item-name">Christian Burton</span>
<span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something.</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span>
<span class="mess-item-name">Tim Collins</span>
<span class="mess-item-txt">Morgan was bothering about something!</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span>
<span class="mess-item-name">Christian Burton</span>
<span class="mess-item-txt">Morgan was bothering about something...</span>
</a>
</div>
</div>
<div class="tab-pane" id="tab-outgoing" role="tabpanel">
<div class="dropdown-menu-messages-list">
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span>
<span class="mess-item-name">Christian Burton</span>
<span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something...</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span>
<span class="mess-item-name">Tim Collins</span>
<span class="mess-item-txt">Morgan was bothering about something! Morgan was bothering about something.</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/avatar-2-64.png" alt=""></span>
<span class="mess-item-name">Christian Burtons</span>
<span class="mess-item-txt">Morgan was bothering about something!</span>
</a>
<a href="profile.html#" class="mess-item">
<span class="avatar-preview avatar-preview-32"><img src="img/photo-64-2.jpg" alt=""></span>
<span class="mess-item-name">Tim Collins</span>
<span class="mess-item-txt">Morgan was bothering about something!</span>
</a>
</div>
</div>
</div>
<div class="dropdown-menu-notif-more">
<a href="profile.html#">See more</a>
</div>
</div>
</div>
<div class="dropdown dropdown-lang">
<button class="dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="flag-icon flag-icon-us"></span>
</button>
<div class="dropdown-menu dropdown-menu-right">
<div class="dropdown-menu-col">
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ru"></span>Русский</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-de"></span>Deutsch</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-it"></span>Italiano</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-es"></span>Español</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-pl"></span>Polski</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-li"></span>Lietuviu</a>
</div>
<div class="dropdown-menu-col">
<a class="dropdown-item current" href="profile.html#"><span class="flag-icon flag-icon-us"></span>English</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-fr"></span>Français</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-by"></span>Беларускi</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ua"></span>Українська</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-cz"></span>Česky</a>
<a class="dropdown-item" href="profile.html#"><span class="flag-icon flag-icon-ch"></span>中國</a>
</div>
</div>
</div>
<div class="dropdown user-menu">
<button class="dropdown-toggle" id="dd-user-menu" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<img src="img/avatar-2-64.png" alt="">
</button>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dd-user-menu">
<a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-user"></span>Profile</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-cog"></span>Settings</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-question-sign"></span>Help</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="profile.html#"><span class="font-icon glyphicon glyphicon-log-out"></span>Logout</a>
</div>
</div>
<button type="button" class="burger-right">
<i class="font-icon-menu-addl"></i>
</button>
</div><!--.site-header-shown-->
<div class="mobile-menu-right-overlay"></div>
<div class="site-header-collapsed">
<div class="site-header-collapsed-in">
<div class="dropdown dropdown-typical">
<a class="dropdown-toggle" id="dd-header-sales" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="font-icon font-icon-wallet"></span>
<span class="lbl">Sales</span>
</a>
<div class="dropdown-menu" aria-labelledby="dd-header-sales">
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
</div>
</div>
<div class="dropdown dropdown-typical">
<a class="dropdown-toggle" id="dd-header-marketing" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="font-icon font-icon-cogwheel"></span>
<span class="lbl">Marketing automation</span>
</a>
<div class="dropdown-menu" aria-labelledby="dd-header-marketing">
<a class="dropdown-item" href="profile.html#">Current Search</a>
<a class="dropdown-item" href="profile.html#">Search for Issues</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">Recent issues</div>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
<div class="dropdown-more">
<div class="dropdown-more-caption padding">more...</div>
<div class="dropdown-more-sub">
<div class="dropdown-more-sub-in">
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
</div>
</div>
</div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="profile.html#">Import Issues from CSV</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">Filters</div>
<a class="dropdown-item" href="profile.html#">My Open Issues</a>
<a class="dropdown-item" href="profile.html#">Reported by Me</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="profile.html#">Manage filters</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">Timesheet</div>
<a class="dropdown-item" href="profile.html#">Subscribtions</a>
</div>
</div>
<div class="dropdown dropdown-typical">
<a class="dropdown-toggle" id="dd-header-social" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="font-icon font-icon-share"></span>
<span class="lbl">Social media</span>
</a>
<div class="dropdown-menu" aria-labelledby="dd-header-social">
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
</div>
</div>
<div class="dropdown dropdown-typical">
<a href="profile.html#" class="dropdown-toggle no-arr">
<span class="font-icon font-icon-page"></span>
<span class="lbl">Projects</span>
<span class="label label-pill label-danger">35</span>
</a>
</div>
<div class="dropdown dropdown-typical">
<a class="dropdown-toggle" id="dd-header-form-builder" data-target="#" href="http://example.com" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="font-icon font-icon-pencil"></span>
<span class="lbl">Form builder</span>
</a>
<div class="dropdown-menu" aria-labelledby="dd-header-form-builder">
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
</div>
</div>
<div class="dropdown">
<button class="btn btn-rounded dropdown-toggle" id="dd-header-add" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Add
</button>
<div class="dropdown-menu" aria-labelledby="dd-header-add">
<a class="dropdown-item" href="profile.html#">Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#">Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#">Prep Official App</a>
<a class="dropdown-item" href="profile.html#">CATprer Test</a>
<a class="dropdown-item" href="profile.html#">Third Party Test</a>
</div>
</div>
<div class="help-dropdown">
<button type="button">
<i class="font-icon font-icon-help"></i>
</button>
<div class="help-dropdown-popup">
<div class="help-dropdown-popup-side">
<ul>
<li><a href="profile.html#">Getting Started</a></li>
<li><a href="profile.html#" class="active">Creating a new project</a></li>
<li><a href="profile.html#">Adding customers</a></li>
<li><a href="profile.html#">Settings</a></li>
<li><a href="profile.html#">Importing data</a></li>
<li><a href="profile.html#">Exporting data</a></li>
</ul>
</div>
<div class="help-dropdown-popup-cont">
<div class="help-dropdown-popup-cont-in">
<div class="jscroll">
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum is simply
<span class="describe">Lorem Ipsum has been the industry's standard dummy text </span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Contrary to popular belief
<span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
The point of using Lorem Ipsum
<span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum
<span class="describe">There are many variations of passages of Lorem Ipsum available</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum is simply
<span class="describe">Lorem Ipsum has been the industry's standard dummy text </span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Contrary to popular belief
<span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
The point of using Lorem Ipsum
<span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum
<span class="describe">There are many variations of passages of Lorem Ipsum available</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum is simply
<span class="describe">Lorem Ipsum has been the industry's standard dummy text </span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Contrary to popular belief
<span class="describe">Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
The point of using Lorem Ipsum
<span class="describe">Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text</span>
</a>
<a href="profile.html#" class="help-dropdown-popup-item">
Lorem Ipsum
<span class="describe">There are many variations of passages of Lorem Ipsum available</span>
</a>
</div>
</div>
</div>
</div>
</div><!--.help-dropdown-->
<div class="site-header-search-container">
<form class="site-header-search closed">
<input type="text" placeholder="Search"/>
<button type="submit">
<span class="font-icon-search"></span>
</button>
<div class="overlay"></div>
</form>
</div>
</div><!--.site-header-collapsed-in-->
</div><!--.site-header-collapsed-->
</div><!--site-header-content-in-->
</div><!--.site-header-content-->
</div><!--.container-fluid-->
</header><!--.site-header-->
<div class="page-content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-lg-push-3 col-md-12">
<form class="box-typical">
<input type="text" class="write-something" placeholder="Write Something..."/>
<div class="box-typical-footer">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<button type="button" class="btn-icon">
<i class="font-icon font-icon-earth"></i>
</button>
<button type="button" class="btn-icon">
<i class="font-icon font-icon-picture"></i>
</button>
<button type="button" class="btn-icon">
<i class="font-icon font-icon-calend"></i>
</button>
<button type="button" class="btn-icon">
<i class="font-icon font-icon-video-fill"></i>
</button>
</div>
<div class="tbl-cell tbl-cell-action">
<button type="submit" class="btn btn-rounded">Send</button>
</div>
</div>
</div>
</div>
</form><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">
Posts
<div class="slider-arrs">
<button type="button" class="posts-slider-prev">
<i class="font-icon font-icon-arrow-left"></i>
</button>
<button type="button" class="posts-slider-next">
<i class="font-icon font-icon-arrow-right"></i>
</button>
</div>
</header>
<div class="posts-slider">
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-1.jpeg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">3 Myths That Confuse the D Myths That Confuse the D Myths That Confuse the D</a>
</div>
<div class="post-announce-date">Februrary 19, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-2.jpg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">How Much Do We Spend on How Much Do We Spend on How Much Do We Spend on </a>
</div>
<div class="post-announce-date">January 21, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-3.jpeg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">Good News You Might Have Good News You Might Have Good News You Might Have </a>
</div>
<div class="post-announce-date">December 30, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-1.jpeg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">3 Myths That Confuse the D Myths That Confuse the D Myths That Confuse the D</a>
</div>
<div class="post-announce-date">Februrary 19, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-2.jpg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">How Much Do We Spend on How Much Do We Spend on How Much Do We Spend on </a>
</div>
<div class="post-announce-date">January 21, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
<div class="slide">
<article class="post-announce">
<div class="post-announce-pic">
<a href="profile.html#">
<img src="img/post-3.jpeg" alt="">
</a>
</div>
<div class="post-announce-title">
<a href="profile.html#">Good News You Might Have Good News You Might Have Good News You Might Have </a>
</div>
<div class="post-announce-date">December 30, 2016</div>
<ul class="post-announce-meta">
<li>
<i class="font-icon font-icon-eye"></i>
18
</li>
<li>
<i class="font-icon font-icon-heart"></i>
5K
</li>
<li>
<i class="font-icon font-icon-comment"></i>
3K
</li>
</ul>
</article>
</div><!--.slide-->
</div><!--.posts-slider-->
</section><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">Background</header>
<article class="profile-info-item">
<header class="profile-info-item-header">
<i class="font-icon font-icon-notebook-bird"></i>
Summary
</header>
<div class="text-block text-block-typical">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. </p>
</div>
</article><!--.profile-info-item-->
<article class="profile-info-item">
<header class="profile-info-item-header">
<i class="font-icon font-icon-case"></i>
Experience
</header>
<ul class="exp-timeline">
<li class="exp-timeline-item">
<div class="dot"></div>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<div class="exp-timeline-range">2000 President</div>
<div class="exp-timeline-status">Co-founder, Chairman</div>
<div class="exp-timeline-location"><a href="profile.html#">Company</a></div>
</div>
<div class="tbl-cell tbl-cell-logo">
<img src="img/logo-2.png" alt="">
</div>
</div>
</div>
</li>
<li class="exp-timeline-item">
<div class="dot"></div>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<div class="exp-timeline-range">1992–1999</div>
<div class="exp-timeline-status">Senior Developer</div>
<div class="exp-timeline-location"><a href="profile.html#">YouTube</a></div>
</div>
<div class="tbl-cell tbl-cell-logo">
<img src="img/logo-2.png" alt="">
</div>
</div>
</div>
</li>
<li class="exp-timeline-item">
<div class="dot"></div>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<div class="exp-timeline-range">2000 President</div>
<div class="exp-timeline-status">Co-founder, Chairman</div>
<div class="exp-timeline-location"><a href="profile.html#">Company</a></div>
</div>
<div class="tbl-cell tbl-cell-logo">
<img src="img/logo-2.png" alt="">
</div>
</div>
</div>
</li>
</ul>
</article><!--.profile-info-item-->
<article class="profile-info-item">
<header class="profile-info-item-header">
<i class="font-icon font-icon-award"></i>
Edication
</header>
<ul class="exp-timeline">
<li class="exp-timeline-item">
<div class="dot"></div>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<div class="exp-timeline-range">1973 – 1975</div>
<div class="exp-timeline-status">Harvard University</div>
<div class="exp-timeline-location"><a href="profile.html#">BS Computer Science</a></div>
</div>
<div class="tbl-cell tbl-cell-logo">
<img src="img/logo-2.png" alt="">
</div>
</div>
</div>
</li>
<li class="exp-timeline-item">
<div class="dot"></div>
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<div class="exp-timeline-range">1960 – 1973</div>
<div class="exp-timeline-status">Lakeside Scool, Seattle</div>
</div>
<div class="tbl-cell tbl-cell-logo">
<img src="img/logo-2.png" alt="">
</div>
</div>
</div>
</li>
</ul>
</article><!--.profile-info-item-->
<article class="profile-info-item">
<header class="profile-info-item-header">
<i class="font-icon font-icon-lamp"></i>
Skills
</header>
<section class="skill-item tbl">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-num">
<div class="skill-circle skill-circle-num">74</div>
</div>
<div class="tbl-cell tbl-cell-txt">Social Media Marketing</div>
<div class="tbl-cell tbl-cell-users">
<img class="skill-user-photo" src="img/avatar-1-64.png" alt=""/>
<img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/>
<img class="skill-user-photo" src="img/photo-64-4.jpg" alt=""/>
<div class="skill-circle skill-circle-users">+74</div>
</div>
</div>
</section><!--.skill-item-->
<section class="skill-item tbl">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-num">
<div class="skill-circle skill-circle-num">67</div>
</div>
<div class="tbl-cell tbl-cell-txt">Web Development</div>
<div class="tbl-cell tbl-cell-users">
<img class="skill-user-photo" src="img/avatar-2-64.png" alt=""/>
<img class="skill-user-photo" src="img/photo-64-2.jpg" alt=""/>
<img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/>
<div class="skill-circle skill-circle-users">+82</div>
</div>
</div>
</section><!--.skill-item-->
<section class="skill-item tbl">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-num">
<div class="skill-circle skill-circle-num">25</div>
</div>
<div class="tbl-cell tbl-cell-txt">Search Engine Optimization</div>
<div class="tbl-cell tbl-cell-users">
<img class="skill-user-photo" src="img/avatar-3-64.png" alt=""/>
<img class="skill-user-photo" src="img/photo-64-1.jpg" alt=""/>
<img class="skill-user-photo" src="img/photo-64-2.jpg" alt=""/>
<div class="skill-circle skill-circle-users">+4</div>
</div>
</div>
</section><!--.skill-item-->
<section class="skill-item tbl">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-num">
<div class="skill-circle skill-circle-num">20</div>
</div>
<div class="tbl-cell tbl-cell-txt">User Experience Design</div>
<div class="tbl-cell tbl-cell-users">
<img class="skill-user-photo" src="img/photo-64-3.jpg" alt=""/>
<img class="skill-user-photo" src="img/photo-64-4.jpg" alt=""/>
<img class="skill-user-photo" src="img/photo-64-1.jpg" alt=""/>
<div class="skill-circle skill-circle-users">+13</div>
</div>
</div>
</section><!--.skill-item-->
</article><!--.profile-info-item-->
<article class="profile-info-item">
<header class="profile-info-item-header">
<i class="font-icon font-icon-star"></i>
More interest
</header>
<div class="profile-interests">
<a href="profile.html#" class="label label-light-grey">Interest</a>
<a href="profile.html#" class="label label-light-grey">Example</a>
<a href="profile.html#" class="label label-light-grey">One more</a>
<a href="profile.html#" class="label label-light-grey">Here is example interest</a>
<a href="profile.html#" class="label label-light-grey">Interest</a>
<a href="profile.html#" class="label label-light-grey">Example</a>
<a href="profile.html#" class="label label-light-grey">One more</a>
<a href="profile.html#" class="label label-light-grey">Here is example interest</a>
<a href="profile.html#" class="label label-light-grey">Interest</a>
<a href="profile.html#" class="label label-light-grey">Example</a>
<a href="profile.html#" class="label label-light-grey">One more</a>
<a href="profile.html#" class="label label-light-grey">Here is example interest</a>
</div>
</article><!--.profile-info-item-->
</section><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">
Recomendations
<div class="slider-arrs">
<button type="button" class="recomendations-slider-prev">
<i class="font-icon font-icon-arrow-left"></i>
</button>
<button type="button" class="recomendations-slider-next">
<i class="font-icon font-icon-arrow-right"></i>
</button>
</div>
</header>
<div class="recomendations-slider">
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-3.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-1.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-4.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
<div class="slide">
<div class="citate-speech-bubble">
<i class="font-icon-quote"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-4.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Molly Bridjet</a></p>
<p class="user-card-row-status"><a href="profile.html#">PatchworkLabs</a></p>
</div>
</div>
</div>
</div><!--.slide-->
</div><!--.recomendations-slider-->
</section><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">Following</header>
<div class="profile-following">
<div class="profile-following-grid">
<div class="col">
<article class="follow-group">
<div class="follow-group-logo">
<a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a>
</div>
<div class="follow-group-name">
<a href="profile.html#">KIPP Foundation</a>
</div>
<div class="follow-group-link">
<a href="profile.html#">
<span class="plus-link-circle"><span>+</span></span>
Follow
</a>
</div>
</article>
</div>
<div class="col">
<article class="follow-group">
<div class="follow-group-logo">
<a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a>
</div>
<div class="follow-group-name">
<a href="profile.html#">KIPP Foundation</a>
</div>
<div class="follow-group-link">
<a href="profile.html#">
<span class="plus-link-circle"><span>+</span></span>
Follow
</a>
</div>
</article>
</div>
<div class="col">
<article class="follow-group">
<div class="follow-group-logo">
<a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a>
</div>
<div class="follow-group-name">
<a href="profile.html#">KIPP Foundation</a>
</div>
<div class="follow-group-link">
<a href="profile.html#">
<span class="plus-link-circle"><span>+</span></span>
Follow
</a>
</div>
</article>
</div>
<div class="col">
<article class="follow-group">
<div class="follow-group-logo">
<a href="profile.html#" class="follow-group-logo-in"><img src="img/logo-2.png" alt=""></a>
</div>
<div class="follow-group-name">
<a href="profile.html#">KIPP Foundation</a>
</div>
<div class="follow-group-link">
<a href="profile.html#">
<span class="plus-link-circle"><span>+</span></span>
Follow
</a>
</div>
</article>
</div>
</div>
<a href="profile.html#" class="btn btn-rounded btn-primary-outline">See all (20)</a>
</div><!--.profile-following-->
</section><!--.box-typical-->
</div><!--.col- -->
<div class="col-lg-3 col-lg-pull-6 col-md-6 col-sm-6">
<section class="box-typical">
<div class="profile-card">
<div class="profile-card-photo">
<img src="img/photo-220-1.jpg" alt=""/>
</div>
<div class="profile-card-name">Sarah Sanchez</div>
<div class="profile-card-status">Company Founder</div>
<div class="profile-card-location">Greater Seattle Area</div>
<button type="button" class="btn btn-rounded">Follow</button>
<div class="btn-group">
<button type="button"
class="btn btn-rounded btn-primary-outline dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false">
Connect
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-home"></span>Quant and Verbal</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-cart"></span>Real Gmat Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-speed"></span>Prep Official App</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-users"></span>CATprer Test</a>
<a class="dropdown-item" href="profile.html#"><span class="font-icon font-icon-comments"></span>Third Party Test</a>
</div>
</div>
</div><!--.profile-card-->
<div class="profile-statistic tbl">
<div class="tbl-row">
<div class="tbl-cell">
<b>200</b>
Connections
</div>
<div class="tbl-cell">
<b>1.9M</b>
Followers
</div>
</div>
</div>
<ul class="profile-links-list">
<li class="nowrap">
<i class="font-icon font-icon-earth-bordered"></i>
<a href="profile.html#">example.com</a>
</li>
<li class="nowrap">
<i class="font-icon font-icon-fb-fill"></i>
<a href="profile.html#">facebook.com/example</a>
</li>
<li class="nowrap">
<i class="font-icon font-icon-vk-fill"></i>
<a href="profile.html#">vk.com/example</a>
</li>
<li class="nowrap">
<i class="font-icon font-icon-in-fill"></i>
<a href="profile.html#">linked.in/example</a>
</li>
<li class="nowrap">
<i class="font-icon font-icon-tw-fill"></i>
<a href="profile.html#">twitter.com/example</a>
</li>
<li class="divider"></li>
<li>
<i class="font-icon font-icon-pdf-fill"></i>
<a href="profile.html#">Export page as PDF</a>
</li>
</ul>
</section><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">
Friends
<a href="profile.html#" class="full-count">268</a>
</header>
<div class="friends-list">
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name status-online"><a href="profile.html#">Dan Cederholm</a></p>
<p class="user-card-row-location">New York</p>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-1.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Oykun Yilmaz</a></p>
<p class="user-card-row-location">Los Angeles</p>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-3.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Bill S Kenney</a></p>
<p class="user-card-row-location">Cardiff</p>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-4.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Maggy Smith</a></p>
<p class="user-card-row-location">Dusseldorf</p>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Dan Cederholm</a></p>
<p class="user-card-row-location">New York</p>
</div>
</div>
</div>
</article>
</div>
</section><!--.box-typical-->
</div><!--.col- -->
<div class="col-lg-3 col-md-6 col-sm-6">
<section class="box-typical">
<header class="box-typical-header-sm">People also viewed</header>
<div class="friends-list stripped">
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name status-online"><a href="profile.html#">Dan Cederholm</a></p>
<p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p>
</div>
<div class="tbl-cell tbl-cell-action">
<a href="profile.html#" class="plus-link-circle"><span>+</span></a>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-1.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Oykun Yilmaz</a></p>
<p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p>
</div>
<div class="tbl-cell tbl-cell-action">
<a href="profile.html#" class="plus-link-circle"><span>+</span></a>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-3.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Bill S Kenney</a></p>
<p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p>
</div>
<div class="tbl-cell tbl-cell-action">
<a href="profile.html#" class="plus-link-circle"><span>+</span></a>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-4.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Maggy Smith</a></p>
<p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p>
</div>
<div class="tbl-cell tbl-cell-action">
<a href="profile.html#" class="plus-link-circle"><span>+</span></a>
</div>
</div>
</div>
</article>
<article class="friends-list-item">
<div class="user-card-row">
<div class="tbl-row">
<div class="tbl-cell tbl-cell-photo">
<a href="profile.html#">
<img src="img/photo-64-2.jpg" alt="">
</a>
</div>
<div class="tbl-cell">
<p class="user-card-row-name"><a href="profile.html#">Susan Andrews</a></p>
<p class="user-card-row-status">Co-founder of <a href="profile.html#">Company</a></p>
</div>
<div class="tbl-cell tbl-cell-action">
<a href="profile.html#" class="plus-link-circle"><span>+</span></a>
</div>
</div>
</div>
</article>
</div>
<div class="see-all">
<a href="profile.html#">See All (300)</a>
</div>
<section>
<header class="box-typical-header-sm">More Influencer</header>
<div class="profile-card-slider">
<div class="slide">
<div class="profile-card">
<div class="profile-card-photo">
<img src="img/photo-220-1.jpg" alt=""/>
</div>
<div class="profile-card-name">Jackie Tran</div>
<div class="profile-card-status">Company Founder</div>
<button type="button" class="btn btn-rounded btn-primary-outline">Follow</button>
</div><!--.profile-card-->
</div><!--.slide-->
<div class="slide">
<div class="profile-card">
<div class="profile-card-photo">
<img src="img/avatar-1-256.png" alt=""/>
</div>
<div class="profile-card-name">Jackie Tran</div>
<div class="profile-card-status">Company Founder</div>
<button type="button" class="btn btn-rounded btn-primary-outline">Follow</button>
</div><!--.profile-card-->
</div><!--.slide-->
<div class="slide">
<div class="profile-card">
<div class="profile-card-photo">
<img src="img/avatar-2-256.png" alt=""/>
</div>
<div class="profile-card-name">Sarah Sanchez</div>
<div class="profile-card-status">Longnameexample<br/>corporation</div>
<button type="button" class="btn btn-rounded btn-primary-outline">Follow</button>
</div><!--.profile-card-->
</div><!--.slide-->
<div class="slide">
<div class="profile-card">
<div class="profile-card-photo">
<img src="img/avatar-3-256.png" alt=""/>
</div>
<div class="profile-card-name">Sarah Sanchez</div>
<div class="profile-card-status">Longnameexample<br/>corporation</div>
<button type="button" class="btn btn-rounded btn-primary-outline">Follow</button>
</div><!--.profile-card-->
</div><!--.slide-->
</div><!--.profile-card-slider-->
</section>
</section><!--.box-typical-->
<section class="box-typical">
<header class="box-typical-header-sm">People you may know</header>
<div class="people-rel-list">
<div class="people-rel-list-name"><a href="profile.html#">Jackie Tran Anh</a> / Designer</div>
<ul class="people-rel-list-photos">
<li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/avatar-1-128.png" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/avatar-2-128.png" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/avatar-3-128.png" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-2.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-3.jpg" alt=""></a></li>
<li><a href="profile.html#"><img src="img/photo-92-1.jpg" alt=""></a></li>
</ul>
<form class="site-header-search">
<input type="text" placeholder="Search for people"/>
<button type="submit">
<span class="font-icon-search"></span>
</button>
<div class="overlay"></div>
</form>
</div>
</section><!--.box-typical-->
</div><!--.col- -->
</div><!--.row-->
</div><!--.container-fluid-->
</div><!--.page-content-->
<!--Progress bar-->
<!--<div class="circle-progress-bar pieProgress" role="progressbar" data-goal="100" data-barcolor="#ac6bec" data-barsize="10" aria-valuemin="0" aria-valuemax="100">-->
<!--<span class="pie_progress__number">0%</span>-->
<!--</div>-->
</body>
</html> | mit |
peteratseneca/dps907fall2013 | Week_03/sep20v1/sep20v1/Areas/HelpPage/SampleGeneration/TextSample.cs | 883 | using System;
namespace sep20v1.Areas.HelpPage
{
/// <summary>
/// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.
/// </summary>
public class TextSample
{
public TextSample(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
Text = text;
}
public string Text { get; private set; }
public override bool Equals(object obj)
{
TextSample other = obj as TextSample;
return other != null && Text == other.Text;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
} | mit |
sinisterchipmunk/bot-away | README.md | 12801 | # bot-away [](http://travis-ci.org/sinisterchipmunk/bot-away)
* http://github.com/sinisterchipmunk/bot-away
Unobtrusively detects form submissions made by spambots, and silently drops those submissions. The key word here is
"unobtrusive" -- this is NOT a CAPTCHA. This is a transparent, modular implementation of the bot-catching techniques
discussed by Ned Batchelder at http://nedbatchelder.com/text/stopbots.html.
## How It Works
If a bot submission is detected, the params hash is cleared, so the data can't be used. Since this includes the
authenticity token, Rails should complain about an invalid or missing authenticity token. Congrats, spam blocked.
The specifics of the techniques employed for filtering spambots are discussed Ned's site in the description; however,
here's a brief run-down of what's going on:
* Your code stays the same. After the Bot-Away gem has been activated, all Rails-generated forms on your site
will automatically be transformed into bot-resistent forms.
* All of the form elements that you create (for instance, a "comment" model with a "body" field) are turned into
dummy elements, or honeypots, and are made invisible to the end user. This is done using div elements and inline
CSS stylesheets (I decided against a JavaScript option because it's the most likely to be disabled on a legitimate
client). There are several ways an element can be hidden, and these approaches are chosen at random to help
minimize predictability.
* In the rare event that a real user actually can see the element, it has a label next to it
along the lines of "Leave this blank" -- though the exact message is randomized to help prevent detection by
bots.
* All of the form elements are mirrored by hashes. The hashes are generated using the session's authenticity token,
so they can't be predicted.
* When data is submitted, Bot-Away steps in and
1. validates that no honeypots have been filled in; and
2. converts the hashed elements back into the field names that you are expecting (replacing the honeypot fields).
Your code is never aware of the difference; it's just business as usual as long as the user is legitimate.
* If a honeypot has been filled in, or a hashed element is missing where it was expected, then the request is
considered to be either spam, or tampered with; and the entire params hash is emptied. Since this happens at the
lowest level, the most likely result is that Rails will complain that the user's authenticity token is invalid. If
that does not happen, then your code will be passed a params hash containing only a "suspected_bot" key, and an
error will result. Either way, the spambot has been foiled!
## Installation:
* gem install bot-away
## Usage:
Whether you're on Rails 2 or Rails 3, adding Bot-Away to your project is as easy as telling Rails where to find it.
### Rails 2.x
The Rails 2.x version will still receive bug fixes, but is no longer under active development. To use bot-away with Rails 2, pull in bot-away v1.x:
# in config/environment.rb:
config.gem 'bot-away', '~> 1.2'
### Rails 3
# in Gemfile
gem 'bot-away', '~> 2.0'
That's it.
## Whitelists
Sometimes you don't care about whether or not a bot is filling out a particular form. Even more, sometimes it's
preferable to make a form bot-friendly. I'm talking specifically about login forms, where all sorts of people
use bots (their Web browsers, usually) in order to prefill the form with their login information. This is perfectly
harmless, and even a malicious bot is not going to be able to cause any trouble on a form like this because it'll only be denied access to the site.
In cases like these, you'll want to go ahead and disable Bot-Away. Since Bot-Away is only disabled on a per-controller or per-action basis, it stays active throughout the remainder of your site, which prevents bots from (for example) creating new users.
To disable Bot-Away for an entire controller, add this line to a file called `config/initializers/bot-away.rb`:
BotAway.disabled_for :controller => 'sessions'
And here's how to do the same for a specific action, leaving Bot-Away active for all other actions:
BotAway.disabled_for :controller => 'sessions', :action => 'login'
You can also disable Bot-Away for a given action in every controller, but I'm not sure how useful that is. In any case, here's how to do it:
BotAway.disabled_for :action => 'index' # all we did was omit :controller
This line can be specified multiple times, for each of the controllers and/or actions that you need it disabled for.
## Disabling Bot-Away in Development
If, while developing your app, you find yourself viewing the HTML source code, it'll probably be more helpful
to have Bot-Away disabled entirely so that you're not confused by MD5 tags and legions of honeypots. This is easy enough to do:
BotAway.disabled_for :mode => 'development'
## Accepting Unfiltered Params
Sometimes you need to tell Bot-Away to explicitly _not_ filter a parameter. This is most notable with fields you've
dynamically added via JavaScript, since those can confuse Bot-Away's catching techniques. (It tends to think Javascript-
generated fields are honeypots, and raises an error based on that.) Here's how to tell Bot-Away that such fields are
not to be checked:
BotAway.accepts_unfiltered_params "name_of_param", "name_of_another_param"
Note that these parameters can be either model keys, field keys or exact matches. For example, imagine the following
scenario: you have two models, `User` and `Group`, and each `has_many :roles`. That means you'll likely have an administration screen somewhere with check boxes representing user roles and group roles. Here are the different ways you can control how Bot-Away interacts with these fields:
BotAway.accepts_unfiltered_params "user"
# disables BotAway filtering for ALL fields belonging to 'user', but NO fields belonging to 'group'
BotAway.accepts_unfiltered_params 'user[role_ids]', 'group[role_ids]'
# disables BotAway filtering for ONLY the 'role_ids' field belonging to BOTH 'user' and 'group', while leaving
# filtering enabled for ALL OTHER fields.
BotAway.accepts_unfiltered_params 'role_ids'
# disables BotAway filtering for ONLY the 'role_ids' fields belonging to ALL MODELS, while leaving all
# other fields enabled.
You can specify this option as many times as you need to do.
## I18n
BotAway is mostly code, and produces mostly code, so there's not that much to translate. However, as mentioned above, the honeypots could theoretically be seen by humans in some rare cases (if they have an exceedingly simplistic browser or have disabled such fundamental Web controls as CSS). In these rare cases, BotAway prefixes the honeypot fields with a message akin to "Leave This Field Empty".
To further confound smart bots, these messages are chosen at random and by default there are 3 such messages BotAway can choose from. However, BotAway only supports the English language by default, so if you are targeting other languages you'll want to add translations. Also, to give your Web app a bit of personalization (highly recommended, if you want to keep the bot-builders guessing!) then you'll want to override and/or add to the English messages as well!
To do this, create a file in `config/locales/bot-away.yml` and add content such as this:
en:
bot_away:
number_of_honeypot_warning_messages: 3
honeypot_warning_1: "Leave this empty: "
honeypot_warning_2: "Don't fill this in: "
honeypot_warning_3: "Keep this blank: "
Shown above is exactly what resides in the default BotAway locale. Change the contents of warning strings 1 through 3 within your own app to override them; change the `number_of_honeypot_warning_messages` field to cause BotAway to choose randomly from more or fewer messages. Also, as the above example implies, you can set a different number of randomized warnings per language.
* If you'd like to add some warning messages to BotAway in currently-unsupported languages (or if you just want
BotAway to have more messages to choose from) then your additions are welcome! Please fork this project,
update the
[lib/locale/honeypots.yml](https://github.com/sinisterchipmunk/bot-away/blob/master/lib/locale/honeypots.yml)
file with your changes, and then send me a pull request!
* Honeypot warning messages are obfuscated: they are sent as reversed, unicode-escaped strings displayed within
right-to-left directional tags (which are standard in HTML 4 and should be recognized by all browsers), so that in
the unlikely event a bot can figure out what your I18n locale's "don't fill this in" text means, it'll also have to
figure out how to read the text in reverse after unescaping the unicode characters. Obviously, human users won't
have this problem.
* To disable obfuscation of the honeypot warning messages (that is, serve them as plain left-to-right text), add
the line `BotAway.obfuscate_honeypot_warning_messages = false` to `config/initializers/bot-away.rb`.
## Further Configuration (Mostly for Debugging):
In general, Bot-Away doesn't have that much to configure. Most options only exist for your debugging pleasure, in
case something isn't quite working as you'd expected. As shown above, these settings should be specified in a file
called `config/initializers/bot-away.rb`. Configuration options available to you are as follows:
### Showing the Honeypots
Generally, you want to keep honeypots hidden, because they will clutter your interface and confuse your users. However, there was an issue awhile back (near the 1.0 release of Bot-Away) where Safari was a bit smarter than its competitors, successfully prefilling honeypots with data where Chrome, FF and IE all failed to do so. Eventually, I added the ability to show honeypots on the screen, proving my suspicion that Safari was being "too smart". After resolving the issue, I decided to leave this option available to Bot-Away as a debugging tool for handling future issues. To enable:
BotAway.show_honeypots = true
### Dumping Params
Like showing honeypots, above, this option is only useful if you're debugging issues in development
mode. You can enable this if you need to see exactly what Rails sees _before_ Bot-Away steps in to intervene. Enabling this is a major security risk in production mode because it'll include sensitive data such as passwords; but it's very useful for debugging false positives (that is, Bot-Away thinks you're a bot, but you're not).
BotAway.dump_params = true
## Features / Problems:
* Wherever protection from forgery is not enabled in your Rails app, the Rails forms will be generated as if this gem
did not exist. That means hashed elements won't be generated, honeypots won't be generated, and posted forms will
not be intercepted.
* By default, protection from forgery is enabled for all Rails controllers, so by default the above-mentioned checks
will also be triggered. For more details on forgery protection, see:
http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html
* The techniques implemented by this library will be very difficult for a spambot to circumvent. However, keep in
mind that since the pages have to be machine-readable by definition, and since this gem has to follow certain
protocols in order to avoid confusing lots of humans (such as hiding the honeypots), it is always theoretically
possible for a spambot to get around it. It's just very, very difficult.
* I feel this library has been fairly well-tested (99.21% test coverage as of this writing), but if you discover a
bug and can't be bothered to let me know about it (or you just don't have time to wait for a fix or fix it
yourself), then you can simply add the name of the offending form element to the BotAway.unfiltered_params
array like so:
BotAway.accepts_unfiltered_params 'role_ids'
BotAway.accepts_unfiltered_params 'user' # this can be called multiple times
You should also take note that this is an array, not a hash. So if you have a `user[role_ids]` as well as a
`group[role_ids]`, the `role_ids` will not be filtered on EITHER of these models.
* Currently, there's no direct support for per-request configuration of unfiltered params. This is mostly due to
Bot-Away's low-level approach to filtering bots: the params have already been filtered by the time your controller
is created. I'd like to revisit per-request filtering sometime in the future, once I figure out the best way to do
it.
## Requirements:
* Rails 3.0 or better.
| mit |
yurijbogdanov/symfony-remote-translations-bundle | Tests/Translation/Loader/AwsS3LoaderTest.php | 636 | <?php
namespace YB\Bundle\RemoteTranslationsBundle\Tests\Translation\Loader;
use PHPUnit_Framework_TestCase;
/**
* Class AwsS3LoaderTest
* @package YB\Bundle\RemoteTranslationsBundle\Tests\Translation\Loader
*/
class AwsS3LoaderTest extends PHPUnit_Framework_TestCase
{
/**
* @param mixed $expected
* @param mixed $result
*
* @dataProvider getExamples
*/
public function testIndex($expected, $result)
{
$this->assertSame($expected, $result);
}
/**
* @return \Generator
*/
public function getExamples()
{
yield ['Lorem Ipsum', 'Lorem Ipsum'];
}
}
| mit |
Syncano/syncano-android-demo | Eclipse/SyncanoLib/src/com/syncano/android/lib/modules/users/ParamsUserNew.java | 1864 | package com.syncano.android.lib.modules.users;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.syncano.android.lib.modules.Params;
import com.syncano.android.lib.modules.Response;
/**
* Params to create new user.
*/
public class ParamsUserNew extends Params {
/** Name of user */
@Expose
@SerializedName(value = "user_name")
private String userName;
/** Nickname of user */
@Expose
private String nick;
/** Avatar base64 for user */
@Expose
private String avatar;
/** User's password. */
@Expose
@SerializedName(value = "password")
private String password;
/**
* @param userName
* User name defining user. Can be <code>null</code>.
*/
public ParamsUserNew(String userName) {
setUserName(userName);
}
@Override
public String getMethodName() {
return "user.new";
}
public Response instantiateResponse() {
return new ResponseUserNew();
}
/**
* @return user name
*/
public String getUserName() {
return userName;
}
/**
* Sets user name
*
* @param user_name
* user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return user nickname
*/
public String getNick() {
return nick;
}
/**
* Sets user nickname
*
* @param nick
* nickname
*/
public void setNick(String nick) {
this.nick = nick;
}
/**
* @return avatar base64
*/
public String getAvatar() {
return avatar;
}
/**
* Sets avatar base64
*
* @param avatar
* avatar base64
*/
public void setAvatar(String avatar) {
this.avatar = avatar;
}
/**
* @return password
*/
public String getPassword() {
return password;
}
/**
* @param Sets
* user password
*/
public void setPassword(String password) {
this.password = password;
}
} | mit |
RyanTech/XHCyclicReuseScrollView | README.md | 140 | XHCyclicReuseScrollView
=======================
XHCyclicReuseScrollView is an extensible, reusable, recyclable rolling scrollView element.
| mit |
amoshyc/CPsolution | docs/poj/p1276.html | 21542 |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[POJ] 1276. Cash Machine — amoshyc's CPsolution 1.0 documentation</title>
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/css/mine.css" type="text/css" />
<link rel="index" title="Index"
href="../genindex.html"/>
<link rel="search" title="Search" href="../search.html"/>
<link rel="top" title="amoshyc's CPsolution 1.0 documentation" href="../index.html"/>
<link rel="up" title="3. POJ" href="poj.html"/>
<link rel="next" title="[POJ] 1308. Is It A Tree?" href="p1308.html"/>
<link rel="prev" title="[POJ] 1151. Atlantis" href="p1151.html"/>
<script src="../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../index.html" class="icon icon-home"> amoshyc's CPsolution
</a>
<div class="version">
1.0
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../tutorials/tutorials.html">1. 常用演算法教學</a></li>
<li class="toctree-l1"><a class="reference internal" href="../cf/cf.html">2. CF</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="poj.html">3. POJ</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="p1151.html">[POJ] 1151. Atlantis</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">[POJ] 1276. Cash Machine</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#id2">題目</a></li>
<li class="toctree-l3"><a class="reference internal" href="#specification">Specification</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id3">分析</a></li>
<li class="toctree-l3"><a class="reference internal" href="#ac-code">AC Code</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="p1308.html">[POJ] 1308. Is It A Tree?</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1330.html">[POJ] 1330. Nearest Common Ancestors</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1442.html">[POJ] 1442. Black Box</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1769.html">[POJ] 1769. Minimizing maximizer</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1984.html">[POJ] 1984. Navigation Nightmare</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1988.html">[POJ] 1988. Cube Stacking</a></li>
<li class="toctree-l2"><a class="reference internal" href="p1990.html">[POJ] 1990. MooFest</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2104.html">[POJ] 2104. K-th Number</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2135.html">[POJ] 2135. Farm Tour</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2186.html">[POJ] 2186. Popular Cows</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2230.html">[POJ] 2230. Watchcow</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2349.html">[POJ] 2349. Arctic Network</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2441.html">[POJ] 2441. Arrange the Bulls</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2686.html">[POJ] 2686. Traveling by Stagecoach</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2836.html">[POJ] 2836. Rectangular Covering</a></li>
<li class="toctree-l2"><a class="reference internal" href="p2891.html">[POJ] 2891. Strange Way to Express Integers</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3041.html">[POJ] 3041. Asteroids</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3045.html">[POJ] 3045. Cow Acrobats</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3057.html">[POJ] 3057. Evacuation</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3171.html">[POJ] 3171. Cleaning Shifts</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3233.html">[POJ] 3233. Matrix Power Series</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3254.html">[POJ] 3254. Corn Fields</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3258.html">[POJ] 3258. River Hopscotch</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3264.html">[POJ] 3264. Balanced Lineup</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3273.html">[POJ] 3273. Monthly Expense</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3281.html">[POJ] 3281. Dining</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3321.html">[POJ] 3321. Apple Tree</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3368.html">[POJ] 3368. Frequent values</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3420.html">[POJ] 3420. Quad Tiling</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3468.html">[POJ] 3468. A Simple Problem with Integers</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3469.html">[POJ] 3469. Dual Core CPU</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3565.html">[POJ] 3565. Ants</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3580.html">[POJ] 3580. SuperMemo</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3686.html">[POJ] 3686. The Windy’s</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3734.html">[POJ] 3734. Blocks</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3735.html">[POJ] 3735. Training little cats</a></li>
<li class="toctree-l2"><a class="reference internal" href="p3977.html">[POJ] 3977. Subset</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../uva/uva.html">4. UVA</a></li>
<li class="toctree-l1"><a class="reference internal" href="../ptc/ptc.html">5. PTC</a></li>
<li class="toctree-l1"><a class="reference internal" href="../other/other.html">6. Other</a></li>
<li class="toctree-l1"><a class="reference internal" href="../template/template.html">7. Template</a></li>
<li class="toctree-l1"><a class="reference internal" href="../tags.html">8. Tags</a></li>
<li class="toctree-l1"><a class="reference internal" href="../cheatsheet.html">9. Cheatsheet</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">amoshyc's CPsolution</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> »</li>
<li><a href="poj.html">3. POJ</a> »</li>
<li>[POJ] 1276. Cash Machine</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/poj/p1276.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="poj-1276-cash-machine">
<h1><a class="toc-backref" href="#id4">[POJ] 1276. Cash Machine</a><a class="headerlink" href="#poj-1276-cash-machine" title="Permalink to this headline">¶</a></h1>
<div class="sidebar">
<p class="first sidebar-title">Tags</p>
<ul class="last simple">
<li><code class="docutils literal"><span class="pre">tag_dp</span></code></li>
</ul>
</div>
<div class="contents topic" id="toc">
<p class="topic-title first">TOC</p>
<ul class="simple">
<li><a class="reference internal" href="#poj-1276-cash-machine" id="id4">[POJ] 1276. Cash Machine</a><ul>
<li><a class="reference internal" href="#id2" id="id5">題目</a></li>
<li><a class="reference internal" href="#specification" id="id6">Specification</a></li>
<li><a class="reference internal" href="#id3" id="id7">分析</a></li>
<li><a class="reference internal" href="#ac-code" id="id8">AC Code</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="id2">
<h2><a class="reference external" href="http://poj.org/problem?id=1276">題目</a><a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>給定 N 個數字 D[i],第 i 個數字有 n[i] 個。
請問在 M 以下(含 M)所能組出的最大總和是多少?</p>
</div>
<div class="section" id="specification">
<h2><a class="toc-backref" href="#id6">Specification</a><a class="headerlink" href="#specification" title="Permalink to this headline">¶</a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="o"><=</span> <span class="n">N</span> <span class="o"><=</span> <span class="mi">10</span>
<span class="mi">1</span> <span class="o"><=</span> <span class="n">M</span> <span class="o"><=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">5</span>
<span class="mi">1</span> <span class="o"><=</span> <span class="n">n</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o"><=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">3</span>
<span class="mi">1</span> <span class="o"><=</span> <span class="n">D</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o"><=</span> <span class="mi">10</span><span class="o">^</span><span class="mi">3</span>
</pre></div>
</div>
</div>
<div class="section" id="id3">
<h2><a class="toc-backref" href="#id7">分析</a><a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">多重背包轉零一背包</p>
</div>
<p>重量與價值是相同值,多重背包裸題。
須二進制拆解轉零一背包加速。</p>
</div>
<div class="section" id="ac-code">
<h2><a class="toc-backref" href="#id8">AC Code</a><a class="headerlink" href="#ac-code" title="Permalink to this headline">¶</a></h2>
<div class="highlight-cpp"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="c1">// #include <bits/stdc++.h></span>
<span class="cp">#include</span> <span class="cpf"><cstdio></span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf"><vector></span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf"><algorithm></span><span class="cp"></span>
<span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="k">typedef</span> <span class="kt">long</span> <span class="kt">long</span> <span class="n">ll</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">Item</span> <span class="p">{</span>
<span class="n">ll</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span><span class="p">;</span>
<span class="p">};</span>
<span class="k">const</span> <span class="kt">int</span> <span class="n">MAX_W</span> <span class="o">=</span> <span class="mi">100000</span><span class="p">;</span>
<span class="n">ll</span> <span class="n">dp</span><span class="p">[</span><span class="n">MAX_W</span> <span class="o">+</span> <span class="mi">1</span><span class="p">];</span>
<span class="n">ll</span> <span class="nf">knapsack01</span><span class="p">(</span><span class="k">const</span> <span class="n">vector</span><span class="o"><</span><span class="n">Item</span><span class="o">>&</span> <span class="n">items</span><span class="p">,</span> <span class="kt">int</span> <span class="n">W</span><span class="p">)</span> <span class="p">{</span>
<span class="n">fill</span><span class="p">(</span><span class="n">dp</span><span class="p">,</span> <span class="n">dp</span> <span class="o">+</span> <span class="n">W</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0ll</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o"><</span> <span class="kt">int</span><span class="p">(</span><span class="n">items</span><span class="p">.</span><span class="n">size</span><span class="p">());</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">W</span><span class="p">;</span> <span class="n">j</span> <span class="o">>=</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">w</span><span class="p">;</span> <span class="n">j</span><span class="o">--</span><span class="p">)</span> <span class="p">{</span>
<span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">max</span><span class="p">(</span><span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">],</span> <span class="n">dp</span><span class="p">[</span><span class="n">j</span> <span class="o">-</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">w</span><span class="p">]</span> <span class="o">+</span> <span class="n">items</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">v</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">dp</span><span class="p">[</span><span class="n">W</span><span class="p">];</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
<span class="n">ll</span> <span class="n">W</span><span class="p">;</span> <span class="kt">int</span> <span class="n">N</span><span class="p">;</span>
<span class="k">while</span> <span class="p">(</span><span class="n">scanf</span><span class="p">(</span><span class="s">"%lld %d"</span><span class="p">,</span> <span class="o">&</span><span class="n">W</span><span class="p">,</span> <span class="o">&</span><span class="n">N</span><span class="p">)</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span> <span class="p">{</span>
<span class="n">vector</span><span class="o"><</span><span class="n">Item</span><span class="o">></span> <span class="n">items</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o"><</span> <span class="n">N</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="n">ll</span> <span class="n">val</span><span class="p">,</span> <span class="n">num</span><span class="p">;</span>
<span class="n">scanf</span><span class="p">(</span><span class="s">"%lld %lld"</span><span class="p">,</span> <span class="o">&</span><span class="n">num</span><span class="p">,</span> <span class="o">&</span><span class="n">val</span><span class="p">);</span>
<span class="k">for</span> <span class="p">(</span><span class="n">ll</span> <span class="n">k</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">k</span> <span class="o"><=</span> <span class="n">num</span><span class="p">;</span> <span class="n">k</span> <span class="o">*=</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span>
<span class="n">items</span><span class="p">.</span><span class="n">push_back</span><span class="p">((</span><span class="n">Item</span><span class="p">)</span> <span class="p">{</span><span class="n">k</span> <span class="o">*</span> <span class="n">val</span><span class="p">,</span> <span class="n">k</span> <span class="o">*</span> <span class="n">val</span><span class="p">});</span>
<span class="n">num</span> <span class="o">-=</span> <span class="n">k</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">num</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="n">items</span><span class="p">.</span><span class="n">push_back</span><span class="p">((</span><span class="n">Item</span><span class="p">)</span> <span class="p">{</span><span class="n">num</span> <span class="o">*</span> <span class="n">val</span><span class="p">,</span> <span class="n">num</span> <span class="o">*</span> <span class="n">val</span><span class="p">});</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">printf</span><span class="p">(</span><span class="s">"%lld</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">knapsack01</span><span class="p">(</span><span class="n">items</span><span class="p">,</span> <span class="n">W</span><span class="p">));</span>
<span class="p">}</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</td></tr></table></div>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="p1308.html" class="btn btn-neutral float-right" title="[POJ] 1308. Is It A Tree?" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="p1151.html" class="btn btn-neutral" title="[POJ] 1151. Atlantis" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2016, amoshyc.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../',
VERSION:'1.0',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | mit |
beachio/beach-api-core | app/interactors/beach_api_core/team_update.rb | 259 | class BeachApiCore::TeamUpdate
include Interactor
def call
if context.team.update context.params
context.status = :ok
else
context.status = :bad_request
context.fail! message: context.team.errors.full_messages
end
end
end
| mit |
cheniison/Experiment | OS/WebServer/server.c | 4428 | #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include "server.h"
#include "rio.h"
int writeTo(int fd, char * string)
{
return write(fd, string, strlen(string));
}
void err_dump(int fd, int status, char * err_msg)
{
char line[LINE_SIZE];
snprintf(line, LINE_SIZE, "HTTP/1.1 %d %s\r\n\r\n", status, err_msg);
writeTo(fd, line);
snprintf(line, LINE_SIZE, "ERROR: %d\r\n", status);
writeTo(fd, line);
snprintf(line, LINE_SIZE, "ERROR MESSAGE: %s\r\n\r\n", err_msg);
writeTo(fd, line);
}
void sig_int(int signo)
{
exit(0);
}
void sig_child(int signo)
{
signal(SIGCHLD, sig_child);
while (waitpid(-1, NULL, WNOHANG) > 0)
;
}
void initServer()
{
/* 忽略 sigpipe 信号 */
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, sig_int);
signal(SIGCHLD, sig_child);
}
/* 打开监听 */
int open_listenfd(int port)
{
int sockfd, res;
struct sockaddr_in addr;
/* 创建socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
fprintf(stderr, "socket error\n");
exit(1);
}
printf("创建socket成功\n");
/* 初始化地址 */
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
printf("初始化地址成功\n");
/* 绑定地址 */
res = bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr));
if (res < 0) {
fprintf(stderr, "bind error\n");
exit(1);
}
printf("绑定地址 %s:%d 成功\n", inet_ntoa(addr.sin_addr), PORT);
/* 监听 */
res = listen(sockfd, 50);
if (res < 0) {
fprintf(stderr, "listen error\n");
exit(1);
}
printf("监听成功\n");
return sockfd;
}
void handleUri(int fd, const char * uri)
{
char whole_uri[URI_LEN] = DOCUMENT_ROOT;
int ffd; /* 文件描述符 */
struct stat f_statue;
char * buf;
if (uri[0] == '/') {
uri += 1;
}
strncat(whole_uri, uri, URI_LEN);
if (stat(whole_uri, &f_statue) < 0) {
err_dump(fd, 404, "Not Found");
return;
}
if (! S_ISREG(f_statue.st_mode)) {
err_dump(fd, 403, "Not Regular File");
return;
}
if ((ffd = open(whole_uri, O_RDONLY)) < 0) {
err_dump(fd, 403, "Forbidden");
return;
}
buf = (char *)mmap((void *)0, f_statue.st_size, PROT_READ, MAP_PRIVATE, ffd, 0);
if (buf == MAP_FAILED) {
err_dump(fd, 501, "Mmap Error");
return;
}
writeTo(fd, "HTTP/1.1 200 OK\r\n\r\n");
writeTo(fd, buf);
}
void doit(int fd)
{
char line[LINE_SIZE];
char method[10], uri[URI_LEN], version[10];
rio_t rio;
rio_init(&rio, fd);
if (rio_readline(&rio, line, LINE_SIZE) <= 0)
{
err_dump(fd, 400, "Bad Request");
return;
}
if (sscanf(line, "%s %s %s", method, uri, version) != 3) {
err_dump(fd, 400, "Bad Request");
return;
}
while(rio_readline(&rio, line, LINE_SIZE) > 0) {
if (strcmp(line, "\r\n") == 0) {
break;
}
}
if (strcmp(method, "GET") != 0) {
err_dump(fd, 501, "No Method");
return;
}
handleUri(fd, uri);
}
int main()
{
int fd, sockfd, pid, num;
socklen_t client_len;
struct sockaddr_in client_addr;
char * client_ip;
initServer();
sockfd = open_listenfd(PORT);
num = 0;
/* 等待请求 */
while (1) {
while ((fd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len)) < 0) {
if (errno != EINTR) {
/* 不是被信号处理函数中断 */
fprintf(stderr, "accept error\n");
exit(1);
}
}
++num;
client_ip = inet_ntoa(client_addr.sin_addr);
printf("请求 %d: %s\n", num, client_ip);
if ((pid = fork()) < 0) {
fprintf(stderr, "fork error\n");
exit(1);
} else if (pid == 0) {
/* child */
close(sockfd);
doit(fd);
printf("结束 %d: %s\n", num, client_ip);
exit(0);
}
close(fd);
}
return 0;
}
| mit |
vicenteneto/online-judge-solutions | URI/1-Beginner/1021.py | 907 | # -*- coding: utf-8 -*-
def calc_note(count, value):
qnt = 0
if count >= value:
qnt = int(count) / value
print '%d nota(s) de R$ %d.00' % (qnt, value)
return count - qnt * value
n = float(raw_input())
print 'NOTAS:'
n = calc_note(n, 100)
n = calc_note(n, 50)
n = calc_note(n, 20)
n = calc_note(n, 10)
n = calc_note(n, 5)
n = calc_note(n, 2)
print 'MOEDAS:'
print '%d moeda(s) de R$ 1.00' % int(n)
n -= int(n)
m50 = n / 0.50
print '%d moeda(s) de R$ 0.50' % m50
n -= int(m50) * 0.50
m25 = n / 0.25
print '%d moeda(s) de R$ 0.25' % m25
n -= int(m25) * 0.25
m10 = n / 0.10
print '%d moeda(s) de R$ 0.10' % m10
n -= int(m10) * 0.10
if round(n, 2) >= 0.05:
print '1 moeda(s) de R$ 0.05'
m1 = (n - 0.05) * 100
else:
print '0 moeda(s) de R$ 0.05'
m1 = round(n, 2) * 100
if round(m1, 0):
print '%.0f moeda(s) de R$ 0.01' % m1
else:
print '0 moeda(s) de R$ 0.01'
| mit |
himynameisdave/postcss-plugins | README-zh_CN.md | 3442 | ## PostCSS 插件列表 [](https://www.npmjs.com/package/postcss-plugins) [](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md)
开箱即用型"官方和非官方"综合[PostCSS](https://github.com/postcss/postcss) 插件
<img align="right" width="100" height="100"
title="Philosopher’s stone, logo of PostCSS"
src="http://postcss.github.io/postcss/logo.svg">
### 目的
这里有 [超过数百人的优秀开发者](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md) 正在构建令人惊叹的 PostCSS 插件。插件运行列表增长速度非常块,而且已经在很多地方投入使用了。通过 [**@mxstbr**](https://github.com/mxstbr) 构建的 [postcss.parts](http://postcss.parts) 可以搜索到。另一个是 [**@chrisopedia**](https://github.com/chrisopedia) 创建的 [PostCSS Alfred Workflow](https://github.com/chrisopedia/alfred-postcss-workflow)。对于开发者来说,这些是非常的好的资源用来查找和使用,而且这个列表会持续更新。
目的尽可能简洁明了但仍然会向开发者提供一些插件相关的数据
**简而言之** 这是一个包含大量 PostCSS 插件的源数据列表
### 安装
**使用 yarn**
```
yarn add postcss-plugins
```
**使用 npm**
```
npm i postcss-plugins
```
### 使用
```javascript
const plugins = require('postcss-plugins');
// 基本用法: 获取数据集里面的每个插件名
const namesOfEveryPlugin = plugins.map(plugin => plugin.name);
// 基本用法: 获取star数最多的插件
const mostStarredPlugin = plugins.reduce((a, p) => a.stars && p.stars > a.stars ? p : a, { stars: 0 });
// 基本用法: 看看 himynameisdave 已经写了多少个插件
const himynameisdavesPlugins = plugins.reduce((a, p) => p.author === 'himynameisdave' ? ++a : a, 0)
```
### 提交一个新的插件
欢迎所有插件,只要符合 [PostCSS Plugin Guidelines](https://github.com/postcss/postcss/blob/master/docs/guidelines/plugin.md) 的插件指南。
这些脚本可以让添加插件变得像回答一些关于它的问题一样简单。
**步骤**:
1. [Fork 这个仓库](https://github.com/himynameisdave/postcss-plugins#fork-destination-box).
1. 运行 `yarn install` / `npm install` 快速安装 [脚本](https://github.com/himynameisdave/postcss-plugins/tree/master/scripts) 所依赖的依赖项。
1. 运行 `yarn run add` / `npm run add`。 然后系统会提示你输入有关插件的信息,按照提示操作即可。
1. 然后将你的插件添加到 [`plugins.json`](https://github.com/himynameisdave/postcss-plugins/blob/master/plugins.json) 和 你的插件名 到 [`authors.md`](https://github.com/himynameisdave/postcss-plugins/blob/master/docs/authors.md) 列表中。
1. 提交并推送变更,然后提交 pull request.
1. [别着急](http://i.imgur.com/dZzkNc7.gif)
**请注意** `plugins.json` 和 `authors.md` **都不要直接编辑**。 反而,请按照上面的步骤确保你的拉取请求能够及时合并。 同时, 不用操心 Github start 数量,因为这是维护人员定期完成的。
### 更新日志
有关发布、更改和更新的列表,请参见[更新日志](https://github.com/himynameisdave/postcss-plugins/blob/master/CHANGELOG.md)。 | mit |
fbiville/annotation-processing-ftw | doc/java/jdk7/java/net/class-use/SocketImplFactory.html | 7301 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:35 PST 2014 -->
<title>Uses of Interface java.net.SocketImplFactory (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface java.net.SocketImplFactory (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/net/class-use/SocketImplFactory.html" target="_top">Frames</a></li>
<li><a href="SocketImplFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface java.net.SocketImplFactory" class="title">Uses of Interface<br>java.net.SocketImplFactory</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#java.net">java.net</a></td>
<td class="colLast">
<div class="block">Provides the classes for implementing networking applications.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="java.net">
<!-- -->
</a>
<h3>Uses of <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a> in <a href="../../../java/net/package-summary.html">java.net</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../java/net/package-summary.html">java.net</a> with parameters of type <a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">ServerSocket.</span><code><strong><a href="../../../java/net/ServerSocket.html#setSocketFactory(java.net.SocketImplFactory)">setSocketFactory</a></strong>(<a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a> fac)</code>
<div class="block">Sets the server socket implementation factory for the
application.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">Socket.</span><code><strong><a href="../../../java/net/Socket.html#setSocketImplFactory(java.net.SocketImplFactory)">setSocketImplFactory</a></strong>(<a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">SocketImplFactory</a> fac)</code>
<div class="block">Sets the client socket implementation factory for the
application.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/net/SocketImplFactory.html" title="interface in java.net">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/net/class-use/SocketImplFactory.html" target="_top">Frames</a></li>
<li><a href="SocketImplFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| mit |
justhamade/grunt-install-dependencies | tasks/install-dependencies.js | 949 | 'use strict';
module.exports = function (grunt) {
var exec = require('child_process').exec;
grunt.registerMultiTask('install-dependencies', 'Installs npm dependencies.', function () {
var cb, options, cp;
cb = this.async();
options = this.options({
cwd: '',
stdout: true,
stderr: true,
failOnError: true,
isDevelopment: false
});
var cmd = "npm install";
if(!options.isDevelopment ) cmd += " -production";
cp = exec(cmd, {cwd: options.cwd}, function (err, stdout, stderr) {
if (err && options.failOnError) {
grunt.warn(err);
}
cb();
});
grunt.verbose.writeflags(options, 'Options');
if (options.stdout || grunt.option('verbose')) {
console.log("Running npm install in: " + options.cwd);
cp.stdout.pipe(process.stdout);
}
if (options.stderr || grunt.option('verbose')) {
cp.stderr.pipe(process.stderr);
}
});
};
| mit |
slx7R4GDZM/Sine-Toolkit | Source/Other/Text.h | 4630 | // Copyright slx7R4GDZM
// Distributed under the terms of the MIT License.
// Refer to the License.txt file for details.
#pragma once
#include "Common-Things.h"
const string BRIGHTNESS_OPTIONS[] =
{
"BRIGHTNESS 15",
"BRIGHTNESS 12",
"BRIGHTNESS 7",
"BRIGHTNESS 0"
};
const string GLOBAL_SCALE_OPTIONS[] =
{
"GLOBAL SCALE (*2)",
"GLOBAL SCALE (*1)",
"GLOBAL SCALE (/2)",
"GLOBAL SCALE (/4)"
};
const string VCTR_OPTIONS[] =
{
"LOCAL SCALE UP",
"LOCAL SCALE DOWN",
"LOCAL SCALE (/512)",
"LOCAL SCALE (*1)"
};
const string LABS_OPTIONS[] =
{
"GLOBAL SCALE UP",
"GLOBAL SCALE DOWN",
"GLOBAL SCALE (*1)",
"GLOBAL SCALE (/2)"
};
const string SVEC_OPTIONS[] =
{
"LOCAL SCALE UP",
"LOCAL SCALE DOWN",
"LOCAL SCALE (*2)",
"LOCAL SCALE (*16)"
};
const string SHIP_CREATOR_OPTIONS[] =
{
"BRIGHTNESS UP",
"BRIGHTNESS DOWN",
"BRIGHTNESS 0",
"BRIGHTNESS 12"
};
/////////////////
const array<string, 5> MAIN_MENU_CHOICES =
{
"EDIT VECTOR OBJECT",
"EDIT TEXT",
"EDIT SHIP",
"EDIT SHIP THRUST",
"TOGGLE VECTORS"
};
const array<string, 3> INSTRUCTION_MENU_CHOICES =
{
"DRAW LONG VECTOR",
"LOAD ABSOLUTE",
"DRAW SHORT VECTOR"
};
const array<string, 5> VECTOR_OBJECT_MENU_CHOICES =
{
"ADD INSTRUCTION",
"REMOVE INSTRUCTION",
"SET GLOBAL SCALE",
"OUTPUT VECTOR OBJECT",
"CLEAR VECTOR OBJECT"
};
const array<string, 4> SHIP_MENU_CHOICES =
{
"ADD INSTRUCTION",
"REMOVE INSTRUCTION",
"OUTPUT SHIP",
"CLEAR SHIP"
};
const array<string, 4> THRUST_MENU_CHOICES =
{
"ADD INSTRUCTION",
"REMOVE INSTRUCTION",
"OUTPUT SHIP THRUST",
"CLEAR SHIP THRUST"
};
const array<string, 3> TOGGLE_VECTORS_MENU_CHOICES =
{
"BOX",
"VECTOR OBJECT",
"SHIP AND THRUST"
};
const string DEFAULT_SETTINGS =
R"(# Lines starting with # are ignored by the program
#==============================================================================
# List of Available Keys
#==============================================================================
# Escape F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 Pause
# Tilde Num1 Num2 Num3 Num4 Num5 Num6 Num7 Num8 Num9 Num0 Hyphen Equal
# Tab Q W E R T Y U I O P LBracket RBracket Backslash Backspace
# A S D F G H J K L Semicolon Quote Enter
# LShift Z X C V B N M Comma Period Slash RShift
# LControl LSystem LAlt Space RAlt RSystem Menu RControl
# Insert Home PageUp Divide Multiply Subtract
# Delete End PageDown Numpad7 Numpad8 Numpad9 Add
# Numpad4 Numpad5 Numpad6
# Up Numpad1 Numpad2 Numpad3
# Left Down Right Numpad0
#==============================================================================
# Button Settings
#==============================================================================
B-Confirm E
B-Cancel F
B-Up W
B-Down S
B-Left A
B-Right D
B-Options Q
B-Toggle-Fullscreen F11
B-Exit Escape
#==============================================================================
# Window Settings
#==============================================================================
## Which mode to start the window with
# 0 = Normal window (default)
# 1 = Borderless window
# 2 = Exclusive fullscreen
Starting-Window-Mode 0
## Starting window resolution
Starting-X-Resolution 1024
Starting-Y-Resolution 790
## Starting position for the program window
# -1 = Don't set the starting position (default)
Start-Window-Position-X -1
Start-Window-Position-Y -1
## What to do when the window isn't focused
# 0 = Pause the program (default)
# 1 = Run in background without input
# 2 = Run in background with input
Inactive-Mode 0
#==============================================================================
# Graphics Settings
#==============================================================================
## The x:y ratio to crop the image to
# < 1 = Crops the image starting with the left and right sides
# 1.0 = Scales the image to the lower resolution axis
# > 1 = Crops the image starting with the top and bottom (default)
Crop-Ratio 1.2962025
## MSAA toggle and quality setting
# 0 = Off
# 1 = 2x
# 2 = 4x
# 3 = 8x (default)
MSAA-Quality 3
## Gamma correction
Gamma-Correction 1.0
## Vertical synchronization
# 0 = Disabled (default)
# 1 = Enabled
V-Sync-Enabled 0
## Whether to use busy waiting or sleeping to limit FPS
# 0 = Use sleeping (default)
# 1 = Use busy waiting; this has high CPU usage, but it's consistent
Frame-Limit-Mode 0
)";
| mit |
thispagecannotbefound/php-signals | tests/bootstrap.php | 173 | <?php
ini_set('display_errors', 1);
ini_set('error_reporting', -1);
$loader = require __DIR__ . '/../vendor/autoload.php';
$loader->add('ThisPageCannotBeFound', __DIR__);
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_95/safe/CWE_95__object-indexArray__func_preg_replace__echo-sprintf_%s_simple_quote.php | 1579 | <?php
/*
Safe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
SANITIZE : use of preg_replace
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
class Input{
private $input;
public function getInput(){
return $this->input['realOne'];
}
public function __construct(){
$this->input = array();
$this->input['test']= 'safe' ;
$this->input['realOne']= $_GET['UserData'] ;
$this->input['trap']= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$tainted = preg_replace('/\'/', '', $tainted);
$query = sprintf("echo $'%s';", $tainted);
$res = eval($query);
?> | mit |
jensonzhao/crm_fieldservices | lib/crm_fieldservices.rb | 470 | ActionController::Dispatcher.to_prepare do
# Extend :account model to add :issues association.
Account.send(:include, AccountServiceRequestAssociations)
# Make issues observable.
ActivityObserver.instance.send :add_observer!, ServiceRequest
# Add :issues plugin helpers.
ActionView::Base.send(:include, ServiceRequestsHelper)
end
# Make the issues commentable.
CommentsController.commentables = CommentsController.commentables + %w(service_request_id) | mit |
massahud/zf2-testeunidade | js-test/fixtures/exemplos/divs.html | 157 | <style type="text/css">
.escondido {
display: none;
}
</style>
<div id="div1" class="xxx">div1</div>
<div id="div2" class="escondido">2</div> | mit |
tpaschalis/tpaschalis.github.io | _posts/2021-03-13-relnote-yes.markdown | 6148 | ---
layout: post
title: How the Go team could track what to include in release notes
date: 2021-03-13
author: Paschalis Ts
tags: [golang, foss]
mathjax: false
description: ""
---
Release notes can sometimes be exciting to read.
Condensing the work since the last release into a couple of paragraphs, announcing new exciting features or deprecating older ones, communicating bugfixes or architectural decisions, making important announcements.. Come to think of it, the couple of times that I've had to *write* them, wasn't so bad at all!
Unfortunately, the current trend is release notes becoming a mix of *Bug fixes*, *Made ur app faster*, *Added new feature, won't tell you what it is*, which can sound like generalities at best and condescending or patronizing at worst; usually like something written just to fill an arbitrary word limit in the last five minutes before a release.
Here's what's currently listed in the "What's New" section for a handful of popular applications in the Google Play Store.
```
- Thanks for choosing Chrome! This release includes stability and performance improvements.
- Every week we polish up the Pinterest app to make it faster and better than ever.
Tell us if you like this newest version at http://help.pinterest.com/contact
- Get the best experience for enjoying recent hits and timeless classics with our latest
Netflix update for your phone and tablet.
- We update the Uber app as often as possible to help make it faster and more reliable
for you. This version includes several bug fixes and performance improvements.
- We’re always making changes and improvements to Spotify. To make sure you don’t miss
a thing, just keep your Updates turned on.
- For new features, look for in-product education & notifications sharing the feature
and how to use it! (FYI this was YouTube, as it doesn't even mention the product's name)
```
The Opera browser, on the other hand has something more reminiscent of actual release notes.
```
What's New
Thanks for choosing Opera! This version includes improvements to Flow,
the share dialog and the built-in video player.
More changes:
- Chromium 87
- Updated onboarding
- Adblocker improvements
- Various fixes and stability improvements
```
Just to make things clear *I'm not bashing these fellow developers at all*. [Here's](https://github.com/beatlabs/patron/releases) the release history of a project I'm helping maintain; our release notes can be just as vague sometimes.
Writing helpful, informative (and even fun!) release notes is time consuming and has little benefit non-technical folks. It's also hard to keep track of what's changed since the last release, and deciding what's important and what's not.
How would *you* do it?
## The Go team solution
So, how is Go team approaching this problem? A typical Go release in the past three years may contain from 1.6k to 2.3k commits.
```
from -> to commits
1.15 -> 1.16 1695
1.14 -> 1.15 1651
1.13 -> 1.14 1754
1.12 -> 1.13 1646
1.11 -> 1.12 1682
1.10 -> 1.11 2268
1.9 -> 1.10 1996
1.8 -> 1.9 2157
```
How do you keep track of what was important, what someone reading the release notes may need to know?
I set to find out, after [Emmanuel](https://twitter.com/odeke_et) (a great person, and one of the best ambassadors the Go community could wish for), added a mysterious comment on one of my [latest CLs](https://go-review.googlesource.com/c/go/+/284136) that read `RELNOTE=yes`.
The [`build`](https://github.com/golang/build) repo holds Go's continuous build and release infrastructure; it also contains the [`relnote` tool](https://github.com/golang/build/blob/master/cmd/relnote/relnote.go) that gathers and summarizes Gerrit changes (CLs) which are marked with RELNOTE annotations. The earliest reference of this idea I could find is [this CL](https://go-review.googlesource.com/c/build/+/30697) from Brad Fitzpatrick, back in October 2016.
So, any time a commit is merged (or close to merging) where someone thinks it may be useful to include in the release notes, they can leave a `RELNOTE=yes` or `RELNOTES=yes` comment. All these CLs are then gathered to be reviewed by the release author. Here's the actual Gerrit API query:
```
query := fmt.Sprintf(`status:merged branch:master since:%s (comment:"RELNOTE" OR comment:"RELNOTES")`
```
Of course, this is not a tool that will automatically generate something you can publish, but it's a pretty good alternative to sieving a couple thousands of commits manually.
I love the simplicity; I feel that it embodies the Go way of doing things. I feel that if my team at work tried to find a solution, we'd come up with something much more complex, fragile and unmaintainable than this. The tool doesn't even support time ranges as input; since Go releases are roughly once every six months, here's how it decides which commits to include
```go
// Releases are every 6 months. Walk forward by 6 month increments to next release.
cutoff := time.Date(2016, time.August, 1, 00, 00, 00, 0, time.UTC)
now := time.Now()
for cutoff.Before(now) {
cutoff = cutoff.AddDate(0, 6, 0)
}
// Previous release was 6 months earlier.
cutoff = cutoff.AddDate(0, -6, 0)
```
## In action!
Here's me running the tool, and a small part of the output.
```bash
$ git clone https://github.com/golang/build
$ cd build/cmd/relnote
$ go build .
$ ./relnote
...
...
https://golang.org/cl/268020: os: avoid allocation in File.WriteString
reflect
https://golang.org/cl/266197: reflect: add Method.IsExported and StructField.IsExported methods
https://golang.org/cl/281233: reflect: add VisibleFields function
syscall
https://golang.org/cl/295371: syscall: do not overflow key memory in GetQueuedCompletionStatus
unicode
https://golang.org/cl/280493: unicode: correctly handle negative runes
```
## Parting words
That's all for today! I hope that my change will find its way on the Go 1.17 release notes; if not I'm happy that I learned something new!
I'm not sure if the `relnote` tool is still being actively used, but I think it would be fun to learn more about what goes into packaging a Go release.
Until next time, bye!
| mit |
liuy97/angular2-material-seed | src/client/app/material/demo-app/chips/chips-demo.ts | 211 | import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'chips-demo',
templateUrl: 'chips-demo.html',
styleUrls: ['chips-demo.css']
})
export class ChipsDemoComponent {
}
| mit |
foysalit/hive-customer | public/modules/consumers/views/create-consumer.client.view.html | 4740 | <section data-ng-controller="ConsumersController">
<div class="page-header">
<h1>New Order</h1>
</div>
<div class="row" ng-show="errors.has()">
<div class="alert alert-danger" ng-repeat="err in errors.all">
{{ err }}
</div>
</div>
<div class="col-md-12" data-ng-init="initializeForm()">
<form class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group">
<label class="control-label" for="firstName">First Name</label>
<div class="controls">
<input type="text" data-ng-model="firstName" id="firstName" class="form-control" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="lastName">Last Name</label>
<div class="controls">
<input type="text" data-ng-model="lastName" id="lastName" class="form-control" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="name">Address</label>
<div class="controls">
<div id="address_input"></div>
<div id="map_canvas">
<ui-gmap-google-map
center="mapConfig.center"
zoom="mapConfig.zoom">
<ui-gmap-search-box
ng-model="address"
parentdiv="mapSearchBoxConfig.parentDiv"
events="mapSearchBoxConfig.events"
template="mapSearchBoxConfig.template"
options="mapSearchBoxConfig.options">
</ui-gmap-search-box>
<ui-gmap-marker
coords="mapMarker.coords"
options="mapMarker.options"
events="mapMarker.events"
idkey="mapMarker.id">
</ui-gmap-google-map>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="apartment">Apartment</label>
<div class="controls">
<input type="text" data-ng-model="apartment" id="apartment" class="form-control" placeholder="Apartment" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="phone">Cell Number</label>
<div class="controls">
<input type="text" data-ng-model="phone" id="phone" class="form-control" placeholder="Cell Number" required>
</div>
</div>
<div class="form-group">
<label class="radio-inline">
<input
type="radio"
ng-model="product"
name="product-{{$index}}"
value="large-pizza">
Large Pizza
</label>
<label class="radio-inline">
<input
type="radio"
ng-model="product"
name="product-{{$index}}"
value="medium-pizza">
Medium Pizza
</label>
<label class="radio-inline">
<input
type="radio"
ng-model="product"
name="product-{{$index}}"
value="small-pizza">
Small Pizza
</label>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default" value="Done">
</div>
</fieldset>
</form>
</div>
<script type="text/ng-template" id="places-autocomplete-template.tmpl.html">
<input
type="text"
ng-model="ngModel"
id="address"
class="form-control"
placeholder="Address"
required>
</script>
</section> | mit |
giggals/Software-University | Exercises-Interfaces/2. Multiple Implementation/IIdentifiable.cs | 131 | using System;
using System.Collections.Generic;
using System.Text;
public interface IIdentifiable
{
string Id { get; }
}
| mit |
V2GClarity/RISE-V2G | RISE-V2G-EVCC/src/main/java/com/v2gclarity/risev2g/evcc/states/WaitForAuthorizationRes.java | 4963 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2019 Dr. Marc Mültin (V2G Clarity)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package com.v2gclarity.risev2g.evcc.states;
import java.util.concurrent.TimeUnit;
import com.v2gclarity.risev2g.evcc.session.V2GCommunicationSessionEVCC;
import com.v2gclarity.risev2g.shared.enumerations.GlobalValues;
import com.v2gclarity.risev2g.shared.enumerations.V2GMessages;
import com.v2gclarity.risev2g.shared.messageHandling.ReactionToIncomingMessage;
import com.v2gclarity.risev2g.shared.messageHandling.TerminateSession;
import com.v2gclarity.risev2g.shared.misc.TimeRestrictions;
import com.v2gclarity.risev2g.shared.utils.SecurityUtils;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.AuthorizationReqType;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.AuthorizationResType;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ChargeParameterDiscoveryReqType;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.EVSEProcessingType;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.PaymentOptionType;
import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.V2GMessage;
public class WaitForAuthorizationRes extends ClientState {
public WaitForAuthorizationRes(V2GCommunicationSessionEVCC commSessionContext) {
super(commSessionContext);
}
@Override
public ReactionToIncomingMessage processIncomingMessage(Object message) {
if (isIncomingMessageValid(message, AuthorizationResType.class)) {
V2GMessage v2gMessageRes = (V2GMessage) message;
AuthorizationResType authorizationRes =
(AuthorizationResType) v2gMessageRes.getBody().getBodyElement().getValue();
if (authorizationRes.getEVSEProcessing() == null)
return new TerminateSession("EVSEProcessing parameter of AuthorizationRes is null. Parameter is mandatory.");
if (authorizationRes.getEVSEProcessing().equals(EVSEProcessingType.FINISHED)) {
getLogger().debug("EVSEProcessing was set to FINISHED");
getCommSessionContext().setOngoingTimer(0L);
getCommSessionContext().setOngoingTimerActive(false);
ChargeParameterDiscoveryReqType chargeParameterDiscoveryReq = getChargeParameterDiscoveryReq();
/*
* Save this request in case the ChargeParameterDiscoveryRes indicates that the EVSE is
* still processing. Then this request can just be resent instead of asking the EV again.
*/
getCommSessionContext().setChargeParameterDiscoveryReq(chargeParameterDiscoveryReq);
return getSendMessage(chargeParameterDiscoveryReq, V2GMessages.CHARGE_PARAMETER_DISCOVERY_RES);
} else {
getLogger().debug("EVSEProcessing was set to ONGOING");
long elapsedTimeInMs = 0;
if (getCommSessionContext().isOngoingTimerActive()) {
long elapsedTime = System.nanoTime() - getCommSessionContext().getOngoingTimer();
elapsedTimeInMs = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);
if (elapsedTimeInMs > TimeRestrictions.V2G_EVCC_ONGOING_TIMEOUT)
return new TerminateSession("Ongoing timer timed out for AuthorizationReq");
} else {
getCommSessionContext().setOngoingTimer(System.nanoTime());
getCommSessionContext().setOngoingTimerActive(true);
}
// [V2G2-684] demands to send an empty AuthorizationReq if the field EVSEProcessing is set to 'Ongoing'
AuthorizationReqType authorizationReq = getAuthorizationReq(null);
return getSendMessage(authorizationReq, V2GMessages.AUTHORIZATION_RES, Math.min((TimeRestrictions.V2G_EVCC_ONGOING_TIMEOUT - (int) elapsedTimeInMs), TimeRestrictions.getV2gEvccMsgTimeout(V2GMessages.AUTHORIZATION_RES)));
}
} else {
return new TerminateSession("Incoming message raised an error");
}
}
}
| mit |
allan-simon/tatoSSO | app/src/contents/Tokens.h | 1177 | /**
* TatoSSO Single Sign On (SSO) system
*
* Copyright (C) 2014 Allan SIMON <[email protected]>
* See accompanying file COPYING.TXT file for licensing details.
*
* @category TatoSSO
* @author Allan SIMON <[email protected]>
* @package Contents
*
*/
#ifndef TATO_SSO_CONTENTS_TOKENS_H
#define TATO_SSO_CONTENTS_TOKENS_H
#include "cppcms_skel/contents/content.h"
#include "contents/forms/external_login.h"
//%%%NEXT_CONTENT_FORM_INCLUDE_MARKER%%%
namespace tatosso {
namespace contents {
namespace tokens {
/**
* @class Tokens
* @brief Base content for every action of Tokens controller
* @since 31 March 2014
*/
struct Tokens : public ::contents::BaseContent {
};
/**
* @struct CheckToken
* @since 31 March 2014
*/
struct CheckToken : public Tokens {
CheckToken() {
}
};
/**
* @struct ExternalLogin
* @since 31 March 2014
*/
struct ExternalLogin : public Tokens {
forms::tokens::ExternalLogin externalLoginForm;
/**
* @brief Constructor
*/
ExternalLogin() {
}
};
//%%%NEXT_CONTENT_MARKER%%%
} // end of namespace tokens
} // end of namespace contents
} // end of namespace tatosso
#endif
| mit |
phpcq/phpcq | tests/Console/Definition/OptionDefinitionTest.php | 2135 | <?php
declare(strict_types=1);
namespace Phpcq\Runner\Test\Console\Definition;
use Phpcq\Runner\Console\Definition\OptionDefinition;
use Phpcq\Runner\Console\Definition\OptionValue\OptionValueDefinition;
use PHPUnit\Framework\TestCase;
/** @covers \Phpcq\Runner\Console\Definition\OptionDefinition */
final class OptionDefinitionTest extends TestCase
{
public function testDefinition(): void
{
$optionValue = $this->getMockForAbstractClass(OptionValueDefinition::class, [], '', false);
$definition = new OptionDefinition(
'foo',
'Full description',
'f',
true,
false,
false,
$optionValue,
'='
);
self::assertSame('foo', $definition->getName());
self::assertSame('Full description', $definition->getDescription());
self::assertSame('f', $definition->getShortcut());
self::assertSame(true, $definition->isRequired());
self::assertSame(false, $definition->isArray());
self::assertSame(false, $definition->isOnlyShortcut());
self::assertSame($optionValue, $definition->getOptionValue());
self::assertSame('=', $definition->getValueSeparator());
}
public function testShortcutOnly(): void
{
$optionValue = $this->getMockForAbstractClass(OptionValueDefinition::class, [], '', false);
$definition = new OptionDefinition(
'foo',
'Full description',
null,
true,
false,
true,
$optionValue,
'='
);
self::assertSame('foo', $definition->getName());
self::assertSame('Full description', $definition->getDescription());
self::assertSame('foo', $definition->getShortcut());
self::assertSame(true, $definition->isRequired());
self::assertSame(false, $definition->isArray());
self::assertSame(true, $definition->isOnlyShortcut());
self::assertSame($optionValue, $definition->getOptionValue());
self::assertSame('=', $definition->getValueSeparator());
}
}
| mit |
akashbachhania/jeet99 | application/views/includes/navbar.php | 45301 | <?php
if (isset($user_data['id'])) {
?>
<script>
var $records_per_page = '<?php echo $this->security->get_csrf_hash(); ?>';
var page_url = '<?php echo base_url(); ?>';
var $user_data ="<?php echo $user_data['id']?>";
</script>
<script src="<?php echo base_url(); ?>assets/js/detail_pages/include/navbar.js"></script>
<?php
}
?>
<!--Main Menu File-->
<!--For Demo Only (Remove below css file and Javascript) -->
<div class="wsmenucontainer clearfix"></div>
<div class="wsmenucontent overlapblackbg "></div>
<div class="wsmenuexpandermain slideRight">
<a id="navToggle" class="animated-arrow slideLeft "><span></span></a>
<a href="<?php echo base_url(); ?>" class="smallogo"><img src="<?php echo base_url(); ?>assets/logos/logo-07.png" width="120" alt=""></a>
<?php if (!empty($user_data['id'])) {
$notyfi_ = $this->M_notify->getnotify($user_data['id'], 1); ?>
<div class="callusicon dropdown notifications">
<a href="" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-globe"></i>
<?php if (count($notyfi_) != 0) {
?><span class="badge bg-lightred"><?php echo count($notyfi_)?></span><?php
} ?>
</a>
<div class="dropdown-menu pull-right with-arrow panel panel-default animated littleFadeInLeft">
<div class="panel-heading">
You have <strong><?php echo count($notyfi_)?></strong> notifications unread
</div>
<ul class="list-group">
<?php
$notify = $this->M_notify->getnotify($user_data['id']);
foreach ($notify as $row) {
if ($row['type'] == 'invite') {
$link = base_url().'chat/dashboard';
} elseif ($row['type'] == 'amper_register') {
$link = base_url().'amper/dashboard_affiliates';
} elseif ($row['type'] == 'amper_register') {
$link = base_url().'amper/dashboard_affiliates';
} elseif ($row['type'] == 'Invite tour') {
$link = $row['active_url'];
} else {
$link = '#';
}
//var_dump($link);exit;
?>
<li class="list-group-item">
<a role="button" tabindex="0" class="media" href="<?=$link?>">
<div class="media-body">
<span class="block"><?php echo $row['messages']?></span>
<small class="text-muted"><?php echo $this->M_user->time_calculation($row['time'])?></small>
</div>
</a>
</li>
<?php
} ?>
</ul>
<div class="panel-footer">
<a href="<?=base_url('notifications/all')?>" role="button" tabindex="0">Show all notifications <i class="fa fa-angle-right pull-right"></i></a>
</div>
</div>
</div>
<?php
}?>
</div>
<?php
$params1 = $this->uri->segment(1);
$params2 = $this->uri->segment(2);
if (($params1 == 'mds' || ($params1 == 'artist' && $params2 == 'amp') || ($params1 == 'artist' && $params2 == 'managerrpk') || $params1 == 'chat' || $params1 == 'social_media' || $params1 == 'the_total_tour') && $user_data['role'] > 2) {
header('Location: '.base_url());
exit;
}
?>
<div class="header">
<div class="wrapper clearfix bigmegamenu">
<?php if (isset($user_data['id']) && $user_data['role'] == 1) {
?>
<nav class="slideLeft ">
<ul class="mobile-sub wsmenu-list wsmenu-list-left_logo">
<!--view login with account artists -->
<li>
<a href="<?php echo base_url(); ?>" title=""><img src="<?php echo base_url(); ?>assets/logos/logo-07.png" alt="" /></a>
<?php
if ($params1 == null) {
?>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li ><a href="<?php echo base_url("features/artist");?>"><i class="fa fa-arrow-circle-right"></i>Artist</a></li>
<li ><a href="<?php echo base_url("features/fan");?>"><i class="fa fa-arrow-circle-right"></i>Fan</a></li>
<li><a href="#worldwide"><i class="fa fa-arrow-circle-right"></i>Worldwide Featured Artist</a></li>
<li><a href="#local"><i class="fa fa-arrow-circle-right"></i>Local-Featured Artist</a></li>
<li><a href="<?php echo base_url("mds");?>"><i class="fa fa-arrow-circle-right"></i>Music Distribution System</a></li>
<li><a href="<?php echo base_url("features/artist#artist_landing");?>"><i class="fa fa-arrow-circle-right"></i>ALP</a></li>
<!--<li><a href="#epk"><i class="fa fa-arrow-circle-right"></i>Electronic Press Kit</a></li>-->
<li><a href="<?php echo base_url("features/artist#ttt");?>"><i class="fa fa-arrow-circle-right"></i>The Total Tour</a></li>
<li><a href="<?php echo base_url("make_money");?>"><i class="fa fa-arrow-circle-right"></i>Artist Music Player</a></li>
<li><a href="<?php echo base_url("features/artist#social_media");?>"><i class="fa fa-arrow-circle-right"></i>One Stop Social Media</a></li>
<li><a href="<?php echo base_url("features/artist#gigs_events");?>"><i class="fa fa-arrow-circle-right"></i>Gigs & Events</a></li>
<!--<li><a href="#dashboard"><i class="fa fa-arrow-circle-right"></i>Dashboard Chat</a></li>-->
<li><a href="<?php echo base_url("features/artist#music_referral");?>"><i class="fa fa-arrow-circle-right"></i>Musicians Referral</a></li>
</ul>
<?php
} ?>
</li>
</ul>
</nav>
<?php
} else {
?>
<div class="logo"><a href="<?php echo base_url(); ?>" title=""><img src="<?php echo base_url(); ?>assets/logos/logo-07.png" alt="" /></a></div>
<?php
}?>
<!--Main Menu HTML Code-->
<nav class="wsmenu slideLeft ">
<ul class="mobile-sub wsmenu-list wsmenu-list-left">
<?php if (isset($user_data)) {
$check_upgrade = $this->M_user->check_upgrade($user_data['id']);
if (isset($user_data['id']) && $user_data['role'] == 1 && $user_data['is_admin'] == 1) {
?>
<!--view login with account ADMIN -->
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'blogs' || $params1 == 'gigs_events' || $params1 == 'find-a-musician' || $params1 == 'find-a-fan' || $params1 == 'find-an-artist' || $params2 == 'find-a-fan' || $params2 == 'find-an-artist' || $params2 == 'world_wide_featured') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Artists & Fans<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'blogs') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('blogs') ?>"><i class="fa fa-arrow-circle-right"></i>Blogs</a></li>
<li><a <?php if ($params1 == 'gigs_events') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('gigs_events') ?>"><i class="fa fa-arrow-circle-right"></i>Book A Show</a></li>
<li><a <?php if ($params1 == 'find-a-musician') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('find-a-musician') ?>"><i class="fa fa-arrow-circle-right"></i>Musicians Referral</a></li>
<li><a <?php if ($params2 == 'find-a-fan') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/find-a-fan') ?>"><i class="fa fa-arrow-circle-right"></i>Find A Fan</a></li>
<li><a <?php if ($params2 == 'find-an-artist') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/find-an-artist') ?>"><i class="fa fa-arrow-circle-right"></i>Find AN Artist</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'new-treding' || $params1 == 'hot_video_picks' || $params1 == 'fancapture' || $params2 == 'hot_video_picks' || $params2 == 'new-trending') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Our Artist's Music <span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'fancapture') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('fancapture') ?>"><i class="fa fa-arrow-circle-right"></i>Meet Our Artist</a></li>
<!--<li><a <?php if ($params2 == 'new-trending') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/new-trending') ?>"><i class="fa fa-arrow-circle-right"></i>New & Trending</a></li>-->
<li><a <?php if ($params2 == 'world_wide_featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('world_wide_featured') ?>"><i class="fa fa-arrow-circle-right"></i>World Wide Featured Artist</a></li>
<li><a <?php if ($params2 == 'hot_video_picks') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/hot_video_picks') ?>"><i class="fa fa-arrow-circle-right"></i>Hot Video Picks</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'artists' || $params1 == 'make_money' || $params1 == 'top-100-list' || $params1 == 'fancapture') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Earn Money<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'artists') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('artists') ?>"><i class="fa fa-arrow-circle-right"></i>Create AMP-Video</a></li>
<li <?php if ($params1 == 'make_money') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url(); ?>make_money"><i class="fa fa-arrow-circle-right"></i>Artist Music Player</a></li>
<!--<li <?php if ($params1 == '#') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('#') ?>"><i class="fa fa-arrow-circle-right"></i>How to Earn Money</a></li>
<li <?php if ($params1 == '#') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url(); ?>#"><i class="fa fa-arrow-circle-right"></i>Signup - AMP</a></li>-->
<li <?php if ($params1 == 'fancapture') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('fancapture') ?>"><i class="fa fa-arrow-circle-right"></i>Fan Capture</a></li>
<li><a <?php if ($params1 == 'top-100-list') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('top-100-list') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span>
<a <?php if ($params1 == 'mds' || ($params1 == 'artist' && $params2 == 'amp') || ($params1 == 'artist' && $params2 == 'dashboard_epk') || $params1 == 'chat' || $params1 == 'social_media' || $params1 == 'the_total_tour') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-hand-pointer-o"></i> Tool<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li><a <?php if ($params1 == 'the_total_tour') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('the_total_tour') ?>"><i class="fa fa-arrow-circle-right"></i>The Total Tour</a></li>
<li><a <?php if ($params1 == 'mds') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('mds') ?>"><i class="fa fa-arrow-circle-right"></i>MDS</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'dashboard_epk') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/dashboard_epk')?>"><i class="fa fa-arrow-circle-right"> </i>EPK</a></li>
<li><a <?php if ($params1 == 'chat') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('chat/dashboard') ?>"><i class="fa fa-arrow-circle-right"> </i>Dashboard Chat</a></li>
<li><a <?php if ($params1 == 'social_media') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('social_media') ?>"><i class="fa fa-arrow-circle-right"></i>Social media</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if (($params1 == 'artist' && $params2 != 'amp') && $params2 != 'dashboard_epk' && $params2 != 'profile') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-heartbeat"></i> Dashboard<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li><a <?php if ($params1 == 'artist' && $params2 == 'managersong') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managersong') ?>"><i class="fa fa-arrow-circle-right"></i>Songs</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managervideo') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managervideo') ?>"><i class="fa fa-arrow-circle-right"></i>Videos</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managerphoto') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managerphoto') ?>"><i class="fa fa-arrow-circle-right"></i>Photos</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'manager-comment') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/manager-comment')?>"><i class="fa fa-arrow-circle-right"></i>Comments</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managerpress') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managerpress') ?>"><i class="fa fa-arrow-circle-right"></i>Press</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'blogsmanager') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/blogsmanager') ?>"><i class="fa fa-arrow-circle-right"></i>Blogs</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'basic_info') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/basic_info'); ?>"><i class="fa fa-arrow-circle-right"></i>Customize Profile</a></li>
</ul>
</li>
<li class="top120">
<span class="wsmenu-click"></span><a <?php if ($params2 == 'stop_typing' || $params1 == 'hot_video_picks') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-align-justify"></i> Social Media<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<!-- TODO: <li <?php if ($params2 == 'stop_typing') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('social_media/stop_typing') ?>"><i class="fa fa-arrow-circle-right"></i>1 stop typing</a></li> -->
<li <?php if ($params1 == 'hot_video_picks') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/hot_video_picks') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li class="top120">
<span class="wsmenu-click"></span><a <?php if ($params1 == 'new_artist') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Music Pages<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'new_artist') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('new_artist') ?>"><i class="fa fa-arrow-circle-right"></i>New Artist</a></li>
</ul>
</li>
<li class="top120">
<span class="wsmenu-click"></span><a <?php if ($params1 == 'features') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-align-justify"></i> Features<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params2 == 'fan') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/fan') ?>"><i class="fa fa-arrow-circle-right"></i>Fan Feature</a></li>
<li <?php if ($params2 == 'artist') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/artist') ?>"><i class="fa fa-arrow-circle-right"></i>Artist Feature</a></li>
<li <?php if ($params2 == 'fan_feature') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/fan_feature') ?>"><i class="fa fa-arrow-circle-right"></i>Fan Features</a>
</li>
</ul>
</li>
<li class="top120">
<span class="wsmenu-click"></span><a <?php if ($params1 == 'local-featured') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Meet Our Artists<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li><a <?php if ($params1 == 'local-featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('local-featured') ?>"><i class="fa fa-arrow-circle-right"></i>Local Featured Artist</a></li>
</ul>
</li>
<!--
<li class="top120">
<li <?php if ($params1 == 'gigs_events') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('gigs_events') ?>"><i class="fa fa-music"></i> SHOWs</a></li>
</li>-->
<li class="top120">
<li <?php if ($params1 == '#') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('#') ?>"><i class="fa fa-search"></i> Search</a>
</li>
<?php
} elseif (isset($user_data['id']) && $user_data['role'] == 1) {
?>
<!--view login with account artists -->
<li>
<span class="wsmenu-click"></span><a <?php if (($params1 == 'artist' && $params2 == 'showgigs') || $params1 == 'blogs' || $params1 == 'gigs_events' || $params1 == 'find-a-musician' || $params1 == 'find-a-fan' || $params1 == 'find-an-artist' || $params2 == 'find-a-fan' || $params2 == 'find-an-artist'|| $params2 == 'world_wide_featured') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Artists & Fans<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'blogs') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('blogs') ?>"><i class="fa fa-arrow-circle-right"></i>Blogs</a></li>
<li><a <?php if ($params1 == 'gigs_events') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('gigs_events') ?>"><i class="fa fa-arrow-circle-right"></i>Book A Show</a></li>
<li><a <?php if ($params1 == 'find-a-musician') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('find-a-musician') ?>"><i class="fa fa-arrow-circle-right"></i>Musicians Referral</a></li>
<li><a <?php if ($params2 == 'find-a-fan') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/find-a-fan') ?>"><i class="fa fa-arrow-circle-right"></i>Find A Fan</a></li>
<li><a <?php if ($params2 == 'find-an-artist') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/find-an-artist') ?>"><i class="fa fa-arrow-circle-right"></i>Find AN Artist</a></li>
<!--<li><a <?php if ($params2 == 'showgigs') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/my_location') ?>"><i class="fa fa-arrow-circle-right"></i>Find AN Location</a></li>-->
<li><a <?php if ($params2 == 'showgigs') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/showgigs') ?>"><i class="fa fa-arrow-circle-right"></i>Gig Finder</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'new-treding' || $params1 == 'hot_video_picks' || $params1 == 'fancapture' || $params2 == 'hot_video_picks' || $params2 == 'new-trending') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Our Artist's Music <span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'fancapture') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('fancapture') ?>"><i class="fa fa-arrow-circle-right"></i>Meet Our Artist</a></li>
<!--<li><a <?php if ($params2 == 'new-trending') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/new-trending') ?>"><i class="fa fa-arrow-circle-right"></i>New & Trending</a></li>-->
<li><a <?php if ($params2 == 'world_wide_featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('world_wide_featured') ?>"><i class="fa fa-arrow-circle-right"></i>World Wide Featured Artist</a></li>
<li><a <?php if ($params2 == 'hot_video_picks') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/hot_video_picks') ?>"><i class="fa fa-arrow-circle-right"></i>Hot Video Picks</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'artists' || $params1 == 'make_money' || $params1 == 'top-100-list') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Earn Money<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'make_money') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('make_money') ?>"><i class="fa fa-arrow-circle-right"></i>How to Earn Money</a></li>
<!--<li <?php if ($params1 == '#') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('#'); ?>"><i class="fa fa-arrow-circle-right"></i>Signup - AMP</a></li>-->
<li <?php if ($params1 == 'fancapture') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('fancapture') ?>"><i class="fa fa-arrow-circle-right"></i>FCP</a></li>
<li><a <?php if ($params1 == 'top-100-list') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('top-100-list') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span>
<a <?php if ($params1 == 'mds' || ($params1 == 'artist' && $params2 == 'amp') || ($params1 == 'artist' && $params2 == 'dashboard_epk') || $params1 == 'chat' || $params1 == 'social_media' || $params1 == 'the_total_tour') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-hand-pointer-o"></i> Tool<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li><a <?php if ($params1 == 'the_total_tour') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('the_total_tour') ?>"><i class="fa fa-arrow-circle-right"></i>The Total Tour</a></li>
<li><a <?php if ($params1 == 'mds') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('mds') ?>"><i class="fa fa-arrow-circle-right"></i>MDS</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'dashboard_epk') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/dashboard_epk')?>"><i class="fa fa-arrow-circle-right"> </i>EPK</a></li>
<li><a <?php if ($params1 == 'chat') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('chat/dashboard') ?>"><i class="fa fa-arrow-circle-right"> </i>Dashboard Chat</a></li>
<li><a <?php if ($params1 == 'social_media') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('social_media') ?>"><i class="fa fa-arrow-circle-right"></i>Social media</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if (($params1 == 'artist' && $params2 != 'amp' && $params2 != 'showgigs' && $params2 != 'dashboard_epk') && $params2 != 'managerrpk' && $params2 != 'profile') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-heartbeat"></i> Dashboard<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li><a <?php if ($params1 == 'artist' && $params2 == 'managersong') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managersong') ?>"><i class="fa fa-arrow-circle-right"></i>Songs</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managervideo') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managervideo') ?>"><i class="fa fa-arrow-circle-right"></i>Videos</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managerphoto') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managerphoto') ?>"><i class="fa fa-arrow-circle-right"></i>Photos</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'manager-comment') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/manager-comment')?>"><i class="fa fa-arrow-circle-right"></i>Comments</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'managerpress') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/managerpress') ?>"><i class="fa fa-arrow-circle-right"></i>Press</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'blogsmanager') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/blogsmanager') ?>"><i class="fa fa-arrow-circle-right"></i>Blogs</a></li>
<li><a <?php if ($params1 == 'artist' && $params2 == 'basic_info') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/basic_info'); ?>"><i class="fa fa-arrow-circle-right"></i>Customize Profile</a></li>
</ul>
</li>
<?php
} elseif (isset($user_data['id']) && $user_data['role'] == 2) {
?>
<!--view login with account fans -->
<li>
<span class="wsmenu-click"></span><a <?php if ($params2 == 'fan_feature') {
echo 'class="active"';
} ?> href="<?php echo base_url('features/fan_feature') ?>">Fan Features</a>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params2 == 'stop_typing' || $params1 == 'top-100-list') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-align-justify"></i> Social Media<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<!-- TODO: <li <?php if ($params2 == 'stop_typing') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('social_media/stop_typing') ?>"><i class="fa fa-arrow-circle-right"></i>1 stop typing</a></li> -->
<li <?php if ($params1 == 'top-100-list') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('top-100-list') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'findamusician' || $params1 == 'artists' || $params1 == 'make_money' || $params1 == 'top-100-list') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Earn Money<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'artists') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('artists') ?>"><i class="fa fa-arrow-circle-right"></i>Create AMP-Video</a></li>
<li <?php if ($params1 == 'make_money') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url(); ?>make_money"><i class="fa fa-arrow-circle-right"></i>Artist Music Player</a></li>
<li <?php if ($params1 == 'top-100-list') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('top-100-list') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'fancapture' || $params2 == 'hot_video_picks' || $params1 == 'new-treding') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Music Pages<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'fancapture') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('fancapture') ?>"><i class="fa fa-arrow-circle-right"></i>Meet Our Artist</a></li>
<li><a <?php if ($params2 == 'hot_video_picks') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('features/hot_video_picks') ?>"><i class="fa fa-arrow-circle-right"></i>Hot Video Picks</a></li>
<li <?php if ($params1 == 'features/new-trending') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/new-trending') ?>"><i class="fa fa-arrow-circle-right"></i>Trending Artist</a></li>
<li><a <?php if ($params2 == 'world_wide_featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('world_wide_featured') ?>"><i class="fa fa-arrow-circle-right"></i>World Wide Featured Artist</a></li>
<li <?php if ($params1 == 'new_artist') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('new_artist') ?>"><i class="fa fa-arrow-circle-right"></i>New Artist</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'amp' && $params2 == $user_data['home_page']) {
echo 'class="active"';
} ?> href="<?php echo base_url('amp/'.$user_data['home_page']) ?>"><i class="fa fa-music"></i> Fan Landing</a>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'find-a-show') {
echo 'class="active"';
} ?> href="<?php echo base_url('find-a-show') ?>"><i class="fa fa-music"></i> Find A Show</a>
</li>
<?php
}//end account Fan
?>
<?php
} else {
?>
<!-- before login -->
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'features' && ($params2 != 'hot_video_picks')) {
echo 'class="active"';
} ?> href="#"><i class="fa fa-align-justify"></i> Features<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params2 == 'fan') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/fan') ?>"><i class="fa fa-arrow-circle-right"></i>Fan Feature</a></li>
<li <?php if ($params2 == 'artist') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/artist') ?>"><i class="fa fa-arrow-circle-right"></i>Artist Feature</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'local-featured' || $params2 == 'hot_video_picks') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Meet Our Artists<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params2 == 'hot_video_picks') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('features/hot_video_picks') ?>"><i class="fa fa-arrow-circle-right"></i>Hot Video Picks</a></li>
<li><a <?php if ($params1 == 'local-featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('local-featured') ?>"><i class="fa fa-arrow-circle-right"></i>Local Featured Artist</a></li>
<li><a <?php if ($params2 == 'world_wide_featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('world_wide_featured') ?>"><i class="fa fa-arrow-circle-right"></i>World Wide Featured Artist</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'findamusician' || $params1 == 'artists' || $params1 == 'make_money' || $params1 == 'top-100-list') {
echo 'class="active"';
} ?> href="#"><i class="fa fa-music"></i> Earn Money<span class="arrow"></span></a>
<ul class="wsmenu-submenu" style="min-width: 160px;">
<li <?php if ($params1 == 'artists') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('artists') ?>"><i class="fa fa-arrow-circle-right"></i>Create AMP-Video</a></li>
<li <?php if ($params1 == 'make_money') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url(); ?>make_money"><i class="fa fa-arrow-circle-right"></i>Artist Music Player</a></li>
<li <?php if ($params1 == 'top-100-list') {
echo 'class="activesub"';
} ?>><a href="<?php echo base_url('top-100-list') ?>"><i class="fa fa-arrow-circle-right"></i>Top 100 Fans - Amp Sales</a></li>
</ul>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == 'gigs_events') {
echo 'class="active"';
} ?> href="<?php echo base_url('gigs_events') ?>"><i class="fa fa-music"></i> SHOWs</a>
</li>
<li>
<span class="wsmenu-click"></span><a <?php if ($params1 == '#') {
echo 'class="active"';
} ?> href="<?php echo base_url('#') ?>"><i class="fa fa-music"></i> Search</a>
</li>
<?php
}?>
</ul>
<ul class="mobile-sub wsmenu-list wsmenu-list-right">
<?php
if (isset($user_data)) {
?>
<li>
<span class="wsmenu-click"></span><a <?php if (($params1 == 'account' && $params2 == 'credit') || ($params1 == 'subscriptions' && $params2 == 'upgrade') || ($params1 == 'artist' && $params2 == 'profile')) {
echo 'class="active"';
}
if($user_data['role'] == 1)
{
$image_url = $this->M_user->get_avata($user_data['id']);
}
else{
$image_url = $this->M_user->get_avata_flp($user_data['id']);
}
?> href="#"><img src="<?php echo $image_url?>" width="30"/> <span><?php echo $this->M_user->get_name($user_data['id'])?></span><span class="arrow"></span></a>
<ul class="wsmenu-submenu responsive_menu" style="min-width: 160px;">
<?php
if ($user_data['role'] == 1) {
if ($user_data['is_admin'] != 0) {
?>
<li><a href="<?php echo base_url('admin/dashboard') ?>"><i class="fa fa-tachometer"></i>Admin Dashboard</a></li>
<?php
} ?>
<li><a <?php if ($params1 == 'artist' && $params2 == 'profile') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('artist/profile') ?>"><i class="fa fa-tachometer"></i> Create Profile</a></li>
<li><a <?php if ($params1 == 'amper' && $params2 == 'dashboard') {
echo 'class="activesub"';
} ?>href="<?php echo base_url('amper/dashboard') ?>"><i class="fa fa-arrow-circle-right"></i>Music-Player Dashboard</a></li>
<?php
if ($check_upgrade) {
?><li><a <?php if ($params1 == 'subscriptions' && $params2 == 'subscriptions_plan') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('subscriptions/subscriptions_plan') ?>"><i class="fa fa-tachometer"></i> Subscriptions & Billing</a></li>
<?php
} ?>
<!--<li><a <?php if ($params1 == 'subscriptions' && $params2 == 'upgrade') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('subscriptions/upgrade') ?>"><i class="fa fa-tachometer"></i> Upgrade Subscriptions </a></li>
<li><a <?php if ($params1 == 'subscriptions' && $params2 == 'featured') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('subscriptions/featured') ?>"><i class="fa fa-tachometer"></i> Upgrade Subscription – Homepage Placement – Get Fans, Get Noticed! </a></li>-->
<li><a href="<?php echo base_url('account/logout') ?>"><i class="fa fa-sign-out"></i>Logout</a></li>
<?php
} elseif ($user_data['role'] == 2) {
?>
<li><a <?php if ($params1 == 'amper' && $params2 == 'dashboard') {
echo 'class="activesub"';
} ?>href="<?php echo base_url('amper/dashboard') ?>"><i class="fa fa-arrow-circle-right"></i>AMPER Dashboard</a></li>
<?php
if ($check_upgrade) {
?><li><a <?php if ($params1 == 'subscriptions' && $params2 == 'subscriptions_plan') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('subscriptions/subscriptions_plan') ?>"><i class="fa fa-tachometer"></i> Subscriptions/Billing </a></li>
<?php
} else {
?><li><a <?php if ($params1 == 'subscriptions' && $params2 == 'upgrade') {
echo 'class="activesub"';
} ?> href="<?php echo base_url('subscriptions/upgrade') ?>"><i class="fa fa-tachometer"></i> Upgrade Subscriptions </a></li>
<?php
} ?>
<li><a href="<?php echo base_url('chat/dashboard') ?>"><i class="fa fa-arrow-circle-right"></i>Dashboard Chat</a></li>
<li><a href="<?php echo base_url('account/logout') ?>"><i class="fa fa-sign-out"></i> Logout</a></li>
<?php
} else {
?>
<li><a href="<?php echo base_url('account/logout') ?>"><i class="fa fa-sign-out"></i> Logout</a></li>
<?php
} ?>
</ul>
</li>
<?php
} else {
?>
<li><a <?php if ($params1 == 'account' && $params2 == 'signup') {
echo 'class="active"';
} ?> href="<?php echo base_url('account/signup') ?>"><i class="fa fa-user-plus"></i> Join</a></li>
<li><a <?php if ($params1 == 'account' && $params2 == 'login') {
echo 'class="active"';
} ?> href="<?php echo base_url('account/login') ?>"><i class="fa fa-sign-in"></i> Login</a></li>
<?php
}
?>
<?php if (!empty($user_data['id'])) {
$notyfi_ = $this->M_notify->getnotify($user_data['id'], 1); ?>
<li class=" dropdown notifications noti2 ">
<a href="" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-globe" style="font-size:2em;display: block!important"></i>
<?php if (count($notyfi_) != 0) {
?><span class="badge bg-lightred"><?php echo count($notyfi_)?></span><?php
} ?>
</a>
<div class="dropdown-menu pull-right with-arrow panel panel-default animated littleFadeInLeft">
<div class="panel-heading">
You have <strong><?php echo count($notyfi_)?></strong> notifications unread
</div>
<ul class="list-group">
<?php
$notify = $this->M_notify->getnotify($user_data['id']);
foreach ($notify as $row) {
if ($row['type'] == 'invite') {
$link = base_url().'chat/dashboard';
} elseif ($row['type'] == 'amper_register') {
$link = base_url().'amper/dashboard_affiliates';
} elseif ($row['type'] == 'amper_register') {
$link = base_url().'amper/dashboard_affiliates';
} elseif ($row['type'] == 'Invite tour') {
$link = $row['active_url'];
} else {
$link = '#';
} ?>
<li class="list-group-item">
<a role="button" tabindex="0" class="media" href="<?=$link?>">
<div class="media-body">
<span class="block"><?php echo $row['messages']?></span>
<small class="text-muted"><?php echo $this->M_user->time_calculation($row['time'])?></small>
</div>
</a>
</li>
<?php
} ?>
</ul>
<div class="panel-footer">
<a href="<?=base_url('notifications/all')?>" role="button" tabindex="0">Show all notifications <i class="fa fa-angle-right pull-right"></i></a>
</div>
</div>
</li>
<?php
}?>
</ul>
</nav>
<!--Menu HTML Code-->
</div>
</div>
<div class="padingheader-top"></div>
| mit |
eddietributecoin/EddieCoin | src/miner.cpp | 19965 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 The NovaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "miner.h"
#include "kernel.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
extern unsigned int nMinerSleep;
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
int64_t nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake, int64_t* pFees)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
CBlockIndex* pindexPrev = pindexBest;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
if (!fProofOfStake)
{
CReserveKey reservekey(pwallet);
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
txNew.vout[0].scriptPubKey.SetDestination(pubkey.GetID());
}
else
{
// Height first in coinbase required for block.version=2
txNew.vin[0].scriptSig = (CScript() << pindexPrev->nHeight+1) + COINBASE_FLAGS;
assert(txNew.vin[0].scriptSig.size() <= 100);
txNew.vout[0].SetEmpty();
}
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64_t nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
// Collect memory pool transactions into the block
int64_t nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !IsFinalTx(tx, pindexPrev->nHeight + 1))
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64_t nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
continue;
// Transaction fee
int64_t nMinFee = tx.GetMinFee(nBlockSize, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
if (!fProofOfStake)
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nFees);
if (pFees)
*pFees = nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
if (!fProofOfStake)
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hashBlock = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if(!pblock->IsProofOfWork())
return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
if (hashBlock > hashTarget)
return error("CheckWork() : proof-of-work not meeting target");
//// debug print
printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckWork() : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckWork() : ProcessBlock, block not accepted");
}
return true;
}
bool CheckStake(CBlock* pblock, CWallet& wallet)
{
uint256 proofHash = 0, hashTarget = 0;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
// verify hash target and signature of coinstake tx
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
return error("CheckStake() : proof-of-stake checking failed");
//// debug print
printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckStake() : generated block is stale");
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckStake() : ProcessBlock, block not accepted");
}
return true;
}
void StakeMiner(CWallet *pwallet)
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("EddieCoin-miner");
bool fTryToSync = true;
while (true)
{
if (fShutdown)
return;
while (pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
MilliSleep(1000);
if (fShutdown)
return;
}
while (vNodes.empty() || IsInitialBlockDownload())
{
nLastCoinStakeSearchInterval = 0;
fTryToSync = true;
MilliSleep(1000);
if (fShutdown)
return;
}
if (fTryToSync)
{
fTryToSync = false;
if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
{
MilliSleep(60000);
continue;
}
}
//
// Create new block
//
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true, &nFees));
if (!pblock.get())
return;
// Trying to sign a block
if (pblock->SignBlock(*pwallet, nFees))
{
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckStake(pblock.get(), *pwallet);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
MilliSleep(500);
}
else
MilliSleep(nMinerSleep);
}
}
| mit |
LykkeCity/MT | src/MarginTrading.Backend.Services/Notifications/IRabbitMqNotifyService.cs | 1359 | using System.Threading.Tasks;
using Lykke.Service.ExchangeConnector.Client.Models;
using MarginTrading.Backend.Core;
using MarginTrading.Contract.RabbitMqMessageModels;
namespace MarginTrading.Backend.Services.Notifications
{
public interface IRabbitMqNotifyService
{
Task AccountHistory(string transactionId, string accountId, string clientId, decimal amount, decimal balance,
decimal withdrawTransferLimit, AccountHistoryType type, decimal amountInUsd = default, string comment = null,
string eventSourceId = null, string legalEntity = null, string auditLog = null);
Task OrderHistory(IOrder order, OrderUpdateType orderUpdateType);
Task OrderReject(IOrder order);
Task OrderBookPrice(InstrumentBidAskPair quote);
Task OrderChanged(IOrder order);
Task AccountUpdated(IMarginTradingAccount account);
Task AccountStopout(string clientId, string accountId, int positionsCount, decimal totalPnl);
Task UserUpdates(bool updateAccountAssets, bool updateAccounts, string[] clientIds);
void Stop();
Task AccountCreated(IMarginTradingAccount account);
Task AccountDeleted(IMarginTradingAccount account);
Task AccountMarginEvent(AccountMarginEventMessage eventMessage);
Task UpdateAccountStats(AccountStatsUpdateMessage message);
Task NewTrade(TradeContract trade);
Task ExternalOrder(ExecutionReport trade);
}
} | mit |
instructure/lti_tool_provider_example | app/controllers/guide_controller.rb | 2081 | require 'ims/lti'
class GuideController < ApplicationController
def home
end
def xml_builder
@placements = CanvasExtensions::PLACEMENTS
end
def xml_config
tc = IMS::LTI::Services::ToolConfig.new(:title => "Example Tool Provider", :launch_url => blti_launch_url)
tc.description = "This is a Sample Tool Provider."
if query_params = request.query_parameters
platform = CanvasExtensions::PLATFORM
tc.set_ext_param(platform, :selection_width, query_params[:selection_width])
tc.set_ext_param(platform, :selection_height, query_params[:selection_height])
tc.set_ext_param(platform, :privacy_level, 'public')
tc.set_ext_param(platform, :text, 'Extension text')
tc.set_ext_param(platform, :icon_url, view_context.asset_url('selector.png'))
tc.set_ext_param(platform, :domain, request.host_with_port)
query_params[:custom_params].each { |_, v| tc.set_custom_param(v[:name].to_sym, v[:value]) } if query_params[:custom_params]
query_params[:placements].each { |k, _| create_placement(tc, k.to_sym) } if query_params[:placements]
end
render xml: tc.to_xml(:indent => 2)
end
private
def create_placement(tc, placement_key)
message_type = request.query_parameters["#{placement_key}_message_type"] || :basic_lti_request
navigation_params = case message_type
when 'content_item_selection'
{url: content_item_launch_url, message_type: 'ContentItemSelection'}
when 'content_item_selection_request'
{url: content_item_request_launch_url, message_type: 'ContentItemSelectionRequest'}
else
{url: blti_launch_url}
end
navigation_params[:icon_url] = view_context.asset_url('selector.png') + "?#{placement_key}"
navigation_params[:canvas_icon_class] = "icon-lti"
navigation_params[:text] = "#{placement_key} Text"
tc.set_ext_param(CanvasExtensions::PLATFORM, placement_key, navigation_params)
end
end
| mit |
ruby/rubyspec | library/digest/sha512/file_spec.rb | 1321 | require_relative '../../../spec_helper'
require_relative 'shared/constants'
require_relative '../../../core/file/shared/read'
describe "Digest::SHA512.file" do
describe "when passed a path to a file that exists" do
before :each do
@file = tmp("md5_temp")
touch(@file, 'wb') {|f| f.write SHA512Constants::Contents }
end
after :each do
rm_r @file
end
it "returns a Digest::SHA512 object" do
Digest::SHA512.file(@file).should be_kind_of(Digest::SHA512)
end
it "returns a Digest::SHA512 object with the correct digest" do
Digest::SHA512.file(@file).digest.should == SHA512Constants::Digest
end
it "calls #to_str on an object and returns the Digest::SHA512 with the result" do
obj = mock("to_str")
obj.should_receive(:to_str).and_return(@file)
result = Digest::SHA512.file(obj)
result.should be_kind_of(Digest::SHA512)
result.digest.should == SHA512Constants::Digest
end
end
it_behaves_like :file_read_directory, :file, Digest::SHA512
it "raises a Errno::ENOENT when passed a path that does not exist" do
lambda { Digest::SHA512.file("") }.should raise_error(Errno::ENOENT)
end
it "raises a TypeError when passed nil" do
lambda { Digest::SHA512.file(nil) }.should raise_error(TypeError)
end
end
| mit |
charliethinker/charliethinker.github.io | _posts/2016-12-07-fundamentals-7-logging.markdown | 6820 | ---
layout: post
title: "ASP.NET Core基本原理(7)-日志"
subtitle: "ASP.NET Core Fundamentals-Logging"
tags: [netcore, fundamentals, logging]
---
ASP.NET Core内置了对日志的支持。通过依赖注入请求`ILoggerFactory`或者`ILogger<T>`可以为应用程序添加日志功能。
## 在应用程序中实现日志
如果请求了`ILoggerFactory`,那么日志记录器(Logger)就必须通过它的`CreateLogger`方法来创建:
```csharp
var logger = loggerFactory.CreateLogger("Catch all Endpoint");
logger.LogInformation("No endpoint found for request {path}", context.Request.Path);
```
当一个Logger被创建时,必须提供一个类别名称。类别名称指定了日志事件的根源。

你可以会发现每次你通过浏览器发起网络请求都会产生多条记录,因为浏览器在尝试加载一个页面的时候会发起多个请求。在控制台记录器显示的日志级别(`info`,`fail`等),类别(`[Catch all Endpoint]`),最后是日志消息。
在真实的应用中,你会希望基于应用程序级别添加日志,而不是基于框架级别或者事件。例如,之前创建的应用[创建ASP.NET Core Web API](http://zhuchenglin.me/my-first-web-api-on-mac)。我们来要为其中的各种操作添加日志记录。
API的逻辑被包含在`UserController`中,在它的构造函数通过依赖注入的方式来请求它所需要的服务。理想情况下,类应当像这个例子一样使用它们的构造函数来[显式地定义它们的依赖项](http://deviq.com/explicit-dependencies-principle/)并作为参数传入,而不是请求一个*ILoggerFactory*并显式创建`ILogger`实例。
在`UserController`中演示了另一种在应用中使用Logger的方式 - 通过请求*ILogger\<T>*(其中*T*是请求Logger的类)。
```csharp
[Route("api/[controller]")]
public class UserController : Controller
{
//public IUserRepository UserItems { get; set; }
private readonly IUserRepository _userRepository;
private readonly ILogger<UserController> _logger;
public UserController(IUserRepository userRepository,ILogger<UserController> logger)
{
_userRepository = userRepository;
_logger = logger;
}
[HttpGet]
public IEnumerable<UserItem> GetAll()
{
_logger.LogInformation("LoggingEvents.LIST_ITEMS","Listing all items");
return _userRepository.GetAll();
}
}
```
在每个控制器动作方法内,通过本地字段*_logger*来记录日志。这种技术并仅限于控制器内,通过依赖注入它能应用于应用程序内的所有服务中。
## 使用ILogger
如您所见,应用程序可以在类的构造函数中通过请求到`ILogger<T>`的实例,其中`T`是执行日志记录的类型。`UserController`就演示了这个方法。当使用这种技术时,Logger会自动使用该类型的名称作为其类别的名称。通过请求`ILogger<T>`的实例,类自己不需要通过`ILoggerFactory`来创建一个Logger实例。这种方法可以用在任何不需要用到`ILoggerFactory`所提供的额外功能的任何地方。
## 日志级别
当添加一个日志语句到的应用程序时,你必须指定一个`LogLevel`。日志级别(LogLevel)可以控制应用程序的日志记录输出的详细程序,以及管理不同类型的日志消息到不同的日志记录器的能力。你可能希望记录调试信息到一个本地文件,且把错误消息记录到计算机的事件日志或者数据库中。
ASP.NET Core定义了日志的6种级别,按重要性和严重程序排序如下:
* Trace
用于定义最详细的日志消息,通常只对开发人员调试一个问题有价值。这些信息可能包含敏感的应用程序数据,因此不应该用于生产环境。*默认为禁用*。比如:`Credentials: {"User":"someuser", "Password":"P@ssword"}`
* Debug
这种信息在开发阶段的短期内比较有用。它包含了一些可能对调试来说有用的信息,但没有长期的价值。默认情况下这是最详细的日志。比如:`Entering method Configure with flag set to true`
* Information
这种信息用于跟踪应用程序的一般流程。与`Debug`级别的信息相反,这些日志应该有一定的长期价值,比如:`Request received for path /foo`。
* Warning
这种信息用于程序流中的异常和意外事件。可能包含错误或者其它不会导致程序停止但可能要在日后调查的流程。比如:`Login failed for IP 127.0.0.1`或者`FileNotFoundException for file foo.txt`
* Error
当应用程序流程由于某些没有被处理到的异常等停止则需要记录错误日志。这些信息应当指定当前活动或者操作(比如当前的HTTP请求),而不是应用程序范围的故障。比如:`Cannot insert record due to duplicate key violation`
* Critical
这种信息用于不可恢复的应用程序错误或系统错误,或者需要立即被关注的灾难性错误。比如:数据丢失、磁盘空间不够等。
`Logging`包为每一个`LogLevel`值提供了Helper扩展方法,允许你去调用。例如,`LogInformation`,而不是更详细的`Log(LogLevel.Information, ...)`。每个`LogLevel`- 扩展方法有多个重载,允许你传递下面的一些或者所有的参数:
* string data
记录信息
* EventId eventId
使用数字类型的id来标记日志,这样可将一系列的日志事件彼此相互关联。事件ID应该是静态的,并且特定于正在记录的特定类型的事件。例如,你可能把添加商品到购物车的事件ID标记为1000,然后把完成一次购买的事件ID标记为1001。这样允许你智能过滤并处理日志记录。`EventId`类型可以隐式转换成`int`,所以,你可以传递一个`int`参数。
* string format
日志信息的格式字符串
* object[] args
用于格式化的一组对象。
* Exception error
用于记录的异常实例。
## 在应用程序中配置日志
为了在ASP.NET Core应用程序中配置日志,你必须在`Startup`类的`Configure`方法中解析`ILoggerFactory`。ASP.NET Core会使用依赖注入自动提供一个`ILoggerFactory`实例。
```csharp
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
```
一旦你添加一个`ILoggerFactory`作为参数,你就可以在`Configure`方法中通过在Logger Factory上调用方法来配置了一个日志记录器(Logger)。比如调用`loggerFactory.AddConsole`添加控制台日志记录。
## 原文链接
[Logging](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging)
## 个人博客
[我的个人博客](http://zhuchenglin.me/)
| mit |
croquet-australia/api.croquet-australia.com.au | source/CroquetAustralia.Domain/Services/Queues/QueueBase.cs | 1778 | using System;
using System.Threading.Tasks;
using Anotar.NLog;
using CroquetAustralia.Domain.Services.Serializers;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace CroquetAustralia.Domain.Services.Queues
{
public abstract class QueueBase : IQueueBase
{
private readonly Lazy<CloudQueue> _lazyQueue;
private readonly string _queueName;
private readonly QueueMessageSerializer _serializer;
protected QueueBase(string queueName, IAzureStorageConnectionString connectionString)
: this(queueName, connectionString, new QueueMessageSerializer())
{
}
protected QueueBase(string queueName, IAzureStorageConnectionString connectionString, QueueMessageSerializer serializer)
{
_queueName = queueName;
_serializer = serializer;
_lazyQueue = new Lazy<CloudQueue>(() => GetQueue(queueName, connectionString.Value));
}
private CloudQueue CloudQueue => _lazyQueue.Value;
public async Task AddMessageAsync(object @event)
{
LogTo.Info($"Adding '{@event.GetType().FullName}' to '{_queueName}' queue.");
var content = _serializer.Serialize(@event);
var message = new CloudQueueMessage(content);
await CloudQueue.AddMessageAsync(message);
}
private static CloudQueue GetQueue(string queueName, string connectionString)
{
var storageAccount = CloudStorageAccount.Parse(connectionString);
var queueClient = storageAccount.CreateCloudQueueClient();
var queue = queueClient.GetQueueReference(queueName);
queue.CreateIfNotExists();
return queue;
}
}
} | mit |
dpawlows/MGITM | src/ModMars.f90 | 45867 |
module ModPlanet
use ModConstants
use ModSizeGITM
implicit none
! Modified (01/18/07) : SWB : Aij, s-exponents for mutual diffusion
! Modified (06/12/08) : SWB : ordering to species revised
! Modified (06/12/08) : SWB : nSpecies = 6; nSpeciesTotal = 11
! Majors (6): COntrol the Pressures Gradients and winds
integer, parameter :: nSpecies = 6
integer, parameter :: iCO2_ = 1
integer, parameter :: iCO_ = 2
integer, parameter :: iO_ = 3
integer, parameter :: iN2_ = 4
integer, parameter :: iO2_ = 5
integer, parameter :: iAr_ = 6
! Minors (6) : Ride on background of mean winds derived from majors
integer, parameter :: iN4S_ = 7
integer, parameter :: iHe_ = 8
integer, parameter :: iH_ = 9
integer, parameter :: iN2D_ = 10
integer, parameter :: iNO_ = 11
integer, parameter :: nSpeciesTotal = iNO_
! Major Ions (5): Most Important to MWACM code
! Modified (05/21/08) : SWB : Add N2+ to major ions list
integer, parameter :: iOP_ = 1
integer, parameter :: iO2P_ = 2
integer, parameter :: iCO2P_ = 3
integer, parameter :: iN2P_ = 4
integer, parameter :: iNOP_ = 5
integer, parameter :: ie_ = 6
integer, parameter :: nIons = ie_
integer, parameter :: nIonsAdvect = 0
integer, parameter :: nSpeciesAll = 16 !Ions plus neutrals
character (len=20) :: cSpecies(nSpeciesTotal)
character (len=20) :: cIons(nIons)
real :: Mass(nSpeciesTotal), MassI(nIons)
real :: Vibration(nSpeciesTotal)
integer, parameter :: nEmissionWavelengths = 1
integer, parameter :: nPhotoBins = 1
! CP : HEAT CAPACITY (OR SPECIFIC HEAT) OF CO2 GAS.
real, parameter :: HeatCapacityCO2 = 735.94 ! J/(Kg*K)
! When you want to program in emissions, you can use this...
integer, parameter :: nEmissions = 10
real, parameter :: GC_Mars = 3.73 ! m/s^2
real, parameter :: RP_Mars = 88775.0 ! seconds
real, parameter :: R_Mars = 3388.25*1000.0 ! meters
real, parameter :: DP_Mars = 0.0
real, parameter :: Gravitational_Constant = GC_Mars
real, parameter :: Rotation_Period = RP_Mars
real, parameter :: RBody = R_Mars
real, parameter :: DipoleStrength = DP_Mars
real, parameter :: OMEGABody = 2.00*pi/Rotation_Period ! rad/s
real, parameter :: HoursPerDay = Rotation_Period / 3600.0
real, parameter :: Tilt = 25.19
! This is the Vernal Equinox at Midnight (Ls = 0!!!)
! Revised by D. Pawlwoski: 18-FEB-2013
! Earth-Mars clocks are set from this epoch at vernal equinox
integer, parameter :: iVernalYear = 1998
integer, parameter :: iVernalMonth = 7
integer, parameter :: iVernalDay = 14
integer, parameter :: iVernalHour = 13
integer, parameter :: iVernalMinute = 40
integer, parameter :: iVernalSecond = 0
! real, parameter :: SunOrbit_A = 1.52
! real, parameter :: SunOrbit_B = 0.04
! real, parameter :: SunOrbit_C = 0.15
! real, parameter :: SunOrbit_D = 0.00
! real, parameter :: SunOrbit_E = 0.00
real, parameter :: SunOrbit_A = 1.52369
real, parameter :: SunOrbit_B = 0.093379
real, parameter :: SunOrbit_C = 335.538
real, parameter :: SunOrbit_D = 355.45332
real, parameter :: SunOrbit_E = 68905103.78
real, parameter :: DaysPerYear = 670.0
real, parameter :: SecondsPerYear = DaysPerYear * Rotation_Period
!Used as a damping term in Vertical solver.
real, dimension(nAlts) :: VertTau = 1.0e9
logical :: IsEarth = .false.
logical :: IsMars = .true.
logical :: IsTitan = .false.
logical :: NonMagnetic = .true.
real, parameter :: PlanetNum = 0.04
character (len=10) :: cPlanet = "Mars"
logical :: UseWValue = .false.
real :: WValue = 28 !eV
integer, parameter :: i3371_ = 1
integer, parameter :: i4278_ = 2
integer, parameter :: i5200_ = 3
integer, parameter :: i5577_ = 4
integer, parameter :: i6300_ = 5
integer, parameter :: i7320_ = 6
integer, parameter :: i10400_ = 7
integer, parameter :: i3466_ = 8
integer, parameter :: i7774_ = 9
integer, parameter :: i8446_ = 10
integer, parameter :: i3726_ = 11
! real :: KappaTemp0 = 2.22e-4
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! These are Modified for Mars by SWB: 1/18/07
! -- Most source state Dij = Dji (check)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
real, parameter, dimension(6, 6) :: Diff0 = 1.0e17 * reshape( (/ &
! These are Aij coefficients from B&K (1973) formulation: Aij*1.0E+17
! Use Jared Bell's Titan GITM formulation for Mars GITM
! integer, parameter :: iCO2_ = 1
! integer, parameter :: iCO_ = 2
! integer, parameter :: iO_ = 3
! integer, parameter :: iN2_ = 4
! integer, parameter :: iO2_ = 5
! integer, parameter :: iAr_ = 6
!------------------------------------------------+
! i=C02 CO O N2 O2 Ar
!------------------------------------------------+
0.0000, 0.7762, 0.2219, 0.6580, 0.5770, 1.1920, & ! CO2
0.7762, 0.0000, 0.9466, 0.9280, 0.8300, 0.6625, & ! CO
0.2219, 0.9466, 0.0000, 0.9690, 0.9690, 0.5510, & ! O
0.6580, 0.9280, 0.9690, 0.0000, 0.7150, 0.6640, & ! N2
0.5770, 0.8300, 0.9690, 0.7150, 0.0000, 0.7170, & ! O2
1.1920, 0.6625, 0.5510, 0.6640, 0.7170, 0.000 /), (/6,6/) )! Ar
! These are s-exponents from B&K (1973) formulation: T**s
real, parameter, dimension(6, 6) :: DiffExp = reshape( (/ &
!------------------------------------------------+
! i=C02 CO O N2 O2 Ar
!------------------------------------------------+
0.000, 0.750, 0.750, 0.752, 0.749, 0.750, & ! CO2
0.750, 0.000, 0.750, 0.710, 0.724, 0.750, & ! CO
0.750, 0.750, 0.000, 0.774, 0.774, 0.841, & ! O
0.752, 0.710, 0.774, 0.000, 0.750, 0.752, & ! N2
0.749, 0.724, 0.774, 0.750, 0.000, 0.736, & ! O2
0.750, 0.750, 0.841, 0.752, 0.736, 0.000 /), (/6,6/) ) ! AR
! Arrays filled in init_radcool in data statements (np = 68)
integer, parameter :: np=68,nInAlts = 124
real,dimension(np) :: pnbr,ef1,ef2,co2vmr,o3pvmr,n2covmr
!! Stuff for initial conditions
real , Dimension(nInAlts) :: newalt
real , Dimension(nInAlts) :: InTemp
real , Dimension(nInAlts) :: IneTemp
real , Dimension(nInAlts) :: InITemp
real , Dimension(nInAlts,nSpeciesTotal) :: InNDensityS
real , Dimension(nInAlts,nIons) :: InIDensityS
integer, parameter:: nDustLinesMax = 4000, nDustLats = 36
integer :: nDustTimes,nConrathTimes
real, dimension(nDustLinesMax) :: TimeDust,TimeConrath
real, dimension(nDustLinesMax,nLats,nBlocksMax) :: HorizontalDustProfile
real, dimension(nDustLinesMax,nLats,nBlocksMax) :: HorizontalConrathProfile
real, dimension(nLons, nLats,nBlocksMax) :: &
fir,fvis,Tbot,TopL,Psurf,P125,iAltMinIono,DustDistribution,ConrathDistribution
!################ Nelli, April 07 ##########################
!Setting up parameters needed by the correlated k lower
!atmosphere radiation code
! Number of atmospheric layers
integer, PARAMETER :: LL_LAYERS = nAlts
! Number of atmospheric levels: 2 * LL_LAYERS + 3
integer, PARAMETER :: LL_LEVELS = 2*LL_LAYERS+3
!C LL_NLAYRAD is the number of radiation code layers
!C LL_NLEVRAD is the number of radiation code levels. Level N is the
!C
integer, PARAMETER :: LL_NLAYRAD = LL_LAYERS+1
integer, PARAMETER :: LL_NLEVRAD = LL_LAYERS+2
! Bottom layer subsurface temperature
real, parameter :: CoreTemp = 175.0
! Surface and subsurface temperature constants
real, parameter :: Pa = 5.927E+7
real, parameter :: Pd = 88775.0
! Stefan-Boltzmann constant in SI
real, parameter :: SBconstant = 5.67E-8
! Ls variable
real :: ell_s
!C======================================================================C
!C
!C RADINC.H RADiation INCludes
!C
!C Includes for the radiation code; RADIATION LAYERS, LEVELS,
!C number of spectral intervals. . .
!C
!C GCM2.0 Feb 2003
!C
!C======================================================================C
!C RADIATION parameters
!C In radiation code, layer 1 corresponds to the stratosphere. Level
!C 1 is the top of the stratosphere. The dummy layer is at the same
!C temperature as the (vertically isothermal) stratosphere, and
!C any time it is explicitly needed, the appropriate quantities will
!C be dealt with (aka "top". . .)
!C
!C L_NSPECTI is the number of IR spectral intervals
!C L_NSPECTV is the number of Visual(or Solar) spectral intervals
!C L_NGAUSS is the number of Gauss points for K-coefficients
!C GAUSS POINT 9 (aka the last one) is the special case
!C L_NWNGI is L_NSPECTI*L_NGAUSS; the total number of "intervals"
!C in the IR
!C L_NWNGV is L_NSPECTV*L_NGAUSS; the total number of "intervals"
!C in the VISUAL
!C
!C L_NPREF is the number of reference pressures that the
!C k-coefficients are calculated on
!C L_PINT is the number of Lagrange interpolated reference
!C pressures for the CO2 k-coefficients.
!C L_NTREF is the number of refernce temperatures for the
!C k-coefficients
!C L_TAUMAX is the largest optical depth - larger ones are set
!C to this value.
!C
!C L_REFH2O The number of different water-mixing ratio values for
!C the k-coefficients that are now CO2+H2O.
!C
!C L_NREFV The spectral interval number of the visible reference
!C wavelength (i.e. the 0.67 micron band)
!C
!C
!C L_NLTE The number of different LTE/NLTE heating rate conversion
!C factors
!C
!C----------------------------------------------------------------------C
integer, parameter :: L_NSPECTI = 5
integer, parameter :: L_NSPECTV = 7
integer, parameter :: L_NGAUSS = 17
integer, parameter :: L_NPREF = 11
integer, parameter :: L_NTREF = 7
integer, parameter :: L_TAUMAX = 35
integer, parameter :: L_PINT = 51
integer, parameter :: L_REFH2O = 10
integer, parameter :: L_NREFV = 6
integer, parameter :: L_NLTE = 37
!C----------------------------------------------------------------------C
!C
!C radcommon.h
!C FORTRAN PARAMETERS
!C GCM2.0 Feb 2003
!C
!C----------------------------------------------------------------------C
!C
!C "Include" grid.h and radinc.h before this file in code that uses
!C some or all of this common data set
!C
!C WNOI - Array of wavenumbers at the spectral interval
!C centers for the infrared. Array is NSPECTI
!C elements long.
!C DWNI - Array of "delta wavenumber", i.e., the width,
!C in wavenumbers (cm^-1) of each IR spectral
!C interval. NSPECTI elements long.
!C WAVEI - Array (NSPECTI elements long) of the wavelenght
!C (in microns) at the center of each IR spectral
!C interval.
!C WNOV - Array of wavenumbers at the spectral interval
!C center for the VISUAL. Array is NSPECTV
!C elements long.
!C DWNV - Array of "delta wavenumber", i.e., the width,
!C in wavenumbers (cm^-1) of each VISUAL spectral
!C interval. NSPECTV elements long.
!C WAVEV - Array (NSPECTV elements long) of the wavelenght
!C (in microns) at the center of each VISUAL spectral
!C interval.
!C SOLARF - Array (NSPECTV elements) of solar flux (W/M^2) in
!C each spectral interval. Values are for 1 AU, and
!C are scaled to the Mars distance elsewhere.
!C SOL - Solar flux at Mars (W/M^2)
!C TAURAY - Array (NSPECTV elements) of the pressure-independent
!C part of Rayleigh scattering optical depth.
!C PTOP - Pressure at the top of the radiation code coordinate;
!C = 0.5*Ptrop
!C FZEROI - Fraction of zeros in the IR CO2 k-coefficients, for
!C each temperature, pressure, and spectral interval
!C FZEROV - Fraction of zeros in the VISUAL CO2 k-coefficients, for
!C each temperature, pressure, and spectral interval
!C
!C AEROSOL RADIATIVE OPTICAL CONSTANTS
!C Values are at the wavelenght interval center
!C
!C MIE SCATTERING - Size distribution weighted
!C Qextv - Extinction efficiency - in the visual.
!C QextREF - Reference visual wavelength (.67 micron band)
!C Qscatv - Scattering efficiency - in the visual.
!C WV - Single scattering albedo - in the visual.
!C GV - Asymmetry parameter - in the visual.
!C
!C Qexti - Extinction efficiency - in the infrared.
!C Qscati - Scattering efficiency - in the infrared.
!C WI - Single scattering albedo - in the infrared.
!C GI - Asymmetry parameter - in the infrared.
!C
!C VIS2IR - VISIBLE (0.67 micron band) to IR (9 micron band) ratio.
!C
!C XLTEFACTOR - correction factor for over-prediction of heating rates
!C by the LTE code. Occurs at pressures where NLTE processes
!C become important
!C
!C XLTEPRESSURE - pressure regime at which each factor is to be applied
!C
!C "Include" grid.h and radinc.h before this file in code that uses
!C some or all of this common data set
REAL :: WNOI(L_NSPECTI), DWNI(L_NSPECTI), WAVEI(L_NSPECTI)
REAL :: WNOV(L_NSPECTV), DWNV(L_NSPECTV), WAVEV(L_NSPECTV)
REAL :: SOLARF(L_NSPECTV), TAURAY(L_NSPECTV),SOL(L_NSPECTV)
real :: CO2I(L_NTREF,L_PINT,L_REFH2O,L_NSPECTI,L_NGAUSS)
real :: CO2V(L_NTREF,L_PINT,L_REFH2O,L_NSPECTV,L_NGAUSS)
real :: FZEROI(L_NSPECTI)
real :: FZEROV(L_NSPECTV)
real :: PGASREF(L_NPREF), TGASREF(L_NTREF)
real :: qextv(L_NSPECTV), qscatv(L_NSPECTV), wv(L_NSPECTV)
real :: gv(L_NSPECTV)
real :: QextREF, VIS2IR, Cmk, tlimit
real :: qexti(L_NSPECTI), qscati(L_NSPECTI), wi(L_NSPECTI)
real :: gi(L_NSPECTI)
real :: planckir(L_NSPECTI,8501)
real :: PTOP, UBARI, GWEIGHT(L_NGAUSS)
real :: PFGASREF(L_PINT)
!C H2O and CO2 k-coefficients mixed
real :: WREFCO2(L_REFH2O), WREFH2O(L_REFH2O)
!C LTE/NLTE heating rate conversion factors and associated pressures
real :: XLTEFACTOR(L_NLTE),XLTEPRESSURE(L_NLTE)
! These are for the Gauss-split 0.95 case
DATA GWEIGHT / 4.8083554740D-02, 1.0563099137D-01,&
1.4901065679D-01, 1.7227479710D-01,&
1.7227479710D-01, 1.4901065679D-01,&
1.0563099137D-01, 4.8083554740D-02,&
2.5307134073D-03, 5.5595258613D-03,&
7.8426661469D-03, 9.0670945845D-03,&
9.0670945845D-03, 7.8426661469D-03,&
5.5595258613D-03, 2.5307134073D-03, 0.0D0 /
DATA UBARI / 0.5 /
!C These are for the CO2+H2O k-coefficients
DATA WREFCO2 / 9.999999D-1, 9.99999D-1, 9.9999D-1, 9.999D-1,&
9.99D-1, 9.9D-1, 9.0D-1, 8.0D-1, 7.0D-1, 6.0D-1 /
DATA WREFH2O / 1.0D-7, 1.0D-6, 1.0D-5, 1.0D-4, 1.0D-3, 1.0D-2,&
1.0D-1, 2.0D-1, 3.0D-1, 4.0D-1 /
DATA Cmk / 3.51E+22 /
DATA TLIMIT / 0.5 /
! ---------------------------------------------------------------------------
! Lopez-Valverde et al. (1998) Table 1, pg. 16809.
!
! DATA XLTEFACTOR / 1.007, 1.007, 1.007, 1.007, 1.008,&
! 1.009, 1.013, 1.017, 1.021, 1.027,&
! 1.033, 1.040, 1.047, 1.054, 1.061,&
! 1.069, 1.078, 1.087, 1.099, 1.112,&
! 1.129, 1.149, 1.174, 1.209, 1.263,&
! 1.344, 1.459, 1.608, 1.796, 2.033,&
! 2.343, 2.777, 3.404, 4.366, 5.856,&
! 8.161, 11.908, 17.791, 27.030, 40.897,&
! 60.798, 82.660,111.855,146.365,185.922,&
! 237.435,284.487,346.883,422.071,513.978,&
! 635.594 /
!
! DATA XLTEPRESSURE / 1.122E-1, 8.822E-2, 6.912E-2, 5.397E-2, 4.202E-2,&
! 3.261E-2, 2.523E-2, 1.946E-2, 1.497E-2, 1.149E-2,&
! 8.793E-3, 6.713E-3, 5.115E-3, 3.890E-3, 2.953E-3,&
! 2.239E-3, 1.696E-3, 1.284E-3, 9.719E-4, 7.355E-4,&
! 5.566E-4, 4.212E-4, 3.187E-4, 2.412E-4, 1.825E-4,&
! 1.381E-4, 1.045E-4, 7.908E-5, 5.984E-5, 4.530E-5,&
! 3.430E-5, 2.600E-5, 1.973E-5, 1.500E-5, 1.145E-5,&
! 8.761E-6, 6.731E-6, 5.192E-6, 4.024E-6, 3.141E-6,&
! 2.478E-6, 1.981E-6, 1.601E-6, 1.306E-6, 1.076E-6,&
! 8.939E-7, 7.462E-7, 6.242E-7, 5.234E-7, 4.397E-7,&
! 3.702E-7 /
!
! ---------------------------------------------------------------------------
! Bougher (2011) Calculated wrt QNLTE from MTGCM case for SZA = 0.0
! -- Ls = 90; F10.7 = 70; dust = weak
DATA XLTEFACTOR / 1.00, 1.000, 1.000, 1.000, 1.000,&
1.000, 1.000, 1.000, 1.000, 1.000,&
1.000, 1.000, 1.000, 1.000, 1.000,&
1.000, 1.000, 1.020, 1.040, 1.081,&
1.13225, 1.13704, 1.2334, 1.32968, 2.47989,&
5.17858, 9.21052, 13.9471, 19.1293, 25.9336,&
45.9666, 113.783, 146.843, 212.959, 500.000,&
1000.00, 1000.00 /
! mbar scale
DATA XLTEPRESSURE / 1.122E-1, 8.822E-2, 6.912E-2, 5.397E-2, 4.202E-2,&
3.261E-2, 2.523E-2, 1.946E-2, 1.497E-2, 1.149E-2,&
8.793E-3, 6.713E-3, 5.115E-3, 3.890E-3, 2.953E-3,&
2.239E-3, 1.696E-3, 1.284E-3, 9.719E-4, 7.982E-4,&
4.841E-4, 2.936E-4, 1.781E-4, 1.080E-4, 6.550E-5,&
3.970E-5, 2.410E-5, 1.460E-5, 8.900E-6, 5.400E-6,&
3.300E-6, 2.000E-6, 1.200E-6, 7.000E-7, 5.234E-7,&
4.397E-7, 3.702E-7 /
! ---------------------------------------------------------------------------
!C PLANCK defined variable
! planckir
!C SETSPI and SETSPV defined variables
! WNOI, DWNI, WAVEI, WNOV, DWNV, WAVEV
! SOLARF, TAURAY, PTOP, TAUREF, GWEIGHT, UBARI
! PFGASREF
!C SETRAD defined variables
! CO2I, CO2V, PGASREF, TGASREF
! QEXTV, QSCATV, WV, GV
! QEXTI, QSCATI, WI, GI, QextREF, VIS2IR
! fzeroi, fzerov
! WREFCO2, WREFH2O
!#####################################################
real*4 :: dummyalbedo(24,36), dummyti(24,36)
contains
subroutine init_planet
use ModTime
use ModIoUnit, only : UnitTmp_
integer :: iTime(7), iiAlt,ialt
! Mass = AMU * mean molecular weight (unlike TGCM codes)
Mass(iO_) = 15.9994 * AMU
Mass(iCO_) = 12.011 * AMU + Mass(iO_)
Mass(iCO2_) = Mass(iCO_) + Mass(iO_)
Mass(iN4S_) = 14.00674 * AMU
Mass(iN2D_) = Mass(iN4S_)
Mass(iN2_) = Mass(iN4S_) * 2
Mass(iNO_) = Mass(iN4S_) + Mass(iO_)
Mass(iO2_) = 2 * Mass(iO_)
Mass(iAr_) = 39.948 * AMU
Mass(iHe_) = 4.0026 * AMU
Mass(iH_) = 1.0079 * AMU
cSpecies(iO_) = "O"
cSpecies(iO2_) = "O!D2!N"
cSpecies(iN4S_) = "N"
cSpecies(iN2_) = "N!D2!N"
cSpecies(iCO_) = "CO"
cSpecies(iCO2_) = "CO!D2!N"
cSpecies(iNO_) = "NO"
cSpecies(iAr_) = "Ar"
cSpecies(iH_) = "H"
cSpecies(iHe_) = "He"
cIons(iO2P_) = "O!D2!U+!N"
cIons(iCO2P_) = "CO!D2!U+!N"
cIons(iNOP_) = "NO!U+!N"
cIons(iOP_) = "O!U+!N"
cIons(iN2P_) = "N!D2!U+!N"
cIons(ie_) = "e-"
Vibration(iCO2_) = 7.0 ! Corrected by Bougher (01/18/07)!!!!
Vibration(iCO_) = 7.0
Vibration(iO_) = 5.0
Vibration(iN2_) = 7.0
MassI(iOP_) = Mass(iO_)
MassI(iNOP_) = Mass(iO_) + Mass(iN2_)/2.0
MassI(iCO2P_) = Mass(iCO2_)
MassI(iO2P_) = Mass(iO2_)
MassI(ie_) = Mass_Electron
itime = 0
itime(1) = iVernalYear
itime(2) = iVernalMonth
itime(3) = iVernalDay
itime(4) = iVernalHour
itime(5) = iVernalMinute
itime(6) = iVernalSecond
call time_int_to_real(itime, VernalTime)
write(*,*) 'Reading in the Mars_input.txt'
open(UNIT = 67, FILE = 'UA/DataIn/ALBEDO_ASCII', &
STATUS='OLD', ACTION = 'READ')
read(67,*) dummyalbedo
close(UNIT = 67)
open(UNIT = 68, FILE = 'UA/DataIn/THERMAL_ASCII', &
STATUS='OLD', ACTION = 'READ')
read(68,*) dummyti
close(UNIT = 68)
open(UNIT = UnitTmp_, FILE = 'UA/DataIn/NewMarsAtm_2p5km.txt', &
STATUS='OLD', ACTION = 'READ')
111 FORMAT(F6.2,1X, F8.2,1X, F8.2,1X, F8.2,1X, &
ES10.3,1X, ES10.3, 1X, ES10.3, 1X, ES10.3, 1X, &
ES10.3, 1X, ES10.3, 1X, ES10.3)
InNDensityS(:,:) = 1.0e+3
InIDensityS(:,:) = 1.0e+3
do iiAlt = 1,124
read(UnitTmp_,111) &
newalt(iiAlt), &
InTemp(iiAlt), &
InITemp(iiAlt), &
IneTemp(iiAlt), &
!
InNDensityS(iiAlt,iCO2_), &
InNDensityS(iiAlt,iO2_), &
InNDensityS(iiAlt,iCO_), &
InNDensityS(iiAlt,iN2_), &
!
InNDensityS(iiAlt,iO_), &
InNDensityS(iiAlt,iAr_), &
InIDensityS(iiAlt,ie_)
end do
InNDensityS = Alog(inNDensityS)
close(Unit = UnitTmp_)
!######## Nelli, April 07 ################################
!
!C PURPOSE IS TO SET UP THE CORRELATED K LOWER ATMOPSHERE
!C RADIATION CODE.
!C INITIALIZATION CONSISTS MAINLY OF READING INPUT VALUES,
!C CALCULATING CONSTANTS FOR USE IN THE RADIATION CODE, AND
!C INITIALIZING THE SET OF VALUES MAINTAINED FOR EACH BAND PASS
!C Set up the radiation code stuff
CALL RADSETUP
!###########################################################
end subroutine init_planet
!################ Nelli, April 07 ##########################
!Filling arrays needed by the correlated k lower
!atmosphere radiation code
subroutine radsetup
!C GCM2.0 Feb 2003
!C
!C PURPOSE:
!C Bundle the new radiation code setup subroutines and call
!C this one subroutine from main, where the three included files
!C are also listed. Quantities are passed between this driver
!C and the radiation code via common (in radcommon.h).
!C
!C----------------------------------------------------------------------C
implicit none
REAL :: FACTOR
INTEGER :: NW
!C======================================================================C
call setspv
call setspi
call setrad
!C Scale IR opacities (Qexti and Qscati) such that
!C TAU(0.67 micron)/TAU(9 micron) = VIS2IR, which nominally is 2.
QextREF = Qextv(L_NREFV)
VIS2IR = 2.75D0
factor = Qextv(6)/(VIS2IR*Qexti(4))
DO NW=1,L_NSPECTI
Qexti(NW) = Qexti(NW)*factor
Qscati(NW) = Qscati(NW)*factor
END DO
PTOP = 10.0**PFGASREF(1)
print*,'vis2ir=',vis2ir
end subroutine radsetup
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SUBROUTINE SETSPV
!C GCM2.0 Feb 2003
!C
!C PURPOSE:
!C Set up the spectral intervals in the Visual (solar). Based
!C on Chris McKay's SETSPV code.
!C
!C AUTHOR
!C Jim Schaeffer
!C
!C UPDATES FOR
!C Bob Haberle
!C
!C ENVIRONMENT
!C Sun ULTRA-2 SOLARIS 2.5.1 FORTRAN
!C
!C REVISION HISTORY
!C Original 9/17/1998
!C VERSION 2.0 OCT 2001
!C
!C INPUT PARAMETERS
!C L_NSPECTV - Number of spectral intervals in the Visual
!C
!C OUTPUT PARAMETERS
!C WNOV - Array of wavenumbers at the spectral interval
!C center for the VISUAL. Array is NSPECTV
!C elements long.
!C DWNV - Array of "delta wavenumber", i.e., the width,
!C in wavenumbers (cm^-1) of each VISUAL spectral
!C interval. NSPECTV elements long.
!C WAVEV - Array (NSPECTV elements long) of the wavelenght
!C (in microns) at the center of each VISUAL spectral
!C interval.
!C SOLARF - Array (NSPECTV elements) of solar flux (W/M^2) in
!C each spectral interval. Values are for 1 AU, and
!C are scaled to the Mars distance elsewhere.
!C TAURAY - Array (NSPECTV elements) of the wavelength dependent
!C part of Rayleigh Scattering. The pressure dependent
!C part is computed elsewhere (OPTCV).
!C CALLED BY
!C RADIATION
!C
!C SUBROUTINES CALLED
!C NONE
!C
!C**********************************************************************C
implicit none
!C BWNV - Bin wavenumber of the edges of the VISUAL spectral bins
!C units are inverse centimeters. Dimension needs to be changed
!C if the number of VISUAL bins changes.
REAL :: BWNV(L_NSPECTV+1)
REAL :: SOLAR(L_NSPECTV)
REAL :: P0, GRAV, SCALEP, SUM, WL
INTEGER :: N, M
!C P0 - Rayleigh scattering reference pressure in pascals.
!C GRAV - Acceleration due to gravity (g) - MKS
!C SCALEP - multiply by 100 to convert pressure from millibars
!C to pascals.
DATA P0 / 9.423D+6 /
DATA GRAV / 3.72 /
DATA SCALEP / 100.0 /
!C Bin wavenumber - wavenumber [cm^(-1)] at the edges of the VISUAL
!C spectral bins. Go from smaller to larger wavenumbers, the same as
!C in the IR.
DATA BWNV / 2222.22D0, 3087.37D0, 4030.63D0, 5370.57D0,&
7651.11D0, 12500.00D0, 25000.00D0, 41666.67D0 /
!C Solar flux within each spectral interval, at 1AU (W/M^2)
!C Sum equals 1356 W/m^2 (values from Allen, 4th edition)
DATA SOLAR / 17.0, 29.0, 52.0, 148.0, 348.0, 643.0, 118.0 /
!C======================================================================C
!C Set up mean wavenumbers and wavenumber deltas. Units of
!C wavenumbers is cm^(-1); units of wavelengths is microns.
do M=1,L_NSPECTV
WNOV(M) = 0.5*(BWNV(M+1)+BWNV(M))
DWNV(M) = BWNV(M+1)-BWNV(M)
WAVEV(M) = 1.0E+4/WNOV(M)
end do
!C Sum the solar flux, and write out the result.
sum = 0.0
do N=1,L_NSPECTV
SOLARF(N) = SOLAR(N)
sum = sum+SOLARF(N)
end do
write(6,'("Solar flux at 1AU = ",f7.2," W/M^2")') sum
!C Set up the wavelength dependent part of Rayleigh Scattering.
!C The pressure dependent part will be computed elsewhere (OPTCV).
!C WAVEV is in microns. There is no Rayleigh scattering in the IR.
do N=1,L_NSPECTV
WL = WAVEV(N)
TAURAY(N) = (8.7/grav)*(1.527*(1.0+0.013/wl**2)/wl**4)*&
scalep/P0
end do
END SUBROUTINE SETSPV
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subroutine setspi
!C GCM2.0 Feb 2003
!C
!C PURPOSE:
!C Set up the spectral intervals in the infrared. Based on
!C Chris McKay's SETSPI code.
!C
!C AUTHOR
!C Jim Schaeffer
!C
!C UPDATES FOR
!C Bob Haberle
!C
!C ENVIRONMENT
!C Sun ULTRA-2 SOLARIS 2.5.1 FORTRAN
!C
!C REVISION HISTORY
!C Original 9/17/1998
!C VERSION 2 OCT 2001
!C
!C INPUT PARAMETERS
!C L_NSPECTI - Number of spectral intervals in the INFRARED
!C
!C OUTPUT PARAMETERS
!C WNOI - Array of wavenumbers at the spectral interval
!C centers for the infrared. Array is NSPECTI
!C elements long.
!C DWNI - Array of "delta wavenumber", i.e., the width,
!C in wavenumbers (cm^-1) of each IR spectral
!C interval. NSPECTI elements long.
!C WAVEI - Array (NSPECTI elements long) of the wavelenght
!C (in microns) at the center of each IR spectral
!C interval.
!C
!C CALLED BY
!C RADIATION
!C
!C SUBROUTINES CALLED
!C NONE
!C
!C**********************************************************************C
implicit none
!C BWNI - Bin wavenumber of the edges of the IR spectral bins
!C units are inverse centimeters. Dimension needs to be changed
!C if the number of IR bins changes.
REAL :: BWNI(L_NSPECTI+1)
real :: a, b, x(12), w(12), ans, y, bpa, bma, T
real :: c1, c2, wn1, wn2, PI
integer :: n, nw, nt, m
!C C1 and C2 values from Goody and Yung (2nd edition) MKS units
!C These values lead to a "sigma" (sigma*T^4) of 5.67032E-8 W m^-2 K^-4
data c1 / 3.741832D-16 / ! W m^-2
data c2 / 1.438786D-2 / ! m K
data PI / 3.14159265358979D0 /
data x / -0.981560634246719D0, -0.904117256370475D0,&
-0.769902674194305D0, -0.587317954286617D0,&
-0.367831498998180D0, -0.125233408511469D0,&
0.125233408511469D0, 0.367831498998180D0,&
0.587317954286617D0, 0.769902674194305D0,&
0.904117256370475D0, 0.981560634246719D0 /
data w / 0.047175336386512D0, 0.106939325995318D0,&
0.160078328543346D0, 0.203167426723066D0,&
0.233492536538355D0, 0.249147045813403D0,&
0.249147045813403D0, 0.233492536538355D0,&
0.203167426723066D0, 0.160078328543346D0,&
0.106939325995318D0, 0.047175336386512D0 /
!C======================================================================C
!C Bin wavenumber - wavenumber [cm^(-1)] at the edges of the IR
!C spectral bins.
BWNI( 1) = 10.000D0
BWNI( 2) = 166.667D0
BWNI( 3) = 416.667D0
BWNI( 4) = 833.333D0
BWNI( 5) = 1250.000D0
BWNI( 6) = 2500.000D0
!C Set up mean wavenumbers and wavenumber deltas. Units of
!C wavenumbers is cm^(-1); units of wavelengths is microns.
do M=1,L_NSPECTI
WNOI(M) = 0.5*(BWNI(M+1)+BWNI(M))
DWNI(M) = BWNI(M+1)-BWNI(M)
WAVEI(M) = 1.0E+4/WNOI(M)
end do
!C For each IR wavelength interval, compute the integral of B(T), the
!C Planck function, divided by the wavelength interval, in cm-1. The
!C integration is in MKS units, the final answer is the same as the
!C original planck.f; W m^-2 wavenumber^-1, where wavenumber is in CM^-1.
DO NW=1,L_NSPECTI
a = 1.0D-2/BWNI(NW+1)
b = 1.0D-2/BWNI(NW)
bpa = (b+a)/2.0
bma = (b-a)/2.0
do nt=500,9000
T = dble(NT)/1.0D+1
ans = 0.0D0
do m=1,12
y = bma*x(m)+bpa
ans = ans + w(m)*c1/(y**5*(exp(c2/(y*T))-1.0D0))
end do
planckir(NW,nt-499) = ans*bma/(PI*DWNI(NW))
end do
END DO
end subroutine setspi
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subroutine setrad
!C GCM2.0 Feb 2003
!C
!C PURPOSE:
!C Set up values used by the radiation code, such as the CO2 gas
!C absorption coefficients. True constants are defined, and the
!C time-independent quantities used by the radiation code are
!C calculated.
!C
!C AUTHOR
!C
!C
!C UPDATES FOR
!C Jim Pollack
!C
!C ENVIRONMENT
!C NAS Cray-YMP UNICOS FORTRAN
!C
!C REVISION HISTORY
!C See notes from J. Pollack dated 2/20/90 and 3/12/90.
!C Modified Cmk See note from Jim Pollack dated 1/11/91.
!C Several - See note dated 1/23/91 from Jim Pollack.
!C VERSION 2.0 OCT 2001
!C
!C INPUT PARAMETERS
!C DTAU(L,M) - Dust optical depth of layer L, and for aerosol
!C species M.
!C ptrop - Pressure of the tropopause (mb)
!C SCALEP - Factor to convert pressures from millibars to
!C Pascals
!C
!C OUTPUT PARAMETERS
!C PTOP - Pressure at the TOP of the stratosphere ( or
!C equivalently, at the bottom of the dummy layer.
!C PTOP = PTROP*SDUMMY
!C
!C AEROSOL RADIATIVE OPTICAL CONSTANTS
!C Values are at the wavelenght interval center
!C
!C MIE SCATTERING - Size distribution weighted
!C Qextv - Extinction efficiency - in the visual.
!C Qscatv - Scattering efficiency - in the visual.
!C WV - Single scattering albedo - in the visual.
!C GV - Asymmetry parameter - in the visual.
!C
!C Qexti - Extinction efficiency - in the infrared.
!C Qscati - Scattering efficiency - in the infrared.
!C WI - Single scattering albedo - in the infrared.
!C GI - Asymmetry parameter - in the infrared.
!C
!C CALLED BY
!C RAD
!C
!C SUBROUTINES CALLED
!C DMIESS, PLNK
!C
!C----------------------------------------------------------------------C
implicit none
integer :: N, NS
real :: qev1(L_NSPECTV)
real :: qsv1(L_NSPECTV)
real :: gv1(L_NSPECTV)
real :: qei1(L_NSPECTI)
real :: qsi1(L_NSPECTI)
real :: gi1(L_NSPECTI)
integer :: nt, np, nw, ng
!C----------------------------------------------------------------------C
!C Visible dust properties: Ockert-Bell Planck-weighted values (T=6000K)
!C Qext - Ockert-Bell values (order is increasing waveNUMBER)
!C VISULAL WAVELENGTHS.
data qev1 / 2.529D0, 2.949D0, 3.209D0, 3.337D0, 3.207D0,&
2.938D0, 2.622D0 /
!C Qscat - Ockert-Bell values
!C VISUAL wavelengths
data qsv1 / 2.374D0, 2.637D0, 3.049D0, 3.201D0, 3.045D0,&
2.513D0, 1.623D0 /
!C G - Ockert-Bell values
!C VISUAL wavelengths
data gv1 / 0.635D0, 0.646D0, 0.630D0, 0.630D0, 0.634D0,&
0.700D0, 0.856D0 /
!C And now the INFRARED
!C Qext for a modified-gamma distribution, ALPHA=2, GAMMA=0.5,
!C Rm = 0.4 microns, using the Forget optical constants (Nr and Ni).
!C Planck-weighted values (T=215K)
!C INFRARED wavelengths. (The order is increasing waveNUMBER.)
data qei1 / 0.193D0, 0.867D0, 1.209D0, 2.173D0, 0.638D0 /
!C Qsca for a modified gamma-distribution, using the Forget
!C optical constants (Nr and Ni). INFRARED wavelengths
data qsi1 / 0.027D0, 0.319D0, 0.558D0, 1.136D0, 0.237D0 /
!C g for a modified gamma-distribution, using the Forget
!C optical constants (Nr and Ni). INFRARED wavelengths
data gi1 / 0.024D0, 0.127D0, 0.288D0, 0.423D0, 0.548D0 /
!C=======================================================================
!C Set the reference pressure and temperature arrays. These are
!C the pressures and temperatures at which we have k-coefficients.
pgasref( 1) = 1.0E-6
pgasref( 2) = 1.0E-5
pgasref( 3) = 1.0E-4
pgasref( 4) = 1.0E-3
pgasref( 5) = 1.0E-2
pgasref( 6) = 1.0E-1
pgasref( 7) = 1.0
pgasref( 8) = 1.0E+1
pgasref( 9) = 1.0E+2
pgasref(10) = 1.0E+3
pgasref(11) = 1.0E+4
tgasref(1) = 50.0
tgasref(2) = 100.0
tgasref(3) = 150.0
tgasref(4) = 200.0
tgasref(5) = 250.0
tgasref(6) = 300.0
tgasref(7) = 350.0
!C Fill the (VISUAL) arrays Qextv, Qscatv, WV, GV
DO N=1,L_NSPECTV
Qextv(n) = qev1(n)
Qscatv(n) = qsv1(n)
IF(Qscatv(n).GE.Qextv(n)) then
Qscatv(n) = 0.99999*Qextv(n)
END IF
WV(n) = Qscatv(n)/Qextv(n)
GV(n) = gv1(n)
END DO
!C Fill the (INFRARED) arrays Qexti, Qscati, WI, GI
DO N=1,L_NSPECTI
Qexti(n) = qei1(n)
Qscati(n) = qsi1(n)
IF(Qscati(n).GE.Qexti(n)) then
Qscati(n) = 0.99999*Qexti(n)
END IF
WI(n) = Qscati(n)/Qexti(n)
GI(n) = gi1(n)
END DO
!C Get CO2 k coefficients, and interpolate them to the finer
!C pressure grid.
call laginterp(pgasref,pfgasref)
end subroutine setrad
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subroutine laginterp(pgref,pint)
!C GCM2.0 Feb 2003
!C Lagrange interpolation (linear in log pressure) of the CO2
!C k-coefficients in the pressure domain. Subsequent use of these
!C values will use a simple linear interpolation in pressure.
implicit none
integer :: n, nt, np, nh, ng, nw, m, i, j, k, l
real :: co2i8(L_NTREF,L_NPREF,L_REFH2O,L_NSPECTI,L_NGAUSS)
real :: co2v8(L_NTREF,L_NPREF,L_REFH2O,L_NSPECTV,L_NGAUSS)
real :: pgref(L_NPREF)
real :: x, xi(4), yi(4), ans
real :: pint(L_PINT), pin(L_PINT), pref(L_NPREF), p
data pin / -6.0D0, -5.8D0, -5.6D0, -5.4D0, -5.2D0,&
-5.0D0, -4.8D0, -4.6D0, -4.4D0, -4.2D0,&
-4.0D0, -3.8D0, -3.6D0, -3.4D0, -3.2D0,&
-3.0D0, -2.8D0, -2.6D0, -2.4D0, -2.2D0,&
-2.0D0, -1.8D0, -1.6D0, -1.4D0, -1.2D0,&
-1.0D0, -0.8D0, -0.6D0, -0.4D0, -0.2D0,&
0.0D0, 0.2D0, 0.4D0, 0.6D0, 0.8D0,&
1.0D0, 1.2D0, 1.4D0, 1.6D0, 1.8D0,&
2.0D0, 2.2D0, 2.4D0, 2.6D0, 2.8D0,&
3.0D0, 3.2D0, 3.4D0, 3.6D0, 3.8D0,&
4.0D0 /
!C======================================================================!
!C Fill pint for output from this subroutine
do n=1,L_PINT
PINT(n) = PIN(n)
end do
!C Take log of the reference pressures
do n=1,L_NPREF
pref(n) = LOG10(PGREF(n))
end do
!C Get CO2 k coefficients
OPEN(Unit=25,file='UA/DataIn/CO2H2O_V_12_95_ASCII',ACTION = 'READ')
DO i=1,L_NTREF
DO j=1,L_NPREF
DO k=1,L_REFH2O
DO l=1,L_NSPECTV
DO m=1,L_NGAUSS
read(25,*)co2v8(i,j,k,l,m)
ENDDO
ENDDO
ENDDO
ENDDO
ENDDO
DO i=1,L_NSPECTV
read(25,*)fzerov(i)
ENDDO
CLOSE(25)
OPEN(unit=35,file='UA/DataIn/CO2H2O_IR_12_95_ASCII',ACTION = 'READ')
DO i=1,L_NTREF
DO j=1,L_NPREF
DO k=1,L_REFH2O
DO l=1,L_NSPECTI
DO m=1,L_NGAUSS
read(35,*)co2i8(i,j,k,l,m)
ENDDO
ENDDO
ENDDO
ENDDO
ENDDO
DO i=1,L_NSPECTI
read(35,*)fzeroi(i)
ENDDO
CLOSE(35)
!!$ print*,'co2v8(3,4,1,3,2) = ',co2v8(3,4,1,3,2)
!!$ print*,'co2v8(1,2,3,4,5) = ',co2v8(1,2,3,4,5)
!!$ print*,'co2v8(3,4,1,3,3) = ',co2v8(3,4,1,3,3)
!!$
!!$ print*,'co2i8(3,4,1,3,2) = ',co2i8(3,4,1,3,2)
!!$ print*,'co2i8(1,2,3,4,5) = ',co2i8(1,2,3,4,5)
!!$ print*,'co2i8(3,4,1,3,3) = ',co2i8(3,4,1,3,3)
!C Take Log10 of the values - we interpolate the log10 of the values,
!C not the values themselves. Smallest value is 1.0E-200.
do nt=1,L_NTREF
do np=1,L_NPREF
do nh=1,L_REFH2O
do ng = 1,L_NGAUSS
do nw=1,L_NSPECTV
if(co2v8(nt,np,nh,nw,ng).gt.1.0e-200) then
co2v8(nt,np,nh,nw,ng) = log10(co2v8(nt,np,nh,nw,ng))
else
co2v8(nt,np,nh,nw,ng) = -200.0
end if
end do
do nw=1,L_NSPECTI
if(co2i8(nt,np,nh,nw,ng).gt.1.0e-200) then
co2i8(nt,np,nh,nw,ng) = log10(co2i8(nt,np,nh,nw,ng))
else
co2i8(nt,np,nh,nw,ng) = -200.0
end if
end do
end do
end do
end do
end do
!C Interpolate the values: first the IR
do nt=1,L_NTREF
do nh=1,L_REFH2O
do nw=1,L_NSPECTI
do ng=1,L_NGAUSS
!C First, the initial interval (P=1e-6 to 1e-5)
n = 1
do m=1,5
x = pint(m)
xi(1) = pref(n)
xi(2) = pref(n+1)
xi(3) = pref(n+2)
xi(4) = pref(n+3)
yi(1) = co2i8(nt,n,nh,nw,ng)
yi(2) = co2i8(nt,n+1,nh,nw,ng)
yi(3) = co2i8(nt,n+2,nh,nw,ng)
yi(4) = co2i8(nt,n+3,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2i(nt,m,nh,nw,ng) = 10.0**ans
end do
do n=2,L_NPREF-2
do m=1,5
i = (n-1)*5+m
x = pint(i)
xi(1) = pref(n-1)
xi(2) = pref(n)
xi(3) = pref(n+1)
xi(4) = pref(n+2)
yi(1) = co2i8(nt,n-1,nh,nw,ng)
yi(2) = co2i8(nt,n,nh,nw,ng)
yi(3) = co2i8(nt,n+1,nh,nw,ng)
yi(4) = co2i8(nt,n+2,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2i(nt,i,nh,nw,ng) = 10.0**ans
end do
end do
!C Now, get the last interval (P=1e+3 to 1e+4)
n = L_NPREF-1
do m=1,5
i = (n-1)*5+m
x = pint(i)
xi(1) = pref(n-2)
xi(2) = pref(n-1)
xi(3) = pref(n)
xi(4) = pref(n+1)
yi(1) = co2i8(nt,n-2,nh,nw,ng)
yi(2) = co2i8(nt,n-1,nh,nw,ng)
yi(3) = co2i8(nt,n,nh,nw,ng)
yi(4) = co2i8(nt,n+1,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2i(nt,i,nh,nw,ng) = 10.0**ans
end do
!C Fill the last pressure point
co2i(nt,L_PINT,nh,nw,ng) = 10.0**co2i8(nt,L_NPREF,nh,nw,ng)
end do
end do
end do
end do
!C Interpolate the values: now the Visual
do nt=1,L_NTREF
do nh=1,L_REFH2O
do nw=1,L_NSPECTV
do ng=1,L_NGAUSS
!C First, the initial interval (P=1e-6 to 1e-5)
n = 1
do m=1,5
x = pint(m)
xi(1) = pref(n)
xi(2) = pref(n+1)
xi(3) = pref(n+2)
xi(4) = pref(n+3)
yi(1) = co2v8(nt,n,nh,nw,ng)
yi(2) = co2v8(nt,n+1,nh,nw,ng)
yi(3) = co2v8(nt,n+2,nh,nw,ng)
yi(4) = co2v8(nt,n+3,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2v(nt,m,nh,nw,ng) = 10.0**ans
end do
do n=2,L_NPREF-2
do m=1,5
i = (n-1)*5+m
x = pint(i)
xi(1) = pref(n-1)
xi(2) = pref(n)
xi(3) = pref(n+1)
xi(4) = pref(n+2)
yi(1) = co2v8(nt,n-1,nh,nw,ng)
yi(2) = co2v8(nt,n,nh,nw,ng)
yi(3) = co2v8(nt,n+1,nh,nw,ng)
yi(4) = co2v8(nt,n+2,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2v(nt,i,nh,nw,ng) = 10.0**ans
end do
end do
!C Now, get the last interval (P=1e+3 to 1e+4)
n = L_NPREF-1
do m=1,5
i = (n-1)*5+m
x = pint(i)
xi(1) = pref(n-2)
xi(2) = pref(n-1)
xi(3) = pref(n)
xi(4) = pref(n+1)
yi(1) = co2v8(nt,n-2,nh,nw,ng)
yi(2) = co2v8(nt,n-1,nh,nw,ng)
yi(3) = co2v8(nt,n,nh,nw,ng)
yi(4) = co2v8(nt,n+1,nh,nw,ng)
call lagrange(x,xi,yi,ans)
co2v(nt,i,nh,nw,ng) = 10.0**ans
end do
!C Fill the last pressure point
co2v(nt,L_PINT,nh,nw,ng) = 10.0**co2v8(nt,L_NPREF,nh,nw,ng)
end do
end do
end do
end do
end subroutine laginterp
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subroutine lagrange(x, xi, yi, ans)
!C GCM2.0 Feb 2003
!C
!C Lagrange interpolation - Polynomial interpolation at point x
!C xi(1) <= x <= xi(4). Yi(n) is the functional value at XI(n).
implicit none
real :: x, xi(4), yi(4), ans
real :: fm1, fm2, fm3, fm4
!C======================================================================!
fm1 = x - XI(1)
fm2 = x - XI(2)
fm3 = x - XI(3)
fm4 = x - XI(4)
!C Get the "answer" at the requested X
ans = fm2*fm3*fm4*YI(1)/&
((XI(1)-XI(2))*(XI(1)-XI(3))*(XI(1)-XI(4))) +&
fm1*fm3*fm4*YI(2)/&
((XI(2)-XI(1))*(XI(2)-XI(3))*(XI(2)-XI(4))) +&
fm1*fm2*fm4*YI(3)/&
((XI(3)-XI(1))*(XI(3)-XI(2))*(XI(3)-XI(4))) +&
fm1*fm2*fm3*YI(4)/&
((XI(4)-XI(1))*(XI(4)-XI(2))*(XI(4)-XI(3)))
end subroutine lagrange
!##########################################################
subroutine init_radcooling
return
end subroutine init_radcooling
subroutine init_magheat
return
end subroutine init_magheat
subroutine init_aerosol
return
end subroutine init_aerosol
end module ModPlanet
| mit |
cicadas-2014/Elsewhere | db/migrate/20140626220711_create_phrases.rb | 250 | class CreatePhrases < ActiveRecord::Migration
def change
create_table :phrases do |t|
t.belongs_to :country
t.string :hello
t.string :please
t.string :thanks
t.string :bathroom
t.timestamps
end
end
end
| mit |
Baransu/Amble-Engine | src/game-preview/js/index.js | 1676 | const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;
window.onload = function() {
ipcRenderer.send('game-preview-loaded');
}
ipcRenderer.on('game-preview-start', function(event, data) {
var app = new Application({
// resize: true,
fullscreen: true,
antyAliasing: true,
preload: function(){
console.log(data.assets);
//load images
for (var i = 0; i < data.assets.length; i++) {
var meta = data.assets[i];
if(meta.type == 'script') {
require(meta.path);
// connect script with uuid
} else {
this.loader.load(meta.type, meta.path, meta.name, meta.uuid);
}
}
//load scene (json)
// this.loader.load('json', scene file path, 'scene.json');
},
//instantiate scene objects
loaded: function(){
//instantiate all object
for(var i = 0; i < data.sceneFile.length; i++) {
if(data.sceneFile[i].tag == 'mainCamera') {
this.mainCamera = this.scene.instantiate(data.sceneFile[i]);
} else {
this.scene.instantiate(data.sceneFile[i]);
}
}
},
//actual start function
start: function(){
//show must go on
},
preupdate: function(){
},
postupdate: function(){
},
postrender: function(){
// var layer = this.mainCamera.camera.layer;
// layer.ctx.save();
// layer.textAlign('left');
// layer.font('30px Arial');
// layer.fillStyle('white');
//
// var fps = (Time.deltaTime).toFixed(3);
//
// layer.fillText(fps || 0, 0,30);
// layer.ctx.restore();
}
});
})
| mit |
yurich/vow-telegram-bot | examples/settings.js | 115 | module.exports = {
token: 'TELEGRAM_BOT_TOKEN',
polling: {
timeout: 3,
limit: 100
}
};
| mit |
amironov73/ManagedIrbis | Source/UITests/Sources/Tests/ColorComboBoxTest.cs | 1565 | /* ColorComboBoxTest.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AM;
using AM.Windows.Forms;
using CodeJam;
using IrbisUI;
using JetBrains.Annotations;
using ManagedIrbis;
using MoonSharp.Interpreter;
using Newtonsoft.Json;
#endregion
namespace UITests
{
public sealed class ColorComboBoxTest
: IUITest
{
#region IUITest members
public void Run
(
IWin32Window ownerWindow
)
{
using (Form form = new Form())
{
form.Size = new Size(800, 600);
ColorComboBox colorBox = new ColorComboBox
{
Location = new Point(10, 10),
Width = 200
};
form.Controls.Add(colorBox);
TextBox textBox = new TextBox
{
Location = new Point(310, 10),
Width = 300
};
form.Controls.Add(textBox);
colorBox.SelectedIndexChanged += (sender, args) =>
{
textBox.Text = colorBox.SelectedColor.ToString();
};
form.ShowDialog(ownerWindow);
}
}
#endregion
}
}
| mit |
yyoshinori/CastlePortal | fuel/app/config/routes.php | 636 | <?php
return array(
'_root_' => 'admin/index', // The default route
'_404_' => 'welcome/404', // The main 404 route
'admin/detail/:id' => array('admin/detail/$1', 'name' => 'detail'),
'admin/write' => '/admin/write/',
'test'=> 'api/test',
'blog'=> 'api/blog',
'blog/insert'=> 'api/blog/insert',
'blog/update'=> 'api/blog/update',
'admin/list/'=> '/admin/list',
'admin/edit/:id' => array('admin/edit/$1', 'name' => 'edit'),
'admin/view/:id' => array('admin/view/$1', 'name' => 'view'),
'test/insert'=> 'api/test/insert',
'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'),
);
| mit |
bradscode/sencha-touch-2-recipes | recipe2/touch/README.md | 515 | Installing Sencha Touch
-----------------------
[Download the Sencha Touch SDK][sdk], and unzip the archive. Assuming that you've saved the SDK into your downloads folder (`~/Downloads/sencha-touch-2-b3`), you can run the following commands in the terminal:
cd path/to/sencha-touch-2-recipes/recipe2
cp -R ~/Downloads/sencha-touch-2-b2/resources touch/
This copies only the parts that we need from the Sencha Touch SDK into the `touch/` directory.
[sdk]: http://www.sencha.com/products/touch/download/
| mit |
freon-lunarion/dew | application/modules/om/views/_element/orgPostStruct_modal.php | 1450 | <!-- Modal -->
<div class="modal fade" id="explor_post" tabindex="-1" role="dialog" aria-labelledby="post_structlLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Organization Position</h4>
</div>
<div class="modal-body" id="post_exp">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$('#explor_post').on('show.bs.modal', function (e) {
StructOrgPost(1);
})
$('#explor_post').on('click', '.nav-open', function(event) {
event.preventDefault();
var id = $(this).data('id');
StructOrgPost(id);
});
$('#explor_post').on('click', '.nav-select', function(event) {
event.preventDefault();
var id = $(this).data('id');
var text = $(this).data('text');
$('#txt_post').val(text);
$('#hdn_post').val(id);
});
function StructOrgPost(id) {
var ajaxUrl = siteUrl + '/Om/Ajax/ShowOrgStrucSelection' ;
$.ajax({
url: ajaxUrl,
type: 'POST',
dataType: 'html',
data: {id: id,mode:'post'}
})
.done(function(respond) {
$('#post_exp').html(respond);
});
}
</script>
| mit |
terrajobst/nquery-vnext | src/NQuery.Authoring.ActiproWpf/QuickInfo/NQueryQuickInfoProvider.cs | 2436 | using System.Collections.ObjectModel;
using ActiproSoftware.Text;
using ActiproSoftware.Text.Utility;
using ActiproSoftware.Windows.Controls.SyntaxEditor;
using ActiproSoftware.Windows.Controls.SyntaxEditor.IntelliPrompt.Implementation;
using NQuery.Authoring.ActiproWpf.SymbolContent;
using NQuery.Authoring.ActiproWpf.Text;
using NQuery.Authoring.QuickInfo;
namespace NQuery.Authoring.ActiproWpf.QuickInfo
{
internal sealed class NQueryQuickInfoProvider : QuickInfoProviderBase, INQueryQuickInfoProvider
{
private readonly IServiceLocator _serviceLocator;
public NQueryQuickInfoProvider(IServiceLocator serviceLocator)
{
_serviceLocator = serviceLocator;
}
private INQuerySymbolContentProvider SymbolContentProvider
{
get { return _serviceLocator.GetService<INQuerySymbolContentProvider>(); }
}
public Collection<IQuickInfoModelProvider> Providers { get; } = new();
public override object GetContext(IEditorView view, int offset)
{
var documentView = view.SyntaxEditor.GetDocumentView();
var document = documentView.Document;
if (!document.TryGetSemanticModel(out var semanticModel))
return null;
var snapshot = document.Text.ToTextSnapshot();
var snapshotOffset = new TextSnapshotOffset(snapshot, offset);
var position = snapshotOffset.ToOffset();
var model = semanticModel.GetQuickInfoModel(position, Providers);
return model;
}
protected override bool RequestSession(IEditorView view, object context)
{
if (context is not QuickInfoModel model)
return false;
var text = model.SemanticModel.SyntaxTree.Text;
var textSnapshotRange = text.ToSnapshotRange(model.Span);
var textRange = textSnapshotRange.TextRange;
var content = SymbolContentProvider.GetContentProvider(model.Glyph, model.Markup).GetContent();
var quickInfoSession = new QuickInfoSession();
quickInfoSession.Context = context;
quickInfoSession.Content = content;
quickInfoSession.Open(view, textRange);
return true;
}
protected override IEnumerable<Type> ContextTypes
{
get { return new[] { typeof(QuickInfoModel) }; }
}
}
} | mit |
BedrockDev/Sunrin2017 | Software/Game Programming/Codes/ConsoleApplication5/ConsoleApplication5/ConstPointer.cpp | 468 | #include <iostream>
using namespace std;
void display(const int *xPos, const int *yPos);
void move(int *xPos, int *yPos);
int main(void) {
int x = 10;
int y = 20;
display(&x, &y);
move(&x, &y);
display(&x, &y);
return 0;
}
void display(const int *xPos, const int *yPos) {
// btw const not needed for this
cout << "Current position [" << *xPos << ", " << *yPos << "]" << endl;
}
void move(int *xPos, int *yPos) {
*xPos = *xPos + 1;
*yPos = *yPos + 1;
} | mit |
yuweijun/yuweijun.github.io | manpages/man1/true.1.html | 2980 | <!DOCTYPE html>
<HTML><head><TITLE>Manpage of TRUE</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">
</head>
<body>
<header class="site-header">
<div class="wrap"> <div class="site-title"><a href="/manpages/index.html">linux manpages</a></div>
<div class="site-description">{"type":"documentation"}</div>
</div>
</header>
<div class="page-content"><div class="wrap">
<H1>TRUE</H1>
Section: User Commands (1)<BR>Updated: June 2012<BR><A HREF="#index">Index</A>
<A HREF="/manpages/index.html">Return to Main Contents</A><HR>
<A NAME="lbAB"> </A>
<H2>NAME</H2>
true - do nothing, successfully
<A NAME="lbAC"> </A>
<H2>SYNOPSIS</H2>
<B>true</B>
[<I>ignored command line arguments</I>]
<BR>
<B>true</B>
<I>OPTION</I>
<A NAME="lbAD"> </A>
<H2>DESCRIPTION</H2>
<P>
Exit with a status code indicating success.
<DL COMPACT>
<DT><B>--help</B><DD>
display this help and exit
<DT><B>--version</B><DD>
output version information and exit
</DL>
<P>
NOTE: your shell may have its own version of true, which usually supersedes
the version described here. Please refer to your shell's documentation
for details about the options it supports.
<A NAME="lbAE"> </A>
<H2>AUTHOR</H2>
Written by Jim Meyering.
<A NAME="lbAF"> </A>
<H2>REPORTING BUGS</H2>
Report true bugs to <A HREF="mailto:[email protected]">[email protected]</A>
<BR>
GNU coreutils home page: <<A HREF="http://www.gnu.org/software/coreutils/">http://www.gnu.org/software/coreutils/</A>>
<BR>
General help using GNU software: <<A HREF="http://www.gnu.org/gethelp/">http://www.gnu.org/gethelp/</A>>
<BR>
Report true translation bugs to <<A HREF="http://translationproject.org/team/">http://translationproject.org/team/</A>>
<A NAME="lbAG"> </A>
<H2>COPYRIGHT</H2>
Copyright © 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <<A HREF="http://gnu.org/licenses/gpl.html">http://gnu.org/licenses/gpl.html</A>>.
<BR>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
<A NAME="lbAH"> </A>
<H2>SEE ALSO</H2>
The full documentation for
<B>true</B>
is maintained as a Texinfo manual. If the
<B>info</B>
and
<B>true</B>
programs are properly installed at your site, the command
<DL COMPACT>
<DT><DD>
<B>info coreutils aqtrue invocationaq</B>
</DL>
<P>
should give you access to the complete manual.
<P>
<HR>
<A NAME="index"> </A><H2>Index</H2>
<DL>
<DT><A HREF="#lbAB">NAME</A><DD>
<DT><A HREF="#lbAC">SYNOPSIS</A><DD>
<DT><A HREF="#lbAD">DESCRIPTION</A><DD>
<DT><A HREF="#lbAE">AUTHOR</A><DD>
<DT><A HREF="#lbAF">REPORTING BUGS</A><DD>
<DT><A HREF="#lbAG">COPYRIGHT</A><DD>
<DT><A HREF="#lbAH">SEE ALSO</A><DD>
</DL>
<HR>
This document was created by
<A HREF="/manpages/index.html">man2html</A>,
using the manual pages.<BR>
Time: 05:29:11 GMT, December 24, 2015
</div></div>
</body>
</HTML>
| mit |
ichylinux/chat | app/models/room.rb | 114 | class Room < ActiveRecord::Base
validates :name, :presence => true
has_many :users
has_many :room_logs
end
| mit |
Ljzn/ljzn.github.io | _site/lrthw/2016/07/04/lrhw-43.html | 23201 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/static/img/ruby.ico" />
<title>43基本的面向对象分析和设计 - LJZN</title>
<meta name="author" content="LJZN" />
<meta name="description" content="43基本的面向对象分析和设计" />
<meta name="keywords" content="43基本的面向对象分析和设计, LJZN, LRTHW" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/static/css/syntax.css">
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
<div class="container">
<div class="col-sm-3">
<a href="/"><img id="about" src="/static/img/ruby.png" height="75px" width="75px" /></a>
<h1 class="author-name">LJZN</h1>
<div id="about">
每天更新Rails练习项目到Github~
</div>
<hr size=2>
» <a href="/">Home</a> <br />
» <a href="/category/original">Category</a> <br />
» <a class="about" href="/about/">About Me</a><br />
» <a class="about" href="https://github.com/ljzn">Github</a><br />
</div>
<div class="col-sm-8 col-offset-1">
<h1>43基本的面向对象分析和设计</h1>
<span class="time">04 Jul 2016</span>
<span class="categories">
» <a href="/category/LRTHW">LRTHW</a>
</span>
<div class="content">
<div class="post">
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"This scene is not yet configured. Subclass it and implement enter()."</span>
<span class="nb">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">Engine</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">scene_map</span><span class="p">)</span>
<span class="vi">@scene_map</span> <span class="o">=</span> <span class="n">scene_map</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">play</span><span class="p">()</span>
<span class="n">current_scene</span> <span class="o">=</span> <span class="vi">@scene_map</span><span class="p">.</span><span class="nf">opening_scene</span><span class="p">()</span>
<span class="n">last_scene</span> <span class="o">=</span> <span class="vi">@scene_map</span><span class="p">.</span><span class="nf">next_scene</span><span class="p">(</span><span class="s1">'finished'</span><span class="p">)</span>
<span class="k">while</span> <span class="n">current_scene</span> <span class="o">!=</span> <span class="n">last_scene</span>
<span class="n">next_scene_name</span> <span class="o">=</span> <span class="n">current_scene</span><span class="p">.</span><span class="nf">enter</span><span class="p">()</span>
<span class="n">current_scene</span> <span class="o">=</span> <span class="vi">@scene_map</span><span class="p">.</span><span class="nf">next_scene</span><span class="p">(</span><span class="n">next_scene_name</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># be sure to print out the last scene</span>
<span class="n">current_scene</span><span class="p">.</span><span class="nf">enter</span><span class="p">()</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">Death</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="vc">@@quips</span> <span class="o">=</span> <span class="p">[</span>
<span class="s2">"You died. You kinda suck at this."</span><span class="p">,</span>
<span class="s2">"Your mom would be proud...if she were smarter."</span><span class="p">,</span>
<span class="s2">"Suck a luser."</span><span class="p">,</span>
<span class="s2">"I have a small puppy that's better at this."</span><span class="p">,</span>
<span class="p">]</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="vc">@@quips</span><span class="p">[</span><span class="nb">rand</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="nf">.</span><span class="p">(</span><span class="vc">@@quips</span><span class="p">.</span><span class="nf">length</span> <span class="o">-</span> <span class="mi">1</span><span class="p">))]</span>
<span class="nb">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">CentralCorridor</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"'Hello!' A red dog says,"</span>
<span class="nb">puts</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="s2">"'What are you doing here?'</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">print</span> <span class="s2">"> "</span>
<span class="n">action</span> <span class="o">=</span> <span class="vg">$stdin</span><span class="p">.</span><span class="nf">gets</span><span class="p">.</span><span class="nf">chomp</span>
<span class="k">if</span> <span class="n">action</span> <span class="o">==</span> <span class="s2">"shoot!"</span>
<span class="nb">puts</span> <span class="s2">"The dog avoid the bullet."</span>
<span class="nb">puts</span> <span class="s2">"And shoot you with his eye."</span>
<span class="nb">puts</span> <span class="s2">"You dead."</span>
<span class="k">return</span> <span class="s1">'death'</span>
<span class="k">elsif</span> <span class="n">action</span> <span class="o">==</span> <span class="s2">"tell a joke"</span>
<span class="nb">puts</span> <span class="s2">"You say:'Catch the ball!'"</span>
<span class="nb">puts</span> <span class="s2">"The dog run away."</span>
<span class="k">return</span> <span class="s1">'laser_weapon_armory'</span>
<span class="k">else</span>
<span class="nb">puts</span> <span class="s2">"The dog says:'Get out!'"</span>
<span class="k">return</span> <span class="s1">'central_corridor'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">LaserWeaponArmory</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"enter 1 numbers:"</span>
<span class="n">code</span> <span class="o">=</span> <span class="s2">"</span><span class="si">#{</span><span class="nb">rand</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">.</span><span class="mi">9</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span>
<span class="nb">print</span> <span class="s2">"[keypad]> "</span>
<span class="n">guess</span> <span class="o">=</span> <span class="vg">$stdin</span><span class="p">.</span><span class="nf">gets</span><span class="p">.</span><span class="nf">chomp</span>
<span class="n">guesses</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">while</span> <span class="n">guess</span> <span class="o">!=</span> <span class="n">code</span> <span class="o">&&</span> <span class="n">guesses</span> <span class="o"><</span> <span class="mi">5</span>
<span class="nb">puts</span> <span class="s2">"Wrong!"</span>
<span class="n">guesses</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="nb">print</span> <span class="s2">"[keypad]> "</span>
<span class="n">guess</span> <span class="o">=</span> <span class="vg">$stdin</span><span class="p">.</span><span class="nf">gets</span><span class="p">.</span><span class="nf">chomp</span>
<span class="k">end</span>
<span class="k">if</span> <span class="n">guess</span> <span class="o">==</span> <span class="n">code</span>
<span class="nb">puts</span> <span class="s2">"The door open."</span>
<span class="nb">puts</span> <span class="s2">"You see a bridge."</span>
<span class="k">return</span> <span class="s1">'the_bridge'</span>
<span class="k">else</span>
<span class="nb">puts</span> <span class="s2">"Huge fire out from the door!</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="s2">"You die."</span>
<span class="k">return</span> <span class="s1">'death'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">TheBridge</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"A large potato lies on the road.</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="s2">"How you go through?</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">print</span> <span class="s2">"> "</span>
<span class="n">action</span> <span class="o">=</span> <span class="vg">$stdin</span><span class="p">.</span><span class="nf">gets</span><span class="p">.</span><span class="nf">chomp</span>
<span class="k">if</span> <span class="n">action</span> <span class="o">==</span> <span class="s2">"throw the bomb"</span>
<span class="nb">puts</span> <span class="s2">"The potato explode and the piece hit you."</span>
<span class="k">return</span> <span class="s1">'death'</span>
<span class="k">elsif</span> <span class="n">action</span> <span class="o">==</span> <span class="s2">"slowly place the bomb"</span>
<span class="nb">puts</span> <span class="s2">"You placed the bomb and run away."</span>
<span class="nb">puts</span> <span class="s2">"You successfully sweep out the potato."</span>
<span class="k">return</span> <span class="s1">'escape_pod'</span>
<span class="k">else</span>
<span class="nb">puts</span> <span class="s2">"Nothing happened."</span>
<span class="k">return</span> <span class="s2">"the_bridge"</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">EscapePod</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"There are 5 pods."</span>
<span class="n">good_pod</span> <span class="o">=</span> <span class="nb">rand</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="nf">.</span><span class="mi">5</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">"[pod #]> "</span>
<span class="n">guess</span> <span class="o">=</span> <span class="vg">$stdin</span><span class="p">.</span><span class="nf">gets</span><span class="p">.</span><span class="nf">chomp</span><span class="p">.</span><span class="nf">to_i</span>
<span class="k">if</span> <span class="n">guess</span> <span class="o">!=</span> <span class="n">good_pod</span>
<span class="nb">puts</span> <span class="s2">"Nothing happened.</span><span class="se">\n</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="s2">"10 days passed, you dead."</span>
<span class="k">return</span> <span class="s1">'death'</span>
<span class="k">else</span>
<span class="nb">puts</span> <span class="s2">"win!"</span>
<span class="k">return</span> <span class="s1">'finished'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">Finished</span> <span class="o"><</span> <span class="no">Scene</span>
<span class="k">def</span> <span class="nf">enter</span><span class="p">()</span>
<span class="nb">puts</span> <span class="s2">"Good job!"</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">class</span> <span class="nc">Map</span>
<span class="vc">@@scenes</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'central_corridor'</span> <span class="o">=></span> <span class="no">CentralCorridor</span><span class="p">.</span><span class="nf">new</span><span class="p">(),</span>
<span class="s1">'laser_weapon_armory'</span> <span class="o">=></span> <span class="no">LaserWeaponArmory</span><span class="p">.</span><span class="nf">new</span><span class="p">(),</span>
<span class="s1">'the_bridge'</span> <span class="o">=></span> <span class="no">TheBridge</span><span class="p">.</span><span class="nf">new</span><span class="p">(),</span>
<span class="s1">'escape_pod'</span> <span class="o">=></span> <span class="no">EscapePod</span><span class="p">.</span><span class="nf">new</span><span class="p">(),</span>
<span class="s1">'death'</span> <span class="o">=></span> <span class="no">Death</span><span class="p">.</span><span class="nf">new</span><span class="p">(),</span>
<span class="p">}</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">start_scene</span><span class="p">)</span>
<span class="vi">@start_scene</span> <span class="o">=</span> <span class="n">start_scene</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">next_scene</span><span class="p">(</span><span class="n">scene_name</span><span class="p">)</span>
<span class="n">val</span> <span class="o">=</span> <span class="vc">@@scenes</span><span class="p">[</span><span class="n">scene_name</span><span class="p">]</span>
<span class="k">return</span> <span class="n">val</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">opening_scene</span><span class="p">()</span>
<span class="k">return</span> <span class="n">next_scene</span><span class="p">(</span><span class="vi">@start_scene</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">a_map</span> <span class="o">=</span> <span class="no">Map</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'central_corridor'</span><span class="p">)</span>
<span class="n">a_game</span> <span class="o">=</span> <span class="no">Engine</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">a_map</span><span class="p">)</span>
<span class="n">a_game</span><span class="p">.</span><span class="nf">play</span><span class="p">()</span></code></pre></figure>
</div>
</div>
<div class="panel-body">
<h4>Related Posts</h4>
<ul>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/10/lrhw-50.html">50sinatra建造网站</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/09/lrhw-49.html">49创建句子</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-48.html">48进阶用户输入</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/08/lrhw-47.html">47自动化测试</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/06/lrhw-46.html">46项目骨架</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
<li class="relatedPost">
<a href="https://ljzn.github.io/lrthw/2016/07/05/lrhw-45.html">45制作一个游戏</a>
(Categories: <a href="/category/LRTHW">LRTHW</a>)
</li>
</ul>
</div>
<div class="PageNavigation">
<a class="prev" href="/lrthw/2016/07/03/lrhw-42.html">« 42对象、类及从属关系</a>
<a class="next" href="/lrthw/2016/07/04/lrhw-44.html">44继承与合成 »</a>
</div>
<div class="disqus-comments">
<div id="disqus_thread"></div>
<script>
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//ljzn.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</div>
<footer>
© LJZN
- <a href="https://github.com/ljzn">https://github.com/ljzn</a> - Powered by Jekyll.
</footer>
</div><!-- end /.col-sm-8 -->
</div><!-- end /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script id="dsq-count-scr" src="//ljzn.disqus.com/count.js" async></script>
</body>
</html>
| mit |
redbaron76/Bisiacaria.com | client/pages/friend_posts.js | 1141 | Template.friendPosts.onCreated(function() {
Bisia.Notification.resetNotify('note', 'post');
})
Template.friendPosts.helpers({
getPost: function(postId) {
var post = Posts.findOne(postId);
if (post) {
var user = Users.findOne({ '_id': post.authorId }, { 'fields': {
'username': 1,
'profile.city': 1,
'profile.gender': 1,
'profile.status': 1,
'profile.avatar': 1,
'profile.online': 1,
'profile.birthday': 1
}});
post.showHeader = true;
post.usern = user.username;
post.profile = user.profile;
return post;
}
},
detectFirstPage: function() {
var increment = Bisia.getController('increment');
var limit = Bisia.getController('params')['pageLimit'];
// Don't show spinner by default
var pageDisplay = true;
// If we are on the first page...
if (!limit || limit == increment) {
// pageDisplay becomes reactive
pageDisplay = this.pageReady;
}
// Add pageDisplay to this
return _.extend(this, {
pageDisplay: pageDisplay
});
}
});
Template.friendPosts.events({
'scroll .content': function(e, t) {
Bisia.Ui.toggleAtBottom(e, '#helpbars', 'bottom-show');
}
}); | mit |
pathephone/pathephone-desktop | src/renderer/sagas/startApp/startServices/startAlbumsSharingService.js | 680 | import { all, takeEvery } from 'redux-saga/effects';
import actions from '#actions';
import handleShareFormChange from './startAlbumsSharingService/handleShareFormChange';
import handleShareFormSubmit from './startAlbumsSharingService/handleShareFormSubmit';
import handleShareItemsSelect from './startAlbumsSharingService/handleShareItemsSelect';
function* startAlbumsSharingService(apis) {
yield all([
takeEvery(actions.uiShareItemsSelected, handleShareItemsSelect, apis),
takeEvery(actions.uiShareFormSubmited, handleShareFormSubmit, apis),
takeEvery(actions.uiShareFormChanged, handleShareFormChange, apis),
]);
}
export default startAlbumsSharingService;
| mit |
furti/mighty-quest-for-tux | parse-content.js | 3541 | var fs = require('fs'),
eol = require('eol'),
path = require('path'),
mkdirp = require('mkdirp'),
watch = require('watch');
var specialFiles = {
'welcome.md': function(fileContent, consoleContent) {
consoleContent.welcome = processFileContent(fileContent);
},
'config.json': function(fileContent, consoleContent) {
var config = JSON.parse(fileContent);
consoleContent.executables = config.executables;
consoleContent.__config = config;
}
};
function processFileContent(fileContent) {
fileContent = eol.lf(fileContent);
fileContent = new Buffer(fileContent).toString('base64');
return fileContent;
}
function createContentFile(fileName, fileContent) {
var parsed = path.parse(fileName);
return {
content: processFileContent(fileContent),
base: fileName,
name: parsed.name,
ext: parsed.ext
};
}
function hasExecutableForFile(executables, fileName) {
if (!executables) {
return false;
}
for (var i in executables) {
if (executables[i].file === fileName) {
return true;
}
}
return false;
}
function setFilePermissions(files, config) {
if (!files) {
return;
}
for (var fileName in files) {
var file = files[fileName];
if (!config.noRead || config.noRead.indexOf(file.base) === -1) {
file.readable = true;
}
if (config.writeable && config.writeable.indexOf(file.base) !== -1) {
file.writeable = true;
}
if (hasExecutableForFile(config.executables, file.base)) {
file.executable = true;
}
}
}
/**
* This badass here reads all files from the console folders and creates the content.json file.
*/
function createConsoleContent() {
var srcPath = './src/content';
var targetPath = './dist/content';
var consoleFolders = fs.readdirSync(srcPath);
if (!consoleFolders) {
return;
}
consoleFolders.forEach(function(folderName) {
var consoleSrcPath = srcPath + '/' + folderName;
var consoleTargetPath = targetPath + '/' + folderName;
var stats = fs.statSync(consoleSrcPath);
if (!stats.isDirectory()) {
return;
}
var files = fs.readdirSync(consoleSrcPath);
if (!files || files.length === 0) {
console.log('No files found for ' + consoleSrcPath);
} else {
console.log('Processing content ' + folderName);
var consoleContent = {
files: {}
};
files.forEach(function(file) {
var fileContent = fs.readFileSync(consoleSrcPath + '/' + file, 'utf8');
if (specialFiles[file]) {
specialFiles[file](fileContent, consoleContent);
} else {
consoleContent.files[file] = createContentFile(file, fileContent);
}
});
if (consoleContent.__config) {
setFilePermissions(consoleContent.files, consoleContent.__config);
delete consoleContent.__config;
}
mkdirp.sync(consoleTargetPath);
fs.writeFileSync(consoleTargetPath + '/content.json', JSON.stringify(consoleContent), 'utf8');
}
});
}
if (process.argv.indexOf('--watching') !== -1) {
watch.watchTree('./src/content', function() {
createConsoleContent();
});
}
else {
createConsoleContent();
} | mit |
tomasvdw/bitcrust | serde_json/travis.sh | 1072 | #!/bin/bash
set -e
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
channel() {
if [ -n "${TRAVIS}" ]; then
if [ "${TRAVIS_RUST_VERSION}" = "${CHANNEL}" ]; then
pwd
(set -x; cargo "$@")
fi
elif [ -n "${APPVEYOR}" ]; then
if [ "${APPVEYOR_RUST_CHANNEL}" = "${CHANNEL}" ]; then
pwd
(set -x; cargo "$@")
fi
else
pwd
(set -x; cargo "+${CHANNEL}" "$@")
fi
}
if [ -n "${CLIPPY}" ]; then
# cached installation will not work on a later nightly
if [ -n "${TRAVIS}" ] && ! cargo install clippy --debug --force; then
echo "COULD NOT COMPILE CLIPPY, IGNORING CLIPPY TESTS"
exit
fi
cargo clippy -- -Dclippy
else
CHANNEL=nightly
channel clean
channel build
(cd "$DIR/tests/deps" && channel build)
channel test
channel test --features preserve_order
for CHANNEL in stable 1.15.0 1.16.0 1.17.0 beta; do
channel clean
channel build
channel build --features preserve_order
done
fi
| mit |
STRVIRTU/tcc-2017 | less/disciplina.class.php | 960 | <?php
include_once('conexao.class.php');
class Disciplina{
public $id_disciplina;
public $nome;
public $professor;
public $curso;
public $carga_horaria;
public function __construct(){
//print "Disciplina instanciada!";
}
public function gravar(){
$sql = "insert into disciplina (nome, professor, curso, carga_horaria) values (?,?,?,?)";
$con = new Conexao();
$stm = $con->prepare($sql);
$stm->bindParam(1, $this->nome);
$stm->bindParam(2, $this->professor);
$stm->bindParam(3, $this->curso);
$stm->bindParam(4, $this->carga_horaria);
$stm->execute();
//echo "gravado";
}
public function __get($var){
return $this->$var;
}
public function __set($var, $valor){
$this->$var = $valor;
}
public function listar(){
$sql = "select * from disciplina";
$con = new Conexao();
$stm = $con->prepare($sql);
$stm->execute();
return $stm;
}
}
?> | mit |
tachyons-css/tachyons-css.github.io | src/components/layout/five-column-collapse-alternate.html | 449 | {{{
"bodyClass" : "bg-white",
"screenshot" : {
"background-size" : "contain"
}
}}}
<div class="cf">
<div class="fl w-50 w-20-ns tc pv5 bg-black-05">
1
</div>
<div class="fl w-50 w-20-ns tc pv5 bg-black-10">
2
</div>
<div class="fl w-100 w-20-ns tc pv5 bg-black-20">
3
</div>
<div class="fl w-50 w-20-ns tc pv5 bg-black-10">
4
</div>
<div class="fl w-50 w-20-ns tc pv5 bg-black-05">
5
</div>
</div>
| mit |
thejunkjon/jones | source/jones/controller/controller.cc | 6251 | //
// MIT License
//
// Copyright 2019
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "controller.hh"
#include "log.hh"
#include <boost/core/ignore_unused.hpp>
#include <boost/static_assert.hpp>
#include <map>
using namespace jones;
using button = jones::controller::button;
using button_state = jones::controller::button_state;
using button_state_map = std::map<button, button_state>;
namespace {
auto position_to_button(const uint8_t position) -> button {
switch (position) {
case 0:
return button::BUTTON_A;
case 1:
return button::BUTTON_B;
case 2:
return button::BUTTON_SELECT;
case 3:
return button::BUTTON_START;
case 4:
return button::BUTTON_UP;
case 5:
return button::BUTTON_DOWN;
case 6:
return button::BUTTON_LEFT;
case 7:
return button::BUTTON_RIGHT;
default:
BOOST_STATIC_ASSERT("unexpected button found");
return button::BUTTON_INVALID;
}
}
} // namespace
auto controller::button_to_string(const button button) -> auto {
switch (button) {
case button::BUTTON_A:
return "BUTTON_A";
case button::BUTTON_B:
return "BUTTON_B";
case button::BUTTON_SELECT:
return "BUTTON_SELECT";
case button::BUTTON_START:
return "BUTTON_START";
case button::BUTTON_UP:
return "BUTTON_UP";
case button::BUTTON_DOWN:
return "BUTTON_DOWN";
case button::BUTTON_LEFT:
return "BUTTON_LEFT";
case button::BUTTON_RIGHT:
return "BUTTON_RIGHT";
default:
return "BUTTON_INVALID";
}
}
auto controller::button_state_to_string(const button_state button_state) -> auto {
switch (button_state) {
case button_state::BUTTON_STATE_DOWN:
return "BUTTON_STATE_DOWN";
case button_state::BUTTON_STATE_UP:
return "BUTTON_STATE_UP";
default:
return "BUTTON_STATE_INVALID";
}
}
auto controller::controller_state_to_string(const controller_state controller_state) -> auto {
switch (controller_state) {
case controller_state::CONTROLLER_STATE_CONNECTED:
return "CONTROLLER_STATE_CONNECTED";
case controller_state::CONTROLLER_STATE_DISCONNECTED:
return "CONTROLLER_STATE_DISCONNECTED";
default:
return "CONTROLLER_STATE_INVALID";
}
}
class controller::controller::impl {
public:
explicit impl(const memory &memory)
: memory_(memory), strobe_(0), index_(0), button_states_(), controller_state_(controller_state::CONTROLLER_STATE_DISCONNECTED) {
boost::ignore_unused(memory_);
}
~impl() = default;
auto set_button_state(const button button, const button_state button_state) -> void {
button_states_[button] = button_state;
LOG_DEBUG << "controller::set_button_state : "
<< "button [" << button_to_string(button) << "] "
<< "button_state [" << button_state_to_string(button_state) << "]";
}
auto get_button_state(const button button) -> auto {
return button_states_[button];
}
auto set_controller_state(const controller_state controller_state) -> void {
controller_state_ = controller_state;
LOG_DEBUG << "controller::set_controller_state : "
<< "controller_state [" << controller_state_to_string(controller_state) << "]";
}
auto get_controller_state() -> auto {
return controller_state_;
}
auto peek(uint16_t const address) const -> uint8_t {
boost::ignore_unused(address);
uint8_t data = 0;
if (index_ < 8) {
auto const button_state = button_states_.find(position_to_button(index_));
if (button_state != button_states_.end() && button_state->second == button_state::BUTTON_STATE_DOWN) {
data = 1;
}
}
return data;
}
auto read(const uint16_t address) -> uint8_t {
auto const data = peek(address);
index_++;
update_button_index();
return data;
}
auto write(uint16_t const address, uint8_t const data) -> void {
boost::ignore_unused(address);
strobe_ = data;
update_button_index();
}
private:
auto update_button_index() -> void {
if ((strobe_ & 0x1U) == 1) {
index_ = 0;
}
}
private:
const memory &memory_;
uint8_t strobe_;
uint8_t index_;
button_state_map button_states_;
controller_state controller_state_;
};
controller::controller::controller(memory const &memory)
: impl_(std::make_unique<impl>(memory)) {
}
controller::controller::~controller() = default;
auto controller::controller::set_button_state(button const button, button_state const state) -> void {
impl_->set_button_state(button, state);
}
auto controller::controller::get_button_state(button const button) const -> button_state {
return impl_->get_button_state(button);
}
auto controller::controller::set_controller_state(controller_state const state) -> void {
impl_->set_controller_state(state);
}
auto controller::controller::get_controller_state() const -> controller_state {
return impl_->get_controller_state();
}
auto controller::controller::peek(uint16_t const address) const -> uint8_t {
return impl_->peek(address);
}
auto controller::controller::read(uint16_t const address) const -> uint8_t {
return impl_->read(address);
}
auto controller::controller::write(uint16_t const address, uint8_t const data) -> void {
impl_->write(address, data);
}
| mit |
siwl/test_website | app/templates/student/edit_student.html | 296 | {% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky - Edit Teacher Profile{% endblock %}
{% block side_content %}
<div class="page-header">
<h1>Edit Student's Info</h1>
</div>
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
{% endblock %} | mit |
clair-design/clair | packages/icons/icons/Camera.ts | 359 | export const Camera = `
<svg viewBox="0 0 28 28">
<g fill="none" fill-rule="evenodd">
<path d="M3 3h22a2 2 0 012 2v18a2 2 0 01-2 2H3a2 2 0 01-2-2V5a2 2 0 012-2z" stroke="currentColor"/>
<circle stroke="currentColor" cx="14" cy="14" r="5"/>
<path d="M22 7h1" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>`;
| mit |
b1thunt3r/BitForm | README.md | 80 | # BitForm
Playing around with the idea of replacing XForms with Custom Property. | mit |
slava-sh/NewsBlur | apps/reader/views.py | 95205 | import datetime
import time
import boto
import redis
import requests
import random
import zlib
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.db import IntegrityError
from django.db.models import Q
from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from django.contrib.auth import login as login_user
from django.contrib.auth import logout as logout_user
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
from django.conf import settings
from django.core.mail import mail_admins
from django.core.validators import email_re
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.models import Site
from django.utils import feedgenerator
from mongoengine.queryset import OperationError
from mongoengine.queryset import NotUniqueError
from apps.recommendations.models import RecommendedFeed
from apps.analyzer.models import MClassifierTitle, MClassifierAuthor, MClassifierFeed, MClassifierTag
from apps.analyzer.models import apply_classifier_titles, apply_classifier_feeds
from apps.analyzer.models import apply_classifier_authors, apply_classifier_tags
from apps.analyzer.models import get_classifiers_for_user, sort_classifiers_by_feed
from apps.profile.models import Profile
from apps.reader.models import UserSubscription, UserSubscriptionFolders, RUserStory, Feature
from apps.reader.forms import SignupForm, LoginForm, FeatureForm
from apps.rss_feeds.models import MFeedIcon, MStarredStoryCounts
from apps.search.models import MUserSearch
from apps.statistics.models import MStatistics
# from apps.search.models import SearchStarredStory
try:
from apps.rss_feeds.models import Feed, MFeedPage, DuplicateFeed, MStory, MStarredStory
except:
pass
from apps.social.models import MSharedStory, MSocialProfile, MSocialServices
from apps.social.models import MSocialSubscription, MActivity, MInteraction
from apps.categories.models import MCategory
from apps.social.views import load_social_page
from apps.rss_feeds.tasks import ScheduleImmediateFetches
from utils import json_functions as json
from utils.user_functions import get_user, ajax_login_required
from utils.feed_functions import relative_timesince
from utils.story_functions import format_story_link_date__short
from utils.story_functions import format_story_link_date__long
from utils.story_functions import strip_tags
from utils import log as logging
from utils.view_functions import get_argument_or_404, render_to, is_true
from utils.view_functions import required_params
from utils.ratelimit import ratelimit
from vendor.timezones.utilities import localtime_for_timezone
BANNED_URLS = [
"brentozar.com",
]
@never_cache
@render_to('reader/dashboard.xhtml')
def index(request, **kwargs):
if request.method == "GET" and request.subdomain and request.subdomain not in ['dev', 'www', 'debug']:
username = request.subdomain
try:
if '.' in username:
username = username.split('.')[0]
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
return HttpResponseRedirect('http://%s%s' % (
Site.objects.get_current().domain,
reverse('index')))
return load_social_page(request, user_id=user.pk, username=request.subdomain, **kwargs)
if request.user.is_anonymous():
return welcome(request, **kwargs)
else:
return dashboard(request, **kwargs)
def dashboard(request, **kwargs):
user = request.user
feed_count = UserSubscription.objects.filter(user=request.user).count()
recommended_feeds = RecommendedFeed.objects.filter(is_public=True,
approved_date__lte=datetime.datetime.now()
).select_related('feed')[:2]
unmoderated_feeds = []
if user.is_staff:
unmoderated_feeds = RecommendedFeed.objects.filter(is_public=False,
declined_date__isnull=True
).select_related('feed')[:2]
statistics = MStatistics.all()
social_profile = MSocialProfile.get_user(user.pk)
start_import_from_google_reader = request.session.get('import_from_google_reader', False)
if start_import_from_google_reader:
del request.session['import_from_google_reader']
if not user.is_active:
url = "https://%s%s" % (Site.objects.get_current().domain,
reverse('stripe-form'))
return HttpResponseRedirect(url)
logging.user(request, "~FBLoading dashboard")
return {
'user_profile' : user.profile,
'feed_count' : feed_count,
'account_images' : range(1, 4),
'recommended_feeds' : recommended_feeds,
'unmoderated_feeds' : unmoderated_feeds,
'statistics' : statistics,
'social_profile' : social_profile,
'start_import_from_google_reader': start_import_from_google_reader,
'debug' : settings.DEBUG,
}, "reader/dashboard.xhtml"
def welcome(request, **kwargs):
user = get_user(request)
statistics = MStatistics.all()
social_profile = MSocialProfile.get_user(user.pk)
if request.method == "POST":
if request.POST.get('submit', '').startswith('log'):
login_form = LoginForm(request.POST, prefix='login')
signup_form = SignupForm(prefix='signup')
else:
login_form = LoginForm(prefix='login')
signup_form = SignupForm(request.POST, prefix='signup')
else:
login_form = LoginForm(prefix='login')
signup_form = SignupForm(prefix='signup')
logging.user(request, "~FBLoading welcome")
return {
'user_profile' : hasattr(user, 'profile') and user.profile,
'login_form' : login_form,
'signup_form' : signup_form,
'statistics' : statistics,
'social_profile' : social_profile,
'post_request' : request.method == 'POST',
}, "reader/welcome.xhtml"
@never_cache
def login(request):
code = -1
message = ""
if request.method == "POST":
form = LoginForm(request.POST, prefix='login')
if form.is_valid():
login_user(request, form.get_user())
if request.POST.get('api'):
logging.user(form.get_user(), "~FG~BB~SKiPhone Login~FW")
code = 1
else:
logging.user(form.get_user(), "~FG~BBLogin~FW")
return HttpResponseRedirect(reverse('index'))
else:
message = form.errors.items()[0][1][0]
if request.POST.get('api'):
return HttpResponse(json.encode(dict(code=code, message=message)), mimetype='application/json')
else:
return index(request)
@never_cache
def signup(request):
if request.method == "POST":
form = SignupForm(prefix='signup', data=request.POST)
if form.is_valid():
new_user = form.save()
login_user(request, new_user)
logging.user(new_user, "~FG~SB~BBNEW SIGNUP: ~FW%s" % new_user.email)
if not new_user.is_active:
url = "https://%s%s" % (Site.objects.get_current().domain,
reverse('stripe-form'))
return HttpResponseRedirect(url)
return index(request)
@never_cache
def logout(request):
logging.user(request, "~FG~BBLogout~FW")
logout_user(request)
if request.GET.get('api'):
return HttpResponse(json.encode(dict(code=1)), mimetype='application/json')
else:
return HttpResponseRedirect(reverse('index'))
def autologin(request, username, secret):
next = request.GET.get('next', '')
if not username or not secret:
return HttpResponseForbidden()
profile = Profile.objects.filter(user__username=username, secret_token=secret)
if not profile:
return HttpResponseForbidden()
user = profile[0].user
user.backend = settings.AUTHENTICATION_BACKENDS[0]
login_user(request, user)
logging.user(user, "~FG~BB~SKAuto-Login. Next stop: %s~FW" % (next if next else 'Homepage',))
if next and not next.startswith('/'):
next = '?next=' + next
return HttpResponseRedirect(reverse('index') + next)
elif next:
return HttpResponseRedirect(next)
else:
return HttpResponseRedirect(reverse('index'))
@ratelimit(minutes=1, requests=24)
@never_cache
@json.json_view
def load_feeds(request):
user = get_user(request)
feeds = {}
include_favicons = request.REQUEST.get('include_favicons', False)
flat = request.REQUEST.get('flat', False)
update_counts = request.REQUEST.get('update_counts', False)
version = int(request.REQUEST.get('v', 1))
if include_favicons == 'false': include_favicons = False
if update_counts == 'false': update_counts = False
if flat == 'false': flat = False
if flat: return load_feeds_flat(request)
try:
folders = UserSubscriptionFolders.objects.get(user=user)
except UserSubscriptionFolders.DoesNotExist:
data = dict(feeds=[], folders=[])
return data
except UserSubscriptionFolders.MultipleObjectsReturned:
UserSubscriptionFolders.objects.filter(user=user)[1:].delete()
folders = UserSubscriptionFolders.objects.get(user=user)
user_subs = UserSubscription.objects.select_related('feed').filter(user=user)
day_ago = datetime.datetime.now() - datetime.timedelta(days=1)
scheduled_feeds = []
for sub in user_subs:
pk = sub.feed_id
if update_counts and sub.needs_unread_recalc:
sub.calculate_feed_scores(silent=True)
feeds[pk] = sub.canonical(include_favicon=include_favicons)
if not sub.active: continue
if not sub.feed.active and not sub.feed.has_feed_exception:
scheduled_feeds.append(sub.feed.pk)
elif sub.feed.active_subscribers <= 0:
scheduled_feeds.append(sub.feed.pk)
elif sub.feed.next_scheduled_update < day_ago:
scheduled_feeds.append(sub.feed.pk)
if len(scheduled_feeds) > 0 and request.user.is_authenticated():
logging.user(request, "~SN~FMTasking the scheduling immediate fetch of ~SB%s~SN feeds..." %
len(scheduled_feeds))
ScheduleImmediateFetches.apply_async(kwargs=dict(feed_ids=scheduled_feeds, user_id=user.pk))
starred_counts, starred_count = MStarredStoryCounts.user_counts(user.pk, include_total=True)
if not starred_count and len(starred_counts):
starred_count = MStarredStory.objects(user_id=user.pk).count()
social_params = {
'user_id': user.pk,
'include_favicon': include_favicons,
'update_counts': update_counts,
}
social_feeds = MSocialSubscription.feeds(**social_params)
social_profile = MSocialProfile.profile(user.pk)
social_services = MSocialServices.profile(user.pk)
categories = None
if not user_subs:
categories = MCategory.serialize()
logging.user(request, "~FB~SBLoading ~FY%s~FB/~FM%s~FB feeds/socials%s" % (
len(feeds.keys()), len(social_feeds), '. ~FCUpdating counts.' if update_counts else ''))
data = {
'feeds': feeds.values() if version == 2 else feeds,
'social_feeds': social_feeds,
'social_profile': social_profile,
'social_services': social_services,
'user_profile': user.profile,
"is_staff": user.is_staff,
'folders': json.decode(folders.folders),
'starred_count': starred_count,
'starred_counts': starred_counts,
'categories': categories
}
return data
@json.json_view
def load_feed_favicons(request):
user = get_user(request)
feed_ids = request.REQUEST.getlist('feed_ids')
if not feed_ids:
user_subs = UserSubscription.objects.select_related('feed').filter(user=user, active=True)
feed_ids = [sub['feed__pk'] for sub in user_subs.values('feed__pk')]
feed_icons = dict([(i.feed_id, i.data) for i in MFeedIcon.objects(feed_id__in=feed_ids)])
return feed_icons
def load_feeds_flat(request):
user = request.user
include_favicons = is_true(request.REQUEST.get('include_favicons', False))
update_counts = is_true(request.REQUEST.get('update_counts', True))
feeds = {}
day_ago = datetime.datetime.now() - datetime.timedelta(days=1)
scheduled_feeds = []
iphone_version = "2.1"
if include_favicons == 'false': include_favicons = False
if update_counts == 'false': update_counts = False
if not user.is_authenticated():
return HttpResponseForbidden()
try:
folders = UserSubscriptionFolders.objects.get(user=user)
except UserSubscriptionFolders.DoesNotExist:
folders = []
user_subs = UserSubscription.objects.select_related('feed').filter(user=user, active=True)
if not user_subs and folders:
folders.auto_activate()
user_subs = UserSubscription.objects.select_related('feed').filter(user=user, active=True)
for sub in user_subs:
if update_counts and sub.needs_unread_recalc:
sub.calculate_feed_scores(silent=True)
feeds[sub.feed_id] = sub.canonical(include_favicon=include_favicons)
if not sub.feed.active and not sub.feed.has_feed_exception:
scheduled_feeds.append(sub.feed.pk)
elif sub.feed.active_subscribers <= 0:
scheduled_feeds.append(sub.feed.pk)
elif sub.feed.next_scheduled_update < day_ago:
scheduled_feeds.append(sub.feed.pk)
if len(scheduled_feeds) > 0 and request.user.is_authenticated():
logging.user(request, "~SN~FMTasking the scheduling immediate fetch of ~SB%s~SN feeds..." %
len(scheduled_feeds))
ScheduleImmediateFetches.apply_async(kwargs=dict(feed_ids=scheduled_feeds, user_id=user.pk))
flat_folders = []
if folders:
flat_folders = folders.flatten_folders(feeds=feeds)
social_params = {
'user_id': user.pk,
'include_favicon': include_favicons,
'update_counts': update_counts,
}
social_feeds = MSocialSubscription.feeds(**social_params)
social_profile = MSocialProfile.profile(user.pk)
social_services = MSocialServices.profile(user.pk)
starred_counts, starred_count = MStarredStoryCounts.user_counts(user.pk, include_total=True)
if not starred_count and len(starred_counts):
starred_count = MStarredStory.objects(user_id=user.pk).count()
categories = None
if not user_subs:
categories = MCategory.serialize()
logging.user(request, "~FB~SBLoading ~FY%s~FB/~FM%s~FB feeds/socials ~FMflat~FB%s" % (
len(feeds.keys()), len(social_feeds), '. ~FCUpdating counts.' if update_counts else ''))
data = {
"flat_folders": flat_folders,
"feeds": feeds,
"social_feeds": social_feeds,
"social_profile": social_profile,
"social_services": social_services,
"user": user.username,
"is_staff": user.is_staff,
"user_profile": user.profile,
"iphone_version": iphone_version,
"categories": categories,
'starred_count': starred_count,
'starred_counts': starred_counts,
}
return data
@ratelimit(minutes=1, requests=10)
@never_cache
@json.json_view
def refresh_feeds(request):
user = get_user(request)
feed_ids = request.REQUEST.getlist('feed_id')
check_fetch_status = request.REQUEST.get('check_fetch_status')
favicons_fetching = request.REQUEST.getlist('favicons_fetching')
social_feed_ids = [feed_id for feed_id in feed_ids if 'social:' in feed_id]
feed_ids = list(set(feed_ids) - set(social_feed_ids))
feeds = {}
if feed_ids or (not social_feed_ids and not feed_ids):
feeds = UserSubscription.feeds_with_updated_counts(user, feed_ids=feed_ids,
check_fetch_status=check_fetch_status)
social_feeds = {}
if social_feed_ids or (not social_feed_ids and not feed_ids):
social_feeds = MSocialSubscription.feeds_with_updated_counts(user, social_feed_ids=social_feed_ids)
favicons_fetching = [int(f) for f in favicons_fetching if f]
feed_icons = {}
if favicons_fetching:
feed_icons = dict([(i.feed_id, i) for i in MFeedIcon.objects(feed_id__in=favicons_fetching)])
for feed_id, feed in feeds.items():
if feed_id in favicons_fetching and feed_id in feed_icons:
feeds[feed_id]['favicon'] = feed_icons[feed_id].data
feeds[feed_id]['favicon_color'] = feed_icons[feed_id].color
feeds[feed_id]['favicon_fetching'] = feed.get('favicon_fetching')
user_subs = UserSubscription.objects.filter(user=user, active=True).only('feed')
sub_feed_ids = [s.feed_id for s in user_subs]
if favicons_fetching:
moved_feed_ids = [f for f in favicons_fetching if f not in sub_feed_ids]
for moved_feed_id in moved_feed_ids:
duplicate_feeds = DuplicateFeed.objects.filter(duplicate_feed_id=moved_feed_id)
if duplicate_feeds and duplicate_feeds[0].feed.pk in feeds:
feeds[moved_feed_id] = feeds[duplicate_feeds[0].feed_id]
feeds[moved_feed_id]['dupe_feed_id'] = duplicate_feeds[0].feed_id
if check_fetch_status:
missing_feed_ids = list(set(feed_ids) - set(sub_feed_ids))
if missing_feed_ids:
duplicate_feeds = DuplicateFeed.objects.filter(duplicate_feed_id__in=missing_feed_ids)
for duplicate_feed in duplicate_feeds:
feeds[duplicate_feed.duplicate_feed_id] = {'id': duplicate_feed.feed_id}
interactions_count = MInteraction.user_unread_count(user.pk)
if True or settings.DEBUG or check_fetch_status:
logging.user(request, "~FBRefreshing %s feeds (%s/%s)" % (
len(feeds.keys()), check_fetch_status, len(favicons_fetching)))
return {
'feeds': feeds,
'social_feeds': social_feeds,
'interactions_count': interactions_count,
}
@json.json_view
def interactions_count(request):
user = get_user(request)
interactions_count = MInteraction.user_unread_count(user.pk)
return {
'interactions_count': interactions_count,
}
@never_cache
@ajax_login_required
@json.json_view
def feed_unread_count(request):
user = request.user
feed_ids = request.REQUEST.getlist('feed_id')
force = request.REQUEST.get('force', False)
social_feed_ids = [feed_id for feed_id in feed_ids if 'social:' in feed_id]
feed_ids = list(set(feed_ids) - set(social_feed_ids))
feeds = {}
if feed_ids:
feeds = UserSubscription.feeds_with_updated_counts(user, feed_ids=feed_ids, force=force)
social_feeds = {}
if social_feed_ids:
social_feeds = MSocialSubscription.feeds_with_updated_counts(user, social_feed_ids=social_feed_ids)
if len(feed_ids) == 1:
if settings.DEBUG:
feed_title = Feed.get_by_id(feed_ids[0]).feed_title
else:
feed_title = feed_ids[0]
elif len(social_feed_ids) == 1:
feed_title = MSocialProfile.objects.get(user_id=social_feed_ids[0].replace('social:', '')).username
else:
feed_title = "%s feeds" % (len(feeds) + len(social_feeds))
logging.user(request, "~FBUpdating unread count on: %s" % feed_title)
return {'feeds': feeds, 'social_feeds': social_feeds}
def refresh_feed(request, feed_id):
user = get_user(request)
feed = get_object_or_404(Feed, pk=feed_id)
feed = feed.update(force=True, compute_scores=False)
usersub = UserSubscription.objects.get(user=user, feed=feed)
usersub.calculate_feed_scores(silent=False)
logging.user(request, "~FBRefreshing feed: %s" % feed)
return load_single_feed(request, feed_id)
@never_cache
@json.json_view
def load_single_feed(request, feed_id):
start = time.time()
user = get_user(request)
# offset = int(request.REQUEST.get('offset', 0))
# limit = int(request.REQUEST.get('limit', 6))
limit = 6
page = int(request.REQUEST.get('page', 1))
offset = limit * (page-1)
order = request.REQUEST.get('order', 'newest')
read_filter = request.REQUEST.get('read_filter', 'all')
query = request.REQUEST.get('query')
include_story_content = is_true(request.REQUEST.get('include_story_content', True))
include_hidden = is_true(request.REQUEST.get('include_hidden', False))
message = None
user_search = None
dupe_feed_id = None
user_profiles = []
now = localtime_for_timezone(datetime.datetime.now(), user.profile.timezone)
if not feed_id: raise Http404
feed_address = request.REQUEST.get('feed_address')
feed = Feed.get_by_id(feed_id, feed_address=feed_address)
if not feed:
raise Http404
try:
usersub = UserSubscription.objects.get(user=user, feed=feed)
except UserSubscription.DoesNotExist:
usersub = None
if query:
if user.profile.is_premium:
user_search = MUserSearch.get_user(user.pk)
user_search.touch_search_date()
stories = feed.find_stories(query, order=order, offset=offset, limit=limit)
else:
stories = []
message = "You must be a premium subscriber to search."
elif read_filter == 'starred':
mstories = MStarredStory.objects(
user_id=user.pk,
story_feed_id=feed_id
).order_by('%sstarred_date' % ('-' if order == 'newest' else ''))[offset:offset+limit]
stories = Feed.format_stories(mstories)
elif usersub and (read_filter == 'unread' or order == 'oldest'):
stories = usersub.get_stories(order=order, read_filter=read_filter, offset=offset, limit=limit,
default_cutoff_date=user.profile.unread_cutoff)
else:
stories = feed.get_stories(offset, limit)
checkpoint1 = time.time()
try:
stories, user_profiles = MSharedStory.stories_with_comments_and_profiles(stories, user.pk)
except redis.ConnectionError:
logging.user(request, "~BR~FK~SBRedis is unavailable for shared stories.")
checkpoint2 = time.time()
# Get intelligence classifier for user
if usersub and usersub.is_trained:
classifier_feeds = list(MClassifierFeed.objects(user_id=user.pk, feed_id=feed_id, social_user_id=0))
classifier_authors = list(MClassifierAuthor.objects(user_id=user.pk, feed_id=feed_id))
classifier_titles = list(MClassifierTitle.objects(user_id=user.pk, feed_id=feed_id))
classifier_tags = list(MClassifierTag.objects(user_id=user.pk, feed_id=feed_id))
else:
classifier_feeds = []
classifier_authors = []
classifier_titles = []
classifier_tags = []
classifiers = get_classifiers_for_user(user, feed_id=feed_id,
classifier_feeds=classifier_feeds,
classifier_authors=classifier_authors,
classifier_titles=classifier_titles,
classifier_tags=classifier_tags)
checkpoint3 = time.time()
unread_story_hashes = []
if stories:
if (read_filter == 'all' or query) and usersub:
unread_story_hashes = UserSubscription.story_hashes(user.pk, read_filter='unread',
feed_ids=[usersub.feed_id],
usersubs=[usersub],
group_by_feed=False,
cutoff_date=user.profile.unread_cutoff)
story_hashes = [story['story_hash'] for story in stories if story['story_hash']]
starred_stories = MStarredStory.objects(user_id=user.pk,
story_feed_id=feed.pk,
story_hash__in=story_hashes)\
.only('story_hash', 'starred_date', 'user_tags')
shared_story_hashes = MSharedStory.check_shared_story_hashes(user.pk, story_hashes)
shared_stories = []
if shared_story_hashes:
shared_stories = MSharedStory.objects(user_id=user.pk,
story_hash__in=shared_story_hashes)\
.only('story_hash', 'shared_date', 'comments')
starred_stories = dict([(story.story_hash, dict(starred_date=story.starred_date,
user_tags=story.user_tags))
for story in starred_stories])
shared_stories = dict([(story.story_hash, dict(shared_date=story.shared_date,
comments=story.comments))
for story in shared_stories])
checkpoint4 = time.time()
for story in stories:
if not include_story_content:
del story['story_content']
story_date = localtime_for_timezone(story['story_date'], user.profile.timezone)
nowtz = localtime_for_timezone(now, user.profile.timezone)
story['short_parsed_date'] = format_story_link_date__short(story_date, nowtz)
story['long_parsed_date'] = format_story_link_date__long(story_date, nowtz)
if usersub:
story['read_status'] = 1
if (read_filter == 'all' or query) and usersub:
story['read_status'] = 1 if story['story_hash'] not in unread_story_hashes else 0
elif read_filter == 'unread' and usersub:
story['read_status'] = 0
if story['story_hash'] in starred_stories:
story['starred'] = True
starred_date = localtime_for_timezone(starred_stories[story['story_hash']]['starred_date'],
user.profile.timezone)
story['starred_date'] = format_story_link_date__long(starred_date, now)
story['starred_timestamp'] = starred_date.strftime('%s')
story['user_tags'] = starred_stories[story['story_hash']]['user_tags']
if story['story_hash'] in shared_stories:
story['shared'] = True
shared_date = localtime_for_timezone(shared_stories[story['story_hash']]['shared_date'],
user.profile.timezone)
story['shared_date'] = format_story_link_date__long(shared_date, now)
story['shared_comments'] = strip_tags(shared_stories[story['story_hash']]['comments'])
else:
story['read_status'] = 1
story['intelligence'] = {
'feed': apply_classifier_feeds(classifier_feeds, feed),
'author': apply_classifier_authors(classifier_authors, story),
'tags': apply_classifier_tags(classifier_tags, story),
'title': apply_classifier_titles(classifier_titles, story),
}
story['score'] = UserSubscription.score_story(story['intelligence'])
# Intelligence
feed_tags = json.decode(feed.data.popular_tags) if feed.data.popular_tags else []
feed_authors = json.decode(feed.data.popular_authors) if feed.data.popular_authors else []
if usersub:
usersub.feed_opens += 1
usersub.needs_unread_recalc = True
usersub.save(update_fields=['feed_opens', 'needs_unread_recalc'])
diff1 = checkpoint1-start
diff2 = checkpoint2-start
diff3 = checkpoint3-start
diff4 = checkpoint4-start
timediff = time.time()-start
last_update = relative_timesince(feed.last_update)
time_breakdown = ""
if timediff > 1 or settings.DEBUG:
time_breakdown = "~SN~FR(~SB%.4s/%.4s/%.4s/%.4s~SN)" % (
diff1, diff2, diff3, diff4)
search_log = "~SN~FG(~SB%s~SN) " % query if query else ""
logging.user(request, "~FYLoading feed: ~SB%s%s (%s/%s) %s%s" % (
feed.feed_title[:22], ('~SN/p%s' % page) if page > 1 else '', order, read_filter, search_log, time_breakdown))
if not include_hidden:
hidden_stories_removed = 0
new_stories = []
for story in stories:
if story['score'] >= 0:
new_stories.append(story)
else:
hidden_stories_removed += 1
stories = new_stories
data = dict(stories=stories,
user_profiles=user_profiles,
feed_tags=feed_tags,
feed_authors=feed_authors,
classifiers=classifiers,
updated=last_update,
user_search=user_search,
feed_id=feed.pk,
elapsed_time=round(float(timediff), 2),
message=message)
if not include_hidden: data['hidden_stories_removed'] = hidden_stories_removed
if dupe_feed_id: data['dupe_feed_id'] = dupe_feed_id
if not usersub:
data.update(feed.canonical())
# if not usersub and feed.num_subscribers <= 1:
# data = dict(code=-1, message="You must be subscribed to this feed.")
# if page <= 3:
# import random
# time.sleep(random.randint(2, 4))
# if page == 2:
# assert False
return data
def load_feed_page(request, feed_id):
if not feed_id:
raise Http404
feed = Feed.get_by_id(feed_id)
if feed and feed.has_page and not feed.has_page_exception:
if settings.BACKED_BY_AWS.get('pages_on_node'):
url = "http://%s/original_page/%s" % (
settings.ORIGINAL_PAGE_SERVER,
feed.pk,
)
page_response = requests.get(url)
if page_response.status_code == 200:
response = HttpResponse(page_response.content, mimetype="text/html; charset=utf-8")
response['Content-Encoding'] = 'gzip'
response['Last-Modified'] = page_response.headers.get('Last-modified')
response['Etag'] = page_response.headers.get('Etag')
response['Content-Length'] = str(len(page_response.content))
logging.user(request, "~FYLoading original page, proxied from node: ~SB%s bytes" %
(len(page_response.content)))
return response
if settings.BACKED_BY_AWS['pages_on_s3'] and feed.s3_page:
if settings.PROXY_S3_PAGES:
key = settings.S3_PAGES_BUCKET.get_key(feed.s3_pages_key)
if key:
compressed_data = key.get_contents_as_string()
response = HttpResponse(compressed_data, mimetype="text/html; charset=utf-8")
response['Content-Encoding'] = 'gzip'
logging.user(request, "~FYLoading original page, proxied: ~SB%s bytes" %
(len(compressed_data)))
return response
else:
logging.user(request, "~FYLoading original page, non-proxied")
return HttpResponseRedirect('//%s/%s' % (settings.S3_PAGES_BUCKET_NAME,
feed.s3_pages_key))
data = MFeedPage.get_data(feed_id=feed_id)
if not data or not feed or not feed.has_page or feed.has_page_exception:
logging.user(request, "~FYLoading original page, ~FRmissing")
return render(request, 'static/404_original_page.xhtml', {},
content_type='text/html',
status=404)
logging.user(request, "~FYLoading original page, from the db")
return HttpResponse(data, mimetype="text/html; charset=utf-8")
@json.json_view
def load_starred_stories(request):
user = get_user(request)
offset = int(request.REQUEST.get('offset', 0))
limit = int(request.REQUEST.get('limit', 10))
page = int(request.REQUEST.get('page', 0))
query = request.REQUEST.get('query')
order = request.REQUEST.get('order', 'newest')
tag = request.REQUEST.get('tag')
story_hashes = request.REQUEST.getlist('h')[:100]
version = int(request.REQUEST.get('v', 1))
now = localtime_for_timezone(datetime.datetime.now(), user.profile.timezone)
message = None
order_by = '-' if order == "newest" else ""
if page: offset = limit * (page - 1)
if query:
# results = SearchStarredStory.query(user.pk, query)
# story_ids = [result.db_id for result in results]
if user.profile.is_premium:
stories = MStarredStory.find_stories(query, user.pk, tag=tag, offset=offset, limit=limit,
order=order)
else:
stories = []
message = "You must be a premium subscriber to search."
elif tag:
if user.profile.is_premium:
mstories = MStarredStory.objects(
user_id=user.pk,
user_tags__contains=tag
).order_by('%sstarred_date' % order_by)[offset:offset+limit]
stories = Feed.format_stories(mstories)
else:
stories = []
message = "You must be a premium subscriber to read saved stories by tag."
elif story_hashes:
mstories = MStarredStory.objects(
user_id=user.pk,
story_hash__in=story_hashes
).order_by('%sstarred_date' % order_by)[offset:offset+limit]
stories = Feed.format_stories(mstories)
else:
mstories = MStarredStory.objects(
user_id=user.pk
).order_by('%sstarred_date' % order_by)[offset:offset+limit]
stories = Feed.format_stories(mstories)
stories, user_profiles = MSharedStory.stories_with_comments_and_profiles(stories, user.pk, check_all=True)
story_hashes = [story['story_hash'] for story in stories]
story_feed_ids = list(set(s['story_feed_id'] for s in stories))
usersub_ids = UserSubscription.objects.filter(user__pk=user.pk, feed__pk__in=story_feed_ids).values('feed__pk')
usersub_ids = [us['feed__pk'] for us in usersub_ids]
unsub_feed_ids = list(set(story_feed_ids).difference(set(usersub_ids)))
unsub_feeds = Feed.objects.filter(pk__in=unsub_feed_ids)
unsub_feeds = dict((feed.pk, feed.canonical(include_favicon=False)) for feed in unsub_feeds)
shared_story_hashes = MSharedStory.check_shared_story_hashes(user.pk, story_hashes)
shared_stories = []
if shared_story_hashes:
shared_stories = MSharedStory.objects(user_id=user.pk,
story_hash__in=shared_story_hashes)\
.only('story_hash', 'shared_date', 'comments')
shared_stories = dict([(story.story_hash, dict(shared_date=story.shared_date,
comments=story.comments))
for story in shared_stories])
nowtz = localtime_for_timezone(now, user.profile.timezone)
for story in stories:
story_date = localtime_for_timezone(story['story_date'], user.profile.timezone)
story['short_parsed_date'] = format_story_link_date__short(story_date, nowtz)
story['long_parsed_date'] = format_story_link_date__long(story_date, nowtz)
starred_date = localtime_for_timezone(story['starred_date'], user.profile.timezone)
story['starred_date'] = format_story_link_date__long(starred_date, nowtz)
story['starred_timestamp'] = starred_date.strftime('%s')
story['read_status'] = 1
story['starred'] = True
story['intelligence'] = {
'feed': 1,
'author': 0,
'tags': 0,
'title': 0,
}
if story['story_hash'] in shared_stories:
story['shared'] = True
story['shared_comments'] = strip_tags(shared_stories[story['story_hash']]['comments'])
search_log = "~SN~FG(~SB%s~SN)" % query if query else ""
logging.user(request, "~FCLoading starred stories: ~SB%s stories %s" % (len(stories), search_log))
return {
"stories": stories,
"user_profiles": user_profiles,
'feeds': unsub_feeds.values() if version == 2 else unsub_feeds,
"message": message,
}
@json.json_view
def starred_story_hashes(request):
user = get_user(request)
include_timestamps = is_true(request.REQUEST.get('include_timestamps', False))
mstories = MStarredStory.objects(
user_id=user.pk
).only('story_hash', 'starred_date').order_by('-starred_date')
if include_timestamps:
story_hashes = [(s.story_hash, s.starred_date.strftime("%s")) for s in mstories]
else:
story_hashes = [s.story_hash for s in mstories]
logging.user(request, "~FYLoading ~FCstarred story hashes~FY: %s story hashes" %
(len(story_hashes)))
return dict(starred_story_hashes=story_hashes)
def starred_stories_rss_feed(request, user_id, secret_token, tag_slug):
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
raise Http404
try:
tag_counts = MStarredStoryCounts.objects.get(user_id=user_id, slug=tag_slug)
except MStarredStoryCounts.MultipleObjectsReturned:
tag_counts = MStarredStoryCounts.objects(user_id=user_id, slug=tag_slug).first()
except MStarredStoryCounts.DoesNotExist:
raise Http404
data = {}
data['title'] = "Saved Stories - %s" % tag_counts.tag
data['link'] = "%s%s" % (
settings.NEWSBLUR_URL,
reverse('saved-stories-tag', kwargs=dict(tag_name=tag_slug)))
data['description'] = "Stories saved by %s on NewsBlur with the tag \"%s\"." % (user.username,
tag_counts.tag)
data['lastBuildDate'] = datetime.datetime.utcnow()
data['generator'] = 'NewsBlur - %s' % settings.NEWSBLUR_URL
data['docs'] = None
data['author_name'] = user.username
data['feed_url'] = "%s%s" % (
settings.NEWSBLUR_URL,
reverse('starred-stories-rss-feed',
kwargs=dict(user_id=user_id, secret_token=secret_token, tag_slug=tag_slug)),
)
rss = feedgenerator.Atom1Feed(**data)
if not tag_counts.tag:
starred_stories = MStarredStory.objects(
user_id=user.pk
).order_by('-starred_date').limit(25)
else:
starred_stories = MStarredStory.objects(
user_id=user.pk,
user_tags__contains=tag_counts.tag
).order_by('-starred_date').limit(25)
for starred_story in starred_stories:
story_data = {
'title': starred_story.story_title,
'link': starred_story.story_permalink,
'description': (starred_story.story_content_z and
zlib.decompress(starred_story.story_content_z)),
'author_name': starred_story.story_author_name,
'categories': starred_story.story_tags,
'unique_id': starred_story.story_guid,
'pubdate': starred_story.starred_date,
}
rss.add_item(**story_data)
logging.user(request, "~FBGenerating ~SB%s~SN's saved story RSS feed (%s, %s stories): ~FM%s" % (
user.username,
tag_counts.tag,
tag_counts.count,
request.META.get('HTTP_USER_AGENT', "")[:24]
))
return HttpResponse(rss.writeString('utf-8'), content_type='application/rss+xml')
@json.json_view
def load_read_stories(request):
user = get_user(request)
offset = int(request.REQUEST.get('offset', 0))
limit = int(request.REQUEST.get('limit', 10))
page = int(request.REQUEST.get('page', 0))
order = request.REQUEST.get('order', 'newest')
query = request.REQUEST.get('query')
now = localtime_for_timezone(datetime.datetime.now(), user.profile.timezone)
message = None
if page: offset = limit * (page - 1)
if query:
stories = []
message = "Not implemented yet."
# if user.profile.is_premium:
# stories = MStarredStory.find_stories(query, user.pk, offset=offset, limit=limit)
# else:
# stories = []
# message = "You must be a premium subscriber to search."
else:
story_hashes = RUserStory.get_read_stories(user.pk, offset=offset, limit=limit, order=order)
mstories = MStory.objects(story_hash__in=story_hashes)
stories = Feed.format_stories(mstories)
stories = sorted(stories, key=lambda story: story_hashes.index(story['story_hash']),
reverse=bool(order=="oldest"))
stories, user_profiles = MSharedStory.stories_with_comments_and_profiles(stories, user.pk, check_all=True)
story_hashes = [story['story_hash'] for story in stories]
story_feed_ids = list(set(s['story_feed_id'] for s in stories))
usersub_ids = UserSubscription.objects.filter(user__pk=user.pk, feed__pk__in=story_feed_ids).values('feed__pk')
usersub_ids = [us['feed__pk'] for us in usersub_ids]
unsub_feed_ids = list(set(story_feed_ids).difference(set(usersub_ids)))
unsub_feeds = Feed.objects.filter(pk__in=unsub_feed_ids)
unsub_feeds = [feed.canonical(include_favicon=False) for feed in unsub_feeds]
shared_stories = MSharedStory.objects(user_id=user.pk,
story_hash__in=story_hashes)\
.only('story_hash', 'shared_date', 'comments')
shared_stories = dict([(story.story_hash, dict(shared_date=story.shared_date,
comments=story.comments))
for story in shared_stories])
starred_stories = MStarredStory.objects(user_id=user.pk,
story_hash__in=story_hashes)\
.only('story_hash', 'starred_date')
starred_stories = dict([(story.story_hash, story.starred_date)
for story in starred_stories])
nowtz = localtime_for_timezone(now, user.profile.timezone)
for story in stories:
story_date = localtime_for_timezone(story['story_date'], user.profile.timezone)
story['short_parsed_date'] = format_story_link_date__short(story_date, nowtz)
story['long_parsed_date'] = format_story_link_date__long(story_date, nowtz)
story['read_status'] = 1
story['intelligence'] = {
'feed': 1,
'author': 0,
'tags': 0,
'title': 0,
}
if story['story_hash'] in starred_stories:
story['starred'] = True
starred_date = localtime_for_timezone(starred_stories[story['story_hash']],
user.profile.timezone)
story['starred_date'] = format_story_link_date__long(starred_date, now)
story['starred_timestamp'] = starred_date.strftime('%s')
if story['story_hash'] in shared_stories:
story['shared'] = True
story['shared_comments'] = strip_tags(shared_stories[story['story_hash']]['comments'])
search_log = "~SN~FG(~SB%s~SN)" % query if query else ""
logging.user(request, "~FCLoading read stories: ~SB%s stories %s" % (len(stories), search_log))
return {
"stories": stories,
"user_profiles": user_profiles,
"feeds": unsub_feeds,
"message": message,
}
@json.json_view
def load_river_stories__redis(request):
limit = 12
start = time.time()
user = get_user(request)
message = None
feed_ids = [int(feed_id) for feed_id in request.REQUEST.getlist('feeds') if feed_id]
if not feed_ids:
feed_ids = [int(feed_id) for feed_id in request.REQUEST.getlist('f') if feed_id]
story_hashes = request.REQUEST.getlist('h')[:100]
original_feed_ids = list(feed_ids)
page = int(request.REQUEST.get('page', 1))
order = request.REQUEST.get('order', 'newest')
read_filter = request.REQUEST.get('read_filter', 'unread')
query = request.REQUEST.get('query')
include_hidden = is_true(request.REQUEST.get('include_hidden', False))
now = localtime_for_timezone(datetime.datetime.now(), user.profile.timezone)
usersubs = []
code = 1
user_search = None
offset = (page-1) * limit
limit = page * limit
story_date_order = "%sstory_date" % ('' if order == 'oldest' else '-')
if story_hashes:
unread_feed_story_hashes = None
read_filter = 'unread'
mstories = MStory.objects(story_hash__in=story_hashes).order_by(story_date_order)
stories = Feed.format_stories(mstories)
elif query:
if user.profile.is_premium:
user_search = MUserSearch.get_user(user.pk)
user_search.touch_search_date()
usersubs = UserSubscription.subs_for_feeds(user.pk, feed_ids=feed_ids,
read_filter='all')
feed_ids = [sub.feed_id for sub in usersubs]
stories = Feed.find_feed_stories(feed_ids, query, order=order, offset=offset, limit=limit)
mstories = stories
unread_feed_story_hashes = UserSubscription.story_hashes(user.pk, feed_ids=feed_ids,
read_filter="unread", order=order,
group_by_feed=False,
cutoff_date=user.profile.unread_cutoff)
else:
stories = []
mstories = []
message = "You must be a premium subscriber to search."
elif read_filter == 'starred':
mstories = MStarredStory.objects(
user_id=user.pk,
story_feed_id__in=feed_ids
).order_by('%sstarred_date' % ('-' if order == 'newest' else ''))[offset:offset+limit]
stories = Feed.format_stories(mstories)
else:
usersubs = UserSubscription.subs_for_feeds(user.pk, feed_ids=feed_ids,
read_filter=read_filter)
all_feed_ids = [f for f in feed_ids]
feed_ids = [sub.feed_id for sub in usersubs]
if feed_ids:
params = {
"user_id": user.pk,
"feed_ids": feed_ids,
"all_feed_ids": all_feed_ids,
"offset": offset,
"limit": limit,
"order": order,
"read_filter": read_filter,
"usersubs": usersubs,
"cutoff_date": user.profile.unread_cutoff,
}
story_hashes, unread_feed_story_hashes = UserSubscription.feed_stories(**params)
else:
story_hashes = []
unread_feed_story_hashes = []
mstories = MStory.objects(story_hash__in=story_hashes).order_by(story_date_order)
stories = Feed.format_stories(mstories)
found_feed_ids = list(set([story['story_feed_id'] for story in stories]))
stories, user_profiles = MSharedStory.stories_with_comments_and_profiles(stories, user.pk)
if not usersubs:
usersubs = UserSubscription.subs_for_feeds(user.pk, feed_ids=found_feed_ids,
read_filter=read_filter)
trained_feed_ids = [sub.feed_id for sub in usersubs if sub.is_trained]
found_trained_feed_ids = list(set(trained_feed_ids) & set(found_feed_ids))
# Find starred stories
if found_feed_ids:
if read_filter == 'starred':
starred_stories = mstories
else:
starred_stories = MStarredStory.objects(
user_id=user.pk,
story_feed_id__in=found_feed_ids
).only('story_hash', 'starred_date')
starred_stories = dict([(story.story_hash, dict(starred_date=story.starred_date,
user_tags=story.user_tags))
for story in starred_stories])
else:
starred_stories = {}
# Intelligence classifiers for all feeds involved
if found_trained_feed_ids:
classifier_feeds = list(MClassifierFeed.objects(user_id=user.pk,
feed_id__in=found_trained_feed_ids,
social_user_id=0))
classifier_authors = list(MClassifierAuthor.objects(user_id=user.pk,
feed_id__in=found_trained_feed_ids))
classifier_titles = list(MClassifierTitle.objects(user_id=user.pk,
feed_id__in=found_trained_feed_ids))
classifier_tags = list(MClassifierTag.objects(user_id=user.pk,
feed_id__in=found_trained_feed_ids))
else:
classifier_feeds = []
classifier_authors = []
classifier_titles = []
classifier_tags = []
classifiers = sort_classifiers_by_feed(user=user, feed_ids=found_feed_ids,
classifier_feeds=classifier_feeds,
classifier_authors=classifier_authors,
classifier_titles=classifier_titles,
classifier_tags=classifier_tags)
# Just need to format stories
nowtz = localtime_for_timezone(now, user.profile.timezone)
for story in stories:
if read_filter == 'starred':
story['read_status'] = 1
else:
story['read_status'] = 0
if read_filter == 'all' or query:
if (unread_feed_story_hashes is not None and
story['story_hash'] not in unread_feed_story_hashes):
story['read_status'] = 1
story_date = localtime_for_timezone(story['story_date'], user.profile.timezone)
story['short_parsed_date'] = format_story_link_date__short(story_date, nowtz)
story['long_parsed_date'] = format_story_link_date__long(story_date, nowtz)
if story['story_hash'] in starred_stories:
story['starred'] = True
starred_date = localtime_for_timezone(starred_stories[story['story_hash']]['starred_date'],
user.profile.timezone)
story['starred_date'] = format_story_link_date__long(starred_date, now)
story['starred_timestamp'] = starred_date.strftime('%s')
story['user_tags'] = starred_stories[story['story_hash']]['user_tags']
story['intelligence'] = {
'feed': apply_classifier_feeds(classifier_feeds, story['story_feed_id']),
'author': apply_classifier_authors(classifier_authors, story),
'tags': apply_classifier_tags(classifier_tags, story),
'title': apply_classifier_titles(classifier_titles, story),
}
story['score'] = UserSubscription.score_story(story['intelligence'])
if not user.profile.is_premium:
message = "The full River of News is a premium feature."
code = 0
# if page > 1:
# stories = []
# else:
# stories = stories[:5]
diff = time.time() - start
timediff = round(float(diff), 2)
logging.user(request, "~FYLoading ~FCriver stories~FY: ~SBp%s~SN (%s/%s "
"stories, ~SN%s/%s/%s feeds, %s/%s)" %
(page, len(stories), len(mstories), len(found_feed_ids),
len(feed_ids), len(original_feed_ids), order, read_filter))
if not include_hidden:
hidden_stories_removed = 0
new_stories = []
for story in stories:
if story['score'] >= 0:
new_stories.append(story)
else:
hidden_stories_removed += 1
stories = new_stories
# if page <= 1:
# import random
# time.sleep(random.randint(0, 6))
data = dict(code=code,
message=message,
stories=stories,
classifiers=classifiers,
elapsed_time=timediff,
user_search=user_search,
user_profiles=user_profiles)
if not include_hidden: data['hidden_stories_removed'] = hidden_stories_removed
return data
@json.json_view
def unread_story_hashes__old(request):
user = get_user(request)
feed_ids = [int(feed_id) for feed_id in request.REQUEST.getlist('feed_id') if feed_id]
include_timestamps = is_true(request.REQUEST.get('include_timestamps', False))
usersubs = {}
if not feed_ids:
usersubs = UserSubscription.objects.filter(Q(unread_count_neutral__gt=0) |
Q(unread_count_positive__gt=0),
user=user, active=True)
feed_ids = [sub.feed_id for sub in usersubs]
else:
usersubs = UserSubscription.objects.filter(Q(unread_count_neutral__gt=0) |
Q(unread_count_positive__gt=0),
user=user, active=True, feed__in=feed_ids)
unread_feed_story_hashes = {}
story_hash_count = 0
usersubs = dict((sub.feed_id, sub) for sub in usersubs)
for feed_id in feed_ids:
if feed_id in usersubs:
us = usersubs[feed_id]
else:
continue
if not us.unread_count_neutral and not us.unread_count_positive:
continue
unread_feed_story_hashes[feed_id] = us.get_stories(read_filter='unread', limit=500,
withscores=include_timestamps,
hashes_only=True,
default_cutoff_date=user.profile.unread_cutoff)
story_hash_count += len(unread_feed_story_hashes[feed_id])
logging.user(request, "~FYLoading ~FCunread story hashes~FY: ~SB%s feeds~SN (%s story hashes)" %
(len(feed_ids), len(story_hash_count)))
return dict(unread_feed_story_hashes=unread_feed_story_hashes)
@json.json_view
def unread_story_hashes(request):
user = get_user(request)
feed_ids = [int(feed_id) for feed_id in request.REQUEST.getlist('feed_id') if feed_id]
include_timestamps = is_true(request.REQUEST.get('include_timestamps', False))
order = request.REQUEST.get('order', 'newest')
read_filter = request.REQUEST.get('read_filter', 'unread')
story_hashes = UserSubscription.story_hashes(user.pk, feed_ids=feed_ids,
order=order, read_filter=read_filter,
include_timestamps=include_timestamps,
cutoff_date=user.profile.unread_cutoff)
logging.user(request, "~FYLoading ~FCunread story hashes~FY: ~SB%s feeds~SN (%s story hashes)" %
(len(feed_ids), len(story_hashes)))
return dict(unread_feed_story_hashes=story_hashes)
@ajax_login_required
@json.json_view
def mark_all_as_read(request):
code = 1
try:
days = int(request.REQUEST.get('days', 0))
except ValueError:
return dict(code=-1, message="Days parameter must be an integer, not: %s" %
request.REQUEST.get('days'))
read_date = datetime.datetime.utcnow() - datetime.timedelta(days=days)
feeds = UserSubscription.objects.filter(user=request.user)
socialsubs = MSocialSubscription.objects.filter(user_id=request.user.pk)
for subtype in [feeds, socialsubs]:
for sub in subtype:
if days == 0:
sub.mark_feed_read()
else:
if sub.mark_read_date < read_date:
sub.needs_unread_recalc = True
sub.mark_read_date = read_date
sub.save()
logging.user(request, "~FMMarking all as read: ~SB%s days" % (days,))
return dict(code=code)
@ajax_login_required
@json.json_view
def mark_story_as_read(request):
story_ids = request.REQUEST.getlist('story_id')
try:
feed_id = int(get_argument_or_404(request, 'feed_id'))
except ValueError:
return dict(code=-1, errors=["You must pass a valid feed_id: %s" %
request.REQUEST.get('feed_id')])
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
except Feed.DoesNotExist:
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id)
if duplicate_feed:
feed_id = duplicate_feed[0].feed_id
try:
usersub = UserSubscription.objects.get(user=request.user,
feed=duplicate_feed[0].feed)
except (Feed.DoesNotExist):
return dict(code=-1, errors=["No feed exists for feed_id %d." % feed_id])
else:
return dict(code=-1, errors=["No feed exists for feed_id %d." % feed_id])
except UserSubscription.DoesNotExist:
usersub = None
if usersub:
data = usersub.mark_story_ids_as_read(story_ids, request=request)
else:
data = dict(code=-1, errors=["User is not subscribed to this feed."])
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'feed:%s' % feed_id)
return data
@ajax_login_required
@json.json_view
def mark_story_hashes_as_read(request):
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
story_hashes = request.REQUEST.getlist('story_hash')
feed_ids, friend_ids = RUserStory.mark_story_hashes_read(request.user.pk, story_hashes)
if friend_ids:
socialsubs = MSocialSubscription.objects.filter(
user_id=request.user.pk,
subscription_user_id__in=friend_ids)
for socialsub in socialsubs:
if not socialsub.needs_unread_recalc:
socialsub.needs_unread_recalc = True
socialsub.save()
r.publish(request.user.username, 'social:%s' % socialsub.subscription_user_id)
# Also count on original subscription
for feed_id in feed_ids:
usersubs = UserSubscription.objects.filter(user=request.user.pk, feed=feed_id)
if usersubs:
usersub = usersubs[0]
if not usersub.needs_unread_recalc:
usersub.needs_unread_recalc = True
usersub.save(update_fields=['needs_unread_recalc'])
r.publish(request.user.username, 'feed:%s' % feed_id)
hash_count = len(story_hashes)
logging.user(request, "~FYRead %s %s in feed/socialsubs: %s/%s" % (
hash_count, 'story' if hash_count == 1 else 'stories', feed_ids, friend_ids))
return dict(code=1, story_hashes=story_hashes,
feed_ids=feed_ids, friend_user_ids=friend_ids)
@ajax_login_required
@json.json_view
def mark_feed_stories_as_read(request):
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
feeds_stories = request.REQUEST.get('feeds_stories', "{}")
feeds_stories = json.decode(feeds_stories)
data = {
'code': -1,
'message': 'Nothing was marked as read'
}
for feed_id, story_ids in feeds_stories.items():
try:
feed_id = int(feed_id)
except ValueError:
continue
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
data = usersub.mark_story_ids_as_read(story_ids, request=request)
except UserSubscription.DoesNotExist:
return dict(code=-1, error="You are not subscribed to this feed_id: %d" % feed_id)
except Feed.DoesNotExist:
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id)
try:
if not duplicate_feed: raise Feed.DoesNotExist
usersub = UserSubscription.objects.get(user=request.user,
feed=duplicate_feed[0].feed)
data = usersub.mark_story_ids_as_read(story_ids, request=request)
except (UserSubscription.DoesNotExist, Feed.DoesNotExist):
return dict(code=-1, error="No feed exists for feed_id: %d" % feed_id)
r.publish(request.user.username, 'feed:%s' % feed_id)
return data
@ajax_login_required
@json.json_view
def mark_social_stories_as_read(request):
code = 1
errors = []
data = {}
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
users_feeds_stories = request.REQUEST.get('users_feeds_stories', "{}")
users_feeds_stories = json.decode(users_feeds_stories)
for social_user_id, feeds in users_feeds_stories.items():
for feed_id, story_ids in feeds.items():
feed_id = int(feed_id)
try:
socialsub = MSocialSubscription.objects.get(user_id=request.user.pk,
subscription_user_id=social_user_id)
data = socialsub.mark_story_ids_as_read(story_ids, feed_id, request=request)
except OperationError, e:
code = -1
errors.append("Already read story: %s" % e)
except MSocialSubscription.DoesNotExist:
MSocialSubscription.mark_unsub_story_ids_as_read(request.user.pk, social_user_id,
story_ids, feed_id,
request=request)
except Feed.DoesNotExist:
duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id)
if duplicate_feed:
try:
socialsub = MSocialSubscription.objects.get(user_id=request.user.pk,
subscription_user_id=social_user_id)
data = socialsub.mark_story_ids_as_read(story_ids, duplicate_feed[0].feed.pk, request=request)
except (UserSubscription.DoesNotExist, Feed.DoesNotExist):
code = -1
errors.append("No feed exists for feed_id %d." % feed_id)
else:
continue
r.publish(request.user.username, 'feed:%s' % feed_id)
r.publish(request.user.username, 'social:%s' % social_user_id)
data.update(code=code, errors=errors)
return data
@required_params('story_id', feed_id=int)
@ajax_login_required
@json.json_view
def mark_story_as_unread(request):
story_id = request.REQUEST.get('story_id', None)
feed_id = int(request.REQUEST.get('feed_id', 0))
try:
usersub = UserSubscription.objects.select_related('feed').get(user=request.user, feed=feed_id)
feed = usersub.feed
except UserSubscription.DoesNotExist:
usersub = None
feed = Feed.get_by_id(feed_id)
if usersub and not usersub.needs_unread_recalc:
usersub.needs_unread_recalc = True
usersub.save(update_fields=['needs_unread_recalc'])
data = dict(code=0, payload=dict(story_id=story_id))
story, found_original = MStory.find_story(feed_id, story_id)
if not story:
logging.user(request, "~FY~SBUnread~SN story in feed: %s (NOT FOUND)" % (feed))
return dict(code=-1, message="Story not found.")
if usersub:
data = usersub.invert_read_stories_after_unread_story(story, request)
message = RUserStory.story_can_be_marked_read_by_user(story, request.user)
if message:
data['code'] = -1
data['message'] = message
return data
social_subs = MSocialSubscription.mark_dirty_sharing_story(user_id=request.user.pk,
story_feed_id=feed_id,
story_guid_hash=story.guid_hash)
dirty_count = social_subs and social_subs.count()
dirty_count = ("(%s social_subs)" % dirty_count) if dirty_count else ""
RUserStory.mark_story_hash_unread(user_id=request.user.pk, story_hash=story.story_hash)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'feed:%s' % feed_id)
logging.user(request, "~FY~SBUnread~SN story in feed: %s %s" % (feed, dirty_count))
return data
@ajax_login_required
@json.json_view
@required_params('story_hash')
def mark_story_hash_as_unread(request):
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
story_hash = request.REQUEST.get('story_hash')
feed_id, _ = MStory.split_story_hash(story_hash)
story, _ = MStory.find_story(feed_id, story_hash)
if not story:
data = dict(code=-1, message="That story has been removed from the feed, no need to mark it unread.")
return data
message = RUserStory.story_can_be_marked_read_by_user(story, request.user)
if message:
data = dict(code=-1, message=message)
return data
# Also count on original subscription
usersubs = UserSubscription.objects.filter(user=request.user.pk, feed=feed_id)
if usersubs:
usersub = usersubs[0]
if not usersub.needs_unread_recalc:
usersub.needs_unread_recalc = True
usersub.save(update_fields=['needs_unread_recalc'])
data = usersub.invert_read_stories_after_unread_story(story, request)
r.publish(request.user.username, 'feed:%s' % feed_id)
feed_id, friend_ids = RUserStory.mark_story_hash_unread(request.user.pk, story_hash)
if friend_ids:
socialsubs = MSocialSubscription.objects.filter(
user_id=request.user.pk,
subscription_user_id__in=friend_ids)
for socialsub in socialsubs:
if not socialsub.needs_unread_recalc:
socialsub.needs_unread_recalc = True
socialsub.save()
r.publish(request.user.username, 'social:%s' % socialsub.subscription_user_id)
logging.user(request, "~FYUnread story in feed/socialsubs: %s/%s" % (feed_id, friend_ids))
return dict(code=1, story_hash=story_hash, feed_id=feed_id, friend_user_ids=friend_ids)
@ajax_login_required
@json.json_view
def mark_feed_as_read(request):
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
feed_ids = request.REQUEST.getlist('feed_id')
cutoff_timestamp = int(request.REQUEST.get('cutoff_timestamp', 0))
direction = request.REQUEST.get('direction', 'older')
multiple = len(feed_ids) > 1
code = 1
errors = []
cutoff_date = datetime.datetime.fromtimestamp(cutoff_timestamp) if cutoff_timestamp else None
for feed_id in feed_ids:
if 'social:' in feed_id:
user_id = int(feed_id.replace('social:', ''))
try:
sub = MSocialSubscription.objects.get(user_id=request.user.pk,
subscription_user_id=user_id)
except MSocialSubscription.DoesNotExist:
logging.user(request, "~FRCouldn't find socialsub: %s" % user_id)
continue
if not multiple:
sub_user = User.objects.get(pk=sub.subscription_user_id)
logging.user(request, "~FMMarking social feed as read: ~SB%s" % (sub_user.username,))
else:
try:
feed = Feed.objects.get(id=feed_id)
sub = UserSubscription.objects.get(feed=feed, user=request.user)
if not multiple:
logging.user(request, "~FMMarking feed as read: ~SB%s" % (feed,))
except (Feed.DoesNotExist, UserSubscription.DoesNotExist), e:
errors.append("User not subscribed: %s" % e)
continue
except (ValueError), e:
errors.append("Invalid feed_id: %s" % e)
continue
if not sub:
errors.append("User not subscribed: %s" % feed_id)
continue
try:
if direction == "older":
marked_read = sub.mark_feed_read(cutoff_date=cutoff_date)
else:
marked_read = sub.mark_newer_stories_read(cutoff_date=cutoff_date)
if marked_read and not multiple:
r.publish(request.user.username, 'feed:%s' % feed_id)
except IntegrityError, e:
errors.append("Could not mark feed as read: %s" % e)
code = -1
if multiple:
logging.user(request, "~FMMarking ~SB%s~SN feeds as read" % len(feed_ids))
r.publish(request.user.username, 'refresh:%s' % ','.join(feed_ids))
if errors:
logging.user(request, "~FMMarking read had errors: ~FR%s" % errors)
return dict(code=code, errors=errors, cutoff_date=cutoff_date, direction=direction)
def _parse_user_info(user):
return {
'user_info': {
'is_anonymous': json.encode(user.is_anonymous()),
'is_authenticated': json.encode(user.is_authenticated()),
'username': json.encode(user.username if user.is_authenticated() else 'Anonymous')
}
}
@ajax_login_required
@json.json_view
def add_url(request):
code = 0
url = request.POST['url']
folder = request.POST.get('folder', '')
new_folder = request.POST.get('new_folder')
auto_active = is_true(request.POST.get('auto_active', 1))
skip_fetch = is_true(request.POST.get('skip_fetch', False))
feed = None
if not url:
code = -1
message = 'Enter in the website address or the feed URL.'
elif any([(banned_url in url) for banned_url in BANNED_URLS]):
code = -1
message = "The publisher of this website has banned NewsBlur."
else:
if new_folder:
usf, _ = UserSubscriptionFolders.objects.get_or_create(user=request.user)
usf.add_folder(folder, new_folder)
folder = new_folder
code, message, us = UserSubscription.add_subscription(user=request.user, feed_address=url,
folder=folder, auto_active=auto_active,
skip_fetch=skip_fetch)
feed = us and us.feed
if feed:
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:%s' % feed.pk)
MUserSearch.schedule_index_feeds_for_search(feed.pk, request.user.pk)
return dict(code=code, message=message, feed=feed)
@ajax_login_required
@json.json_view
def add_folder(request):
folder = request.POST['folder']
parent_folder = request.POST.get('parent_folder', '')
folders = None
logging.user(request, "~FRAdding Folder: ~SB%s (in %s)" % (folder, parent_folder))
if folder:
code = 1
message = ""
user_sub_folders_object, _ = UserSubscriptionFolders.objects.get_or_create(user=request.user)
user_sub_folders_object.add_folder(parent_folder, folder)
folders = json.decode(user_sub_folders_object.folders)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
else:
code = -1
message = "Gotta write in a folder name."
return dict(code=code, message=message, folders=folders)
@ajax_login_required
@json.json_view
def delete_feed(request):
feed_id = int(request.POST['feed_id'])
in_folder = request.POST.get('in_folder', None)
if not in_folder or in_folder == ' ':
in_folder = ""
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders.delete_feed(feed_id, in_folder)
feed = Feed.objects.filter(pk=feed_id)
if feed:
feed[0].count_subscribers()
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, message="Removed %s from '%s'." % (feed, in_folder))
@ajax_login_required
@json.json_view
def delete_feed_by_url(request):
message = ""
code = 0
url = request.POST['url']
in_folder = request.POST.get('in_folder', '')
if in_folder == ' ':
in_folder = ""
feed = Feed.get_feed_from_url(url, create=False)
if feed:
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders.delete_feed(feed.pk, in_folder)
code = 1
feed = Feed.objects.filter(pk=feed.pk)
if feed:
feed[0].count_subscribers()
else:
code = -1
message = "URL not found."
return dict(code=code, message=message)
@ajax_login_required
@json.json_view
def delete_folder(request):
folder_to_delete = request.POST.get('folder_name') or request.POST.get('folder_to_delete')
in_folder = request.POST.get('in_folder', None)
feed_ids_in_folder = [int(f) for f in request.REQUEST.getlist('feed_id') if f]
request.user.profile.send_opml_export_email(reason="You have deleted an entire folder of feeds, so here's a backup just in case.")
# Works piss poor with duplicate folder titles, if they are both in the same folder.
# Deletes all, but only in the same folder parent. But nobody should be doing that, right?
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders.delete_folder(folder_to_delete, in_folder, feed_ids_in_folder)
folders = json.decode(user_sub_folders.folders)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=folders)
@required_params('feeds_by_folder')
@ajax_login_required
@json.json_view
def delete_feeds_by_folder(request):
feeds_by_folder = json.decode(request.POST['feeds_by_folder'])
request.user.profile.send_opml_export_email(reason="You have deleted a number of feeds at once, so here's a backup just in case.")
# Works piss poor with duplicate folder titles, if they are both in the same folder.
# Deletes all, but only in the same folder parent. But nobody should be doing that, right?
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders.delete_feeds_by_folder(feeds_by_folder)
folders = json.decode(user_sub_folders.folders)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=folders)
@ajax_login_required
@json.json_view
def rename_feed(request):
feed = get_object_or_404(Feed, pk=int(request.POST['feed_id']))
user_sub = UserSubscription.objects.get(user=request.user, feed=feed)
feed_title = request.POST['feed_title']
logging.user(request, "~FRRenaming feed '~SB%s~SN' to: ~SB%s" % (
feed.feed_title, feed_title))
user_sub.user_title = feed_title
user_sub.save()
return dict(code=1)
@ajax_login_required
@json.json_view
def rename_folder(request):
folder_to_rename = request.POST.get('folder_name') or request.POST.get('folder_to_rename')
new_folder_name = request.POST['new_folder_name']
in_folder = request.POST.get('in_folder', '')
code = 0
# Works piss poor with duplicate folder titles, if they are both in the same folder.
# renames all, but only in the same folder parent. But nobody should be doing that, right?
if folder_to_rename and new_folder_name:
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders.rename_folder(folder_to_rename, new_folder_name, in_folder)
code = 1
else:
code = -1
return dict(code=code)
@ajax_login_required
@json.json_view
def move_feed_to_folders(request):
feed_id = int(request.POST['feed_id'])
in_folders = request.POST.getlist('in_folders', '')
to_folders = request.POST.getlist('to_folders', '')
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders = user_sub_folders.move_feed_to_folders(feed_id, in_folders=in_folders,
to_folders=to_folders)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@ajax_login_required
@json.json_view
def move_feed_to_folder(request):
feed_id = int(request.POST['feed_id'])
in_folder = request.POST.get('in_folder', '')
to_folder = request.POST.get('to_folder', '')
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders = user_sub_folders.move_feed_to_folder(feed_id, in_folder=in_folder,
to_folder=to_folder)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@ajax_login_required
@json.json_view
def move_folder_to_folder(request):
folder_name = request.POST['folder_name']
in_folder = request.POST.get('in_folder', '')
to_folder = request.POST.get('to_folder', '')
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
user_sub_folders = user_sub_folders.move_folder_to_folder(folder_name, in_folder=in_folder, to_folder=to_folder)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@required_params('feeds_by_folder', 'to_folder')
@ajax_login_required
@json.json_view
def move_feeds_by_folder_to_folder(request):
feeds_by_folder = json.decode(request.POST['feeds_by_folder'])
to_folder = request.POST['to_folder']
new_folder = request.POST.get('new_folder', None)
request.user.profile.send_opml_export_email(reason="You have moved a number of feeds at once, so here's a backup just in case.")
user_sub_folders = get_object_or_404(UserSubscriptionFolders, user=request.user)
if new_folder:
user_sub_folders.add_folder(to_folder, new_folder)
to_folder = new_folder
user_sub_folders = user_sub_folders.move_feeds_by_folder_to_folder(feeds_by_folder, to_folder)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
return dict(code=1, folders=json.decode(user_sub_folders.folders))
@login_required
def add_feature(request):
if not request.user.is_staff:
return HttpResponseForbidden()
code = -1
form = FeatureForm(request.POST)
if form.is_valid():
form.save()
code = 1
return HttpResponseRedirect(reverse('index'))
return dict(code=code)
@json.json_view
def load_features(request):
user = get_user(request)
page = max(int(request.REQUEST.get('page', 0)), 0)
logging.user(request, "~FBBrowse features: ~SBPage #%s" % (page+1))
features = Feature.objects.all()[page*3:(page+1)*3+1].values()
features = [{
'description': f['description'],
'date': localtime_for_timezone(f['date'], user.profile.timezone).strftime("%b %d, %Y")
} for f in features]
return features
@ajax_login_required
@json.json_view
def save_feed_order(request):
folders = request.POST.get('folders')
if folders:
# Test that folders can be JSON decoded
folders_list = json.decode(folders)
assert folders_list is not None
logging.user(request, "~FBFeed re-ordering: ~SB%s folders/feeds" % (len(folders_list)))
user_sub_folders = UserSubscriptionFolders.objects.get(user=request.user)
user_sub_folders.folders = folders
user_sub_folders.save()
return {}
@json.json_view
def feeds_trainer(request):
classifiers = []
feed_id = request.REQUEST.get('feed_id')
user = get_user(request)
usersubs = UserSubscription.objects.filter(user=user, active=True)
if feed_id:
feed = get_object_or_404(Feed, pk=feed_id)
usersubs = usersubs.filter(feed=feed)
usersubs = usersubs.select_related('feed').order_by('-feed__stories_last_month')
for us in usersubs:
if (not us.is_trained and us.feed.stories_last_month > 0) or feed_id:
classifier = dict()
classifier['classifiers'] = get_classifiers_for_user(user, feed_id=us.feed.pk)
classifier['feed_id'] = us.feed_id
classifier['stories_last_month'] = us.feed.stories_last_month
classifier['num_subscribers'] = us.feed.num_subscribers
classifier['feed_tags'] = json.decode(us.feed.data.popular_tags) if us.feed.data.popular_tags else []
classifier['feed_authors'] = json.decode(us.feed.data.popular_authors) if us.feed.data.popular_authors else []
classifiers.append(classifier)
user.profile.has_trained_intelligence = True
user.profile.save()
logging.user(user, "~FGLoading Trainer: ~SB%s feeds" % (len(classifiers)))
return classifiers
@ajax_login_required
@json.json_view
def save_feed_chooser(request):
is_premium = request.user.profile.is_premium
approved_feeds = [int(feed_id) for feed_id in request.POST.getlist('approved_feeds') if feed_id]
if not is_premium:
approved_feeds = approved_feeds[:64]
activated = 0
usersubs = UserSubscription.objects.filter(user=request.user)
for sub in usersubs:
try:
if sub.feed_id in approved_feeds:
activated += 1
if not sub.active:
sub.active = True
sub.save()
if sub.feed.active_subscribers <= 0:
sub.feed.count_subscribers()
elif sub.active:
sub.active = False
sub.save()
except Feed.DoesNotExist:
pass
request.user.profile.queue_new_feeds()
request.user.profile.refresh_stale_feeds(exclude_new=True)
r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL)
r.publish(request.user.username, 'reload:feeds')
logging.user(request, "~BB~FW~SBFeed chooser: ~FC%s~SN/~SB%s" % (
activated,
usersubs.count()
))
return {'activated': activated}
@ajax_login_required
def retrain_all_sites(request):
for sub in UserSubscription.objects.filter(user=request.user):
sub.is_trained = False
sub.save()
return feeds_trainer(request)
@login_required
def activate_premium_account(request):
try:
usersubs = UserSubscription.objects.select_related('feed').filter(user=request.user)
for sub in usersubs:
sub.active = True
sub.save()
if sub.feed.premium_subscribers <= 0:
sub.feed.count_subscribers()
sub.feed.schedule_feed_fetch_immediately()
except Exception, e:
subject = "Premium activation failed"
message = "%s -- %s\n\n%s" % (request.user, usersubs, e)
mail_admins(subject, message, fail_silently=True)
request.user.profile.is_premium = True
request.user.profile.save()
return HttpResponseRedirect(reverse('index'))
@login_required
def login_as(request):
if not request.user.is_staff:
logging.user(request, "~SKNON-STAFF LOGGING IN AS ANOTHER USER!")
assert False
return HttpResponseForbidden()
username = request.GET['user']
user = get_object_or_404(User, username__iexact=username)
user.backend = settings.AUTHENTICATION_BACKENDS[0]
login_user(request, user)
return HttpResponseRedirect(reverse('index'))
def iframe_buster(request):
logging.user(request, "~FB~SBiFrame bust!")
return HttpResponse(status=204)
@required_params('story_id', feed_id=int)
@ajax_login_required
@json.json_view
def mark_story_as_starred(request):
return _mark_story_as_starred(request)
@required_params('story_hash')
@ajax_login_required
@json.json_view
def mark_story_hash_as_starred(request):
return _mark_story_as_starred(request)
def _mark_story_as_starred(request):
code = 1
feed_id = int(request.REQUEST.get('feed_id', 0))
story_id = request.REQUEST.get('story_id', None)
story_hash = request.REQUEST.get('story_hash', None)
user_tags = request.REQUEST.getlist('user_tags')
message = ""
if story_hash:
story, _ = MStory.find_story(story_hash=story_hash)
feed_id = story and story.story_feed_id
else:
story, _ = MStory.find_story(story_feed_id=feed_id, story_id=story_id)
if not story:
return {'code': -1, 'message': "Could not find story to save."}
story_db = dict([(k, v) for k, v in story._data.items()
if k is not None and v is not None])
story_db.pop('user_id', None)
story_db.pop('starred_date', None)
story_db.pop('id', None)
story_db.pop('user_tags', None)
now = datetime.datetime.now()
story_values = dict(starred_date=now, user_tags=user_tags, **story_db)
params = dict(story_guid=story.story_guid, user_id=request.user.pk)
starred_story = MStarredStory.objects(**params).limit(1)
created = False
removed_user_tags = []
if not starred_story:
params.update(story_values)
starred_story = MStarredStory.objects.create(**params)
created = True
MActivity.new_starred_story(user_id=request.user.pk,
story_title=story.story_title,
story_feed_id=feed_id,
story_id=starred_story.story_guid)
new_user_tags = user_tags
MStarredStoryCounts.adjust_count(request.user.pk, feed_id=feed_id, amount=1)
else:
starred_story = starred_story[0]
new_user_tags = list(set(user_tags) - set(starred_story.user_tags or []))
removed_user_tags = list(set(starred_story.user_tags or []) - set(user_tags))
starred_story.user_tags = user_tags
starred_story.save()
for tag in new_user_tags:
MStarredStoryCounts.adjust_count(request.user.pk, tag=tag, amount=1)
for tag in removed_user_tags:
MStarredStoryCounts.adjust_count(request.user.pk, tag=tag, amount=-1)
if random.random() < 0.01:
MStarredStoryCounts.schedule_count_tags_for_user(request.user.pk)
MStarredStoryCounts.count_for_user(request.user.pk, total_only=True)
starred_counts, starred_count = MStarredStoryCounts.user_counts(request.user.pk, include_total=True)
if not starred_count and len(starred_counts):
starred_count = MStarredStory.objects(user_id=request.user.pk).count()
if created:
logging.user(request, "~FCStarring: ~SB%s (~FM~SB%s~FC~SN)" % (story.story_title[:32], starred_story.user_tags))
else:
logging.user(request, "~FCUpdating starred:~SN~FC ~SB%s~SN (~FM~SB%s~FC~SN)" % (story.story_title[:32], starred_story.user_tags))
return {'code': code, 'message': message, 'starred_count': starred_count, 'starred_counts': starred_counts}
@required_params('story_id')
@ajax_login_required
@json.json_view
def mark_story_as_unstarred(request):
return _mark_story_as_unstarred(request)
@required_params('story_hash')
@ajax_login_required
@json.json_view
def mark_story_hash_as_unstarred(request):
return _mark_story_as_unstarred(request)
def _mark_story_as_unstarred(request):
code = 1
story_id = request.POST.get('story_id', None)
story_hash = request.REQUEST.get('story_hash', None)
starred_counts = None
starred_story = None
if story_id:
starred_story = MStarredStory.objects(user_id=request.user.pk, story_guid=story_id)
if not story_id or not starred_story:
starred_story = MStarredStory.objects(user_id=request.user.pk, story_hash=story_hash or story_id)
if starred_story:
starred_story = starred_story[0]
logging.user(request, "~FCUnstarring: ~SB%s" % (starred_story.story_title[:50]))
user_tags = starred_story.user_tags
feed_id = starred_story.story_feed_id
MActivity.remove_starred_story(user_id=request.user.pk,
story_feed_id=starred_story.story_feed_id,
story_id=starred_story.story_guid)
starred_story.user_id = 0
try:
starred_story.save()
except NotUniqueError:
starred_story.delete()
MStarredStoryCounts.adjust_count(request.user.pk, feed_id=feed_id, amount=-1)
for tag in user_tags:
try:
MStarredStoryCounts.adjust_count(request.user.pk, tag=tag, amount=-1)
except MStarredStoryCounts.DoesNotExist:
pass
# MStarredStoryCounts.schedule_count_tags_for_user(request.user.pk)
MStarredStoryCounts.count_for_user(request.user.pk, total_only=True)
starred_counts = MStarredStoryCounts.user_counts(request.user.pk)
else:
code = -1
return {'code': code, 'starred_counts': starred_counts}
@ajax_login_required
@json.json_view
def send_story_email(request):
code = 1
message = 'OK'
story_id = request.POST['story_id']
feed_id = request.POST['feed_id']
to_addresses = request.POST.get('to', '').replace(',', ' ').replace(' ', ' ').strip().split(' ')
from_name = request.POST['from_name']
from_email = request.POST['from_email']
email_cc = is_true(request.POST.get('email_cc', 'true'))
comments = request.POST['comments']
comments = comments[:2048] # Separated due to PyLint
from_address = '[email protected]'
share_user_profile = MSocialProfile.get_user(request.user.pk)
if not to_addresses:
code = -1
message = 'Please provide at least one email address.'
elif not all(email_re.match(to_address) for to_address in to_addresses if to_addresses):
code = -1
message = 'You need to send the email to a valid email address.'
elif not email_re.match(from_email):
code = -1
message = 'You need to provide your email address.'
elif not from_name:
code = -1
message = 'You need to provide your name.'
else:
story, _ = MStory.find_story(feed_id, story_id)
story = Feed.format_story(story, feed_id, text=True)
feed = Feed.get_by_id(story['story_feed_id'])
params = {
"to_addresses": to_addresses,
"from_name": from_name,
"from_email": from_email,
"email_cc": email_cc,
"comments": comments,
"from_address": from_address,
"story": story,
"feed": feed,
"share_user_profile": share_user_profile,
}
text = render_to_string('mail/email_story.txt', params)
html = render_to_string('mail/email_story.xhtml', params)
subject = '%s' % (story['story_title'])
cc = None
if email_cc:
cc = ['%s <%s>' % (from_name, from_email)]
subject = subject.replace('\n', ' ')
msg = EmailMultiAlternatives(subject, text,
from_email='NewsBlur <%s>' % from_address,
to=to_addresses,
cc=cc,
headers={'Reply-To': '%s <%s>' % (from_name, from_email)})
msg.attach_alternative(html, "text/html")
try:
msg.send()
except boto.ses.connection.ResponseError, e:
code = -1
message = "Email error: %s" % str(e)
logging.user(request, '~BMSharing story by email to %s recipient%s: ~FY~SB%s~SN~BM~FY/~SB%s' %
(len(to_addresses), '' if len(to_addresses) == 1 else 's',
story['story_title'][:50], feed and feed.feed_title[:50]))
return {'code': code, 'message': message}
@json.json_view
def load_tutorial(request):
if request.REQUEST.get('finished'):
logging.user(request, '~BY~FW~SBFinishing Tutorial')
return {}
else:
newsblur_feed = Feed.objects.filter(feed_address__icontains='blog.newsblur.com').order_by('-pk')[0]
logging.user(request, '~BY~FW~SBLoading Tutorial')
return {
'newsblur_feed': newsblur_feed.canonical()
}
| mit |
JiachengSHI/JiachengSHI.github.io | _layouts/post.html | 4430 | <!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
{% include head.html %}
</head>
<body id="post">
{% include navigation.html %}
<div id="main" role="main">
<article class="hentry">
<img src="{{ site.url }}/images/sheep-land3.jpg" class="entry-feature-image" alt="{{ page.title }}" {% if site.logo == null %}style="margin-top:0;"{% endif %}><p class="image-credit">Photo Credit: <a href="http://jiachengpark.appspot.com">Jiacheng park</a>
<div class="entry-wrapper">
<header class="entry-header">
<span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags/#{{ tag | cgi_encode }}" title="Pages tagged {{ tag }}">{{ tag }}</a>{% unless forloop.last %} • {% endunless %}{% endfor %}</span>
{% if page.link %}
<h1 class="entry-title"><a href="{{ page.link }}">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %} <span class="link-arrow">→</span></a></h1>
{% else %}
<h1 class="entry-title">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %}</h1>
{% endif %}
</header>
<footer class="entry-meta">
<img src="{{ site.url }}/images/{{ site.owner.avatar }}" alt="{{ site.owner.name }} photo" class="author-photo">
<span class="author vcard">By <span class="fn"><a href="{{ site.url }}/about/" title="About {{ site.owner.name }}">{{ site.owner.name }}</a></span></span>
<span class="entry-date date published"><time datetime="{{ page.date | date_to_xmlschema }}"><i class="icon-calendar-empty"></i> {{ page.date | date: "%B %d, %Y" }}</time></span>
{% if page.modified %}<span class="entry-date date modified"><time datetime="{{ page.modified }}"><i class="icon-pencil"></i> {{ page.modified | date: "%B %d, %Y" }}</time></span>{% endif %}
{% if site.disqus_shortname and page.comments %}<span class="entry-comments"><i class="icon-comment-alt"></i> <a href="{{ site.url }}{{ page.url }}#disqus_thread">Comment</a></span>{% endif %}
<span><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}"><i class="icon-link"></i> Permalink</a></span>
{% if page.share %}
<span class="social-share-facebook">
<a href="https://www.facebook.com/sharer/sharer.php?u={{ site.url }}{{ page.url }}" title="Share on Facebook" itemprop="Facebook" target="_blank"><i class="icon-facebook-sign"></i> Like</a></span>
<span class="social-share-twitter">
<a href="https://twitter.com/intent/tweet?hashtags={{ page.categories | join: ',' }}&text={{ page.title }}&url={{ site.url }}{{ page.url }}&via={{site.owner.twitter}}" title="Share on Twitter" itemprop="Twitter" target="_blank"><i class="icon-twitter-sign"></i> Tweet</a></span>
<span class="social-share-googleplus">
<a href="https://plus.google.com/share?url={{ site.url }}{{ page.url }}" title="Share on Google Plus" itemprop="GooglePlus" target="_blank"><i class="icon-google-plus-sign"></i> +1</a></span>
<!-- /.social-share -->{% endif %}
</footer>
<div class="entry-content">
{{ content }}
{% if site.disqus_shortname and page.comments %}<div id="disqus_thread"></div>
{% include disqus_comments.html %}
<!-- /#disqus_thread -->{% endif %}
</div><!-- /.entry-content -->
<div class="entry-top">
<i class="icon-arrow-up icon-2x"></i>
</div><!-- /.entry-top -->
</div><!-- /.entry-wrapper -->
<nav class="pagination" role="navigation">
{% if page.previous %}
<a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
{% endif %}
{% if page.next %}
<a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
{% endif %}
</nav><!-- /.pagination -->
</article>
</div><!-- /#main -->
<div class="footer-wrapper">
<footer role="contentinfo">
{% include footer.html %}
</footer>
</div><!-- /.footer-wrapper -->
{% include scripts.html %}
</body>
</html>
| mit |
ConsenSys/truffle | packages/core/lib/commands/test/determineTestFilesToRun.js | 744 | const determineTestFilesToRun = ({ inputFile, inputArgs = [], config }) => {
const path = require("path");
const fs = require("fs");
const glob = require("glob");
let filesToRun = [];
if (inputFile) {
filesToRun.push(inputFile);
} else if (inputArgs.length > 0) {
inputArgs.forEach(inputArg => filesToRun.push(inputArg));
}
if (filesToRun.length === 0) {
const directoryContents = glob.sync(
`${config.test_directory}${path.sep}**${path.sep}*`
);
filesToRun =
directoryContents.filter(item => fs.statSync(item).isFile()) || [];
}
return filesToRun.filter(file => {
return file.match(config.test_file_extension_regexp) !== null;
});
};
module.exports = {
determineTestFilesToRun
};
| mit |
ReaxDev/typeorm | test/github-issues/182/issue-182.ts | 2660 | import "reflect-metadata";
import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
import {Connection} from "../../../src/connection/Connection";
import {Post} from "./entity/Post";
import {expect} from "chai";
import {PostStatus} from "./model/PostStatus";
describe("github issues > #182 enums are not saved properly", () => {
let connections: Connection[];
before(async () => connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
schemaCreate: true,
dropSchemaOnConnection: true,
enabledDrivers: ["mysql"] // we can properly test lazy-relations only on one platform
}));
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));
it("should persist successfully with enum values", () => Promise.all(connections.map(async connection => {
const post1 = new Post();
post1.status = PostStatus.NEW;
post1.title = "Hello Post #1";
// persist
await connection.entityManager.persist(post1);
const loadedPosts1 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" });
expect(loadedPosts1!).not.to.be.empty;
loadedPosts1!.should.be.eql({
id: 1,
title: "Hello Post #1",
status: PostStatus.NEW
});
// remove persisted
await connection.entityManager.remove(post1);
const post2 = new Post();
post2.status = PostStatus.ACTIVE;
post2.title = "Hello Post #1";
// persist
await connection.entityManager.persist(post2);
const loadedPosts2 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" });
expect(loadedPosts2!).not.to.be.empty;
loadedPosts2!.should.be.eql({
id: 2,
title: "Hello Post #1",
status: PostStatus.ACTIVE
});
// remove persisted
await connection.entityManager.remove(post2);
const post3 = new Post();
post3.status = PostStatus.ACHIEVED;
post3.title = "Hello Post #1";
// persist
await connection.entityManager.persist(post3);
const loadedPosts3 = await connection.entityManager.findOne(Post, { title: "Hello Post #1" });
expect(loadedPosts3!).not.to.be.empty;
loadedPosts3!.should.be.eql({
id: 3,
title: "Hello Post #1",
status: PostStatus.ACHIEVED
});
// remove persisted
await connection.entityManager.remove(post3);
})));
});
| mit |
SBFE/js-combine-pack | lib/tool/lineStream.js | 680 | // nodejs按行读取文件流
var Stream = require('stream').Stream,
util = require('util');
var LineStream = function() {
this.writable = true;
this.readable = true;
this.buffer = '';
};
util.inherits(LineStream, Stream);
LineStream.prototype.write = function(data, encoding) {
if (Buffer.isBuffer(data)) {
data = data.toString(encoding || 'utf8');
}
var parts = data.split(/\n/g);
var len = parts.length;
for (var i = 0; i < len; i++) {
this.emit('data', parts[i]+'\n');
}
};
LineStream.prototype.end = function() {
if(this.buffer.length > 0){
this.emit('data',this.buffer);
this.buffer = '';
}
this.emit('end');
};
module.exports = LineStream;
| mit |
krasimirkrustev/ta-library-system | LibrarySystem/LibrarySystem/Account/Manage.aspx.cs | 4298 | using LibrarySystem.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LibrarySystem.Account
{
public partial class Manage : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
protected bool CanRemoveExternalLogins
{
get;
private set;
}
protected void Page_Load()
{
if (!IsPostBack)
{
// Determine the sections to render
ILoginManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Logins;
if (manager.HasLocalLogin(User.Identity.GetUserId()))
{
changePasswordHolder.Visible = true;
}
else
{
setPassword.Visible = true;
changePasswordHolder.Visible = false;
}
CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
SuccessMessage =
message == "ChangePwdSuccess" ? "Your password has been changed."
: message == "SetPwdSuccess" ? "Your password has been set."
: message == "RemoveLoginSuccess" ? "The account was removed."
: String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
}
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
IPasswordManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Passwords;
IdentityResult result = manager.ChangePassword(User.Identity.GetUserName(), CurrentPassword.Text, NewPassword.Text);
if (result.Success)
{
Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
}
else
{
AddErrors(result);
}
}
}
protected void SetPassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Create the local login info and link the local account to the user
ILoginManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Logins;
IdentityResult result = manager.AddLocalLogin(User.Identity.GetUserId(), User.Identity.GetUserName(), password.Text);
if (result.Success)
{
Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
}
else
{
AddErrors(result);
}
}
}
public IEnumerable<IUserLogin> GetLogins()
{
ILoginManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Logins;
var accounts = manager.GetLogins(User.Identity.GetUserId());
CanRemoveExternalLogins = accounts.Count() > 1;
return accounts;
}
public void RemoveLogin(string loginProvider, string providerKey)
{
ILoginManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Logins;
var result = manager.RemoveLogin(User.Identity.GetUserId(), loginProvider, providerKey);
var msg = result.Success
? "?m=RemoveLoginSuccess"
: String.Empty;
Response.Redirect("~/Account/Manage" + msg);
}
private void AddErrors(IdentityResult result) {
foreach (var error in result.Errors) {
ModelState.AddModelError("", error);
}
}
}
} | mit |
kif/freesas | freesas/average.py | 9116 | __author__ = "Guillaume"
__license__ = "MIT"
__copyright__ = "2015, ESRF"
import numpy
from freesas.model import SASModel
class Grid:
"""
This class is used to create a grid which include all the input models
"""
def __init__(self, inputfiles):
"""
:param inputfiles: list of pdb files needed for averaging
"""
self.inputs = inputfiles
self.size = []
self.nbknots = None
self.radius = None
self.coordknots = []
def __repr__(self):
return "Grid with %i knots"%self.nbknots
def spatial_extent(self):
"""
Calculate the maximal extent of input models
:return self.size: 6-list with x,y,z max and then x,y,z min
"""
atoms = []
models_fineness = []
for files in self.inputs:
m = SASModel(files)
if len(atoms)==0:
atoms = m.atoms
else:
atoms = numpy.append(atoms, m.atoms, axis=0)
models_fineness.append(m.fineness)
mean_fineness = sum(models_fineness) / len(models_fineness)
coordmin = atoms.min(axis=0) - mean_fineness
coordmax = atoms.max(axis=0) + mean_fineness
self.size = [coordmax[0],coordmax[1],coordmax[2],coordmin[0],coordmin[1],coordmin[2]]
return self.size
def calc_radius(self, nbknots=None):
"""
Calculate the radius of each point of a hexagonal close-packed grid,
knowing the total volume and the number of knots in this grid.
:param nbknots: number of knots wanted for the grid
:return radius: the radius of each knot of the grid
"""
if len(self.size)==0:
self.spatial_extent()
nbknots = nbknots if nbknots is not None else 5000
size = self.size
dx = size[0] - size[3]
dy = size[1] - size[4]
dz = size[2] - size[5]
volume = dx * dy * dz
density = numpy.pi / (3*2**0.5)
radius = ((3 /( 4 * numpy.pi)) * density * volume / nbknots)**(1.0/3)
self.radius = radius
return radius
def make_grid(self):
"""
Create a grid using the maximal size and the radius previously computed.
The geometry used is a face-centered cubic lattice (fcc).
:return knots: 2d-array, coordinates of each dot of the grid. Saved as self.coordknots.
"""
if len(self.size)==0:
self.spatial_extent()
if self.radius is None:
self.calc_radius()
radius = self.radius
a = numpy.sqrt(2.0)*radius
xmax = self.size[0]
xmin = self.size[3]
ymax = self.size[1]
ymin = self.size[4]
zmax = self.size[2]
zmin = self.size[5]
x = 0.0
y = 0.0
z = 0.0
xlist = []
ylist = []
zlist = []
knots = numpy.empty((1,4), dtype="float")
while (zmin + z) <= zmax:
zlist.append(z)
z += a
while (ymin + y) <= ymax:
ylist.append(y)
y += a
while (xmin + x) <= xmax:
xlist.append(x)
x += a
for i in range(len(zlist)):
z = zlist[i]
if i % 2 ==0:
for j in range(len(xlist)):
x = xlist[j]
if j % 2 == 0:
for y in ylist[0:-1:2]:
knots = numpy.append(knots, [[xmin+x, ymin+y, zmin+z, 0.0]], axis=0)
else:
for y in ylist[1:-1:2]:
knots = numpy.append(knots, [[xmin+x, ymin+y, zmin+z, 0.0]], axis=0)
else:
for j in range(len(xlist)):
x = xlist[j]
if j % 2 == 0:
for y in ylist[1:-1:2]:
knots = numpy.append(knots, [[xmin+x, ymin+y, zmin+z, 0.0]], axis=0)
else:
for y in ylist[0:-1:2]:
knots = numpy.append(knots, [[xmin+x, ymin+y, zmin+z, 0.0]], axis=0)
knots = numpy.delete(knots, 0, axis=0)
self.nbknots = knots.shape[0]
self.coordknots = knots
return knots
class AverModels():
"""
Provides tools to create an averaged models using several aligned dummy atom models
"""
def __init__(self, inputfiles, grid):
"""
:param inputfiles: list of pdb files of aligned models
:param grid: 2d-array coordinates of each point of a grid, fourth column full of zeros
"""
self.inputfiles = inputfiles
self.models = []
self.header = []
self.radius = None
self.atoms = []
self.grid = grid
def __repr__(self):
return "Average SAS model with %i atoms"%len(self.atoms)
def read_files(self, reference=None):
"""
Read all the pdb file in the inputfiles list, creating SASModels.
The SASModels created are save in a list, the reference model is the first model in the list.
:param reference: position of the reference model file in the inputfiles list
"""
ref = reference if reference is not None else 0
inputfiles = self.inputfiles
models = []
models.append(SASModel(inputfiles[ref]))
for i in range(len(inputfiles)):
if i==ref:
continue
else:
models.append(SASModel(inputfiles[i]))
self.models = models
return models
def calc_occupancy(self, griddot):
"""
Assign an occupancy and a contribution factor to the point of the grid.
:param griddot: 1d-array, coordinates of a point of the grid
:return tuple: 2-tuple containing (occupancy, contribution)
"""
occ = 0.0
contrib = 0
for model in self.models:
f = model.fineness
for i in range(model.atoms.shape[0]):
dx = model.atoms[i, 0] - griddot[0]
dy = model.atoms[i, 1] - griddot[1]
dz = model.atoms[i, 2] - griddot[2]
dist = dx * dx + dy * dy + dz * dz
add = max(1 - (dist / f), 0)
if add != 0:
contrib += 1
occ += add
return occ, contrib
def assign_occupancy(self):
"""
For each point of the grid, total occupancy and contribution factor are computed and saved.
The grid is then ordered with decreasing value of occupancy.
The fourth column of the array correspond to the occupancy of the point and the fifth to
the contribution for this point.
:return sortedgrid: 2d-array, coordinates of each point of the grid
"""
grid = self.grid
nbknots = grid.shape[0]
grid = numpy.append(grid, numpy.zeros((nbknots, 1), dtype="float"), axis=1)
for i in range(nbknots):
occ, contrib = self.calc_occupancy(grid[i, 0:3])
grid[i, 3] = occ
grid[i, 4] = contrib
order = numpy.argsort(grid, axis=0)[:, -2]
sortedgrid = numpy.empty_like(grid)
for i in range(nbknots):
sortedgrid[nbknots - i - 1, :] = grid[order[i], :]
return sortedgrid
def make_header(self):
"""
Create the layout of the pdb file for the averaged model.
"""
header = []
header.append("Number of files averaged : %s\n"%len(self.inputfiles))
for i in self.inputfiles:
header.append(i + "\n")
header.append("Total number of dots in the grid : %s\n"%self.grid.shape[0])
decade = 1
for i in range(self.grid.shape[0]):
line = "ATOM CA ASP 1 20.00 2 201\n"
line = line[:7] + "%4.i"%(i + 1) + line[11:]
if not (i + 1) % 10:
decade += 1
line = line[:21] + "%4.i"%decade + line[25:]
header.append(line)
self.header = header
return header
def save_aver(self, filename):
"""
Save the position of each occupied dot of the grid, its occupancy and its contribution
in a pdb file.
:param filename: name of the pdb file to write
"""
if len(self.header) == 0:
self.make_header()
assert self.grid.shape[-1] == 5
nr = 0
with open(filename, "w") as pdbout:
for line in self.header:
if line.startswith("ATOM"):
if nr < self.grid.shape[0] and self.grid[nr, 4] != 0:
coord = "%8.3f%8.3f%8.3f" % tuple(self.grid[nr, 0:3])
occ = "%6.2f" % self.grid[nr, 3]
contrib = "%2.f" % self.grid[nr, 4]
line = line[:30] + coord + occ + line[60:66] + contrib + line[68:]
else:
line = ""
nr += 1
pdbout.write(line)
| mit |
rachwal/DesignPatterns | structural/src/flyweight/btree.cc | 1119 | // Based on "Design Patterns: Elements of Reusable Object-Oriented Software"
// book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm
//
// Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan.
#include "btree.h"
namespace structural
{
namespace flyweight
{
BTree::BTree(long size) : size_(size)
{
leafs_ = new operational::iterator::List<Font*>();
nodes_ = new int[size_];
for (auto i = 0; i < size_; i++)
{
nodes_[i] = -1;
}
}
BTree::BTree() : BTree(1000) { }
void BTree::Set(Font* font, const int& index, const int& span) const
{
auto font_index = -1;
for (auto i = 0; i < leafs_->Count(); i++)
{
if (&leafs_->Get(i) == &font)
{
font_index = i;
}
}
if (font_index == -1)
{
leafs_->Append(font);
font_index = leafs_->Count() - 1;
}
for (auto j = index; j < index + span; j++)
{
nodes_[j] = font_index;
}
}
Font *BTree::Get(int index) const
{
if (index > size_)
{
return nullptr;
}
auto font_index = nodes_[index];
if (font_index == -1)
{
return nullptr;
}
return leafs_->Get(font_index);
}
}
}
| mit |
minimalism/omr-client | README.md | 389 | # OpenMultiplayerRobot
This is a work in progress.
## Install
```bash
npm install
npm install -g typings gulp
typings install
gulp
npm start
```
## Credits
- Developed by [Andreas Carlson](http://andreascarlson.se)
Thanks to:
- [iggyfisk](https://github.com/iggyfisk)
- Based on [electron-typescript-react quickstart](https://github.com/claudioc/electron-typescript-react-quick-start) | mit |
mzgoddard/tomlc | toml.c | 25919 | #include <assert.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// #include <antlr3.h>
#include "toml.h"
#include "toml-parser.h"
// #include "tomlParser.h"
// #include "tomlLexer.h"
struct _TOMLStringifyData {
TOMLError *error;
int bufferSize;
int bufferIndex;
char *buffer;
int tableNameDepth;
int tableNameStackSize;
TOMLString **tableNameStack;
};
int _TOML_stringify( struct _TOMLStringifyData *self, TOMLRef src );
TOMLRef TOML_alloc( TOMLType type ) {
switch ( type ) {
case TOML_TABLE:
return TOML_allocTable( NULL, NULL );
case TOML_ARRAY:
return TOML_allocArray( TOML_NOTYPE );
case TOML_STRING:
return TOML_allocString( "" );
case TOML_INT:
return TOML_allocInt( 0 );
case TOML_DOUBLE:
return TOML_allocDouble( 0 );
case TOML_BOOLEAN:
return TOML_allocBoolean( 0 );
case TOML_DATE:
return TOML_allocEpochDate( 0 );
default:
return NULL;
}
}
TOMLTable * TOML_allocTable( TOMLString *key, TOMLRef value, ... ) {
TOMLTable *self = malloc( sizeof(TOMLTable) );
self->type = TOML_TABLE;
self->keys = TOML_allocArray( TOML_STRING, NULL );
self->values = TOML_allocArray( TOML_NOTYPE, NULL );
if ( key != NULL ) {
TOMLArray_append( self->keys, key );
TOMLArray_append( self->values, value );
} else {
return self;
}
va_list args;
va_start( args, value );
key = va_arg( args, TOMLString * );
while ( key != NULL ) {
value = va_arg( args, TOMLRef );
TOMLArray_append( self->keys, key );
TOMLArray_append( self->values, value );
key = va_arg( args, TOMLString * );
}
va_end( args );
return self;
}
TOMLArray * TOML_allocArray( TOMLType memberType, ... ) {
TOMLArray *self = malloc( sizeof(TOMLArray) );
self->type = TOML_ARRAY;
self->memberType = memberType;
self->size = 0;
self->members = NULL;
va_list args;
va_start( args, memberType );
TOMLRef member = va_arg( args, TOMLRef );
while ( member != NULL ) {
TOMLArray_append( self, member );
member = va_arg( args, TOMLRef );
}
va_end( args );
return self;
}
TOMLString * TOML_allocString( char *content ) {
int size = strlen( content );
TOMLString *self = malloc( sizeof(TOMLString) + size + 1 );
self->type = TOML_STRING;
self->size = size;
self->content[ self->size ] = 0;
strncpy( self->content, content, size );
return self;
}
TOMLString * TOML_allocStringN( char *content, int n ) {
TOMLString *self = malloc( sizeof(TOMLString) + n + 1 );
self->type = TOML_STRING;
self->size = n;
self->content[ n ] = 0;
strncpy( self->content, content, n );
return self;
}
TOMLNumber * TOML_allocInt( int value ) {
TOMLNumber *self = malloc( sizeof(TOMLNumber) );
self->type = TOML_INT;
// self->numberType = TOML_INT;
self->intValue = value;
return self;
}
TOMLNumber * TOML_allocDouble( double value ) {
TOMLNumber *self = malloc( sizeof(TOMLNumber) );
self->type = TOML_DOUBLE;
// self->numberType = TOML_DOUBLE;
self->doubleValue = value;
return self;
}
TOMLBoolean * TOML_allocBoolean( int truth ) {
TOMLBoolean *self = malloc( sizeof(TOMLBoolean) );
self->type = TOML_BOOLEAN;
self->isTrue = truth;
return self;
}
int _TOML_isLeapYear( int year ) {
if ( year % 400 == 0 ) {
return 1;
} else if ( year % 100 == 0 ) {
return 0;
} else if ( year % 4 == 0 ) {
return 1;
} else {
return 0;
}
}
TOMLDate * TOML_allocDate(
int year, int month, int day, int hour, int minute, int second
) {
TOMLDate *self = malloc( sizeof(TOMLDate) );
self->type = TOML_DATE;
self->year = year;
self->month = month;
self->day = day;
self->hour = hour;
self->minute = minute;
self->second = second;
struct tm _time = {
second,
minute,
hour,
day,
month,
year - 1900
};
// local time
time_t localEpoch = mktime( &_time );
// gm time
_time = *gmtime( &localEpoch );
time_t gmEpoch = mktime( &_time );
double diff = difftime( localEpoch, gmEpoch );
// Adjust the localEpock made by mktime to a gmt epoch.
self->sinceEpoch = localEpoch + diff;
return self;
}
TOMLDate * TOML_allocEpochDate( time_t stamp ) {
TOMLDate *self = malloc( sizeof(TOMLDate) );
self->type = TOML_DATE;
self->sinceEpoch = stamp;
struct tm _time = *gmtime( &stamp );
self->second = _time.tm_sec;
self->minute = _time.tm_min;
self->hour = _time.tm_hour;
self->day = _time.tm_mday;
self->month = _time.tm_mon;
self->year = _time.tm_year + 1900;
return self;
}
TOMLError * TOML_allocError( int code ) {
TOMLError *self = malloc( sizeof(TOMLError) );
self->type = TOML_ERROR;
self->code = code;
self->lineNo = 0;
self->line = NULL;
self->message = NULL;
self->fullDescription = NULL;
return self;
}
char * _TOML_cstringCopy( char *str ) {
if ( !str ) {
return NULL;
}
int size = strlen( str );
char *newstr = malloc( size + 1 );
newstr[ size ] = 0;
strncpy( newstr, str, size );
return newstr;
}
TOMLRef TOML_copy( TOMLRef self ) {
TOMLBasic *basic = (TOMLBasic *) self;
if ( basic->type == TOML_TABLE ) {
TOMLTable *table = (TOMLTable *) self;
TOMLTable *newTable = malloc( sizeof(TOMLTable) );
newTable->type = TOML_TABLE;
newTable->keys = TOML_copy( table->keys );
newTable->values = TOML_copy( table->values );
return newTable;
} else if ( basic->type == TOML_ARRAY ) {
TOMLArray *array = (TOMLArray *) self;
TOMLArray *newArray = malloc( sizeof(TOMLArray) );
newArray->type = TOML_ARRAY;
newArray->memberType = array->memberType;
int i;
for ( i = 0; i < array->size; ++i ) {
TOMLArray_append(
newArray,
TOML_copy( TOMLArray_getIndex( array, i ) )
);
}
return newArray;
} else if ( basic->type == TOML_STRING ) {
TOMLString *string = (TOMLString *) self;
TOMLString *newString = malloc( sizeof(TOMLString) + string->size + 1 );
newString->type = TOML_STRING;
newString->size = string->size;
strncpy( newString->content, string->content, string->size + 1 );
return newString;
} else if ( basic->type == TOML_INT || basic->type == TOML_DOUBLE ) {
TOMLNumber *number = (TOMLNumber *) self;
TOMLNumber *newNumber = malloc( sizeof(TOMLNumber) );
newNumber->type = number->type;
// newNumber->numberType = number->numberType;
memcpy( newNumber->bytes, number->bytes, 8 );
return newNumber;
} else if ( basic->type == TOML_BOOLEAN ) {
TOMLBoolean *boolean = (TOMLBoolean *) self;
TOMLBoolean *newBoolean = malloc( sizeof(TOMLBoolean) );
newBoolean->type = boolean->type;
newBoolean->isTrue = boolean->isTrue;
return newBoolean;
} else if ( basic->type == TOML_DATE ) {
TOMLDate *date = (TOMLDate *) self;
TOMLDate *newDate = malloc( sizeof(TOMLDate) );
*newDate = *date;
return newDate;
} else if ( basic->type == TOML_ERROR ) {
TOMLError *error = (TOMLError *) self;
TOMLError *newError = malloc( sizeof(TOMLError) );
newError->type = TOML_ERROR;
newError->code = error->code;
newError->lineNo = error->lineNo;
newError->line = _TOML_cstringCopy( error->line );
newError->message = _TOML_cstringCopy( error->message );
newError->fullDescription = _TOML_cstringCopy( error->fullDescription );
return newError;
} else {
return NULL;
}
}
void TOML_free( TOMLRef self ) {
TOMLBasic *basic = (TOMLBasic *) self;
if ( basic->type == TOML_TABLE ) {
TOMLTable *table = (TOMLTable *) self;
TOML_free( table->keys );
TOML_free( table->values );
} else if ( basic->type == TOML_ARRAY ) {
TOMLArray *array = (TOMLArray *) self;
int i;
for ( i = 0; i < array->size; ++i ) {
TOML_free( array->members[ i ] );
}
free( array->members );
} else if ( basic->type == TOML_ERROR ) {
TOMLError *error = (TOMLError *) self;
free( error->line );
free( error->message );
free( error->fullDescription );
}
free( self );
}
int TOML_isType( TOMLRef self, TOMLType type ) {
TOMLBasic *basic = (TOMLBasic *) self;
return basic->type == type;
}
int TOML_isNumber( TOMLRef self ) {
TOMLBasic *basic = (TOMLBasic *) self;
return basic->type == TOML_INT || basic->type == TOML_DOUBLE;
}
TOMLRef TOML_find( TOMLRef self, ... ) {
TOMLBasic *basic = self;
va_list args;
va_start( args, self );
char *key;
do {
if ( basic->type == TOML_TABLE ) {
key = va_arg( args, char * );
if ( key == NULL ) {
break;
}
basic = self = TOMLTable_getKey( self, key );
} else if ( basic->type == TOML_ARRAY ) {
key = va_arg( args, char * );
if ( key == NULL ) {
break;
}
basic = self = TOMLArray_getIndex( self, atoi( key ) );
} else {
break;
}
} while ( self );
va_end( args );
return self;
}
TOMLRef TOMLTable_getKey( TOMLTable *self, char *key ) {
int keyLength = strlen( key );
int i;
for ( i = 0; i < self->keys->size; ++i ) {
TOMLString *tableKey = TOMLArray_getIndex( self->keys, i );
int minSize = keyLength < tableKey->size ? keyLength : tableKey->size;
if ( strncmp( tableKey->content, key, minSize + 1 ) == 0 ) {
return TOMLArray_getIndex( self->values, i );
}
}
return NULL;
}
void TOMLTable_setKey( TOMLTable *self, char *key, TOMLRef value ) {
int keyLength = strlen( key );
int i;
for ( i = 0; i < self->keys->size; ++i ) {
TOMLString *tableKey = TOMLArray_getIndex( self->keys, i );
int minSize = keyLength < tableKey->size ? keyLength : tableKey->size;
if ( strncmp( tableKey->content, key, minSize ) == 0 ) {
TOMLArray_setIndex( self->values, i, value );
return;
}
}
TOMLArray_append( self->keys, TOML_allocString( key ) );
TOMLArray_append( self->values, value );
}
TOMLRef TOMLArray_getIndex( TOMLArray *self, int index ) {
return self->members && self->size > index ? self->members[ index ] : NULL;
}
void TOMLArray_setIndex( TOMLArray *self, int index, TOMLRef value ) {
if ( index < self->size ) {
TOML_free( self->members[ index ] );
self->members[ index ] = value;
} else {
TOMLArray_append( self, value );
}
}
void TOMLArray_append( TOMLArray *self, TOMLRef value ) {
TOMLRef *oldMembers = self->members;
self->members = malloc( ( self->size + 1 ) * sizeof(TOMLRef) );
int i = 0;
for ( ; i < self->size; ++i ) {
self->members[ i ] = oldMembers[ i ];
}
// memcpy( self->members, oldMembers, self->size * sizeof(TOMLRef) );
self->members[ self->size ] = value;
self->size++;
free( oldMembers );
}
char * TOML_toString( TOMLString *self ) {
char *string = malloc( self->size + 1 );
TOML_copyString( self, self->size + 1, string );
return string;
}
#define RETURN_VALUE switch ( self->type ) { \
case TOML_INT: \
return self->intValue; \
case TOML_DOUBLE: \
return self->doubleValue; \
default: \
return 0; \
}
int TOML_toInt( TOMLNumber *self ) {
RETURN_VALUE;
}
double TOML_toDouble( TOMLNumber *self ) {
RETURN_VALUE;
}
#undef RETURN_VALUE
struct tm TOML_toTm( TOMLDate *self ) {
return *gmtime( &self->sinceEpoch );
}
int TOML_toBoolean( TOMLBoolean *self ) {
return self->isTrue;
}
TOMLToken * TOML_newToken( TOMLToken *token ) {
TOMLToken *heapToken = malloc( sizeof(TOMLToken) );
memcpy( heapToken, token, sizeof(TOMLToken) );
int size = token->end - token->start;
heapToken->tokenStr = malloc( size + 1 );
heapToken->tokenStr[ size ] = 0;
strncpy( heapToken->tokenStr, token->start, size );
return heapToken;
}
void TOML_strcpy( char *buffer, TOMLString *self, int size ) {
if ( self->type != TOML_STRING ) {
buffer[0] = 0;
} else {
strncpy(
buffer, self->content, size < self->size + 1 ? size : self->size + 1
);
}
}
char * _TOML_increaseBuffer( char *oldBuffer, int *size ) {
int newSize = *size + 1024;
char *newBuffer = malloc( newSize + 1 );
// Always have a null terminator so TOMLScan can exit without segfault.
newBuffer[ newSize ] = 0;
if ( oldBuffer ) {
strncpy( newBuffer, oldBuffer, *size + 1 );
free( oldBuffer );
}
*size = newSize;
return newBuffer;
}
int TOML_load( char *filename, TOMLTable **dest, TOMLError *error ) {
assert( *dest == NULL );
FILE *fd = fopen( filename, "r" );
if ( fd == NULL ) {
if ( error ) {
error->code = TOML_ERROR_FILEIO;
error->lineNo = -1;
error->line = NULL;
int messageSize = strlen( TOMLErrorDescription[ error->code ] );
error->message =
malloc( messageSize + 1 );
strcpy( error->message, TOMLErrorDescription[ error->code ] );
error->message[ messageSize ] = 0;
int fullDescSize = messageSize + strlen( filename ) + 8;
error->fullDescription = malloc( fullDescSize + 1 );
snprintf(
error->fullDescription,
fullDescSize,
"%s File: %s",
error->message,
filename
);
}
return TOML_ERROR_FILEIO;
}
int bufferSize = 0;
char * buffer = _TOML_increaseBuffer( NULL, &bufferSize );
int copyBufferSize = 0;
char * copyBuffer = _TOML_increaseBuffer( NULL, ©BufferSize );
int read = fread( buffer, 1, bufferSize, fd );
int incomplete = read == bufferSize;
int hTokenId;
TOMLToken token = { 0, NULL, NULL, buffer, 0, buffer, NULL };
TOMLToken lastToken = token;
TOMLTable *topTable = *dest = TOML_allocTable( NULL, NULL );
TOMLParserState state = { topTable, topTable, 0, error, &token };
pTOMLParser parser = TOMLParserAlloc( malloc );
while (
state.errorCode == 0 && (
TOMLScan( token.end, &hTokenId, &token ) || incomplete
)
) {
while ( token.end >= buffer + bufferSize && incomplete ) {
int lineSize = buffer + bufferSize - lastToken.lineStart;
if ( lastToken.lineStart == buffer ) {
int oldBufferSize = bufferSize;
strncpy( copyBuffer, lastToken.lineStart, lineSize );
buffer = _TOML_increaseBuffer( buffer, &bufferSize );
copyBuffer = _TOML_increaseBuffer( copyBuffer, ©BufferSize );
strncpy( buffer, copyBuffer, lineSize );
} else {
strncpy( copyBuffer, lastToken.lineStart, lineSize );
strncpy( buffer, copyBuffer, lineSize );
}
int read = fread( buffer + lineSize, 1, bufferSize - lineSize, fd );
incomplete = read == bufferSize - lineSize;
if ( !incomplete ) {
buffer[ lineSize + read ] = 0;
}
token = lastToken;
token.end = buffer + ( token.end - token.lineStart );
token.lineStart = buffer;
lastToken = token;
TOMLScan( token.end, &hTokenId, &token );
}
lastToken = token;
int tmpSize = token.end - token.start;
char *tmp = malloc( tmpSize + 1 );
strncpy( tmp, token.start, tmpSize );
tmp[ tmpSize ] = 0;
free( tmp );
TOMLParser( parser, hTokenId, TOML_newToken( &token ), &state );
}
if ( state.errorCode == 0 ) {
TOMLParser( parser, hTokenId, TOML_newToken( &token ), &state );
}
TOMLParserFree( parser, free );
free( copyBuffer );
free( buffer );
fclose( fd );
if ( state.errorCode != 0 ) {
TOML_free( *dest );
*dest = NULL;
return state.errorCode;
}
return 0;
}
// int TOML_dump( char *filename, TOMLTable * );
int TOML_parse( char *buffer, TOMLTable **dest, TOMLError *error ) {
assert( *dest == NULL );
int hTokenId;
TOMLToken token = { 0, NULL, NULL, buffer, 0, buffer, NULL };
TOMLTable *topTable = *dest = TOML_allocTable( NULL, NULL );
TOMLParserState state = { topTable, topTable, 0, error, &token };
pTOMLParser parser = TOMLParserAlloc( malloc );
while ( state.errorCode == 0 && TOMLScan( token.end, &hTokenId, &token ) ) {
TOMLParser( parser, hTokenId, TOML_newToken( &token ), &state );
}
if ( state.errorCode == 0 ) {
TOMLParser( parser, hTokenId, TOML_newToken( &token ), &state );
}
TOMLParserFree( parser, free );
if ( state.errorCode != 0 ) {
TOML_free( *dest );
*dest = NULL;
return state.errorCode;
}
return 0;
}
TOMLString ** _TOML_increaseNameStack(
TOMLString **nameStack, int *nameStackSize
) {
TOMLString **oldStack = nameStack;
int oldSize = *nameStackSize;
*nameStackSize += 16;
nameStack = malloc( *nameStackSize * sizeof(TOMLString *) );
if ( oldStack ) {
memcpy( nameStack, oldStack, oldSize );
free( oldStack );
}
return nameStack;
}
void _TOML_stringifyPushName(
struct _TOMLStringifyData *self, TOMLRef src
) {
if ( self->tableNameDepth >= self->tableNameStackSize ) {
self->tableNameStack = _TOML_increaseNameStack(
self->tableNameStack,
&( self->tableNameStackSize )
);
}
self->tableNameStack[ self->tableNameDepth ] = src;
self->tableNameDepth++;
}
void _TOML_stringifyPopName(
struct _TOMLStringifyData *self
) {
self->tableNameDepth--;
self->tableNameStack[ self->tableNameDepth ] = NULL;
}
void _TOML_stringifyText( struct _TOMLStringifyData *self, char *text, int n ) {
if ( self->bufferIndex + n + 1 >= self->bufferSize ) {
self->buffer = _TOML_increaseBuffer( self->buffer, &self->bufferSize );
}
strncpy( self->buffer + self->bufferIndex, text, n );
self->bufferIndex += n;
self->buffer[ self->bufferIndex ] = 0;
}
void _TOML_stringifyTableHeader(
struct _TOMLStringifyData *self, TOMLTable *table
) {
TOMLBasic *first = TOMLArray_getIndex( table->values, 0 );
if (
!first ||
first->type == TOML_TABLE || (
first->type == TOML_ARRAY &&
((TOMLArray *) first)->memberType == TOML_TABLE
)
) {
return;
}
if ( self->bufferIndex != 0 ) {
_TOML_stringifyText( self, "\n", 1 );
}
_TOML_stringifyText( self, "[", 1 );
for ( int i = 0; i < self->tableNameDepth; ++i ) {
TOMLString *tableName = self->tableNameStack[ i ];
if ( i > 0 ) {
_TOML_stringifyText( self, ".", 1 );
}
_TOML_stringifyText( self, tableName->content, tableName->size );
}
_TOML_stringifyText( self, "]\n", 2 );
}
void _TOML_stringifyArrayHeader( struct _TOMLStringifyData *self ) {
if ( self->bufferIndex != 0 ) {
_TOML_stringifyText( self, "\n", 1 );
}
_TOML_stringifyText( self, "[[", 2 );
for ( int i = 0; i < self->tableNameDepth; ++i ) {
TOMLString *tableName = self->tableNameStack[ i ];
if ( i > 0 ) {
_TOML_stringifyText( self, ".", 1 );
}
_TOML_stringifyText( self, tableName->content, tableName->size );
}
_TOML_stringifyText( self, "]]\n", 3 );
}
void _TOML_stringifyString(
struct _TOMLStringifyData *self, TOMLString *string
) {
char *cursor = string->content;
while ( cursor != NULL ) {
// Scan for escapable character or unicode.
char *next = cursor;
unsigned int ch = *next;
for ( ;
!(
ch == 0 ||
ch == '\b' ||
ch == '\t' ||
ch == '\f' ||
ch == '\n' ||
ch == '\r' ||
ch == '"' ||
ch == '/' ||
ch == '\\' ||
ch > 0x7f
);
next++, ch = *next
) {}
if ( *next == 0 ) {
next = NULL;
}
// Copy text up to character and then insert escaped character.
if ( next ) {
_TOML_stringifyText( self, cursor, next - cursor );
#define REPLACE( match, value ) \
if ( *next == match ) { \
_TOML_stringifyText( self, value, 2 ); \
}
REPLACE( '\b', "\\b" )
else REPLACE( '\t', "\\t" )
else REPLACE( '\f', "\\f" )
else REPLACE( '\n', "\\n" )
else REPLACE( '\r', "\\r" )
else REPLACE( '"', "\\\"" )
else REPLACE( '/', "\\/" )
else REPLACE( '\\', "\\\\" )
#undef REPLACE
else if ( ((unsigned int) *next ) > 0x7f ) {
int num = 0;
int chsize;
// Decode the numeric representation of the utf8 character
if ( ( *next & 0xe0 ) == 0xe0 ) {
chsize = 3;
num =
( ( next[0] & 0x0f ) << 12 ) |
( ( next[1] & 0x3f ) << 6 ) |
( next[2] & 0x3f );
} else if ( ( *next & 0xc0 ) == 0xc0 ) {
chsize = 2;
num =
( ( next[0] & 0x1f ) << 6 ) |
( next[1] & 0x3f );
} else {
assert( 0 );
}
// Stringify \uxxxx
char utf8Buffer[5];
snprintf( utf8Buffer, 5, "%04x", num );
_TOML_stringifyText( self, "\\u", 2 );
_TOML_stringifyText( self, utf8Buffer, 4 );
next += chsize - 1;
}
next++;
// Copy everything up to the end.
} else {
_TOML_stringifyText( self, cursor, strlen( cursor ) );
}
cursor = next;
}
}
void _TOML_stringifyEntry(
struct _TOMLStringifyData *self, TOMLString *key, TOMLBasic *value
) {
_TOML_stringifyText( self, key->content, key->size );
_TOML_stringifyText( self, " = ", 3 );
if ( value->type == TOML_STRING ) {
_TOML_stringifyText( self, "\"", 1 );
_TOML_stringifyString( self, (TOMLString *) value );
_TOML_stringifyText( self, "\"", 1 );
} else {
_TOML_stringify( self, value );
}
_TOML_stringifyText( self, "\n", 1 );
}
int _TOML_stringify(
struct _TOMLStringifyData *self, TOMLRef src
) {
// Cast to TOMLBasic to discover type.
TOMLBasic *basic = src;
// if null
if ( src == NULL ) {
_TOML_stringifyText( self, "(null)", 6 );
// if table
} else if ( basic->type == TOML_TABLE ) {
TOMLTable *table = src;
// loop keys
for ( int i = 0; i < table->keys->size; ++i ) {
TOMLRef key = TOMLArray_getIndex( table->keys, i );
TOMLRef value = TOMLArray_getIndex( table->values, i );
TOMLBasic *basicValue = value;
// if value is table, print header, recurse
if ( basicValue->type == TOML_TABLE ) {
TOMLTable *tableValue = value;
_TOML_stringifyPushName( self, key );
_TOML_stringifyTableHeader( self, value );
_TOML_stringify( self, value );
_TOML_stringifyPopName( self );
// if value is array
} else if ( basicValue->type == TOML_ARRAY ) {
TOMLArray *array = value;
// if value is object array
if ( array->memberType == TOML_TABLE ) {
// loop indices, print headers, recurse
for ( int j = 0; j < array->size; ++j ) {
_TOML_stringifyPushName( self, key );
_TOML_stringifyArrayHeader( self );
_TOML_stringify( self, TOMLArray_getIndex( array, j ) );
_TOML_stringifyPopName( self );
}
} else {
// print entry line with dense (no newlines) array
_TOML_stringifyEntry( self, key, value );
}
} else {
// if value is string or number, print entry
_TOML_stringifyEntry( self, key, value );
}
}
// if array
} else if ( basic->type == TOML_ARRAY ) {
TOMLArray *array = src;
// print array densely
_TOML_stringifyText( self, "[", 1 );
for ( int i = 0; i < array->size; ++i ) {
_TOML_stringifyText( self, " ", 1 );
TOMLBasic *arrayValue = TOMLArray_getIndex( array, i );
if ( arrayValue->type == TOML_STRING ) {
_TOML_stringifyText( self, "\"", 1 );
_TOML_stringifyString( self, (TOMLString *) arrayValue );
_TOML_stringifyText( self, "\"", 1 );
} else {
_TOML_stringify( self, arrayValue );
}
if ( i != array->size - 1 ) {
_TOML_stringifyText( self, ",", 1 );
} else {
_TOML_stringifyText( self, " ", 1 );
}
}
_TOML_stringifyText( self, "]", 1 );
// if string
} else if ( basic->type == TOML_STRING ) {
TOMLString *string = src;
// print string
_TOML_stringifyText( self, string->content, string->size );
// if number
} else if ( TOML_isNumber( basic ) ) {
TOMLNumber *number = src;
char numberBuffer[ 16 ];
memset( numberBuffer, 0, 16 );
int size;
if ( number->type == TOML_INT ) {
size = snprintf( numberBuffer, 15, "%d", number->intValue );
} else if ( fmod( number->doubleValue, 1 ) == 0 ) {
size = snprintf( numberBuffer, 15, "%.1f", number->doubleValue );
} else {
size = snprintf( numberBuffer, 15, "%g", number->doubleValue );
}
// print number
_TOML_stringifyText( self, numberBuffer, size );
} else if ( basic->type == TOML_BOOLEAN ) {
TOMLBoolean *boolean = (TOMLBoolean *) basic;
if ( boolean->isTrue ) {
_TOML_stringifyText( self, "true", 4 );
} else {
_TOML_stringifyText( self, "false", 5 );
}
} else if ( basic->type == TOML_DATE ) {
TOMLDate *date = (TOMLDate *) basic;
char numberBuffer[ 16 ];
int size;
#define STRINGIFY_DATE_SECTION( format, part, spacer ) \
size = snprintf( numberBuffer, 15, format, date->part ); \
_TOML_stringifyText( self, numberBuffer, size ); \
_TOML_stringifyText( self, spacer, 1 )
STRINGIFY_DATE_SECTION( "%d", year, "-" );
STRINGIFY_DATE_SECTION( "%0.2d", month, "-" );
STRINGIFY_DATE_SECTION( "%0.2d", day, "T" );
STRINGIFY_DATE_SECTION( "%0.2d", hour, ":" );
STRINGIFY_DATE_SECTION( "%0.2d", minute, ":" );
STRINGIFY_DATE_SECTION( "%0.2d", second, "Z" );
#undef STRINGIFY_DATE_SECTION
} else {
assert( 0 );
}
// if error
// print error
return 0;
}
int TOML_stringify( char **buffer, TOMLRef src, TOMLError *error ) {
int bufferSize = 0;
char *output = _TOML_increaseBuffer( NULL, &bufferSize );
int stackSize = 0;
TOMLString **tableNameStack = _TOML_increaseNameStack( NULL, &stackSize );
struct _TOMLStringifyData stringifyData = {
error,
bufferSize,
0,
output,
0,
stackSize,
tableNameStack
};
int errorCode = _TOML_stringify( &stringifyData, src );
free( tableNameStack );
*buffer = stringifyData.buffer;
return errorCode;
}
| mit |
anamartinez/enefele | config/environments/test.rb | 1561 | Enefele::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| mit |
javanigus/zabuun | essay/0006-the-first-song.php | 1193 | <!doctype html>
<html class="no-js" lang="">
<head>
<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
<meta name="description" content="">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>
<div class="content">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>
<div class="main">
<div class="location">
<p class="breadcrumbs">Essays > The First Song</p>
<p class="expandcollapse">
<a href="">Expand All</a> | <a href="">Collapse All</a>
</p>
</div>
<!-- begin essay -->
<h1>The First Song</h1>
<p> She sits in the car. Her dad turns on the radio. A song plays. She taps her feet. She sways her head. Her dad laughs at her. He likes the song too. The song is over. The radio plays a different song. She does not like the new song. She sits quietly. </p>
<!-- end essay -->
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>
</body>
</html> | mit |
mouadino/go-nano | cli/nano-client/main.go | 551 | package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "nano-client"
app.Usage = "Send a request to service"
app.Version = Version
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "service, s",
Usage: "Service endpoint to send request to (Required)",
},
cli.StringFlag{
Name: "method, m",
Usage: "RPC method to call (Required)",
},
cli.StringFlag{
Name: "params, p",
Usage: "Parameters as JSON (Required)",
},
}
//app.Action = SendRequest
app.Run(os.Args)
}
| mit |
feathersjs/generator-feathers | generators/app/templates/ts/src/index.ts | 352 | import logger from './logger';
import app from './app';
const port = app.get('port');
const server = app.listen(port);
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d', app.get('host'), port)
);
| mit |
EvilFreelancer/gistoria | README.md | 1172 | # Gistoria
[**Gistoria**](http://gistoria.drteam.rocks/) it's a **Gist** of the some of **Stories** - a project devoted to Russian literature.
Online development streams every Monday, Wednesday and Friday.
https://www.twitch.tv/evilfreelancer
If you can help to **Gistoria** it will be great!
## How to install
git clone [email protected]:EvilFreelancer/gistoria.git
cd gistoria
composer update
bower update
Next you need to create the Mongo database.
[Here](https://github.com/EvilFreelancer/gistoria/blob/master/backup/gistoria.mongo) you can find few simple steps for this.
And if you follow [this link](http://gistoria.drteam.rocks/dumps/), you can get the full Gistoria dump.
## Mockups
* [Authors list](https://wireframe.cc/VoEgll)
* [Author books](https://wireframe.cc/UhQfqU)
* [All chapters of book](https://wireframe.cc/lGuckb)
* [Book chapter with pages](https://wireframe.cc/suaAiC)
## Authors
* [@EvilFreelancer](https://github.com/EvilFreelancer)
## System Requirements
* MongoDB >= 2.6
* PHP >= 7.0
* php-mbstring
* php-mongodb
## Links
* [Start Bootstrap - New Age](https://github.com/BlackrockDigital/startbootstrap-new-age)
| mit |
gphat/datadog-scala | src/test/scala/ServiceCheckSpec.scala | 1484 | package test
import akka.actor.ActorSystem
import akka.pattern.AskTimeoutException
import github.gphat.datadog._
import java.nio.charset.StandardCharsets
import org.json4s._
import org.json4s.native.JsonMethods._
import org.specs2.mutable.Specification
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await,Future,Promise}
import scala.util.Try
import spray.http._
class ServiceCheckSpec extends Specification {
implicit val formats = DefaultFormats
// Sequential because it's less work to share the client instance
sequential
"Client" should {
val adapter = new OkHttpAdapter()
val client = new Client(
apiKey = "apiKey",
appKey = "appKey",
httpAdapter = adapter
)
"handle add service check" in {
val res = Await.result(
client.addServiceCheck(
check = "app.is_ok", hostName = "app1", status = 0
), Duration(5, "second")
)
res.statusCode must beEqualTo(200)
val uri = adapter.getRequest.get.uri.toString
uri must contain("https://app.datadoghq.com/api/v1/check_run")
val params = adapter.getRequest.get.uri.query.toMap
params must havePairs(
"api_key" -> "apiKey",
"application_key" -> "appKey",
"check" -> "app.is_ok",
"host_name" -> "app1",
"status" -> "0"
)
adapter.getRequest must beSome.which(_.method == HttpMethods.POST)
}
}
}
| mit |
mezza/rubyXL | rdoc/RubyXL/CellStyle.html | 2528 | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>class RubyXL::CellStyle - rubyXL 3.3.29</title>
<script type="text/javascript">
var rdoc_rel_prefix = "../";
var index_rel_prefix = "../";
</script>
<script src="../js/jquery.js"></script>
<script src="../js/darkfish.js"></script>
<link href="../css/fonts.css" rel="stylesheet">
<link href="../css/rdoc.css" rel="stylesheet">
<body id="top" role="document" class="class">
<nav role="navigation">
<div id="project-navigation">
<div id="home-section" role="region" title="Quick navigation" class="nav-section">
<h2>
<a href="../index.html" rel="home">Home</a>
</h2>
<div id="table-of-contents-navigation">
<a href="../table_of_contents.html#pages">Pages</a>
<a href="../table_of_contents.html#classes">Classes</a>
<a href="../table_of_contents.html#methods">Methods</a>
</div>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<div id="search-field-wrapper">
<input id="search-field" role="combobox" aria-label="Search"
aria-autocomplete="list" aria-controls="search-results"
type="text" name="search" placeholder="Search" spellcheck="false"
title="Type to search, Up and Down to navigate, Enter to load">
</div>
<ul id="search-results" aria-label="Search Results"
aria-busy="false" aria-expanded="false"
aria-atomic="false" class="initially-hidden"></ul>
</form>
</div>
</div>
<div id="class-metadata">
<div id="parent-class-section" class="nav-section">
<h3>Parent</h3>
<p class="link">OOXMLObject
</div>
</div>
</nav>
<main role="main" aria-labelledby="class-RubyXL::CellStyle">
<h1 id="class-RubyXL::CellStyle" class="class">
class RubyXL::CellStyle
</h1>
<section class="description">
<p><a
href="http://www.datypic.com/sc/ooxml/e-ssml_cellStyle-1.html">www.datypic.com/sc/ooxml/e-ssml_cellStyle-1.html</a></p>
</section>
<section id="5Buntitled-5D" class="documentation-section">
</section>
</main>
<footer id="validator-badges" role="contentinfo">
<p><a href="http://validator.w3.org/check/referer">Validate</a>
<p>Generated by <a href="https://rdoc.github.io/rdoc">RDoc</a> 5.1.0.
<p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/ContactFolderCollectionResponse.java | 765 | // Template Source: BaseEntityCollectionResponse.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.ContactFolder;
import com.microsoft.graph.http.BaseCollectionResponse;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Contact Folder Collection Response.
*/
public class ContactFolderCollectionResponse extends BaseCollectionResponse<ContactFolder> {
}
| mit |
zxing-js/library | src/test/core/common/reedsolomon/ReedSolomon.spec.ts | 32086 | /*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*package com.google.zxing.common.reedsolomon;*/
import * as assert from 'assert';
import { ZXingStringBuilder } from '@zxing/library';
import Random from '../../../core/util/Random';
import { ZXingSystem } from '@zxing/library';
import { GenericGF } from '@zxing/library';
import { ReedSolomonEncoder } from '@zxing/library';
import { ReedSolomonDecoder } from '@zxing/library';
/*import java.util.Random;*/
import { corrupt } from './ReedSolomonCorrupt';
/**
* @author Rustam Abdullaev
*/
describe('ReedSolomonSpec', () => {
it('testDataMatrix 1 - real life test case', () => {
testEncodeDecode(
GenericGF.DATA_MATRIX_FIELD_256,
Int32Array.from([142, 164, 186]),
Int32Array.from([114, 25, 5, 88, 102])
);
});
it('testDataMatrix 2 - real life test case', () => {
testEncodeDecode(
GenericGF.DATA_MATRIX_FIELD_256,
Int32Array.from([
0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64,
0x70, 0x65, 0x66, 0x2F, 0x68, 0x70, 0x70, 0x68,
0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71,
0x30, 0x7B, 0x79, 0x6A, 0x6F, 0x68, 0x30, 0x81,
0xF0, 0x88, 0x1F, 0xB5
]),
Int32Array.from([
0x1C, 0x64, 0xEE, 0xEB, 0xD0, 0x1D, 0x00, 0x03,
0xF0, 0x1C, 0xF1, 0xD0, 0x6D, 0x00, 0x98, 0xDA,
0x80, 0x88, 0xBE, 0xFF, 0xB7, 0xFA, 0xA9, 0x95
])
);
});
it('testDataMatrix 3.1 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 10, 240);
});
it('testDataMatrix 3.2 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 128, 127);
});
it('testDataMatrix 3.3 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 220, 35);
});
it('testQRCode 1 - from example given in ISO 18004, Annex I', () => {
// Test case from example given in ISO 18004, Annex I
testEncodeDecode(
GenericGF.QR_CODE_FIELD_256,
Int32Array.from([
0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11
]),
Int32Array.from([
0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87,
0x2C, 0x55
])
);
});
it('testQRCode 2 - real life test case', () => {
testEncodeDecode(
GenericGF.QR_CODE_FIELD_256,
Int32Array.from([
0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F,
0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50, 0x61, 0x67,
0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11
]),
Int32Array.from([
0xD8, 0xB8, 0xEF, 0x14, 0xEC, 0xD0, 0xCC, 0x85,
0x73, 0x40, 0x0B, 0xB5, 0x5A, 0xB8, 0x8B, 0x2E,
0x08, 0x62
])
);
});
it('testQRCode 3.1 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 10, 240);
});
it('testQRCode 3.2 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 128, 127);
});
it('testQRCode 3.3 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 220, 35);
});
it('testAztec 1 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_PARAM,
Int32Array.from([0x5, 0x6]),
Int32Array.from([0x3, 0x2, 0xB, 0xB, 0x7])
);
});
it('testAztec 2 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_PARAM,
Int32Array.from([0x0, 0x0, 0x0, 0x9]),
Int32Array.from([0xA, 0xD, 0x8, 0x6, 0x5, 0x6])
);
});
it('testAztec 3 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_PARAM,
Int32Array.from([0x2, 0x8, 0x8, 0x7]),
Int32Array.from([0xE, 0xC, 0xA, 0x9, 0x6, 0x8])
);
});
it('testAztec 4 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_DATA_6,
Int32Array.from([0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B]),
Int32Array.from([0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14])
);
});
it('testAztec 5 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_DATA_8,
Int32Array.from([
0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6,
0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA, 0xF8, 0xCE,
0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9,
0x6C, 0x6B, 0x9F, 0x08, 0xCA, 0x74, 0xAD, 0xAF,
0x8C, 0xEB, 0x7C, 0x10, 0xC8, 0x53, 0x1D, 0x09,
0x52, 0xD8, 0xD7, 0x3E, 0x11, 0x94, 0xE9, 0x5B,
0x5F, 0x19, 0xD6, 0xFB, 0xD1, 0x0C, 0x85, 0x31,
0xD0, 0x95, 0x2D, 0x8D, 0x73, 0xE1, 0x19, 0x4E,
0x95, 0xB5, 0xF1, 0x9D, 0x6F]),
Int32Array.from([
0x31, 0xD7, 0x04, 0x46, 0xB2, 0xC1, 0x06, 0x94,
0x17, 0xE5, 0x0C, 0x2B, 0xA3, 0x99, 0x15, 0x7F,
0x16, 0x3C, 0x66, 0xBA, 0x33, 0xD9, 0xE8, 0x87,
0x86, 0xBB, 0x4B, 0x15, 0x4E, 0x4A, 0xDE, 0xD4,
0xED, 0xA1, 0xF8, 0x47, 0x2A, 0x50, 0xA6, 0xBC,
0x53, 0x7D, 0x29, 0xFE, 0x06, 0x49, 0xF3, 0x73,
0x9F, 0xC1, 0x75])
);
});
it('testAztec 6 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_DATA_10,
Int32Array.from([
0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD,
0x02E, 0x056, 0x26A, 0x281, 0x1C2, 0x1A6, 0x296, 0x045,
0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2,
0x036, 0x1AD, 0x04E, 0x090, 0x271, 0x0D3, 0x02E, 0x0D5,
0x2D4, 0x032, 0x2CA, 0x281, 0x0AA, 0x04E, 0x024, 0x2D3,
0x296, 0x281, 0x0E2, 0x08A, 0x1AA, 0x28A, 0x280, 0x07C,
0x286, 0x0A1, 0x1D0, 0x1AD, 0x154, 0x032, 0x2C2, 0x1C1,
0x145, 0x02B, 0x2D4, 0x2B0, 0x033, 0x2D5, 0x276, 0x1C1,
0x282, 0x10A, 0x2B5, 0x154, 0x003, 0x385, 0x20F, 0x0C4,
0x02D, 0x050, 0x266, 0x0D5, 0x033, 0x2D5, 0x276, 0x1C1,
0x0D4, 0x2A0, 0x08F, 0x0C4, 0x024, 0x20F, 0x2E2, 0x1AD,
0x154, 0x02E, 0x056, 0x26A, 0x281, 0x090, 0x1E5, 0x14E,
0x0CF, 0x2B6, 0x1C1, 0x28A, 0x2A1, 0x04E, 0x0D5, 0x003,
0x391, 0x122, 0x286, 0x1AD, 0x2D4, 0x028, 0x262, 0x2EA,
0x0A2, 0x004, 0x176, 0x295, 0x201, 0x0D5, 0x024, 0x20F,
0x116, 0x0C1, 0x056, 0x095, 0x213, 0x004, 0x1EA, 0x28A,
0x02A, 0x234, 0x2CE, 0x037, 0x157, 0x0D3, 0x262, 0x026,
0x262, 0x2A0, 0x086, 0x106, 0x2A1, 0x126, 0x1E5, 0x266,
0x26A, 0x2A1, 0x0E6, 0x1AA, 0x281, 0x2B6, 0x271, 0x154,
0x02F, 0x0C4, 0x02D, 0x213, 0x0CE, 0x003, 0x38F, 0x2CD,
0x1A2, 0x036, 0x1B5, 0x26A, 0x086, 0x280, 0x086, 0x1AA,
0x2A1, 0x226, 0x1AD, 0x0CF, 0x2A6, 0x292, 0x2C6, 0x022,
0x1AA, 0x256, 0x0D5, 0x02D, 0x050, 0x266, 0x0D5, 0x004,
0x176, 0x295, 0x201, 0x0D3, 0x055, 0x031, 0x2CD, 0x2EA,
0x1E2, 0x261, 0x1EA, 0x28A, 0x004, 0x145, 0x026, 0x1A6,
0x1C6, 0x1F5, 0x2CE, 0x034, 0x051, 0x146, 0x1E1, 0x0B0,
0x1B0, 0x261, 0x0D5, 0x025, 0x142, 0x1C0, 0x07C, 0x0B0,
0x1E6, 0x081, 0x044, 0x02F, 0x2CF, 0x081, 0x290, 0x0A2,
0x1A6, 0x281, 0x0CD, 0x155, 0x031, 0x1A2, 0x086, 0x262,
0x2A1, 0x0CD, 0x0CA, 0x0E6, 0x1E5, 0x003, 0x394, 0x0C5,
0x030, 0x26F, 0x053, 0x0C1, 0x1B6, 0x095, 0x2D4, 0x030,
0x26F, 0x053, 0x0C0, 0x07C, 0x2E6, 0x295, 0x143, 0x2CD,
0x2CE, 0x037, 0x0C9, 0x144, 0x2CD, 0x040, 0x08E, 0x054,
0x282, 0x022, 0x2A1, 0x229, 0x053, 0x0D5, 0x262, 0x027,
0x26A, 0x1E8, 0x14D, 0x1A2, 0x004, 0x26A, 0x296, 0x281,
0x176, 0x295, 0x201, 0x0E2, 0x2C4, 0x143, 0x2D4, 0x026,
0x262, 0x2A0, 0x08F, 0x0C4, 0x031, 0x213, 0x2B5, 0x155,
0x213, 0x02F, 0x143, 0x121, 0x2A6, 0x1AD, 0x2D4, 0x034,
0x0C5, 0x026, 0x295, 0x003, 0x396, 0x2A1, 0x176, 0x295,
0x201, 0x0AA, 0x04E, 0x004, 0x1B0, 0x070, 0x275, 0x154,
0x026, 0x2C1, 0x2B3, 0x154, 0x2AA, 0x256, 0x0C1, 0x044,
0x004, 0x23F
]),
Int32Array.from([
0x379, 0x099, 0x348, 0x010, 0x090, 0x196, 0x09C, 0x1FF,
0x1B0, 0x32D, 0x244, 0x0DE, 0x201, 0x386, 0x163, 0x11F,
0x39B, 0x344, 0x3FE, 0x02F, 0x188, 0x113, 0x3D9, 0x102,
0x04A, 0x2E1, 0x1D1, 0x18E, 0x077, 0x262, 0x241, 0x20D,
0x1B8, 0x11D, 0x0D0, 0x0A5, 0x29C, 0x24D, 0x3E7, 0x006,
0x2D0, 0x1B7, 0x337, 0x178, 0x0F1, 0x1E0, 0x00B, 0x01E,
0x0DA, 0x1C6, 0x2D9, 0x00D, 0x28B, 0x34A, 0x252, 0x27A,
0x057, 0x0CA, 0x2C2, 0x2E4, 0x3A6, 0x0E3, 0x22B, 0x307,
0x174, 0x292, 0x10C, 0x1ED, 0x2FD, 0x2D4, 0x0A7, 0x051,
0x34F, 0x07A, 0x1D5, 0x01D, 0x22E, 0x2C2, 0x1DF, 0x08F,
0x105, 0x3FE, 0x286, 0x2A2, 0x3B1, 0x131, 0x285, 0x362,
0x315, 0x13C, 0x0F9, 0x1A2, 0x28D, 0x246, 0x1B3, 0x12C,
0x2AD, 0x0F8, 0x222, 0x0EC, 0x39F, 0x358, 0x014, 0x229,
0x0C8, 0x360, 0x1C2, 0x031, 0x098, 0x041, 0x3E4, 0x046,
0x332, 0x318, 0x2E3, 0x24E, 0x3E2, 0x1E1, 0x0BE, 0x239,
0x306, 0x3A5, 0x352, 0x351, 0x275, 0x0ED, 0x045, 0x229,
0x0BF, 0x05D, 0x253, 0x1BE, 0x02E, 0x35A, 0x0E4, 0x2E9,
0x17A, 0x166, 0x03C, 0x007
])
);
});
it('testAztec 7 - real life test case', () => {
testEncodeDecode(
GenericGF.AZTEC_DATA_12,
Int32Array.from([
0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85,
0x69A, 0xA81, 0x709, 0xA6A, 0x584, 0x510, 0x4AA, 0x256,
0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C,
0x4D3, 0x0B8, 0xD5B, 0x503, 0x2B2, 0xA81, 0x2A8, 0x4E0,
0x92D, 0x3A5, 0xA81, 0x388, 0x8A6, 0xAA8, 0xAA0, 0x07C,
0xA18, 0xA17, 0x41A, 0xD55, 0x032, 0xB09, 0xC15, 0x142,
0xBB5, 0x2B0, 0x0CE, 0xD59, 0xD9C, 0x1A0, 0x90A, 0xAD5,
0x540, 0x0F8, 0x583, 0xCC4, 0x0B4, 0x509, 0x98D, 0x50C,
0xED5, 0x9D9, 0xC13, 0x52A, 0x023, 0xCC4, 0x092, 0x0FB,
0x89A, 0xD55, 0x02E, 0x15A, 0x6AA, 0x049, 0x079, 0x54E,
0x33E, 0xB67, 0x068, 0xAA8, 0x44E, 0x354, 0x03E, 0x452,
0x2A1, 0x9AD, 0xB50, 0x289, 0x8AE, 0xA28, 0x804, 0x5DA,
0x958, 0x04D, 0x509, 0x20F, 0x458, 0xC11, 0x589, 0x584,
0xC04, 0x7AA, 0x8A0, 0xAA3, 0x4B3, 0x837, 0x55C, 0xD39,
0x882, 0x698, 0xAA0, 0x219, 0x06A, 0x852, 0x679, 0x666,
0x9AA, 0xA13, 0x99A, 0xAA0, 0x6B6, 0x9C5, 0x540, 0xBCC,
0x40B, 0x613, 0x338, 0x03E, 0x3EC, 0xD68, 0x836, 0x6D6,
0x6A2, 0x1A8, 0x021, 0x9AA, 0xA86, 0x266, 0xB4C, 0xFA9,
0xA92, 0xB18, 0x226, 0xAA5, 0x635, 0x42D, 0x142, 0x663,
0x540, 0x45D, 0xA95, 0x804, 0xD31, 0x543, 0x1B3, 0x6EA,
0x78A, 0x617, 0xAA8, 0xA01, 0x145, 0x099, 0xA67, 0x19F,
0x5B3, 0x834, 0x145, 0x467, 0x84B, 0x06C, 0x261, 0x354,
0x255, 0x09C, 0x01F, 0x0B0, 0x798, 0x811, 0x102, 0xFB3,
0xC81, 0xA40, 0xA26, 0x9A8, 0x133, 0x555, 0x0C5, 0xA22,
0x1A6, 0x2A8, 0x4CD, 0x328, 0xE67, 0x940, 0x3E5, 0x0C5,
0x0C2, 0x6F1, 0x4CC, 0x16D, 0x895, 0xB50, 0x309, 0xBC5,
0x330, 0x07C, 0xB9A, 0x955, 0x0EC, 0xDB3, 0x837, 0x325,
0x44B, 0x344, 0x023, 0x854, 0xA08, 0x22A, 0x862, 0x914,
0xCD5, 0x988, 0x279, 0xA9E, 0x853, 0x5A2, 0x012, 0x6AA,
0x5A8, 0x15D, 0xA95, 0x804, 0xE2B, 0x114, 0x3B5, 0x026,
0x98A, 0xA02, 0x3CC, 0x40C, 0x613, 0xAD5, 0x558, 0x4C2,
0xF50, 0xD21, 0xA99, 0xADB, 0x503, 0x431, 0x426, 0xA54,
0x03E, 0x5AA, 0x15D, 0xA95, 0x804, 0xAA1, 0x380, 0x46C,
0x070, 0x9D5, 0x540, 0x9AC, 0x1AC, 0xD54, 0xAAA, 0x563,
0x044, 0x401, 0x220, 0x9F1, 0x4F0, 0xDAA, 0x170, 0x90F,
0x106, 0xE66, 0x85C, 0x2B4, 0xD54, 0x0B8, 0x4D3, 0x52C,
0x228, 0x825, 0x512, 0xB67, 0x007, 0xC7D, 0x9AD, 0x106,
0xCD6, 0x89C, 0x484, 0xE26, 0x985, 0xC6A, 0xDA8, 0x195,
0x954, 0x095, 0x427, 0x049, 0x69D, 0x2D4, 0x09C, 0x445,
0x355, 0x455, 0x003, 0xE50, 0xC50, 0xBA0, 0xD6A, 0xA81,
0x958, 0x4E0, 0xA8A, 0x15D, 0xA95, 0x806, 0x76A, 0xCEC,
0xE0D, 0x048, 0x556, 0xAAA, 0x007, 0xC2C, 0x1E6, 0x205,
0xA28, 0x4CC, 0x6A8, 0x676, 0xACE, 0xCE0, 0x9A9, 0x501,
0x1E6, 0x204, 0x907, 0xDC4, 0xD6A, 0xA81, 0x70A, 0xD35,
0x502, 0x483, 0xCAA, 0x719, 0xF5B, 0x383, 0x455, 0x422,
0x71A, 0xA01, 0xF22, 0x915, 0x0CD, 0x6DA, 0x814, 0x4C5,
0x751, 0x440, 0x22E, 0xD4A, 0xC02, 0x6A8, 0x490, 0x7A2,
0xC60, 0x8AC, 0x4AC, 0x260, 0x23D, 0x545, 0x055, 0x1A5,
0x9C1, 0xBAA, 0xE69, 0xCC4, 0x134, 0xC55, 0x010, 0xC83,
0x542, 0x933, 0xCB3, 0x34D, 0x550, 0x9CC, 0xD55, 0x035,
0xB4E, 0x2AA, 0x05E, 0x620, 0x5B0, 0x999, 0xC01, 0xF1F,
0x66B, 0x441, 0xB36, 0xB35, 0x10D, 0x401, 0x0CD, 0x554,
0x313, 0x35A, 0x67D, 0x4D4, 0x958, 0xC11, 0x355, 0x2B1,
0xAA1, 0x68A, 0x133, 0x1AA, 0x022, 0xED4, 0xAC0, 0x269,
0x8AA, 0x18D, 0x9B7, 0x53C, 0x530, 0xBD5, 0x450, 0x08A,
0x284, 0xCD3, 0x38C, 0xFAD, 0x9C1, 0xA0A, 0x2A3, 0x3C2,
0x583, 0x613, 0x09A, 0xA12, 0xA84, 0xE00, 0xF85, 0x83C,
0xC40, 0x888, 0x17D, 0x9E4, 0x0D2, 0x051, 0x34D, 0x409,
0x9AA, 0xA86, 0x2D1, 0x10D, 0x315, 0x426, 0x699, 0x473,
0x3CA, 0x01F, 0x286, 0x286, 0x137, 0x8A6, 0x60B, 0x6C4,
0xADA, 0x818, 0x4DE, 0x299, 0x803, 0xE5C, 0xD4A, 0xA87,
0x66D, 0x9C1, 0xB99, 0x2A2, 0x59A, 0x201, 0x1C2, 0xA50,
0x411, 0x543, 0x148, 0xA66, 0xACC, 0x413, 0xCD4, 0xF42,
0x9AD, 0x100, 0x935, 0x52D, 0x40A, 0xED4, 0xAC0, 0x271,
0x588, 0xA1D, 0xA81, 0x34C, 0x550, 0x11E, 0x620, 0x630,
0x9D6, 0xAAA, 0xC26, 0x17A, 0x869, 0x0D4, 0xCD6, 0xDA8,
0x1A1, 0x8A1, 0x352, 0xA01, 0xF2D, 0x50A, 0xED4, 0xAC0,
0x255, 0x09C, 0x023, 0x603, 0x84E, 0xAAA, 0x04D, 0x60D,
0x66A, 0xA55, 0x52B, 0x182, 0x220, 0x091, 0x00F, 0x8A7,
0x86D, 0x50B, 0x848, 0x788, 0x373, 0x342, 0xE15, 0xA6A,
0xA05, 0xC26, 0x9A9, 0x611, 0x441, 0x2A8, 0x95B, 0x380,
0x3E3, 0xECD, 0x688, 0x366, 0xB44, 0xE24, 0x271, 0x34C,
0x2E3, 0x56D, 0x40C, 0xACA, 0xA04, 0xAA1, 0x382, 0x4B4,
0xE96, 0xA04, 0xE22, 0x29A, 0xAA2, 0xA80, 0x1F2, 0x862,
0x85D, 0x06B, 0x554, 0x0CA, 0xC27, 0x054, 0x50A, 0xED4,
0xAC0, 0x33B, 0x567, 0x670, 0x682, 0x42A, 0xB55, 0x500,
0x3E1, 0x60F, 0x310, 0x2D1, 0x426, 0x635, 0x433, 0xB56,
0x767, 0x04D, 0x4A8, 0x08F, 0x310, 0x248, 0x3EE, 0x26B,
0x554, 0x0B8, 0x569, 0xAA8, 0x124, 0x1E5, 0x538, 0xCFA,
0xD9C, 0x1A2, 0xAA1, 0x138, 0xD50, 0x0F9, 0x148, 0xA86,
0x6B6, 0xD40, 0xA26, 0x2BA, 0x8A2, 0x011, 0x76A, 0x560,
0x135, 0x424, 0x83D, 0x163, 0x045, 0x625, 0x613, 0x011,
0xEAA, 0x282, 0xA8D, 0x2CE, 0x0DD, 0x573, 0x4E6, 0x209,
0xA62, 0xA80, 0x864, 0x1AA, 0x149, 0x9E5, 0x99A, 0x6AA,
0x84E, 0x66A, 0xA81, 0xADA, 0x715, 0x502, 0xF31, 0x02D,
0x84C, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xB59, 0xA88,
0x6A0, 0x086, 0x6AA, 0xA18, 0x99A, 0xD33, 0xEA6, 0xA4A,
0xC60, 0x89A, 0xA95, 0x8D5, 0x0B4, 0x509, 0x98D, 0x501,
0x176, 0xA56, 0x013, 0x4C5, 0x50C, 0x6CD, 0xBA9, 0xE29,
0x85E, 0xAA2, 0x804, 0x514, 0x266, 0x99C, 0x67D, 0x6CE,
0x0D0, 0x515, 0x19E, 0x12C, 0x1B0, 0x984, 0xD50, 0x954,
0x270, 0x07C, 0x2C1, 0xE62, 0x044, 0x40B, 0xECF, 0x206,
0x902, 0x89A, 0x6A0, 0x4CD, 0x554, 0x316, 0x888, 0x698,
0xAA1, 0x334, 0xCA3, 0x99E, 0x500, 0xF94, 0x314, 0x309,
0xBC5, 0x330, 0x5B6, 0x256, 0xD40, 0xC26, 0xF14, 0xCC0,
0x1F2, 0xE6A, 0x554, 0x3B3, 0x6CE, 0x0DC, 0xC95, 0x12C,
0xD10, 0x08E, 0x152, 0x820, 0x8AA, 0x18A, 0x453, 0x356,
0x620, 0x9E6, 0xA7A, 0x14D, 0x688, 0x049, 0xAA9, 0x6A0,
0x576, 0xA56, 0x013, 0x8AC, 0x450, 0xED4, 0x09A, 0x62A,
0x808, 0xF31, 0x031, 0x84E, 0xB55, 0x561, 0x30B, 0xD43,
0x486, 0xA66, 0xB6D, 0x40D, 0x0C5, 0x09A, 0x950, 0x0F9,
0x6A8, 0x576, 0xA56, 0x012, 0xA84, 0xE01, 0x1B0, 0x1C2,
0x755, 0x502, 0x6B0, 0x6B3, 0x552, 0xAA9, 0x58C, 0x111,
0x004, 0x882, 0x7C5, 0x3C3, 0x6A8, 0x5C2, 0x43C, 0x41B,
0x99A, 0x170, 0xAD3, 0x550, 0x2E1, 0x34D, 0x4B0, 0x8A2,
0x095, 0x44A, 0xD9C, 0x01F, 0x1F6, 0x6B4, 0x41B, 0x35A,
0x271, 0x213, 0x89A, 0x617, 0x1AB, 0x6A0, 0x656, 0x550,
0x255, 0x09C, 0x125, 0xA74, 0xB50, 0x271, 0x114, 0xD55,
0x154, 0x00F, 0x943, 0x142, 0xE83, 0x5AA, 0xA06, 0x561,
0x382, 0xA28, 0x576, 0xA56, 0x019, 0xDAB, 0x3B3, 0x834,
0x121, 0x55A, 0xAA8, 0x01F, 0x0B0, 0x798, 0x816, 0x8A1,
0x331, 0xAA1, 0x9DA, 0xB3B, 0x382, 0x6A5, 0x404, 0x798,
0x812, 0x41F, 0x713, 0x5AA, 0xA05, 0xC2B, 0x4D5, 0x409,
0x20F, 0x2A9, 0xC67, 0xD6C, 0xE0D, 0x155, 0x089, 0xC6A,
0x807, 0xC8A, 0x454, 0x335, 0xB6A, 0x051, 0x315, 0xD45,
0x100, 0x8BB, 0x52B, 0x009, 0xAA1, 0x241, 0xE8B, 0x182,
0x2B1, 0x2B0, 0x980, 0x8F5, 0x514, 0x154, 0x696, 0x706,
0xEAB, 0x9A7, 0x310, 0x4D3, 0x154, 0x043, 0x20D, 0x50A,
0x4CF, 0x2CC, 0xD35, 0x542, 0x733, 0x554, 0x0D6, 0xD38,
0xAA8, 0x179, 0x881, 0x6C2, 0x667, 0x007, 0xC7D, 0x9AD,
0x106, 0xCDA, 0xCD4, 0x435, 0x004, 0x335, 0x550, 0xC4C,
0xD69, 0x9F5, 0x352, 0x563, 0x044, 0xD54, 0xAC6, 0xA85,
0xA28, 0x4CC, 0x6A8, 0x08B, 0xB52, 0xB00, 0x9A6, 0x2A8,
0x636, 0x6DD, 0x4F1, 0x4C2, 0xF55, 0x140, 0x228, 0xA13,
0x34C, 0xE33, 0xEB6, 0x706, 0x828, 0xA8C, 0xF09, 0x60D,
0x84C, 0x26A, 0x84A, 0xA13, 0x803, 0xE16, 0x0F3, 0x102,
0x220, 0x5F6, 0x790, 0x348, 0x144, 0xD35, 0x026, 0x6AA,
0xA18, 0xB44, 0x434, 0xC55, 0x099, 0xA65, 0x1CC, 0xF28,
0x07C, 0xA18, 0xA18, 0x4DE, 0x299, 0x82D, 0xB12, 0xB6A,
0x061, 0x378, 0xA66, 0x00F, 0x973, 0x52A, 0xA1D, 0x9B6,
0x706, 0xE64, 0xA89, 0x668, 0x804, 0x70A, 0x941, 0x045,
0x50C, 0x522, 0x99A, 0xB31, 0x04F, 0x353, 0xD0A, 0x6B4,
0x402, 0x4D5, 0x4B5, 0x02B, 0xB52, 0xB00, 0x9C5, 0x622,
0x876, 0xA04, 0xD31, 0x540, 0x479, 0x881, 0x8C2, 0x75A,
0xAAB, 0x098, 0x5EA, 0x1A4, 0x353, 0x35B, 0x6A0, 0x686,
0x284, 0xD4A, 0x807, 0xCB5, 0x42B, 0xB52, 0xB00, 0x954,
0x270, 0x08D, 0x80E, 0x13A, 0xAA8, 0x135, 0x835, 0x9AA,
0x801, 0xF14, 0xF0D, 0xAA1, 0x709, 0x0F1, 0x06E, 0x668,
0x5C2, 0xB4D, 0x540, 0xB84, 0xD35, 0x2C2, 0x288, 0x255,
0x12B, 0x670, 0x07C, 0x7D9, 0xAD1, 0x06C, 0xD68, 0x9C4,
0x84E, 0x269, 0x85C, 0x6AD, 0xA81, 0x959, 0x540, 0x954,
0x270, 0x496, 0x9D2, 0xD40, 0x9C4, 0x453, 0x554, 0x550,
0x03E, 0x50C, 0x50B, 0xA0D, 0x6AA, 0x819, 0x584, 0xE0A,
0x8A1, 0x5DA, 0x958, 0x067, 0x6AC, 0xECE, 0x0D0, 0x485,
0x56A, 0xAA0, 0x07C, 0x2C1, 0xE62, 0x05A, 0x284, 0xCC6,
0xA86, 0x76A, 0xCEC, 0xE09, 0xA95, 0x011, 0xE62, 0x049,
0x07D, 0xC4D, 0x6AA, 0x817, 0x0AD, 0x355, 0x024, 0x83C,
0xAA7, 0x19F, 0x5B3, 0x834, 0x554, 0x227, 0x1AA, 0x01F,
0x229, 0x150, 0xCD6, 0xDA8, 0x144, 0xC57, 0x514, 0x402,
0x2ED, 0x4AC, 0x026, 0xA84, 0x907, 0xA2C, 0x608, 0xAC4,
0xAC2, 0x602, 0x3D5, 0x450, 0x551, 0xA59, 0xC1B, 0xAAE,
0x69C, 0xC41, 0x34C, 0x550, 0x10C, 0x835, 0x429, 0x33C,
0xB33, 0x4D5, 0x509, 0xCCD, 0x550, 0x35B, 0x4E2, 0xAA0,
0x5E6, 0x205, 0xB09, 0x99C, 0x09F
]),
Int32Array.from([
0xD54, 0x221, 0x154, 0x7CD, 0xBF3, 0x112, 0x89B, 0xC5E,
0x9CD, 0x07E, 0xFB6, 0x78F, 0x7FA, 0x16F, 0x377, 0x4B4,
0x62D, 0x475, 0xBC2, 0x861, 0xB72, 0x9D0, 0x76A, 0x5A1,
0x22A, 0xF74, 0xDBA, 0x8B1, 0x139, 0xDCD, 0x012, 0x293,
0x705, 0xA34, 0xDD5, 0x3D2, 0x7F8, 0x0A6, 0x89A, 0x346,
0xCE0, 0x690, 0x40E, 0xFF3, 0xC4D, 0x97F, 0x9C9, 0x016,
0x73A, 0x923, 0xBCE, 0xFA9, 0xE6A, 0xB92, 0x02A, 0x07C,
0x04B, 0x8D5, 0x753, 0x42E, 0x67E, 0x87C, 0xEE6, 0xD7D,
0x2BF, 0xFB2, 0xFF8, 0x42F, 0x4CB, 0x214, 0x779, 0x02D,
0x606, 0xA02, 0x08A, 0xD4F, 0xB87, 0xDDF, 0xC49, 0xB51,
0x0E9, 0xF89, 0xAEF, 0xC92, 0x383, 0x98D, 0x367, 0xBD3,
0xA55, 0x148, 0x9DB, 0x913, 0xC79, 0x6FF, 0x387, 0x6EA,
0x7FA, 0xC1B, 0x12D, 0x303, 0xBCA, 0x503, 0x0FB, 0xB14,
0x0D4, 0xAD1, 0xAFC, 0x9DD, 0x404, 0x145, 0x6E5, 0x8ED,
0xF94, 0xD72, 0x645, 0xA21, 0x1A8, 0xABF, 0xC03, 0x91E,
0xD53, 0x48C, 0x471, 0x4E4, 0x408, 0x33C, 0x5DF, 0x73D,
0xA2A, 0x454, 0xD77, 0xC48, 0x2F5, 0x96A, 0x9CF, 0x047,
0x611, 0xE92, 0xC2F, 0xA98, 0x56D, 0x919, 0x615, 0x535,
0x67A, 0x8C1, 0x2E2, 0xBC4, 0xBE8, 0x328, 0x04F, 0x257,
0x3F9, 0xFA5, 0x477, 0x12E, 0x94B, 0x116, 0xEF7, 0x65F,
0x6B3, 0x915, 0xC64, 0x9AF, 0xB6C, 0x6A2, 0x50D, 0xEA3,
0x26E, 0xC23, 0x817, 0xA42, 0x71A, 0x9DD, 0xDA8, 0x84D,
0x3F3, 0x85B, 0xB00, 0x1FC, 0xB0A, 0xC2F, 0x00C, 0x095,
0xC58, 0x0E3, 0x807, 0x962, 0xC4B, 0x29A, 0x6FC, 0x958,
0xD29, 0x59E, 0xB14, 0x95A, 0xEDE, 0xF3D, 0xFB8, 0x0E5,
0x348, 0x2E7, 0x38E, 0x56A, 0x410, 0x3B1, 0x4B0, 0x793,
0xAB7, 0x0BC, 0x648, 0x719, 0xE3E, 0xFB4, 0x3B4, 0xE5C,
0x950, 0xD2A, 0x50B, 0x76F, 0x8D2, 0x3C7, 0xECC, 0x87C,
0x53A, 0xBA7, 0x4C3, 0x148, 0x437, 0x820, 0xECD, 0x660,
0x095, 0x2F4, 0x661, 0x6A4, 0xB74, 0x5F3, 0x1D2, 0x7EC,
0x8E2, 0xA40, 0xA6F, 0xFC3, 0x3BE, 0x1E9, 0x52C, 0x233,
0x173, 0x4EF, 0xA7C, 0x40B, 0x14C, 0x88D, 0xF30, 0x8D9,
0xBDB, 0x0A6, 0x940, 0xD46, 0xB2B, 0x03E, 0x46A, 0x641,
0xF08, 0xAFF, 0x496, 0x68A, 0x7A4, 0x0BA, 0xD43, 0x515,
0xB26, 0xD8F, 0x05C, 0xD6E, 0xA2C, 0xF25, 0x628, 0x4E5,
0x81D, 0xA2A, 0x1FF, 0x302, 0xFBD, 0x6D9, 0x711, 0xD8B,
0xE5C, 0x5CF, 0x42E, 0x008, 0x863, 0xB6F, 0x1E1, 0x3DA,
0xACE, 0x82B, 0x2DB, 0x7EB, 0xC15, 0x79F, 0xA79, 0xDAF,
0x00D, 0x2F6, 0x0CE, 0x370, 0x7E8, 0x9E6, 0x89F, 0xAE9,
0x175, 0xA95, 0x06B, 0x9DF, 0xAFF, 0x45B, 0x823, 0xAA4,
0xC79, 0x773, 0x886, 0x854, 0x0A5, 0x6D1, 0xE55, 0xEBB,
0x518, 0xE50, 0xF8F, 0x8CC, 0x834, 0x388, 0xCD2, 0xFC1,
0xA55, 0x1F8, 0xD1F, 0xE08, 0xF93, 0x362, 0xA22, 0x9FA,
0xCE5, 0x3C3, 0xDD4, 0xC53, 0xB94, 0xAD0, 0x6EB, 0x68D,
0x660, 0x8FC, 0xBCD, 0x914, 0x16F, 0x4C0, 0x134, 0xE1A,
0x76F, 0x9CB, 0x660, 0xEA0, 0x320, 0x15A, 0xCE3, 0x7E8,
0x03E, 0xB9A, 0xC90, 0xA14, 0x256, 0x1A8, 0x639, 0x7C6,
0xA59, 0xA65, 0x956, 0x9E4, 0x592, 0x6A9, 0xCFF, 0x4DC,
0xAA3, 0xD2A, 0xFDE, 0xA87, 0xBF5, 0x9F0, 0xC32, 0x94F,
0x675, 0x9A6, 0x369, 0x648, 0x289, 0x823, 0x498, 0x574,
0x8D1, 0xA13, 0xD1A, 0xBB5, 0xA19, 0x7F7, 0x775, 0x138,
0x949, 0xA4C, 0xE36, 0x126, 0xC85, 0xE05, 0xFEE, 0x962,
0x36D, 0x08D, 0xC76, 0x1E1, 0x1EC, 0x8D7, 0x231, 0xB68,
0x03C, 0x1DE, 0x7DF, 0x2B1, 0x09D, 0xC81, 0xDA4, 0x8F7,
0x6B9, 0x947, 0x9B0
])
);
});
it('testAztec 8.1 - synthetic test cases (compact mode message)', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_PARAM, 2, 5);
});
it('testAztec 8.2 - synthetic test cases (full mode message)', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_PARAM, 4, 6);
});
it('testAztec 8.3 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_6, 10, 7);
});
it('testAztec 8.4 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_6, 20, 12);
});
it('testAztec 8.5 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_8, 20, 11);
});
it('testAztec 8.6 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_8, 128, 127);
});
it('testAztec 8.7 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_10, 128, 128);
});
it('testAztec 8.8 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_10, 768, 255);
});
it('testAztec 8.9 - synthetic test cases', () => {
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_12, 3072, 1023);
});
});
const DECODER_RANDOM_TEST_ITERATIONS: number /*int*/ = 3;
const DECODER_TEST_ITERATIONS: number /*int*/ = 10;
function testEncodeDecodeRandom(field: GenericGF, dataSize: number /*int*/, ecSize: number /*int*/): void {
assert.strictEqual(dataSize > 0 && dataSize <= field.getSize() - 3, true, 'Invalid data size for ' + field);
assert.strictEqual(ecSize > 0 && ecSize + dataSize <= field.getSize(), true, 'Invalid ECC size for ' + field);
const encoder = new ReedSolomonEncoder(field);
const message = new Int32Array(dataSize + ecSize);
const dataWords = new Int32Array(dataSize); /*Int32Array(dataSize)*/
const ecWords = new Int32Array(ecSize); /*Int32Array(ecSize)*/
const random: Random = getPseudoRandom();
const iterations: number /*int*/ = field.getSize() > 256 ? 1 : DECODER_RANDOM_TEST_ITERATIONS;
for (let i: number /*int*/ = 0; i < iterations; i++) {
// generate random data
for (let k: number /*int*/ = 0; k < dataSize; k++) {
dataWords[k] = random.next(field.getSize());
}
// generate ECC words
ZXingSystem.arraycopy(dataWords, 0, message, 0, dataWords.length);
encoder.encode(message, ecWords.length);
ZXingSystem.arraycopy(message, dataSize, ecWords, 0, ecSize);
// check to see if Decoder can fix up to ecWords/2 random errors
testDecoder(field, dataWords, ecWords);
}
}
function testEncodeDecode(field: GenericGF, dataWords: Int32Array, ecWords: Int32Array): void {
testEncoder(field, dataWords, ecWords);
testDecoder(field, dataWords, ecWords);
}
function testEncoder(field: GenericGF, dataWords: Int32Array, ecWords: Int32Array): void {
const encoder = new ReedSolomonEncoder(field);
const messageExpected = new Int32Array(dataWords.length + ecWords.length);
const message = new Int32Array(dataWords.length + ecWords.length);
ZXingSystem.arraycopy(dataWords, 0, messageExpected, 0, dataWords.length);
ZXingSystem.arraycopy(ecWords, 0, messageExpected, dataWords.length, ecWords.length);
ZXingSystem.arraycopy(dataWords, 0, message, 0, dataWords.length);
encoder.encode(message, ecWords.length);
assertDataEquals(message, messageExpected, 'Encode in ' + field + ' (' + dataWords.length + ',' + ecWords.length + ') failed');
}
function testDecoder(field: GenericGF, dataWords: Int32Array, ecWords: Int32Array): void {
const decoder = new ReedSolomonDecoder(field);
const message = new Int32Array(dataWords.length + ecWords.length);
const maxErrors: number /*int*/ = Math.floor(ecWords.length / 2);
const random: Random = getPseudoRandom();
const iterations: number /*int*/ = field.getSize() > 256 ? 1 : DECODER_TEST_ITERATIONS;
for (let j: number /*int*/ = 0; j < iterations; j++) {
for (let i: number /*int*/ = 0; i < ecWords.length; i++) {
if (i > 10 && i < Math.floor(ecWords.length / 2) - 10) {
// performance improvement - skip intermediate cases in long-running tests
i += Math.floor(ecWords.length / 10);
}
ZXingSystem.arraycopy(dataWords, 0, message, 0, dataWords.length);
ZXingSystem.arraycopy(ecWords, 0, message, dataWords.length, ecWords.length);
corrupt(message, i, random, field.getSize());
try {
decoder.decode(message, ecWords.length);
} catch (e/*ReedSolomonException e*/) {
// fail only if maxErrors exceeded
assert.strictEqual(i > maxErrors, true,
'Decode in ' + field + ' (' + dataWords.length + ',' + ecWords.length + ') failed at ' + i + ' errors: ' + e);
// else stop
break;
}
if (i < maxErrors) {
assertDataEquals(message,
dataWords,
'Decode in ' + field + ' (' + dataWords.length + ',' + ecWords.length + ') failed at ' + i + ' errors');
}
}
}
}
function assertDataEquals(received: Int32Array, expected: Int32Array, message: string): void {
for (let i: number /*int*/ = 0; i < expected.length; i++) {
if (expected[i] !== received[i]) {
const receivedToString = arrayToString(Int32Array.from(received.subarray(0, expected.length)));
assert.ok(false, `${message}. Mismatch at ${i}. Expected ${arrayToString(expected)}, got ${receivedToString}`);
}
}
}
function arrayToString(data: Int32Array): String {
const sb = new ZXingStringBuilder();
sb.append('{');
for (let i: number /*int*/ = 0; i < data.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(data[i].toString(16));
}
return sb.append('}').toString();
}
function getPseudoRandom(): Random {
return new Random('0xDEADBEEF');
}
| mit |
alphagov/service-manual-publisher | spec/spec_helper.rb | 463 | require "capybara/rspec"
require "webmock/rspec"
require "plek"
require "gds_api/test_helpers/publishing_api"
WebMock.disable_net_connect!(allow_localhost: true)
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.include GdsApi::TestHelpers::PublishingApi
end
| mit |
18F/quotable | app_config.py | 1915 | #!/usr/bin/env python
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
# Project name used for display
PROJECT_NAME = 'quotable'
# Project name in urls
# Use dashes, not underscores!
PROJECT_SLUG = 'quotable'
# The name of the repository containing the source
REPOSITORY_NAME = 'quotable'
REPOSITORY_URL = '[email protected]:nprapps/%s.git' % REPOSITORY_NAME
REPOSITORY_ALT_URL = None # '[email protected]:nprapps/%s.git' % REPOSITORY_NAME'
# The name to be used in paths on the server
PROJECT_FILENAME = 'quotable'
"""
DEPLOYMENT
"""
FILE_SERVER = 'tools.apps.npr.org'
S3_BUCKET = 'tools.apps.npr.org'
ASSETS_S3_BUCKET = 'assets.apps.npr.org'
# These variables will be set at runtime. See configure_targets() below
DEBUG = True
"""
COPY EDITING
"""
COPY_GOOGLE_DOC_KEY = '0AlXMOHKxzQVRdHZuX1UycXplRlBfLVB0UVNldHJYZmc'
"""
SHARING
"""
PROJECT_DESCRIPTION = 'An opinionated project template for (mostly) server-less apps.'
SHARE_URL = 'http://%s/%s/' % (S3_BUCKET, PROJECT_SLUG)
TWITTER = {
'TEXT': PROJECT_NAME,
'URL': SHARE_URL,
# Will be resized to 120x120, can't be larger than 1MB
'IMAGE_URL': ''
}
FACEBOOK = {
'TITLE': PROJECT_NAME,
'URL': SHARE_URL,
'DESCRIPTION': PROJECT_DESCRIPTION,
# Should be square. No documented restrictions on size
'IMAGE_URL': TWITTER['IMAGE_URL'],
'APP_ID': '138837436154588'
}
GOOGLE = {
# Thumbnail image for Google News / Search.
# No documented restrictions on resolution or size
'IMAGE_URL': TWITTER['IMAGE_URL']
}
NPR_DFP = {
'STORY_ID': '203618536',
'TARGET': 'News_NPR_News_Investigations',
'ENVIRONMENT': 'NPRTEST',
'TESTSERVER': 'true'
}
"""
SERVICES
"""
GOOGLE_ANALYTICS_ID = 'UA-5828686-4'
| mit |
aquilax/quantified.avtobiografia.com | content/post/2019-12-01.md | 1298 | {
"date": "2019-12-01",
"type": "post",
"title": "Report for Sunday 1st of December 2019",
"slug": "2019\/12\/01",
"categories": [
"Daily report"
],
"images": [],
"health": {
"weight": 82.9,
"height": 173,
"age": 14228
},
"nutrition": {
"calories": 3074.97,
"fat": 183.53,
"carbohydrates": 255.86,
"protein": 87.53
},
"exercise": {
"pushups": 0,
"crunches": 0,
"steps": 0
},
"media": {
"books": [],
"podcast": [],
"youtube": [],
"movies": [
{
"id": "tt1206885",
"title": "Rambo: Last Blood",
"year": "2019",
"url": "https:\/\/www.imdb.com\/title\/tt1206885\/"
}
],
"photos": []
}
}
Today I am <strong>14228 days</strong> old and my weight is <strong>82.9 kg</strong>. During the day, I consumed <strong>3074.97 kcal</strong> coming from <strong>183.53 g</strong> fat, <strong>255.86 g</strong> carbohydrates and <strong>87.53 g</strong> protein. Managed to do <strong>0 push-ups</strong>, <strong>0 crunches</strong> and walked <strong>0 steps</strong> during the day which is approximately <strong>0 km</strong>. | mit |
rabbitfighter81/reMORSE | src/app/components/legend/legend.component.html | 749 | <table class="legend-table" *ngIf="units">
<thead>
<tr class="header">
<th>Chraracter</th>
<th>Length (seconds)</th>
</tr>
</thead>
<tbody>
<tr>
<th>Dot ( ● )</th>
<td class="red">{{ units.dot }} Seconds</td>
</tr>
<tr>
<th>Dash ( - )</th>
<td class="red">{{ units.dash }} Seconds</td>
</tr>
<tr>
<th>Between Letters ( [ ] )</th>
<td class="red">{{ units.space.between_letters }} Seconds</td>
</tr>
<tr>
<th>Between Same Letter</th>
<td class="red">{{ units.space.between_same_letter }} Seconds</td>
</tr>
<tr>
<th>Between Words</th>
<td class="red">{{ units.space.between_words }} Seconds</td>
</tr>
</tbody>
</table>
| mit |
variousweddingdress/variousweddingdress.github.io | _posts/2015-10-13-Watters-Wtoo-Wtoo-Maids-Dress-891-2015-Spring-Sleeveless-KneeLength-AlinePrincess.md | 1244 | ---
layout: post
date: '2015-10-13'
title: "Watters - Wtoo Wtoo Maids Dress 891 2015 Spring Sleeveless Knee-Length Aline/Princess"
category: Watters - Wtoo
tags: [Watters - Wtoo,Wtoo,Aline/Princess ,Jewel,Knee-Length,Sleeveless,2015,Spring]
---
### Watters - Wtoo Wtoo Maids Dress 891
Just **$189.99**
### 2015 Spring Sleeveless Knee-Length Aline/Princess
<table><tr><td>BRANDS</td><td>Wtoo</td></tr><tr><td>Silhouette</td><td>Aline/Princess </td></tr><tr><td>Neckline</td><td>Jewel</td></tr><tr><td>Hemline/Train</td><td>Knee-Length</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr><tr><td>Years</td><td>2015</td></tr><tr><td>Season</td><td>Spring</td></tr></table>
<a href="https://www.readybrides.com/en/watters-wtoo/14643-watters-dress-891.html"><img src="//static.msromantic.com/33438/watters-dress-891.jpg" alt="Wtoo Maids Dress 891" style="width:100%;" /></a>
<!-- break --><a href="https://www.readybrides.com/en/watters-wtoo/14643-watters-dress-891.html"><img src="//static.msromantic.com/33437/watters-dress-891.jpg" alt="Wtoo Maids Dress 891" style="width:100%;" /></a>
Buy it: [https://www.readybrides.com/en/watters-wtoo/14643-watters-dress-891.html](https://www.readybrides.com/en/watters-wtoo/14643-watters-dress-891.html)
| mit |
jdh8/metallic | src/soft/integer/modti3.c | 219 | #include "udivmodti4.h"
__int128 __modti3(__int128 a, __int128 b)
{
unsigned __int128 r;
unsigned __int128 sign = a >> 127;
udivmodti4_(a + sign ^ sign, b < 0 ? -b : b, &r);
return r + sign ^ sign;
}
| mit |
cliffano/swaggy-jenkins | clients/powershell/generated/tests/Model/EmptyChangeLogSet.Tests.ps1 | 615 | #
# Swaggy Jenkins
# Jenkins API clients generated from Swagger / Open API specification
# Version: 1.1.2-pre.0
# Contact: [email protected]
# Generated by OpenAPI Generator: https://openapi-generator.tech
#
Describe -tag 'PSOpenAPITools' -name 'EmptyChangeLogSet' {
Context 'EmptyChangeLogSet' {
It 'Initialize-EmptyChangeLogSet' {
# a simple test to create an object
#$NewObject = Initialize-EmptyChangeLogSet -Class "TEST_VALUE" -Kind "TEST_VALUE"
#$NewObject | Should -BeOfType EmptyChangeLogSet
#$NewObject.property | Should -Be 0
}
}
}
| mit |
thatguyandy27/SkillsCompiler | skills_app/db/migrate/20140316173555_add_index_to_skill_totals.rb | 147 | class AddIndexToSkillTotals < ActiveRecord::Migration
def change
add_index :skill_totals, :name
add_index :skill_totals, :date
end
end
| mit |
hardylake8020/youka-server | web/home_page/views/index.client.view.html | 13908 | <!DOCTYPE html>
<html>
<head lang="en">
<title>柱柱签收-移动互联网时代的物流,运输全程可视,让物流更简单</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="keywords" content="柱柱签收,物流管理系统,车队系统,第三方物流系统,物流签收, 签收单, 回单,车队管理,车辆管理,TMS,运输管理系统,OTMS,签收" />
<meta content="柱柱签收是国际领先的移动互联网时代的物流,向货主、物流公司、专线公司、车队、司机、收货人
提供运输全程可视化的物流管理系统,解决传统物流时代回单、签收、物流管理难等问题,
一封Emai,一个APP,极速链接各类合作伙伴和司机。" name="description" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="icon" type="image/x-icon" href="../../home_page/images/favicon.ico">
<script type="text/javascript" src="../../libraries/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../../zz_supports/js/jquery.cookie.js"></script>
<script type="text/javascript" src="../../libraries/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://7xjfim.com2.z0.glb.qiniucdn.com/Iva.js"></script>
<script type="text/javascript" src="../../zz_supports/js/global.client.support.js"></script>
<script type="text/javascript" src="../../home_page/controllers/import.client.controller.js"></script>
<script type="text/javascript" src="../../home_page/controllers/dialog.client.controller.js"></script>
<script type="text/javascript" src="../../home_page/controllers/sliding_menu.client.controller.js"></script>
<script type="text/javascript" src="../../home_page/controllers/header.client.controller.js"></script>
<script type="text/javascript" src="../../home_page/controllers/index.client.controller.js"></script>
<link rel="stylesheet" type="text/css" href="../../libraries/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/global.client.style.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/header.client.style.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/footer.client.style.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/dialog.client.style.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/sliding_menu.client.style.css">
<link rel="stylesheet" type="text/css" href="../../home_page/css/index.client.style.css">
</head>
<body>
<div class="wrap">
<div class="wrap-background">
<p class="p-background"></p>
</div>
<div class="operation">
<div id="header" class="zz-home-header"></div>
<p class="operation-title-one">一款移动互联网时代的</p>
<p class="operation-title-two">开放式物流管理平台</p>
<form class="operation-signin">
<div class="signin-title">
<span>即刻登录,享受零成本投入的超高服务回报,开启您的全新物流运输管理模式:</span>
</div>
<div class="signin-content row">
<div class="col-md-5 col-xs-12 col-sm-12">
<input class=" username" name="username" type="text" placeholder="输入或手机" autocomplete="off" />
</div>
<div class="col-md-5 col-xs-12 col-sm-12">
<input class="password" name="password" type="password" placeholder="输入密码" autocomplete="off" />
</div>
<div class="col-md-2 col-xs-12 col-sm-12">
<input class="signin" type="submit" value="登录" />
</div>
</div>
<span class="error zz-hidden"></span>
</form>
</div>
<div class="wrap-container">
<div class="video-container">
<a name="video-entrance" id="video-entrance" style="height: 0; width: 0"></a>
<!-- 锚点-->
<p class="video-container-title">什么是柱柱签收</p>
<p class="video-container-contents">柱柱签收网是新一代的物流管理云平台,基于网页以及司机手机的简单操作,对货物单据, 运输轨迹,收发货时间,货物条码信息等实现实时、真实等管理,同时可以方便地将物流信息分享给上下游客户。
</p>
<div class="download-ppt">
<a class="chinese-ppt" href="/zzqs2/resources/product_introduction_zh.pdf">柱柱签收介绍
<span class="icon"></span>
</a>
<a class="english-ppt" href="/zzqs2/resources/product_example_zh.pdf">柱柱签收案例
<span class="icon"></span>
</a>
</div>
<div class="device">
<img src="../../home_page/images/index/device.png" style="width: 100%;max-width: 1160px">
</div>
</div>
<div class="description">
<p class="description-title">为什么选择柱柱</p>
<div class="level">
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="location">
<p class="level-title">节点追踪 全程定位</p>
<p class="level-container">柱柱签收通过APP要求司机在指定时间、指定地点按指定步骤拍摄货物信息,生成时间轴方便管理者查看,不允许从相册上传图片,保证纪录的真实性。</p>
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="message">
<p class="level-title">微信推送 异常报警</p>
<p class="level-container">柱柱签收微信分享和图片语音实时传输技术把信息的顺序传递变成了同时传递。</p>
</div>
</div>
</div>
</div>
<div class="level">
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="electronic">
<p class="level-title">电子围栏 安全交付</p>
<p class="level-container">柱柱签收利用电子围栏技术,如果不在指定地点交货,系统会立即报警。</p>
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="plate">
<p class="level-title">车牌对比 提送一致</p>
<p class="level-container">柱柱签收采用图片识别技术,自动识别提、送货车牌号,与数据库资料进行对比,确保货运车辆的一致性。</p>
</div>
</div>
</div>
</div>
<div class="level">
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="delivery">
<p class="level-title">扫码交货 无单签收</p>
<p class="level-container">柱柱签收支持按货物明细签收,通过扫码交接,帮您轻松实现电子签收,甚至能通过支付平台帮你代收货款。</p>
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="insurance">
<p class="level-title">在线保险 保障全程</p>
<p class="level-container">我们与多家保险公司合作基于真实的业务背景,为每票货物提供保险服务,保障货物安全。</p>
</div>
</div>
</div>
</div>
<div class="level">
<div class="row">
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="credit">
<p class="level-title">信用评估 运力推荐</p>
<p class="level-container">柱柱为甲方输出客观的评估报告,包括服务评价、运输公司的KPI、保险状况、银行授信等数据,向甲方企业推荐运力。</p>
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6">
<div class="financial">
<p class="level-title">网上金融 轻松融资</p>
<p class="level-container">基于真实数据和良好的发展前景,我们与平安银行合作,推出“回单贷”业务,依据柱柱签收的送达照片,触发贷款业务。</p>
</div>
</div>
</div>
</div>
</div>
<div class="partner">
<p class="partner-title">部分合作客户</p>
<p class="partner-container">目前柱柱签收网注册用户已达数万人,为数百家公司提供物流运输可视化服务</p>
<div class="company">
<div class="row">
<div class="col-md-2 col-xs-6 col-sm-3">
<!--<div class="industry">快消行业:</div>-->
<img src="home_page/images/index/industry_kuaixiao.png" title="快消行业" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_kele.png" title="郑州太古可口可乐" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_jiahua.png" title="上海家化" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_bufandi.png" title="不凡帝范梅勒糖果" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_haizhibao.png" title="孩之宝" style="margin-top: 20px">
</div>
</div>
</div>
<div class="company">
<div class="row">
<div class="col-md-2 col-xs-6 col-sm-3">
<!--<div class="industry">危化行业:</div>-->
<img src="home_page/images/index/industry_weihua.png" title="危化行业" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_zhonghua.png" title="中国中化集团" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_yehuakongqi.png" title="液化空气集团" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_zhaohegaofenzi.png" title="昭和高分子集团" style="margin-top: 20px">
</div>
</div>
</div>
<div class="company">
<div class="row">
<div class="col-md-2 col-xs-6 col-sm-3">
<!--<div class="industry">工业行业:</div>-->
<img src="home_page/images/index/industry_gongye.png" title="工业行业" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_minsheng.png" title="长安民生物流" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_sanling.png" title="三菱" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_lilezhongguo.png" title="利乐中国" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_fushishile.png" title="富士施乐" style="margin-top: 20px">
</div>
</div>
</div>
<div class="company">
<div class="row">
<div class="col-md-2 col-xs-6 col-sm-3">
<!--<div class="industry">O2O行业:</div>-->
<img src="home_page/images/index/industry_o2o.png" title="o2o行业" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_houchuguanjia.png" title="后厨管家" style="margin-top: 20px">
</div>
<div class="col-md-2 col-xs-6 col-sm-3">
<img src="home_page/images/index/company_youyou.png" title="悠悠果业" style="margin-top: 20px">
</div>
</div>
</div>
</div>
<div class="app-download">
<p class="app-download-title">
APP下载</p>
<div class="download-button">
<a class="download-ios" href="<%= apple_app_download %>">IOS下载</a>
<a class="download-android" href="/zzqs2/toDownloadApp">Android下载</a>
</div>
<img class="qr-code" src="/zzqs2/appDownloadBarcode">
<form class="download-register" autocomplete="off">
<div class="row">
<div class="col-md-5 col-xs-12 col-sm-12">
<input class="username" name="username" type="text" placeholder="输入邮箱或手机" autocomplete="off">
</div>
<div class="col-md-5 col-xs-12 col-sm-12">
<input class="password" name="password" type="password" placeholder="输入密码" autocomplete="off">
</div>
<div class="col-md-2 col-xs-12 col-sm-12">
<p class="register">注册</p>
</div>
</div>
<p class="error-tip zz-hidden"></p>
</form>
</div>
<div class="zz-home-footer"></div>
</div>
</div>
</body>
</html> | mit |
Subsets and Splits