code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ColorPickerModule } from 'angular2-color-picker';
// components
import { ShellComponent } from './components/shell';
import { HelloComponent } from './components/hello';
import { OpenFolderComponent } from './components/folder';
import { SettingsComponent } from './components/settings';
import { AboutComponent } from './components/about';
// pipes
import { SVGPipe } from './pipes/SVGPipe';
// services
import { IpcRendererService } from './services/ipcRender';
import { StorageService } from './services/storage';
import { ComponentService } from './services/componentService';
// directives
import { WebviewDirective } from './directives/webview';
// routes
import { appRoutes } from './routes';
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
ColorPickerModule,
RouterModule.forRoot(appRoutes)
],
declarations: [
ShellComponent,
HelloComponent,
OpenFolderComponent,
SettingsComponent,
AboutComponent,
SVGPipe,
WebviewDirective
],
bootstrap: [ShellComponent],
providers: [IpcRendererService, StorageService, ComponentService]
})
export class Module { } | vijayantkatyal/svg-bits | src/module.ts | TypeScript | mit | 1,406 |
<?php
$_pluginInfo=array(
'name'=>'Inet',
'version'=>'1.0.3',
'description'=>"Get the contacts from a Inet account",
'base_version'=>'1.8.0',
'type'=>'email',
'check_url'=>'http://inet.ua/index.php',
'requirement'=>'email',
'allowed_domains'=>array('/(inet.ua)/i','/(fm.com.ua)/i'),
);
/**
* Inet Plugin
*
* Imports user's contacts from Inet AddressBook
*
* @author OpenInviter
* @version 1.0.0
*/
class inet extends openinviter_base
{
private $login_ok=false;
public $showContacts=true;
public $internalError=false;
protected $timeout=30;
public $debug_array=array(
'initial_get'=>'login_username',
'login_post'=>'frame',
'url_redirect'=>'passport',
'url_export'=>'FORENAME',
);
/**
* Login function
*
* Makes all the necessary requests to authenticate
* the current user to the server.
*
* @param string $user The current user.
* @param string $pass The password for the current user.
* @return bool TRUE if the current user was authenticated successfully, FALSE otherwise.
*/
public function login($user,$pass)
{
$this->resetDebugger();
$this->service='inet';
$this->service_user=$user;
$this->service_password=$pass;
if (!$this->init()) return false;
$res=$this->get("http://inet.ua/index.php");
if ($this->checkResponse("initial_get",$res))
$this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET');
else
{
$this->updateDebugBuffer('initial_get',"http://inet.ua/index.php",'GET',false);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$user_array=explode('@',$user);$username=$user_array[0];
$form_action="http://newmail.inet.ua/login.php";
$post_elements=array('username'=>$username,'password'=>$pass,'server_id'=>0,'template'=>'v-webmail','language'=>'ru','login_username'=>$username,'servname'=>'inet.ua','login_password'=>$pass,'version'=>1,'x'=>rand(1,100),'y'=>rand(1,100));
$res=$this->post($form_action,$post_elements,true);
if ($this->checkResponse('login_post',$res))
$this->updateDebugBuffer('login_post',$form_action,'POST',true,$post_elements);
else
{
$this->updateDebugBuffer('login_post',$form_action,'POST',false,$post_elements);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$this->login_ok="http://newmail.inet.ua/download.php?act=process_export&method=csv&addresses=all";
return true;
}
/**
* Get the current user's contacts
*
* Makes all the necesarry requests to import
* the current user's contacts
*
* @return mixed The array if contacts if importing was successful, FALSE otherwise.
*/
public function getMyContacts()
{
if (!$this->login_ok)
{
$this->debugRequest();
$this->stopPlugin();
return false;
}
else $url=$this->login_ok;
$res=$this->get($url);
if ($this->checkResponse("url_export",$res))
$this->updateDebugBuffer('url_export',$url,'GET');
else
{
$this->updateDebugBuffer('url_export',$url,'GET',false);
$this->debugRequest();
$this->stopPlugin();
return false;
}
$tempFile=explode(PHP_EOL,$res);$contacts=array();unset($tempFile[0]);
foreach ($tempFile as $valuesTemp)
{
$values=explode('~',$valuesTemp);
if (!empty($values[3]))
$contacts[$values[3]]=array('first_name'=>(!empty($values[1])?$values[1]:false),
'middle_name'=>(!empty($values[2])?$values[2]:false),
'last_name'=>false,
'nickname'=>false,
'email_1'=>(!empty($values[3])?$values[3]:false),
'email_2'=>(!empty($values[4])?$values[4]:false),
'email_3'=>(!empty($values[5])?$values[5]:false),
'organization'=>false,
'phone_mobile'=>(!empty($values[8])?$values[8]:false),
'phone_home'=>(!empty($values[6])?$values[6]:false),
'pager'=>false,
'address_home'=>false,
'address_city'=>(!empty($values[11])?$values[11]:false),
'address_state'=>(!empty($values[12])?$values[12]:false),
'address_country'=>(!empty($values[14])?$values[14]:false),
'postcode_home'=>(!empty($values[13])?$values[13]:false),
'company_work'=>false,
'address_work'=>false,
'address_work_city'=>false,
'address_work_country'=>false,
'address_work_state'=>false,
'address_work_postcode'=>false,
'fax_work'=>false,
'phone_work'=>(!empty($values[7])?$values[7]:false),
'website'=>false,
'isq_messenger'=>false,
'skype_essenger'=>false,
'yahoo_essenger'=>false,
'msn_messenger'=>false,
'aol_messenger'=>false,
'other_messenger'=>false,
);
}
foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]);
return $this->returnContacts($contacts);
}
/**
* Terminate session
*
* Terminates the current user's session,
* debugs the request and reset's the internal
* debudder.
*
* @return bool TRUE if the session was terminated successfully, FALSE otherwise.
*/
public function logout()
{
if (!$this->checkSession()) return false;
$res=$this->get('http://newmail.inet.ua/logout.php?vwebmailsession=',true);
$this->debugRequest();
$this->resetDebugger();
$this->stopPlugin();
return true;
}
}
?> | mbrung/lcOpenInviterPlugin | lib/extern/openInviter/plugins/inet.plg.php | PHP | mit | 5,581 |
package org.workcraft.plugins.circuit;
import org.workcraft.annotations.DisplayName;
import org.workcraft.annotations.Hotkey;
import org.workcraft.annotations.SVGIcon;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.BoundingBoxHelper;
import org.workcraft.dom.visual.DrawRequest;
import org.workcraft.formula.BooleanFormula;
import org.workcraft.formula.visitors.FormulaRenderingResult;
import org.workcraft.formula.visitors.FormulaToGraphics;
import org.workcraft.gui.tools.Decoration;
import org.workcraft.observation.PropertyChangedEvent;
import org.workcraft.observation.StateEvent;
import org.workcraft.observation.StateObserver;
import org.workcraft.plugins.circuit.renderers.ComponentRenderingResult.RenderType;
import org.workcraft.serialisation.NoAutoSerialisation;
import org.workcraft.utils.ColorUtils;
import org.workcraft.utils.Hierarchy;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.*;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
@DisplayName("Input/output port")
@Hotkey(KeyEvent.VK_P)
@SVGIcon("images/circuit-node-port.svg")
public class VisualFunctionContact extends VisualContact implements StateObserver {
private static final double size = 0.3;
private static FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true);
private static Font functionFont;
private FormulaRenderingResult renderedSetFunction = null;
private FormulaRenderingResult renderedResetFunction = null;
private static double functionFontSize = CircuitSettings.getFunctionFontSize();
static {
try {
functionFont = Font.createFont(Font.TYPE1_FONT, ClassLoader.getSystemResourceAsStream("fonts/eurm10.pfb"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
public VisualFunctionContact(FunctionContact contact) {
super(contact);
}
@Override
public FunctionContact getReferencedComponent() {
return (FunctionContact) super.getReferencedComponent();
}
@NoAutoSerialisation
public BooleanFormula getSetFunction() {
return getReferencedComponent().getSetFunction();
}
@NoAutoSerialisation
public void setSetFunction(BooleanFormula setFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedSetFunction = null;
getReferencedComponent().setSetFunction(setFunction);
}
@NoAutoSerialisation
public BooleanFormula getResetFunction() {
return getReferencedComponent().getResetFunction();
}
@NoAutoSerialisation
public void setForcedInit(boolean value) {
getReferencedComponent().setForcedInit(value);
}
@NoAutoSerialisation
public boolean getForcedInit() {
return getReferencedComponent().getForcedInit();
}
@NoAutoSerialisation
public void setInitToOne(boolean value) {
getReferencedComponent().setInitToOne(value);
}
@NoAutoSerialisation
public boolean getInitToOne() {
return getReferencedComponent().getInitToOne();
}
@NoAutoSerialisation
public void setResetFunction(BooleanFormula resetFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedResetFunction = null;
getReferencedComponent().setResetFunction(resetFunction);
}
public void invalidateRenderedFormula() {
renderedSetFunction = null;
renderedResetFunction = null;
}
private Font getFunctionFont() {
return functionFont.deriveFont((float) CircuitSettings.getFunctionFontSize());
}
private FormulaRenderingResult getRenderedSetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedSetFunction = null;
}
BooleanFormula setFunction = getReferencedComponent().getSetFunction();
if (setFunction == null) {
renderedSetFunction = null;
} else if (renderedSetFunction == null) {
renderedSetFunction = FormulaToGraphics.render(setFunction, context, getFunctionFont());
}
return renderedSetFunction;
}
private Point2D getSetFormulaOffset() {
double xOffset = size;
double yOffset = -size / 2;
FormulaRenderingResult renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getSetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult setRenderingResult = getRenderedSetFunction();
if (setRenderingResult != null) {
bb = BoundingBoxHelper.move(setRenderingResult.boundingBox, getSetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private FormulaRenderingResult getRenderedResetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedResetFunction = null;
}
BooleanFormula resetFunction = getReferencedComponent().getResetFunction();
if (resetFunction == null) {
renderedResetFunction = null;
} else if (renderedResetFunction == null) {
renderedResetFunction = FormulaToGraphics.render(resetFunction, context, getFunctionFont());
}
return renderedResetFunction;
}
private Point2D getResetFormulaOffset() {
double xOffset = size;
double yOffset = size / 2;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
yOffset = size / 2 + renderingResult.boundingBox.getHeight();
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getResetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
bb = BoundingBoxHelper.move(renderingResult.boundingBox, getResetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private void drawArrow(Graphics2D g, int arrowType, double arrX, double arrY) {
double s = CircuitSettings.getFunctionFontSize();
g.setStroke(new BasicStroke((float) s / 25));
double s1 = 0.75 * s;
double s2 = 0.45 * s;
double s3 = 0.30 * s;
if (arrowType == 1) {
// arrow down
Line2D line = new Line2D.Double(arrX, arrY - s1, arrX, arrY - s3);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s3);
path.lineTo(arrX + 0.05, arrY - s3);
path.lineTo(arrX, arrY);
path.closePath();
g.fill(path);
g.draw(line);
} else if (arrowType == 2) {
// arrow up
Line2D line = new Line2D.Double(arrX, arrY, arrX, arrY - s2);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s2);
path.lineTo(arrX + 0.05, arrY - s2);
path.lineTo(arrX, arrY - s1);
path.closePath();
g.fill(path);
g.draw(line);
}
}
private void drawFormula(Graphics2D g, int arrowType, Point2D offset, FormulaRenderingResult renderingResult) {
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
AffineTransform savedTransform = g.getTransform();
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
g.transform(rotateTransform);
}
double dXArrow = -0.15;
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
dXArrow = renderingResult.boundingBox.getWidth() + 0.15;
}
drawArrow(g, arrowType, offset.getX() + dXArrow, offset.getY());
g.translate(offset.getX(), offset.getY());
renderingResult.draw(g);
g.setTransform(savedTransform);
}
}
@Override
public void draw(DrawRequest r) {
if (needsFormulas()) {
Graphics2D g = r.getGraphics();
Decoration d = r.getDecoration();
g.setColor(ColorUtils.colorise(getForegroundColor(), d.getColorisation()));
FormulaRenderingResult renderingResult;
renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Point2D offset = getSetFormulaOffset();
drawFormula(g, 2, offset, renderingResult);
}
renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Point2D offset = getResetFormulaOffset();
drawFormula(g, 1, offset, renderingResult);
}
}
super.draw(r);
}
private boolean needsFormulas() {
boolean result = false;
Node parent = getParent();
if (parent != null) {
// Primary input port
if (!(parent instanceof VisualCircuitComponent) && isInput()) {
result = true;
}
// Output port of a BOX-rendered component
if ((parent instanceof VisualFunctionComponent) && isOutput()) {
VisualFunctionComponent component = (VisualFunctionComponent) parent;
if (component.getRenderType() == RenderType.BOX) {
result = true;
}
}
}
return result;
}
@Override
public Rectangle2D getBoundingBoxInLocalSpace() {
Rectangle2D bb = super.getBoundingBoxInLocalSpace();
if (needsFormulas()) {
bb = BoundingBoxHelper.union(bb, getSetBoundingBox());
bb = BoundingBoxHelper.union(bb, getResetBoundingBox());
}
return bb;
}
private Collection<VisualFunctionContact> getAllContacts() {
HashSet<VisualFunctionContact> result = new HashSet<>();
Node root = Hierarchy.getRoot(this);
if (root != null) {
result.addAll(Hierarchy.getDescendantsOfType(root, VisualFunctionContact.class));
}
return result;
}
@Override
public void notify(StateEvent e) {
if (e instanceof PropertyChangedEvent) {
PropertyChangedEvent pc = (PropertyChangedEvent) e;
String propertyName = pc.getPropertyName();
if (propertyName.equals(FunctionContact.PROPERTY_SET_FUNCTION) || propertyName.equals(FunctionContact.PROPERTY_RESET_FUNCTION)) {
invalidateRenderedFormula();
}
if (propertyName.equals(Contact.PROPERTY_NAME)) {
for (VisualFunctionContact vc : getAllContacts()) {
vc.invalidateRenderedFormula();
}
}
}
super.notify(e);
}
}
| tuura/workcraft | workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualFunctionContact.java | Java | mit | 13,140 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[])
# Add the edges
self.add_edges([])
# Set the graph attributes
self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule']
self["MT_constraint__"] = """return True"""
self["name"] = """"""
self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS')
self["equations"] = []
# Set the node attributes
# match class Family(Fam) node
self.add_node()
self.vs[0]["MT_pre__attr1"] = """return True"""
self.vs[0]["MT_label__"] = """1"""
self.vs[0]["mm__"] = """MT_pre__Family"""
self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam')
# match class Child(Child) node
self.add_node()
self.vs[1]["MT_pre__attr1"] = """return True"""
self.vs[1]["MT_label__"] = """2"""
self.vs[1]["mm__"] = """MT_pre__Child"""
self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child')
# match association null--daughters-->nullnode
self.add_node()
self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """
self.vs[2]["MT_label__"] = """3"""
self.vs[2]["mm__"] = """MT_pre__directLink_S"""
self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child')
# Add the edges
self.add_edges([
(0,2), # match class null(Fam) -> association daughters
(2,1), # association null -> match class null(Child)
])
# define evaluation methods for each match class.
def eval_attr11(self, attr_value, this):
return True
def eval_attr12(self, attr_value, this):
return True
# define evaluation methods for each match association.
def eval_attr13(self, attr_value, this):
return attr_value == "daughters"
def constraint(self, PreNode, graph):
return True
| levilucio/SyVOLT | ExFamToPerson/contracts/unit/HUnitDaughter2Woman_ConnectedLHS.py | Python | mit | 2,107 |
<?php
/* TwigBundle:Exception:traces.html.twig */
class __TwigTemplate_9109da3b5a8f9508fb31e1e2c4868542dc8f79b94134ac992407a779404545e3 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"block\">
";
// line 2
if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) {
// line 3
echo " <h2>
<span><small>[";
// line 4
echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true);
echo "/";
echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true);
echo "]</small></span>
";
// line 5
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array()));
echo ": ";
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true)));
echo "
";
// line 6
ob_start();
// line 7
echo " <a href=\"#\" onclick=\"toggle('traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "', 'traces'); switchIcons('icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open', 'icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-";
// line 8
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none"));
echo "\" />
<img class=\"toggle\" id=\"icon-traces-";
// line 9
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline"));
echo "\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 12
echo " </h2>
";
} else {
// line 14
echo " <h2>Stack Trace</h2>
";
}
// line 16
echo "
<a id=\"traces-link-";
// line 17
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\"></a>
<ol class=\"traces list-exception\" id=\"traces-";
// line 18
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none"));
echo "\">
";
// line 19
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
foreach ($context['_seq'] as $context["i"] => $context["trace"]) {
// line 20
echo " <li>
";
// line 21
$this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"]));
// line 22
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 24
echo " </ol>
</div>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("<div class=\"block\">
{% if count > 0 %}
<h2>
<span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span>
{{ exception.class|abbr_class }}: {{ exception.message|nl2br|format_file_from_text }}
{% spaceless %}
<a href=\"#\" onclick=\"toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-{{ position }}-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: {{ 0 == count ? 'inline' : 'none' }}\" />
<img class=\"toggle\" id=\"icon-traces-{{ position }}-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: {{ 0 == count ? 'none' : 'inline' }}\" />
</a>
{% endspaceless %}
</h2>
{% else %}
<h2>Stack Trace</h2>
{% endif %}
<a id=\"traces-link-{{ position }}\"></a>
<ol class=\"traces list-exception\" id=\"traces-{{ position }}\" style=\"display: {{ 0 == count ? 'block' : 'none' }}\">
{% for i, trace in exception.trace %}
<li>
{% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %}
</li>
{% endfor %}
</ol>
</div>
", "TwigBundle:Exception:traces.html.twig", "C:\\inetpub\\wwwroot\\Cupon1\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/traces.html.twig");
}
}
| cristian3040/Cupon | app/cache/dev/twig/89/89ed4a643ac881b9b276624f1e201f6f6459e825e3dad4b2ed9447cc114d4ee5.php | PHP | mit | 9,187 |
var models=require('../models/models.js');
// Autoload :id de comentarios
exports.load=function (req,res,next,commentId) {
models.Comment.find({
where:{
id:Number(commentId)
}
}).then(function (comment) {
if(comment){
req.comment=comment;
next();
}else{
next(new Error('No existe commentId=' +commentId))
}
}).catch(function (error) {
next(error);
});
};
//GET /quizes/:quizId/comments/new
exports.new=function (req,res) {
res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]});
};
//POST /quizes/:quizId/comments
exports.create=function (req,res) {
var comment =models.Comment.build(
{
texto:req.body.comment.texto,
QuizId:req.params.quizId,
});
comment
.validate()
.then(
function (err) {
if(err){
res.render('comments/new.ejs',
{comment:comment,quizid:req.params.quizId,errors:err.errors});
}else{
comment //save :guarda en DB campo texto
.save()
.then(function () {
res.redirect('/quizes/'+req.params.quizId);
});
}
}
).catch(function (error) {
next(error);
});
};
//GET /quizes/:quizId/comments/:commentId/publish
exports.publish=function (req,res) {
req.comment.publicado=true;
req.comment.save({fields:["publicado"]}).then(
function () {
res.redirect('/quizes/'+req.params.quizId);
}).catch(function (error) {
next(error);
});
};
| armero1989/quiz-2016 | controllers/comment_controller.js | JavaScript | mit | 1,348 |
package net.dirtyfilthy.bouncycastle.asn1.nist;
import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECNamedCurves;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECObjectIdentifiers;
import net.dirtyfilthy.bouncycastle.asn1.x9.X9ECParameters;
import net.dirtyfilthy.bouncycastle.util.Strings;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
*/
public class NISTNamedCurves
{
static final Hashtable objIds = new Hashtable();
static final Hashtable names = new Hashtable();
static void defineCurve(String name, DERObjectIdentifier oid)
{
objIds.put(name, oid);
names.put(oid, name);
}
static
{
// TODO Missing the "K-" curves
defineCurve("B-571", SECObjectIdentifiers.sect571r1);
defineCurve("B-409", SECObjectIdentifiers.sect409r1);
defineCurve("B-283", SECObjectIdentifiers.sect283r1);
defineCurve("B-233", SECObjectIdentifiers.sect233r1);
defineCurve("B-163", SECObjectIdentifiers.sect163r2);
defineCurve("P-521", SECObjectIdentifiers.secp521r1);
defineCurve("P-384", SECObjectIdentifiers.secp384r1);
defineCurve("P-256", SECObjectIdentifiers.secp256r1);
defineCurve("P-224", SECObjectIdentifiers.secp224r1);
defineCurve("P-192", SECObjectIdentifiers.secp192r1);
}
public static X9ECParameters getByName(
String name)
{
DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
if (oid != null)
{
return getByOID(oid);
}
return null;
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters getByOID(
DERObjectIdentifier oid)
{
return SECNamedCurves.getByOID(oid);
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DERObjectIdentifier getOID(
String name)
{
return (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
}
/**
* return the named curve name represented by the given object identifier.
*/
public static String getName(
DERObjectIdentifier oid)
{
return (String)names.get(oid);
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static Enumeration getNames()
{
return objIds.keys();
}
}
| dirtyfilthy/dirtyfilthy-bouncycastle | net/dirtyfilthy/bouncycastle/asn1/nist/NISTNamedCurves.java | Java | mit | 2,937 |
<?php
// Include the API
require '../../lastfmapi/lastfmapi.php';
// Get the session auth data
$file = fopen('../auth.txt', 'r');
// Put the auth data into an array
$authVars = array(
'apiKey' => trim(fgets($file)),
'secret' => trim(fgets($file)),
'username' => trim(fgets($file)),
'sessionKey' => trim(fgets($file)),
'subscriber' => trim(fgets($file))
);
$config = array(
'enabled' => true,
'path' => '../../lastfmapi/',
'cache_length' => 1800
);
// Pass the array to the auth class to eturn a valid auth
$auth = new lastfmApiAuth('setsession', $authVars);
$apiClass = new lastfmApi();
$tagClass = $apiClass->getPackage($auth, 'tag', $config);
// Setup the variables
$methodVars = array(
'tag' => 'Emo'
);
if ( $albums = $tagClass->getTopAlbums($methodVars) ) {
echo '<b>Data Returned</b>';
echo '<pre>';
print_r($albums);
echo '</pre>';
}
else {
die('<b>Error '.$tagClass->error['code'].' - </b><i>'.$tagClass->error['desc'].'</i>');
}
?> | SimonTalaga/MusicalTastesViz | vendor/lastfm/examples/tag.gettopalbums/index.php | PHP | mit | 960 |
package com.cosmos.kafka.client.producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
import java.util.Random;
import static org.apache.kafka.clients.producer.ProducerConfig.*;
/**
* Producer using multiple partition
*/
public class MultipleBrokerProducer implements Runnable {
private KafkaProducer<Integer, String> producer;
private String topic;
public MultipleBrokerProducer(String topic) {
final Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093,localhost:9094");
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer");
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(PARTITIONER_CLASS_CONFIG, "org.apache.kafka.clients.producer.internals.DefaultPartitioner");
props.put(ACKS_CONFIG, "1");
this.producer = new KafkaProducer<>(props);
this.topic = topic;
}
@Override
public void run() {
System.out.println("Sending 1000 messages");
Random rnd = new Random();
int i = 1;
while (i <= 1000) {
int key = rnd.nextInt(255);
String message = String.format("Message for key - [%d]: %d", key, i);
System.out.printf("Send: %s\n", message);
this.producer.send(new ProducerRecord<>(this.topic, key, message));
i++;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
producer.close();
}
}
| dantin/kafka-demo | kafka-producer/src/main/java/com/cosmos/kafka/client/producer/MultipleBrokerProducer.java | Java | mit | 1,747 |
#David Hickox
#Feb 15 17
#Squares (counter update)
#descriptions, description, much descripticve
#variables
# limit, where it stops
# num, sentry variable
#creates array if needbe
#array = [[0 for x in range(h)] for y in range(w)]
#imports date time and curency handeling because i hate string formating (this takes the place of #$%.2f"%)
import locale
locale.setlocale( locale.LC_ALL, '' )
#use locale.currency() for currency formating
print("Welcome to the (insert name here bumbblefack) Program\n")
limit = float(input("How many squares do you want? "))
num = 1
print("number\tnumber^2")
while num <= limit:
#prints the number and squares it then seperates by a tab
print (num,num**2,sep='\t')
#increments
num += 1
input("\nPress Enter to Exit")
| dwhickox/NCHS-Programming-1-Python-Programs | Chap 3/Squares.py | Python | mit | 778 |
<?php
namespace Minsal\GinecologiaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SrgTipoConsultaPf
*
* @ORM\Table(name="srg_tipo_consulta_pf")
* @ORM\Entity
*/
class SrgTipoConsultaPf
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="SEQUENCE")
* @ORM\SequenceGenerator(sequenceName="srg_tipo_consulta_pf_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="tipo_consulta_pf", type="string", length=20, nullable=true)
*/
private $tipoConsultaPf;
/**
* @ORM\OneToMany(targetEntity="SrgSeguimientoSubsecuente", mappedBy="idTipoConsultaPf", cascade={"all"}, orphanRemoval=true))
**/
private $SrgSeguimientoSubsecuente;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tipoConsultaPf
*
* @param string $tipoConsultaPf
* @return SrgTipoConsultaPf
*/
public function setTipoConsultaPf($tipoConsultaPf)
{
$this->tipoConsultaPf = $tipoConsultaPf;
return $this;
}
/**
* Get tipoConsultaPf
*
* @return string
*/
public function getTipoConsultaPf()
{
return $this->tipoConsultaPf;
}
/**
* Constructor
*/
public function __construct()
{
$this->SrgSeguimientoSubsecuente = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add SrgSeguimientoSubsecuente
*
* @param \Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente
* @return SrgTipoConsultaPf
*/
public function addSrgSeguimientoSubsecuente(\Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente)
{
$this->SrgSeguimientoSubsecuente[] = $srgSeguimientoSubsecuente;
return $this;
}
/**
* Remove SrgSeguimientoSubsecuente
*
* @param \Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente
*/
public function removeSrgSeguimientoSubsecuente(\Minsal\GinecologiaBundle\Entity\SrgSeguimientoSubsecuente $srgSeguimientoSubsecuente)
{
$this->SrgSeguimientoSubsecuente->removeElement($srgSeguimientoSubsecuente);
}
/**
* Get SrgSeguimientoSubsecuente
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getSrgSeguimientoSubsecuente()
{
return $this->SrgSeguimientoSubsecuente;
}
public function __toString() {
return $this->id? (string) $this->id: '';
}
}
| sisreg/siap | src/Minsal/GinecologiaBundle/Entity/SrgTipoConsultaPf.php | PHP | mit | 2,743 |
using System;
using AppStudio.Uwp;
namespace DJNanoShow.ViewModels
{
public class PrivacyViewModel : ObservableBase
{
public Uri Url
{
get
{
return new Uri(UrlText, UriKind.RelativeOrAbsolute);
}
}
public string UrlText
{
get
{
return "http://1drv.ms/1llJOkM";
}
}
}
}
| wasteam/DJNanoSampleApp | W10/DJNanoShow.W10/ViewModels/PrivacyViewModel.cs | C# | mit | 435 |
import React, { PropTypes } from 'react';
import TodoItem from './TodoItem';
const TodoList = ({todos}) => (
<ul className="todo-list">
{todos.map(todo =>
<TodoItem key={todo.id} {...todo} />
)}
</ul>
);
TodoList.propTypes = {
todos: PropTypes.array.isRequired
}
export default TodoList;
| johny/react-redux-todo-app | src/components/TodoList.js | JavaScript | mit | 312 |
<?php
namespace Podlove\Settings\Dashboard;
use Podlove\Model;
class FileValidation
{
public static function content()
{
global $wpdb;
$sql = '
SELECT
p.post_status,
mf.episode_id,
mf.episode_asset_id,
mf.size,
mf.id media_file_id
FROM
`'.Model\MediaFile::table_name().'` mf
JOIN `'.Model\Episode::table_name().'` e ON e.id = mf.`episode_id`
JOIN `'.$wpdb->posts."` p ON e.`post_id` = p.`ID`
WHERE
p.`post_type` = 'podcast'
AND p.post_status in ('private', 'draft', 'publish', 'pending', 'future')
";
$rows = $wpdb->get_results($sql, ARRAY_A);
$media_files = [];
foreach ($rows as $row) {
if (!isset($media_files[$row['episode_id']])) {
$media_files[$row['episode_id']] = ['post_status' => $row['post_status']];
}
$media_files[$row['episode_id']][$row['episode_asset_id']] = [
'size' => $row['size'],
'media_file_id' => $row['media_file_id'],
];
}
$podcast = Model\Podcast::get();
$episodes = $podcast->episodes(['post_status' => ['private', 'draft', 'publish', 'pending', 'future']]);
$assets = Model\EpisodeAsset::all();
$header = [__('Episode', 'podlove-podcasting-plugin-for-wordpress')];
foreach ($assets as $asset) {
$header[] = $asset->title;
}
$header[] = __('Status', 'podlove-podcasting-plugin-for-wordpress');
\Podlove\load_template('settings/dashboard/file_validation', [
'episodes' => $episodes,
'assets' => $assets,
'media_files' => $media_files,
'header' => $header,
]);
}
}
| podlove/podlove-publisher | lib/settings/dashboard/file_validation.php | PHP | mit | 1,726 |
/*
* Copyright (c) 2016. Xiaomu Tech.(Beijing) LLC. All rights reserved.
*/
package de.mpg.mpdl.labcam.code.common.widget;
/**
* Created by yingli on 10/19/15.
*/
public class Constants {
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String KEY_CLASS_NAME = "key_class_name";
/************************** SHARED_PREFERENCES **********************************/
public static final String SHARED_PREFERENCES = "myPref"; // name of shared preferences
public static final String API_KEY = "apiKey";
public static final String USER_ID = "userId";
public static final String USER_NAME = "username";
public static final String FAMILY_NAME = "familyName";
public static final String GIVEN_NAME = "givenName";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String SERVER_NAME = "serverName";
public static final String OTHER_SERVER = "otherServer";
public static final String COLLECTION_ID = "collectionID";
public static final String OCR_IS_ON = "ocrIsOn";
public static final String IS_ALBUM = "isAlbum";
}
| MPDL/MPDL-Cam | app/src/main/java/de/mpg/mpdl/labcam/code/common/widget/Constants.java | Java | mit | 1,174 |
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2017 Christian Boulanger
License:
MIT: https://opensource.org/licenses/MIT
See the LICENSE file in the project's top-level directory for details.
Authors:
* Christian Boulanger (info@bibliograph.org, @cboulanger)
************************************************************************ */
const process = require("process");
const path = require("upath");
const semver = require("semver");
const fs = qx.tool.utils.Promisify.fs;
/**
* Installs a package
*/
qx.Class.define("qx.tool.cli.commands.package.Migrate", {
extend: qx.tool.cli.commands.Package,
statics: {
/**
* Flag to prevent recursive call to process()
*/
migrationInProcess: false,
/**
* Return the Yargs configuration object
* @return {{}}
*/
getYargsCommand: function() {
return {
command: "migrate",
describe: "migrates the package system to a newer version.",
builder: {
"verbose": {
alias: "v",
describe: "Verbose logging"
},
"quiet": {
alias: "q",
describe: "No output"
}
}
};
}
},
members: {
/**
* Announces or applies a migration
* @param {Boolean} announceOnly If true, announce the migration without
* applying it.
*/
process: async function(announceOnly=false) {
const self = qx.tool.cli.commands.package.Migrate;
if (self.migrationInProcess) {
return;
}
self.migrationInProcess = true;
let needFix = false;
// do not call this.base(arguments) here!
let pkg = qx.tool.cli.commands.Package;
let cwd = process.cwd();
let migrateFiles = [
[
path.join(cwd, pkg.lockfile.filename),
path.join(cwd, pkg.lockfile.legacy_filename)
],
[
path.join(cwd, pkg.cache_dir),
path.join(cwd, pkg.legacy_cache_dir)
],
[
path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.package_cache_name),
path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.legacy_package_cache_name)
]
];
if (this.checkFilesToRename(migrateFiles).length) {
let replaceInFiles = [{
files: path.join(cwd, ".gitignore"),
from: pkg.legacy_cache_dir + "/",
to: pkg.cache_dir + "/"
}];
await this.migrate(migrateFiles, replaceInFiles, announceOnly);
if (announceOnly) {
needFix = true;
} else {
if (!this.argv.quiet) {
qx.tool.compiler.Console.info("Fixing path names in the lockfile...");
}
this.argv.reinstall = true;
await (new qx.tool.cli.commands.package.Upgrade(this.argv)).process();
}
}
// Migrate all manifest in a package
const registryModel = qx.tool.config.Registry.getInstance();
let manifestModels =[];
if (await registryModel.exists()) {
// we have a qooxdoo.json index file containing the paths of libraries in the repository
await registryModel.load();
let libraries = registryModel.getLibraries();
for (let library of libraries) {
manifestModels.push((new qx.tool.config.Abstract(qx.tool.config.Manifest.config)).set({baseDir: path.join(cwd, library.path)}));
}
} else if (fs.existsSync(qx.tool.config.Manifest.config.fileName)) {
manifestModels.push(qx.tool.config.Manifest.getInstance());
}
for (const manifestModel of manifestModels) {
await manifestModel.set({warnOnly: true}).load();
manifestModel.setValidate(false);
needFix = false;
let s = "";
if (!qx.lang.Type.isArray(manifestModel.getValue("info.authors"))) {
needFix = true;
s += " missing info.authors\n";
}
if (!semver.valid(manifestModel.getValue("info.version"))) {
needFix = true;
s += " missing or invalid info.version\n";
}
let obj = {
"info.qooxdoo-versions": null,
"info.qooxdoo-range": null,
"provides.type": null,
"requires.qxcompiler": null,
"requires.qooxdoo-sdk": null,
"requires.qooxdoo-compiler": null
};
if (manifestModel.keyExists(obj)) {
needFix = true;
s += " obsolete entry:\n";
for (let key in obj) {
if (obj[key]) {
s += " " + key + "\n";
}
}
}
if (needFix) {
if (announceOnly) {
qx.tool.compiler.Console.warn("*** Manifest(s) need to be updated:\n" + s);
} else {
manifestModel
.transform("info.authors", authors => {
if (authors === "") {
return [];
} else if (qx.lang.Type.isString(authors)) {
return [{name: authors}];
} else if (qx.lang.Type.isObject(authors)) {
return [{
name: authors.name,
email: authors.email
}];
} else if (qx.lang.Type.isArray(authors)) {
return authors.map(r =>
qx.lang.Type.isObject(r) ? {
name: r.name,
email: r.email } :
{
name: r
}
);
}
return [];
})
.transform("info.version", version => {
let coerced = semver.coerce(version);
if (coerced === null) {
qx.tool.compiler.Console.warn(`*** Version string '${version}' could not be interpreted as semver, changing to 1.0.0`);
return "1.0.0";
}
return String(coerced);
})
.unset("info.qooxdoo-versions")
.unset("info.qooxdoo-range")
.unset("provides.type")
.unset("requires.qxcompiler")
.unset("requires.qooxdoo-compiler")
.unset("requires.qooxdoo-sdk");
await manifestModel.save();
if (!this.argv.quiet) {
qx.tool.compiler.Console.info(`Updated settings in ${manifestModel.getRelativeDataPath()}.`);
}
}
}
// check framework and compiler dependencies
// if none are given in the Manifest, use the present framework and compiler
const compiler_version = qx.tool.compiler.Version.VERSION;
const compiler_range = manifestModel.getValue("requires.@qooxdoo/compiler") || compiler_version;
const framework_version = await this.getLibraryVersion(await this.getGlobalQxPath());
const framework_range = manifestModel.getValue("requires.@qooxdoo/framework") || framework_version;
if (
!semver.satisfies(compiler_version, compiler_range) ||
!semver.satisfies(framework_version, framework_range)) {
needFix = true;
if (announceOnly) {
qx.tool.compiler.Console.warn(`*** Mismatch between installed framework version (${framework_version}) and/or compiler version (${compiler_version}) and the declared dependencies in the Manifest.`);
} else {
manifestModel
.setValue("requires.@qooxdoo/compiler", "^" + compiler_version)
.setValue("requires.@qooxdoo/framework", "^" + framework_version);
manifestModel.setWarnOnly(false);
// now model should validate
await manifestModel.save();
if (!this.argv.quiet) {
qx.tool.compiler.Console.info(`Updated dependencies in ${manifestModel.getRelativeDataPath()}.`);
}
}
}
manifestModel.setValidate(true);
}
if (!announceOnly) {
let compileJsonFilename = path.join(process.cwd(), "compile.json");
let replaceInFiles = [{
files: compileJsonFilename,
from: "\"qx/browser\"",
to: "\"@qooxdoo/qx/browser\""
}];
await this.migrate([compileJsonFilename], replaceInFiles);
}
let compileJsFilename = path.join(process.cwd(), "compile.js");
if (await fs.existsAsync(compileJsFilename)) {
let data = await fs.readFileAsync(compileJsFilename, "utf8");
if (data.indexOf("module.exports") < 0) {
qx.tool.compiler.Console.warn("*** Your compile.js appears to be missing a `module.exports` statement - please see https://git.io/fjBqU for more details");
}
}
self.migrationInProcess = false;
if (needFix) {
if (announceOnly) {
qx.tool.compiler.Console.error(`*** Try executing 'qx package migrate' to apply the changes. Alternatively, upgrade or downgrade framework and/or compiler to match the library dependencies.`);
process.exit(1);
}
qx.tool.compiler.Console.info("Migration completed.");
} else if (!announceOnly && !this.argv.quiet) {
qx.tool.compiler.Console.info("Everything is up-to-date. No migration necessary.");
}
}
}
});
| johnspackman/qxcompiler | source/class/qx/tool/cli/commands/package/Migrate.js | JavaScript | mit | 9,371 |
package gavilan.irc;
import java.util.Set;
import javax.annotation.PreDestroy;
import org.pircbotx.PircBotX;
public interface TwitchCore {
void doGreet(ChatMessage cm);
Set<String> getPendings();
void message(String channel, String message);
void onMessage(ChatMessage cm);
@PreDestroy
void shutdown();
void startAll(PircBotX pircBotX);
}
| gavilancomun/irc-explorer | src/main/java/gavilan/irc/TwitchCore.java | Java | mit | 366 |
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Documento
*
* @ORM\Table(name="documentos")
* @ORM\Entity
*/
class Documento
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var text
*
* @ORM\Column(name="descripcion", type="text",nullable=true)
*/
private $descripcion;
/**
* @var \DateTime
*
* @ORM\Column(name="fecha_ingreso", type="date")
*/
private $fechaIngreso;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Expediente",inversedBy="documentos")
* @ORM\JoinColumn(name="expediente_id", referencedColumnName="id")
*/
private $expediente;
/**
* @ORM\ManyToOne(targetEntity="TipoDocumentoExpediente",inversedBy="documentos")
* @ORM\JoinColumn(name="tipo_documento_expediente_id", referencedColumnName="id")
*/
private $tipoDocumentoExpediente;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Hoja", mappedBy="documento",cascade={"persist", "remove"})
* @ORM\OrderBy({"numero" = "ASC"})
*/
private $hojas;
/**
* @var datetime $creado
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(name="creado", type="datetime")
*/
private $creado;
/**
* @var datetime $actualizado
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(name="actualizado",type="datetime")
*/
private $actualizado;
/**
* @var integer $creadoPor
*
* @Gedmo\Blameable(on="create")
* @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
* @ORM\JoinColumn(name="creado_por", referencedColumnName="id", nullable=true)
*/
private $creadoPor;
/**
* @var integer $actualizadoPor
*
* @Gedmo\Blameable(on="update")
* @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
* @ORM\JoinColumn(name="actualizado_por", referencedColumnName="id", nullable=true)
*/
private $actualizadoPor;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set descripcion
*
* @param string $descripcion
*
* @return Documento
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* @return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* Set fechaIngreso
*
* @param \DateTime $fechaIngreso
*
* @return Documento
*/
public function setFechaIngreso($fechaIngreso)
{
$this->fechaIngreso = $fechaIngreso;
return $this;
}
/**
* Get fechaIngreso
*
* @return \DateTime
*/
public function getFechaIngreso()
{
return $this->fechaIngreso;
}
/**
* Set orden
*
* @param integer $orden
*
* @return Documento
*/
public function setOrden($orden)
{
$this->orden = $orden;
return $this;
}
/**
* Get orden
*
* @return integer
*/
public function getOrden()
{
return $this->orden;
}
/**
* Constructor
*/
public function __construct()
{
$this->hojas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set creado
*
* @param \DateTime $creado
*
* @return Documento
*/
public function setCreado($creado)
{
$this->creado = $creado;
return $this;
}
/**
* Get creado
*
* @return \DateTime
*/
public function getCreado()
{
return $this->creado;
}
/**
* Set actualizado
*
* @param \DateTime $actualizado
*
* @return Documento
*/
public function setActualizado($actualizado)
{
$this->actualizado = $actualizado;
return $this;
}
/**
* Get actualizado
*
* @return \DateTime
*/
public function getActualizado()
{
return $this->actualizado;
}
/**
* Set expediente
*
* @param \AppBundle\Entity\Expediente $expediente
*
* @return Documento
*/
public function setExpediente(\AppBundle\Entity\Expediente $expediente = null)
{
$this->expediente = $expediente;
return $this;
}
/**
* Get expediente
*
* @return \AppBundle\Entity\Expediente
*/
public function getExpediente()
{
return $this->expediente;
}
/**
* Add hoja
*
* @param \AppBundle\Entity\Hoja $hoja
*
* @return Documento
*/
public function addHoja(\AppBundle\Entity\Hoja $hoja)
{
$this->hojas[] = $hoja;
return $this;
}
/**
* Remove hoja
*
* @param \AppBundle\Entity\Hoja $hoja
*/
public function removeHoja(\AppBundle\Entity\Hoja $hoja)
{
$this->hojas->removeElement($hoja);
}
/**
* Get hojas
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getHojas()
{
return $this->hojas;
}
/**
* Set creadoPor
*
* @param \UsuariosBundle\Entity\Usuario $creadoPor
*
* @return Documento
*/
public function setCreadoPor(\UsuariosBundle\Entity\Usuario $creadoPor = null)
{
$this->creadoPor = $creadoPor;
return $this;
}
/**
* Get creadoPor
*
* @return \UsuariosBundle\Entity\Usuario
*/
public function getCreadoPor()
{
return $this->creadoPor;
}
/**
* Set actualizadoPor
*
* @param \UsuariosBundle\Entity\Usuario $actualizadoPor
*
* @return Documento
*/
public function setActualizadoPor(\UsuariosBundle\Entity\Usuario $actualizadoPor = null)
{
$this->actualizadoPor = $actualizadoPor;
return $this;
}
/**
* Get actualizadoPor
*
* @return \UsuariosBundle\Entity\Usuario
*/
public function getActualizadoPor()
{
return $this->actualizadoPor;
}
/**
* Set tipoDocumentoExpediente
*
* @param \AppBundle\Entity\TipoDocumentoExpediente $tipoDocumentoExpediente
*
* @return Documento
*/
public function setTipoDocumentoExpediente(\AppBundle\Entity\TipoDocumentoExpediente $tipoDocumentoExpediente = null)
{
$this->tipoDocumentoExpediente = $tipoDocumentoExpediente;
return $this;
}
/**
* Get tipoDocumentoExpediente
*
* @return \AppBundle\Entity\TipoDocumentoExpediente
*/
public function getTipoDocumentoExpediente()
{
return $this->tipoDocumentoExpediente;
}
}
| johnnykatz/colegio | src/AppBundle/Entity/Documento.php | PHP | mit | 7,069 |
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("Immune System")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Immune System")]
[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("58cabef6-9a10-46c5-918c-bbc68318c99a")]
// 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")]
| preslavc/SoftUni | Programming Fundamentals/More Exercises/Dictionaries and Lists/Immune System/Properties/AssemblyInfo.cs | C# | mit | 1,397 |
package com.github.visgeek.utils.collections;
import java.util.Iterator;
class LinqConcateIterator<T> implements Iterator<T> {
// コンストラクター
public LinqConcateIterator(Iterable<T> source, Iterable<? extends T> second) {
this.second = second;
this.itr = source.iterator();
this.isSwitched = false;
}
// フィールド
private final Iterable<? extends T> second;
private Iterator<? extends T> itr;
private boolean isSwitched;
// プロパティ
// メソッド
@Override
public boolean hasNext() {
boolean result = false;
result = this.itr.hasNext();
if (!this.isSwitched) {
if (!result) {
this.itr = this.second.iterator();
result = this.itr.hasNext();
this.isSwitched = true;
}
}
return result;
}
@Override
public T next() {
return this.itr.next();
}
// スタティックフィールド
// スタティックイニシャライザー
// スタティックメソッド
}
| visGeek/JavaVisGeekCollections | src/src/main/java/com/github/visgeek/utils/collections/LinqConcateIterator.java | Java | mit | 1,003 |
package de.csmath.QT;
import java.util.Collection;
import java.util.List;
/**
* This class builds a FTypeAtom from given parameters.
* @author lpfeiler
*/
public class FTypeAtomBuilder extends QTAtomBuilder {
/**
* @see FTypeAtom#majBrand
*/
private int majBrand = 0;
/**
* @see FTypeAtom#minVersion
*/
private int minVersion = 0;
/**
* @see FTypeAtom#compBrands
*/
private Collection<Integer> compBrands;
/**
* Constructs a FTypeAtomBuilder.
* @param size the size of the FTypeAtom in the file
* @param type the type of the atom, should be set to 'ftyp'
*/
public FTypeAtomBuilder(int size, int type) {
super(size, type);
}
/**
* Returns a new FTypeAtom.
* @return a new FTypeAtom
*/
public FTypeAtom build() {
return new FTypeAtom(size,type,majBrand,minVersion,compBrands);
}
/**
* Sets the major brand.
* @see FTypeAtom#majBrand
* @param majBrand the major brand
* @return a reference to this object
*/
public FTypeAtomBuilder withMajBrand(int majBrand) {
this.majBrand = majBrand;
return this;
}
/**
* Sets the minor version.
* @see FTypeAtom#minVersion
* @param minVersion the minor version
* @return a reference to this object
*/
public FTypeAtomBuilder withMinVersion(int minVersion) {
this.minVersion = minVersion;
return this;
}
/**
* Sets the compatible brands.
* @param compBrands a collection of compatible brands
* @return a reference to this object
*/
public FTypeAtomBuilder withCompBrands(Collection<Integer> compBrands) {
this.compBrands = compBrands;
return this;
}
}
| lpcsmath/QTReader | src/main/java/de/csmath/QT/FTypeAtomBuilder.java | Java | mit | 1,783 |
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY
const daggy = require('daggy')
const compose = (f, g) => x => f(g(x))
const id = x => x
//===============Define Coyoneda=========
// create constructor with props 'x' and 'f'
// 'x' is our value, 'f' is a function
const Coyoneda = daggy.tagged('x', 'f')
// map composes the function
Coyoneda.prototype.map = function(f) {
return Coyoneda(this.x, compose(f, this.f))
}
Coyoneda.prototype.lower = function() {
return this.x.map(this.f)
}
// lift starts off Coyoneda with the 'id' function
Coyoneda.lift = x => Coyoneda(x, id)
//===============Map over a non-Functor - Set =========
// Set does not have a 'map' method
const set = new Set([1, 1, 2, 3, 3, 4])
console.log("Set([1, 1, 2, 3, 3, 4]) : ", set)
// Wrap set into Coyoneda with 'id' function
const coyoResult = Coyoneda.lift(set)
.map(x => x + 1)
.map(x => `${x}!`)
console.log(
"Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ",
coyoResult
)
// equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x
const {f: builtUpFn, x: ourSet} = coyoResult
console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet)
ourSet
.forEach(n => console.log(builtUpFn(n)))
// 2!
// 3!
// 4!
// 5!
//===============Lift a functor in (Array) and achieve Loop fusion=========
console.log(
`Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `,
Coyoneda.lift([1,2,3])
.map(x => x * 2)
.map(x => x - 1)
.lower()
)
// [ 1, 3, 5 ]
//===============Make Any Type a Functor=========
// Any object becomes a functor when placed in Coyoneda
const Container = daggy.tagged('x')
const tunacan = Container("tuna")
const res = Coyoneda.lift(tunacan)
.map(x => x.toUpperCase())
.map(x => x + '!')
const {f: fn, x: can} = res
console.log(fn(can.x))
// TUNA!
| dmitriz/functional-examples | examples/coyoneda.js | JavaScript | mit | 1,828 |
package org.coursera.androidcapstone.symptomchecker.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PatientRepository extends PagingAndSortingRepository<Patient, Long> {
@Query("From Patient p where :doctor member p.doctors")
public Page<Patient> findByDoctor(@Param("doctor") Doctor doctor, Pageable page);
@Query("From Patient p where :doctor member p.doctors AND UPPER(fullName)=:fullName")
public List<Patient> findByDoctorAndFullName(@Param("doctor") Doctor doctor, @Param("fullName") String fullName);
}
| emadhilo/capstone | SymptomCheckerService/src/main/java/org/coursera/androidcapstone/symptomchecker/repository/PatientRepository.java | Java | mit | 860 |
var map, boroughSearch = [],
theaterSearch = [],
museumSearch = [];
/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png");
var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png");
var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png");
var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", {
maxZoom: 19,
});
var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", {
maxZoom: 19,
}), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", {
maxZoom: 19,
subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"],
})]);
map = L.map("map", {
zoom: 5,
center: [39, -95],
layers: [mapquestOSM]
});
/* Larger screens get expanded layer control */
if (document.body.clientWidth <= 767) {
var isCollapsed = true;
} else {
var isCollapsed = false;
}
var baseLayers = {
"Street Map": mapquestOSM,
"Aerial Imagery": mapquestOAM,
"Imagery with Streets": mapquestHYB
};
var overlays = {};
var layerControl = L.control.layers(baseLayers, {}, {
collapsed: isCollapsed
}).addTo(map);
/* Add overlay layers to map after defining layer control to preserver order */
var sidebar = L.control.sidebar("sidebar", {
closeButton: true,
position: "left"
}).addTo(map);
sidebar.toggle();
/* Highlight search box text on click */
$("#searchbox").click(function () {
$(this).select();
});
/* Placeholder hack for IE */
if (navigator.appName == "Microsoft Internet Explorer") {
$("input").each(function () {
if ($(this).val() === "" && $(this).attr("placeholder") !== "") {
$(this).val($(this).attr("placeholder"));
$(this).focus(function () {
if ($(this).val() === $(this).attr("placeholder")) $(this).val("");
});
$(this).blur(function () {
if ($(this).val() === "") $(this).val($(this).attr("placeholder"));
});
}
});
}
$(function(){
var popup = {
init : function() {
// position popup
windowW = $(window).width();
$("#map").on("mousemove", function(e) {
var x = e.pageX + 20;
var y = e.pageY;
var windowH = $(window).height();
if (y > (windowH - 100)) {
var y = e.pageY - 100;
} else {
var y = e.pageY - 20;
}
$("#info").css({
"left": x,
"top": y
});
});
}
};
popup.init();
}) | availabs/transit_analyst | assets/js/main.js | JavaScript | mit | 2,596 |
# frozen_string_literal: true
require 'spec_helper'
describe ErrorTracking::ProjectErrorTrackingSetting do
include ReactiveCachingHelpers
set(:project) { create(:project) }
subject { create(:project_error_tracking_setting, project: project) }
describe 'Associations' do
it { is_expected.to belong_to(:project) }
end
describe 'Validations' do
context 'when api_url is over 255 chars' do
before do
subject.api_url = 'https://' + 'a' * 250
end
it 'fails validation' do
expect(subject).not_to be_valid
expect(subject.errors.messages[:api_url]).to include('is too long (maximum is 255 characters)')
end
end
context 'With unsafe url' do
it 'fails validation' do
subject.api_url = "https://replaceme.com/'><script>alert(document.cookie)</script>"
expect(subject).not_to be_valid
end
end
context 'presence validations' do
using RSpec::Parameterized::TableSyntax
valid_api_url = 'http://example.com/api/0/projects/org-slug/proj-slug/'
valid_token = 'token'
where(:enabled, :token, :api_url, :valid?) do
true | nil | nil | false
true | nil | valid_api_url | false
true | valid_token | nil | false
true | valid_token | valid_api_url | true
false | nil | nil | true
false | nil | valid_api_url | true
false | valid_token | nil | true
false | valid_token | valid_api_url | true
end
with_them do
before do
subject.enabled = enabled
subject.token = token
subject.api_url = api_url
end
it { expect(subject.valid?).to eq(valid?) }
end
end
context 'URL path' do
it 'fails validation with wrong path' do
subject.api_url = 'http://gitlab.com/project1/something'
expect(subject).not_to be_valid
expect(subject.errors.messages[:api_url]).to include('path needs to start with /api/0/projects')
end
it 'passes validation with correct path' do
subject.api_url = 'http://gitlab.com/api/0/projects/project1/something'
expect(subject).to be_valid
end
end
context 'non ascii chars in api_url' do
before do
subject.api_url = 'http://gitlab.com/api/0/projects/project1/something€'
end
it 'fails validation' do
expect(subject).not_to be_valid
end
end
end
describe '#sentry_external_url' do
let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' }
before do
subject.api_url = sentry_url
end
it 'returns the correct url' do
expect(subject.class).to receive(:extract_sentry_external_url).with(sentry_url).and_call_original
result = subject.sentry_external_url
expect(result).to eq('https://sentrytest.gitlab.com/sentry-org/sentry-project')
end
end
describe '#sentry_client' do
it 'returns sentry client' do
expect(subject.sentry_client).to be_a(Sentry::Client)
end
end
describe '#list_sentry_issues' do
let(:issues) { [:list, :of, :issues] }
let(:opts) do
{ issue_status: 'unresolved', limit: 10 }
end
let(:result) do
subject.list_sentry_issues(**opts)
end
context 'when cached' do
let(:sentry_client) { spy(:sentry_client) }
before do
stub_reactive_cache(subject, issues, opts)
synchronous_reactive_cache(subject)
expect(subject).to receive(:sentry_client).and_return(sentry_client)
end
it 'returns cached issues' do
expect(sentry_client).to receive(:list_issues).with(opts)
.and_return(issues)
expect(result).to eq(issues: issues)
end
end
context 'when not cached' do
it 'returns nil' do
expect(subject).not_to receive(:sentry_client)
expect(result).to be_nil
end
end
end
describe '#list_sentry_projects' do
let(:projects) { [:list, :of, :projects] }
let(:sentry_client) { spy(:sentry_client) }
it 'calls sentry client' do
expect(subject).to receive(:sentry_client).and_return(sentry_client)
expect(sentry_client).to receive(:list_projects).and_return(projects)
result = subject.list_sentry_projects
expect(result).to eq(projects: projects)
end
end
context 'slugs' do
shared_examples_for 'slug from api_url' do |method, slug|
context 'when api_url is correct' do
before do
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug/'
end
it 'returns slug' do
expect(subject.public_send(method)).to eq(slug)
end
end
context 'when api_url is blank' do
before do
subject.api_url = nil
end
it 'returns nil' do
expect(subject.public_send(method)).to be_nil
end
end
end
it_behaves_like 'slug from api_url', :project_slug, 'project-slug'
it_behaves_like 'slug from api_url', :organization_slug, 'org-slug'
end
context 'names from api_url' do
shared_examples_for 'name from api_url' do |name, titleized_slug|
context 'name is present in DB' do
it 'returns name from DB' do
subject[name] = 'Sentry name'
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug'
expect(subject.public_send(name)).to eq('Sentry name')
end
end
context 'name is null in DB' do
it 'titleizes and returns slug from api_url' do
subject[name] = nil
subject.api_url = 'http://gitlab.com/api/0/projects/org-slug/project-slug'
expect(subject.public_send(name)).to eq(titleized_slug)
end
it 'returns nil when api_url is incorrect' do
subject[name] = nil
subject.api_url = 'http://gitlab.com/api/0/projects/'
expect(subject.public_send(name)).to be_nil
end
it 'returns nil when api_url is blank' do
subject[name] = nil
subject.api_url = nil
expect(subject.public_send(name)).to be_nil
end
end
end
it_behaves_like 'name from api_url', :organization_name, 'Org Slug'
it_behaves_like 'name from api_url', :project_name, 'Project Slug'
end
describe '.build_api_url_from' do
it 'correctly builds api_url with slugs' do
api_url = described_class.build_api_url_from(
api_host: 'http://sentry.com/',
organization_slug: 'org-slug',
project_slug: 'proj-slug'
)
expect(api_url).to eq('http://sentry.com/api/0/projects/org-slug/proj-slug/')
end
it 'correctly builds api_url without slugs' do
api_url = described_class.build_api_url_from(
api_host: 'http://sentry.com/',
organization_slug: nil,
project_slug: nil
)
expect(api_url).to eq('http://sentry.com/api/0/projects/')
end
it 'does not raise exception with invalid url' do
api_url = described_class.build_api_url_from(
api_host: ':::',
organization_slug: 'org-slug',
project_slug: 'proj-slug'
)
expect(api_url).to eq(':::')
end
end
describe '#api_host' do
context 'when api_url exists' do
before do
subject.api_url = 'https://example.com/api/0/projects/org-slug/proj-slug/'
end
it 'extracts the api_host from api_url' do
expect(subject.api_host).to eq('https://example.com/')
end
end
context 'when api_url is nil' do
before do
subject.api_url = nil
end
it 'returns nil' do
expect(subject.api_url).to eq(nil)
end
end
end
end
| axilleas/gitlabhq | spec/models/error_tracking/project_error_tracking_setting_spec.rb | Ruby | mit | 7,804 |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"configText": "Ustaw tekst konfiguracyjny:",
"generalSettings": {
"tabTitle": "Ustawienia ogólne",
"measurementUnitLabel": "Jednostka miary",
"currencyLabel": "Symbol miary",
"roundCostLabel": "Zaokrąglaj koszt",
"projectOutputSettings": "Ustawienia wynikowe projektu",
"typeOfProjectAreaLabel": "Typ obszaru projektu",
"bufferDistanceLabel": "Odległość buforowania",
"roundCostValues": {
"twoDecimalPoint": "Dwa miejsca po przecinku",
"nearestWholeNumber": "Najbliższa liczba całkowita",
"nearestTen": "Najbliższa dziesiątka",
"nearestHundred": "Najbliższa setka",
"nearestThousand": "Najbliższe tysiące",
"nearestTenThousands": "Najbliższe dziesiątki tysięcy"
},
"projectAreaType": {
"outline": "Obrys",
"buffer": "Bufor"
},
"errorMessages": {
"currency": "Nieprawidłowa jednostka waluty",
"bufferDistance": "Nieprawidłowa odległość buforowania",
"outOfRangebufferDistance": "Wartość powinna być większa niż 0 i mniejsza niż lub równa 100"
}
},
"projectSettings": {
"tabTitle": "Ustawienia projektu",
"costingGeometrySectionTitle": "Zdefiniuj obszar geograficzny na potrzeby kalkulacji kosztów (opcjonalnie)",
"costingGeometrySectionNote": "Uwaga: skonfigurowanie tej warstwy umożliwi użytkownikowi konfigurowanie równań kosztów szablonów obiektów na podstawie obszarów geograficznych.",
"projectTableSectionTitle": "Możliwość zapisania/wczytania ustawień projektu (opcjonalnie)",
"projectTableSectionNote": "Uwaga: skonfigurowanie wszystkich tabel i warstw umożliwi użytkownikowi zapisanie/wczytanie projektu w celu ponownego wykorzystania.",
"costingGeometryLayerLabel": "Warstwa geometrii kalkulacji kosztów",
"fieldLabelGeography": "Pole do oznaczenia etykietą obszaru geograficznego",
"projectAssetsTableLabel": "Tabela zasobów projektu",
"projectMultiplierTableLabel": "Tabela kosztów dodatkowych mnożnika projektu",
"projectLayerLabel": "Warstwa projektu",
"configureFieldsLabel": "Skonfiguruj pola",
"fieldDescriptionHeaderTitle": "Opis pola",
"layerFieldsHeaderTitle": "Pole warstwy",
"selectLabel": "Zaznacz",
"errorMessages": {
"duplicateLayerSelection": "Warstwa ${layerName} jest już wybrana",
"invalidConfiguration": "Należy wybrać wartość ${fieldsString}"
},
"costingGeometryHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć możliwość wykonywania zapytania</li><li>\tWarstwa musi zawierać pole GlobalID</li></p>",
"fieldToLabelGeographyHelp": "<p>Pola znakowe i liczbowe wybranej warstwy geometrii kalkulacji kosztów zostaną wyświetlone w menu rozwijanym Pole do oznaczenia etykietą obszaru geograficznego.</p>",
"projectAssetsTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać sześć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tAssetGUID (pole typu GUID)</li><li>\tCostEquation (pole typu String)</li><li>\tScenario (pole typu String)</li><li>\tTemplateName (pole typu String)</li><li> GeographyGUID (pole typu GUID)</li><li>\tProjectGUID (pole typu GUID)</li></ul> </p>",
"projectMultiplierTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tDescription (pole typu String)</li><li>\tType (pole typu String)</li><li>\tValue (pole typu Float/Double)</li><li>\tCostindex (pole typu Integer)</li><li> \tProjectGUID (pole typu GUID))</li></ul> </p>",
"projectLayerHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>Warstwa musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Warstwa musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>ProjectName (pole typu String)</li><li>Description (pole typu String)</li><li>Totalassetcost (pole typu Float/Double)</li><li>Grossprojectcost (pole typu Float/Double)</li><li>GlobalID (pole typu GlobalID)</li></ul> </p>",
"pointLayerCentroidLabel": "Centroid warstwy punktowej",
"selectRelatedPointLayerDefaultOption": "Zaznacz",
"pointLayerHintText": "<p>Zostaną wyświetlone warstwy punktowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć pole 'Projectid' (typ GUID)</li><li>\tWarstwa musi mieć możliwość edycji, a więc atrybut 'Tworzenie', 'Usuwanie' i 'Aktualizacja'</li></p>"
},
"layerSettings": {
"tabTitle": "Ustawienia warstwy",
"layerNameHeaderTitle": "Nazwa warstwy",
"layerNameHeaderTooltip": "Lista warstw na mapie",
"EditableLayerHeaderTitle": "Edytowalne",
"EditableLayerHeaderTooltip": "Dołącz warstwę i jej szablony w widżecie kalkulacji kosztów",
"SelectableLayerHeaderTitle": "Podlegające selekcji",
"SelectableLayerHeaderTooltip": "Geometria z obiektu może zostać użyta do wygenerowania nowego elementu kosztu",
"fieldPickerHeaderTitle": "ID projektu (opcjonalnie)",
"fieldPickerHeaderTooltip": "Pole opcjonalne (typu znakowego), w którym będzie przechowywany identyfikator projektu",
"selectLabel": "Zaznacz",
"noAssetLayersAvailable": "Nie znaleziono warstwy zasobów na wybranej mapie internetowej",
"disableEditableCheckboxTooltip": "Ta warstwa nie ma możliwości edycji",
"missingCapabilitiesMsg": "Dla tej warstwy brak następujących funkcji:",
"missingGlobalIdMsg": "Ta warstwa nie ma pola GlobalId",
"create": "Tworzenie",
"update": "Aktualizuj",
"delete": "Usuwanie",
"attributeSettingHeaderTitle": "Ustawienia atrybutów",
"addFieldLabelTitle": "Dodaj atrybuty",
"layerAttributesHeaderTitle": "Atrybuty warstwy",
"projectLayerAttributesHeaderTitle": "Atrybuty warstwy projektu",
"attributeSettingsPopupTitle": "Ustawienia atrybutów warstwy"
},
"costingInfo": {
"tabTitle": "Informacje o kalkulacji kosztów",
"proposedMainsLabel": "Proponowane elementy główne",
"addCostingTemplateLabel": "Dodaj szablon kalkulacji kosztów",
"manageScenariosTitle": "Zarządzaj scenariuszami",
"featureTemplateTitle": "Szablon obiektu",
"costEquationTitle": "Równanie kosztów",
"geographyTitle": "Obszar geograficzny",
"scenarioTitle": "Scenariusz",
"actionTitle": "Działania",
"scenarioNameLabel": "Nazwa scenariusza",
"addBtnLabel": "Dodaj",
"srNoLabel": "Nie.",
"deleteLabel": "Usuwanie",
"duplicateScenarioName": "Duplikuj nazwę scenariusza",
"hintText": "<div>Wskazówka: użyj następujących słów kluczowych</div><ul><li><b>{TOTALCOUNT}</b>: używa łącznej liczby zasobów tego samego typu w obszarze geograficznym</li><li><b>{MEASURE}</b>: używa długości dla zasobu liniowego i pola powierzchni dla zasobu poligonowego</li><li><b>{TOTALMEASURE}</b>: używa łącznej długości dla zasobu liniowego i łącznego pola powierzchni dla zasobu poligonowego tego samego typu w obszarze geograficznym</li></ul> Możesz użyć funkcji, takich jak:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Należy zmodyfikować równanie kosztów zgodnie z wymaganiami projektu.",
"noneValue": "Brak",
"requiredCostEquation": "Niepoprawne równanie kosztów dla warstwy ${layerName} : ${templateName}",
"duplicateTemplateMessage": "Istnieje podwójny wpis szablonu dla warstwy ${layerName} : ${templateName}",
"defaultEquationRequired": "Wymagane jest domyślne równanie dla warstwy ${layerName} : ${templateName}",
"validCostEquationMessage": "Wprowadź prawidłowe równanie kosztów",
"costEquationHelpText": "Edytuj równanie kosztów zgodnie z wymaganiami projektu",
"scenarioHelpText": "Wybierz scenariusz zgodnie z wymaganiami projektu",
"copyRowTitle": "Kopiuj wiersz",
"noTemplateAvailable": "Dodaj co najmniej jeden szablon dla warstwy ${layerName}",
"manageScenarioLabel": "Zarządzaj scenariuszem",
"noLayerMessage": "Wprowadź co najmniej jedną warstwę w ${tabName}",
"noEditableLayersAvailable": "Warstwy, które należy oznaczyć jako możliwe do edycji na karcie ustawień warstwy",
"updateProjectCostCheckboxLabel": "Aktualizuj równania projektu",
"updateProjectCostEquationHint": "Wskazówka: Umożliwia użytkownikowi aktualizowanie równań kosztów zasobów, które zostały już dodane do istniejących projektów, za pomocą nowych równań zdefiniowanych niżej na podstawie szablonu obiektu, geografii i scenariusza. Jeśli brak określonej kombinacji, zostanie przyjęty koszt domyślny, tzn. geografia i scenariusz ma wartość 'None' (brak). W przypadku usunięcia szablonu obiektu ustawiony zostanie koszt równy 0."
},
"statisticsSettings": {
"tabTitle": "Dodatkowe ustawienia",
"addStatisticsLabel": "Dodaj statystykę",
"fieldNameTitle": "Pole",
"statisticsTitle": "Etykieta",
"addNewStatisticsText": "Dodaj nową statystykę",
"deleteStatisticsText": "Usuń statystykę",
"moveStatisticsUpText": "Przesuń statystykę w górę",
"moveStatisticsDownText": "Przesuń statystykę w dół",
"selectDeselectAllTitle": "Zaznacz wszystkie"
},
"projectCostSettings": {
"addProjectCostLabel": "Dodaj koszt dodatkowy projektu",
"additionalCostValueColumnHeader": "Wartość",
"invalidProjectCostMessage": "Nieprawidłowa wartość kosztu projektu",
"additionalCostLabelColumnHeader": "Etykieta",
"additionalCostTypeColumnHeader": "Typ"
},
"statisticsType": {
"countLabel": "Liczba",
"averageLabel": "Średnia",
"maxLabel": "Maksimum",
"minLabel": "Minimum",
"summationLabel": "Zsumowanie",
"areaLabel": "Pole powierzchni",
"lengthLabel": "Długość"
}
}); | tmcgee/cmv-wab-widgets | wab/2.13/widgets/CostAnalysis/setting/nls/pl/strings.js | JavaScript | mit | 10,828 |
<?php
/**
* Created by PhpStorm.
* User: Renfrid-Sacids
* Date: 2/4/2016
* Time: 9:44 AM
*/
class Xform_model extends CI_Model
{
/**
* Table name for xform definitions
*
* @var string
*/
private static $xform_table_name = "xforms"; //default value
/**
* Table name for archived/deleted xforms
*
* @var string
*/
private static $archive_xform_table_name = "archive_xformx"; //default value
public function __construct()
{
$this->initialize_table();
}
/**
* Initializes table names from configuration files
*/
private function initialize_table()
{
if ($this->config->item("table_xform"))
self::$xform_table_name = $this->config->item("table_xform");
if ($this->config->item("table_archive_xform"))
self::$archive_xform_table_name = $this->config->item("table_archive_xform");
}
/**
* @param $statement
* @return bool
*/
public function create_table($statement)
{
if ($this->db->simple_query($statement)) {
log_message("debug", "Success!");
return TRUE;
} else {
$error = $this->db->error(); // Has keys 'code' and 'message'
log_message("debug", $statement . ", error " . json_encode($error));
return FALSE;
}
}
/**
* @param $statement
* @return bool
*/
public function insert_data($statement)
{
if ($this->db->simple_query($statement)) {
log_message("debug", "Success!");
return TRUE;
} else {
$error = $this->db->error(); // Has keys 'code' and 'message'
log_message("debug", $statement . ", error " . json_encode($error));
}
}
/**
* @param $form_details an array of form details with keys match db field names
* @return id for the created form
*/
public function create_xform($form_details)
{
$this->db->insert(self::$xform_table_name, $form_details);
return $this->db->insert_id();
}
/**
* @param int xform_id the row that needs to be updated
* @param string form_id
* @return bool
*/
public function update_form_id($xform_id, $form_id)
{
$data = array('form_id' => $form_id);
$this->db->where('id', $xform_id);
return $this->db->update(self::$xform_table_name, $data);
}
/**
* @param $form_id
* @param $form_details
* @return mixed
*/
public function update_form($form_id, $form_details)
{
$this->db->where('id', $form_id);
return $this->db->update(self::$xform_table_name, $form_details);
}
/**
* @param null $user_id
* @param int $limit
* @param int $offset
* @return mixed returns list of forms available.
*/
public function get_form_list($user_id = NULL, $limit = 30, $offset = 0)
{
if ($user_id != NULL)
$this->db->where("user_id", $user_id);
$this->db->limit($limit, $offset);
return $this->db->get(self::$xform_table_name)->result();
}
/**
* Finds a table field with point data type
*
* @param $table_name
* @return field name or FALSE
*/
public function get_point_field($table_name)
{
$sql = " SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS ";
$sql .= " WHERE table_name = '{$table_name}' ";
$sql .= " AND DATA_TYPE = 'point'";
$query = $this->db->query($sql);
return ($query->num_rows() == 1) ? $query->row(1)->COLUMN_NAME : FALSE;
}
/**
* @param $form_id
* @return mixed
*/
public function find_by_id($form_id)
{
$this->db->where("id", $form_id);
return $this->db->get(self::$xform_table_name)->row();
}
/**
* @param $xform_id
* @return mixed
*/
public function delete_form($xform_id)
{
$this->db->limit(1);
$this->db->where("id", $xform_id);
return $this->db->delete(self::$xform_table_name);
}
/**
* @param $xform_archive_data
* @return mixed
*/
public function create_archive($xform_archive_data)
{
return $this->db->insert(self::$archive_xform_table_name, $xform_archive_data);
}
/**
* @param $table_name
* @param int $limit
* @param int $offset
* @return mixed returns data from tables created by uploading xform definitions files.
*/
public function find_form_data($table_name, $limit = 30, $offset = 0)
{
$this->db->limit($limit, $offset);
return $this->db->get($table_name)->result();
}
/**
* @param $table_name
* @return mixed return an object of fields of the specified table
*/
public function find_table_columns($table_name)
{
return $this->db->list_fields($table_name);
}
/**
* @param $table_name
* @return mixed returns table fields/columns with metadata object
*/
public function find_table_columns_data($table_name)
{
return $this->db->field_data($table_name);
}
public function get_graph_data($table_name, $x_axis_column, $y_axis_column, $y_axis_action = "COUNT")
{
if ($y_axis_action == "COUNT") {
$this->db->select("`" . $y_axis_column . "`, COUNT(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`");
$this->db->group_by($x_axis_column);
}
if ($y_axis_action == "SUM") {
$this->db->select("`" . $y_axis_column . "`, SUM(" . $y_axis_column . ") AS `" . strtolower($y_axis_action) . "`");
$this->db->group_by($x_axis_column);
}
$this->db->from($table_name);
return $this->db->get()->result();
}
} | renfrid/dataManager | application/models/Xform_model.php | PHP | mit | 5,088 |
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body>
<!-- Main navigation -->
<?php
do_action( 'omega_before_header' );
?>
<!-- Featured post -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 col-sm-12 col-xs-12">
<div id="header-template">
</div>
</div>
</div>
</div>
<script type='template' id='headerTemplate'>
<a href="<%- url %>">
<div class="header-feature">
<div class="header-mask">
<img class="header-mask-image" src="<%= thumbnail_images == 'undefined' ? 'http://placehold.it/350x150' : thumbnail_images.large.url %>" alt="<%- title %>">
</div>
<div class="header-feature-text">
<h5>
<%= custom_fields.participant %>
</h5>
<h1>
<%= title %>
</h1>
</div>
</div>
</a>
</script>
| serpentinegalleries/radio-serpentine | header-home.php | PHP | mit | 1,005 |
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use AppBundle\Entity\User;
class registerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('eMail', EmailType::class)
->add('password', RepeatedType::class, [
'type' => PasswordType::class
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class
]);
}
public function getBlockPrefix()
{
return 'app_bundleregister_type';
}
}
| Fabcra/bien_etre | src/AppBundle/Form/registerType.php | PHP | mit | 962 |
/*
* This file is part of the Cliche project, licensed under MIT License. See LICENSE.txt file in root folder of Cliche
* sources.
*/
package net.dudehook.cliche2.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author ASG
*/
public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V>
{
private Map<K, List<V>> listMap;
public ArrayHashMultiMap()
{
listMap = new HashMap<K, List<V>>();
}
public ArrayHashMultiMap(MultiMap<K, V> map)
{
this();
putAll(map);
}
public void put(K key, V value)
{
List<V> values = listMap.get(key);
if (values == null)
{
values = new ArrayList<V>();
listMap.put(key, values);
}
values.add(value);
}
public Collection<V> get(K key)
{
List<V> result = listMap.get(key);
if (result == null)
{
result = new ArrayList<V>();
}
return result;
}
public Set<K> keySet()
{
return listMap.keySet();
}
public void remove(K key, V value)
{
List<V> values = listMap.get(key);
if (values != null)
{
values.remove(value);
if (values.isEmpty())
{
listMap.remove(key);
}
}
}
public void removeAll(K key)
{
listMap.remove(key);
}
public int size()
{
int sum = 0;
for (K key : listMap.keySet())
{
sum += listMap.get(key).size();
}
return sum;
}
public void putAll(MultiMap<K, V> map)
{
for (K key : map.keySet())
{
for (V val : map.get(key))
{
put(key, val);
}
}
}
@Override
public String toString()
{
return listMap.toString();
}
}
| dudehook/Cliche2 | src/main/java/net/dudehook/cliche2/util/ArrayHashMultiMap.java | Java | mit | 2,003 |
const fs = require('fs')
const { normalize, resolve, join, sep } = require('path')
function getAppDir () {
let dir = process.cwd()
while (dir.length && dir[dir.length - 1] !== sep) {
if (fs.existsSync(join(dir, 'quasar.conf.js'))) {
return dir
}
dir = normalize(join(dir, '..'))
}
const { fatal } = require('./helpers/logger')
fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`)
}
const appDir = getAppDir()
const cliDir = resolve(__dirname, '..')
const srcDir = resolve(appDir, 'src')
const pwaDir = resolve(appDir, 'src-pwa')
const ssrDir = resolve(appDir, 'src-ssr')
const cordovaDir = resolve(appDir, 'src-cordova')
const capacitorDir = resolve(appDir, 'src-capacitor')
const electronDir = resolve(appDir, 'src-electron')
const bexDir = resolve(appDir, 'src-bex')
module.exports = {
cliDir,
appDir,
srcDir,
pwaDir,
ssrDir,
cordovaDir,
capacitorDir,
electronDir,
bexDir,
resolve: {
cli: dir => join(cliDir, dir),
app: dir => join(appDir, dir),
src: dir => join(srcDir, dir),
pwa: dir => join(pwaDir, dir),
ssr: dir => join(ssrDir, dir),
cordova: dir => join(cordovaDir, dir),
capacitor: dir => join(capacitorDir, dir),
electron: dir => join(electronDir, dir),
bex: dir => join(bexDir, dir)
}
}
| rstoenescu/quasar-framework | app/lib/app-paths.js | JavaScript | mit | 1,321 |
<?php
require_once('config.php');
$session->requireLoggedIn();
require('design_head.php');
$text = '';
if (!empty($_POST['text'])) {
$text = $_POST['text'];
guessLanguage($text);
}
?>
<h2>Guess language</h2>
Enter some text and see if the program can guess the language that the text were written in.
<form method="post" action="">
<textarea name="text" cols="70" rows="20"></textarea><br/>
<input type="submit" class="button" value="Submit"/>
</form>
<?php
require('design_foot.php');
?>
| martinlindhe/core_dev | projects/lang/guess_language.php | PHP | mit | 538 |
'use strict';
import Maths from './maths.js'
import FSM from './fsm.js'
import { Animation, Interpolation } from './animation.js'
export { Maths, FSM, Interpolation, Animation }
| InconceivableVizzini/interjs | src/inter.js | JavaScript | mit | 179 |
namespace Free.FileFormats.VRML.Interfaces
{
public interface IX3DTexturePropertiesNode
{
}
}
| shintadono/Free.FileFormats.VRML | 18 Texturing/Interfaces/IX3DTexturePropertiesNode.cs | C# | mit | 100 |
// Runs the wiki on port 80
var server = require('./server');
server.run(80); | rswingler/byuwiki | server/controller/js/wiki.js | JavaScript | mit | 79 |
using System;
using System.Linq;
namespace CapnProto.Schema.Parser
{
class CapnpVisitor
{
protected Boolean mEnableNestedType = true;
protected CapnpModule mActiveModule;
protected void EnableNestedType()
{
mEnableNestedType = true;
}
protected void DisableNestedType()
{
mEnableNestedType = false;
}
public virtual CapnpType Visit(CapnpType target)
{
if (target == null) return null;
return target.Accept(this);
}
protected internal virtual CapnpType VisitPrimitive(CapnpPrimitive primitive)
{
return primitive;
}
protected internal virtual CapnpType VisitList(CapnpList list)
{
list.Parameter = Visit(list.Parameter);
return list;
}
protected internal virtual Value VisitValue(Value value)
{
return value;
}
protected internal virtual CapnpModule VisitModule(CapnpModule module)
{
// An imported module has already been processed.
if (mActiveModule != null && mActiveModule != module) return module;
mActiveModule = module;
module.Structs = module.Structs.Select(s => VisitStruct(s)).ToArray();
module.Interfaces = module.Interfaces.Select(i => VisitInterface(i)).ToArray();
module.Constants = module.Constants.Select(c => VisitConst(c)).ToArray();
module.Enumerations = module.Enumerations.Select(e => VisitEnum(e)).ToArray();
module.AnnotationDefs = module.AnnotationDefs.Select(a => VisitAnnotationDecl(a)).ToArray();
module.Usings = module.Usings.Select(u => VisitUsing(u)).ToArray();
module.Annotations = module.Annotations.Select(a => VisitAnnotation(a)).ToArray();
return module;
}
protected internal virtual Annotation VisitAnnotation(Annotation annotation)
{
if (annotation == null) return null;
annotation.Declaration = Visit(annotation.Declaration);
annotation.Argument = VisitValue(annotation.Argument);
return annotation;
}
protected internal virtual CapnpStruct VisitStruct(CapnpStruct @struct)
{
if (!mEnableNestedType) return @struct;
@struct.Structs = @struct.Structs.Select(s => VisitStruct(s)).ToArray();
@struct.Interfaces = @struct.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@struct.Enumerations = @struct.Enumerations.Select(e => VisitEnum(e)).ToArray();
@struct.Fields = @struct.Fields.Select(f => VisitField(f)).ToArray();
@struct.AnnotationDefs = @struct.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@struct.Annotations = @struct.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@struct.Usings = @struct.Usings.Select(u => VisitUsing(u)).ToArray();
@struct.Constants = @struct.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @struct;
}
protected internal virtual CapnpInterface VisitInterface(CapnpInterface @interface)
{
if (!mEnableNestedType) return @interface;
@interface.Structs = @interface.Structs.Select(s => VisitStruct(s)).ToArray();
@interface.Interfaces = @interface.Interfaces.Select(i => VisitInterface(i)).ToArray();
DisableNestedType();
@interface.Enumerations = @interface.Enumerations.Select(e => VisitEnum(e)).ToArray();
@interface.BaseInterfaces = @interface.BaseInterfaces.Select(i => Visit(i)).ToArray();
@interface.AnnotationDefs = @interface.AnnotationDefs.Select(ad => VisitAnnotationDecl(ad)).ToArray();
@interface.Annotations = @interface.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@interface.Methods = @interface.Methods.Select(m => VisitMethod(m)).ToArray();
@interface.Usings = @interface.Usings.Select(u => VisitUsing(u)).ToArray();
@interface.Constants = @interface.Constants.Select(c => VisitConst(c)).ToArray();
EnableNestedType();
return @interface;
}
protected internal virtual CapnpGenericParameter VisitGenericParameter(CapnpGenericParameter @param)
{
return @param;
}
protected internal virtual CapnpBoundGenericType VisitClosedType(CapnpBoundGenericType closed)
{
closed.OpenType = (CapnpNamedType)Visit(closed.OpenType);
if (closed.ParentScope != null)
closed.ParentScope = VisitClosedType(closed.ParentScope);
return closed;
}
protected internal virtual CapnpEnum VisitEnum(CapnpEnum @enum)
{
@enum.Annotations = @enum.Annotations.Select(a => VisitAnnotation(a)).ToArray();
@enum.Enumerants = @enum.Enumerants.Select(e => VisitEnumerant(e)).ToArray();
return @enum;
}
protected internal virtual Enumerant VisitEnumerant(Enumerant e)
{
e.Annotation = VisitAnnotation(e.Annotation);
return e;
}
protected internal virtual Field VisitField(Field fld)
{
fld.Type = Visit(fld.Type);
fld.Value = VisitValue(fld.Value);
fld.Annotation = VisitAnnotation(fld.Annotation);
return fld;
}
protected internal virtual Method VisitMethod(Method method)
{
if (method.Arguments.Params != null)
method.Arguments.Params = method.Arguments.Params.Select(p => VisitParameter(p)).ToArray();
else
method.Arguments.Struct = Visit(method.Arguments.Struct);
if (method.ReturnType.Params != null)
method.ReturnType.Params = method.ReturnType.Params.Select(p => VisitParameter(p)).ToArray();
else
method.ReturnType.Struct = Visit(method.ReturnType.Struct);
method.Annotation = VisitAnnotation(method.Annotation);
return method;
}
protected internal virtual Parameter VisitParameter(Parameter p)
{
p.Type = Visit(p.Type);
p.Annotation = VisitAnnotation(p.Annotation);
p.DefaultValue = VisitValue(p.DefaultValue);
return p;
}
protected internal virtual CapnpGroup VisitGroup(CapnpGroup grp)
{
grp.Fields = grp.Fields.Select(f => VisitField(f)).ToArray();
return grp;
}
protected internal virtual CapnpUnion VisitUnion(CapnpUnion union)
{
union.Fields = union.Fields.Select(u => VisitField(u)).ToArray();
return union;
}
protected internal virtual CapnpType VisitReference(CapnpReference @ref)
{
return @ref;
}
protected internal virtual CapnpConst VisitConst(CapnpConst @const)
{
@const.Value = VisitValue(@const.Value);
return @const;
}
protected internal virtual CapnpType VisitImport(CapnpImport import)
{
import.Type = Visit(import.Type);
return import;
}
protected internal virtual CapnpUsing VisitUsing(CapnpUsing @using)
{
@using.Target = Visit(@using.Target);
return @using;
}
protected internal virtual CapnpAnnotation VisitAnnotationDecl(CapnpAnnotation annotation)
{
annotation.ArgumentType = Visit(annotation.ArgumentType);
return annotation;
}
}
} | tempbottle/capnproto-net | CapnProto.net.Schema/Parser/CapnpVisitor.cs | C# | mit | 7,402 |
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("MultiMiner.Update")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MultiMiner.Update")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("d18592f7-b2be-41cb-9f51-a5d6bd6563c7")]
// 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("4.2.3.379")]
[assembly: AssemblyVersion("4.2.3.379")]
[assembly: AssemblyFileVersion("4.2.3.379")]
| nwoolls/MultiMiner | MultiMiner.Update/Properties/AssemblyInfo.cs | C# | mit | 1,454 |
package pipe.actions.gui;
import pipe.controllers.PetriNetController;
import pipe.controllers.PlaceController;
import uk.ac.imperial.pipe.models.petrinet.Connectable;
import uk.ac.imperial.pipe.models.petrinet.Place;
import java.awt.event.MouseEvent;
import java.util.Map;
/**
* Abstract action responsible for adding and deleting tokens to places
*/
public abstract class TokenAction extends CreateAction {
/**
*
* @param name image name
* @param tooltip tooltip message
* @param key keyboard shortcut
* @param modifiers keyboard accelerator
* @param applicationModel current PIPE application model
*/
public TokenAction(String name, String tooltip, int key, int modifiers, PipeApplicationModel applicationModel) {
super(name, tooltip, key, modifiers, applicationModel);
}
/**
* Noop action when a component has not been clicked on
* @param event mouse event
* @param petriNetController controller for the petri net
*/
@Override
public void doAction(MouseEvent event, PetriNetController petriNetController) {
// Do nothing unless clicked a connectable
}
/**
* Performs the subclass token action on the place
* @param connectable item clicked
* @param petriNetController controller for the petri net
*/
@Override
public void doConnectableAction(Connectable connectable, PetriNetController petriNetController) {
//TODO: Maybe a method, connectable.containsTokens() or visitor pattern
if (connectable instanceof Place) {
Place place = (Place) connectable;
String token = petriNetController.getSelectedToken();
performTokenAction(petriNetController.getPlaceController(place), token);
}
}
/**
* Subclasses should perform their relevant action on the token e.g. add/delete
*
* @param placeController
* @param token
*/
protected abstract void performTokenAction(PlaceController placeController, String token);
/**
* Sets the place to contain counts.
* <p/>
* Creates a new history edit
*
* @param placeController
* @param counts
*/
protected void setTokenCounts(PlaceController placeController, Map<String, Integer> counts) {
placeController.setTokenCounts(counts);
}
}
| frig-neutron/PIPE | pipe-gui/src/main/java/pipe/actions/gui/TokenAction.java | Java | mit | 2,378 |
var Type = require("@kaoscript/runtime").Type;
module.exports = function(expect) {
class Shape {
constructor() {
this.__ks_init();
this.__ks_cons(arguments);
}
__ks_init_0() {
this._color = "";
}
__ks_init() {
Shape.prototype.__ks_init_0.call(this);
}
__ks_cons_0(color) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(color === void 0 || color === null) {
throw new TypeError("'color' is not nullable");
}
else if(!Type.isString(color)) {
throw new TypeError("'color' is not of type 'String'");
}
this._color = color;
}
__ks_cons(args) {
if(args.length === 1) {
Shape.prototype.__ks_cons_0.apply(this, args);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
__ks_func_color_0() {
return this._color;
}
color() {
if(arguments.length === 0) {
return Shape.prototype.__ks_func_color_0.apply(this);
}
throw new SyntaxError("Wrong number of arguments");
}
__ks_func_draw_0() {
return "I'm drawing a " + this._color + " rectangle.";
}
draw() {
if(arguments.length === 0) {
return Shape.prototype.__ks_func_draw_0.apply(this);
}
throw new SyntaxError("Wrong number of arguments");
}
}
Shape.prototype.__ks_cons_1 = function() {
this._color = "red";
};
Shape.prototype.__ks_cons = function(args) {
if(args.length === 0) {
Shape.prototype.__ks_cons_1.apply(this);
}
else if(args.length === 1) {
Shape.prototype.__ks_cons_0.apply(this, args);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
let shape = new Shape();
expect(shape.draw()).to.equals("I'm drawing a red rectangle.");
}; | kaoscript/kaoscript | test/fixtures/compile/implement/implement.ctor.nseal.alias.js | JavaScript | mit | 1,741 |
module TasksFileMutations
AddFilesToTask = GraphQL::Relay::Mutation.define do
name 'AddFilesToTask'
input_field :id, !types.ID
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability'])
files = [ctx[:file]].flatten.reject{ |f| f.blank? }
if task.is_a?(Task) && !files.empty?
task.add_files(files)
end
{ task: task }
}
end
RemoveFilesFromTask = GraphQL::Relay::Mutation.define do
name 'RemoveFilesFromTask'
input_field :id, !types.ID
input_field :filenames, types[types.String]
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability'])
filenames = inputs['filenames']
if task.is_a?(Task) && !filenames.empty?
task.remove_files(filenames)
end
{ task: task }
}
end
end
| meedan/check-api | app/graph/mutations/tasks_file_mutations.rb | Ruby | mit | 972 |
package uk.co.nevarneyok.entities.product;
import com.google.gson.annotations.SerializedName;
public class ProductSize {
private long id;
@SerializedName("remote_id")
private long remoteId;
private String value;
public ProductSize() {
}
public ProductSize(long id, long remoteId, String value) {
this.id = id;
this.remoteId = remoteId;
this.value = value;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getRemoteId() {
return remoteId;
}
public void setRemoteId(long remoteId) {
this.remoteId = remoteId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductSize that = (ProductSize) o;
if (id != that.id) return false;
if (remoteId != that.remoteId) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (int) (remoteId ^ (remoteId >>> 32));
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ProductSize{" +
"id=" + id +
", remoteId=" + remoteId +
", value='" + value + '\'' +
'}';
}
}
| tugrulkarakaya/NeVarNeYok | app/src/main/java/uk/co/nevarneyok/entities/product/ProductSize.java | Java | mit | 1,689 |
# -*- coding: utf-8 -*-
"""
将json文件中的数据存到数据库中
"""
import requests
import json
import os
from word.models import (Word, EnDefinition, CnDefinition, Audio, Pronunciation, Example, Note)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)
def process_data(data):
data = data['data']['reviews']
print('len', len(data))
for item in data:
content = item['content']
print('uk_audio', item['uk_audio'])
print('us_audio', item['us_audio'])
obj = Word.objects.create(content=content)
if item['uk_audio']:
uk_audio_filepath = save_files('uk', item['content'], item['uk_audio'])
if item['us_audio']:
us_audio_filepath = save_files('us', item['content'], item['us_audio'])
if filepath is not None:
pass
Audio.objects.create(word=obj, us_audio=us_audio_filepath, uk_audio=uk_audio_filepath)
def save_files(tp, word, url):
filepath = '%s/media/audio/%stp/%s.mp3' % (BASE_DIR, tp, word)
with open(BASE_DIR + '/media/audio/'+ tp +'/'+word+'.mp3', 'wb') as handle:
response = requests.get(url, stream=True)
if response.ok:
# Something went wrong
for block in response.iter_content(1024):
handle.write(block)
return filepath
return None
def serialize_data(file_name):
"""
"""
with open(file_name, 'r') as f:
data = json.loads(f.read())
process_data(data)
# data = requests.get('', stream=True)
if __name__ == "__main__":
serialize_data("data1.json") | HideMode/ShanBay | data/script.py | Python | mit | 1,642 |
namespace Watcher.Messages.Person
{
public class PersonRequest
{
}
}
| ronaldme/Watcher | Watcher.Messages/Person/PersonRequest.cs | C# | mit | 84 |
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("GenericApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Medline Industries, Inc.")]
[assembly: AssemblyProduct("GenericApp")]
[assembly: AssemblyCopyright("Copyright © Medline Industries, Inc. 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("10196d63-1170-4124-9a14-48ebdefab06f")]
// 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")]
| jeffld/CSharp-Regex | GenericApp/GenericApp.Program/Properties/AssemblyInfo.cs | C# | mit | 1,480 |
<?php namespace System\Classes;
use App;
use Url;
use File;
use Lang;
use Event;
use Cache;
use Route;
use Config;
use Request;
use Response;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Assetic\Asset\AssetCache;
use Assetic\Asset\AssetCollection;
use Assetic\Factory\AssetFactory;
use October\Rain\Parse\Assetic\FilesystemCache;
use System\Helpers\Cache as CacheHelper;
use ApplicationException;
use DateTime;
/**
* Combiner class used for combining JavaScript and StyleSheet files.
*
* This works by taking a collection of asset locations, serializing them,
* then storing them in the session with a unique ID. The ID is then used
* to generate a URL to the `/combine` route via the system controller.
*
* When the combine route is hit, the unique ID is used to serve up the
* assets -- minified, compiled or both. Special E-Tags are used to prevent
* compilation and delivery of cached assets that are unchanged.
*
* Use the `CombineAssets::combine` method to combine your own assets.
*
* The functionality of this class is controlled by these config items:
*
* - cms.enableAssetCache - Cache untouched assets
* - cms.enableAssetMinify - Compress assets using minification
* - cms.enableAssetDeepHashing - Advanced caching of imports
*
* @see System\Classes\SystemController System controller
* @see https://octobercms.com/docs/services/session Session service
* @package october\system
* @author Alexey Bobkov, Samuel Georges
*/
class CombineAssets
{
use \October\Rain\Support\Traits\Singleton;
/**
* @var array A list of known JavaScript extensions.
*/
protected static $jsExtensions = ['js'];
/**
* @var array A list of known StyleSheet extensions.
*/
protected static $cssExtensions = ['css', 'less', 'scss', 'sass'];
/**
* @var array Aliases for asset file paths.
*/
protected $aliases = [];
/**
* @var array Bundles that are compiled to the filesystem.
*/
protected $bundles = [];
/**
* @var array Filters to apply to each file.
*/
protected $filters = [];
/**
* @var string The local path context to find assets.
*/
protected $localPath;
/**
* @var string The output folder for storing combined files.
*/
protected $storagePath;
/**
* @var bool Cache untouched files.
*/
public $useCache = false;
/**
* @var bool Compress (minify) asset files.
*/
public $useMinify = false;
/**
* @var bool When true, cache will be busted when an import is modified.
* Enabling this feature will make page loading slower.
*/
public $useDeepHashing = false;
/**
* @var array Cache of registration callbacks.
*/
private static $callbacks = [];
/**
* Constructor
*/
public function init()
{
/*
* Register preferences
*/
$this->useCache = Config::get('cms.enableAssetCache', false);
$this->useMinify = Config::get('cms.enableAssetMinify', null);
$this->useDeepHashing = Config::get('cms.enableAssetDeepHashing', null);
if ($this->useMinify === null) {
$this->useMinify = !Config::get('app.debug', false);
}
if ($this->useDeepHashing === null) {
$this->useDeepHashing = Config::get('app.debug', false);
}
/*
* Register JavaScript filters
*/
$this->registerFilter('js', new \October\Rain\Parse\Assetic\JavascriptImporter);
/*
* Register CSS filters
*/
$this->registerFilter('css', new \Assetic\Filter\CssImportFilter);
$this->registerFilter(['css', 'less', 'scss'], new \Assetic\Filter\CssRewriteFilter);
$this->registerFilter('less', new \October\Rain\Parse\Assetic\LessCompiler);
$this->registerFilter('scss', new \October\Rain\Parse\Assetic\ScssCompiler);
/*
* Minification filters
*/
if ($this->useMinify) {
$this->registerFilter('js', new \Assetic\Filter\JSMinFilter);
$this->registerFilter(['css', 'less', 'scss'], new \October\Rain\Parse\Assetic\StylesheetMinify);
}
/*
* Common Aliases
*/
$this->registerAlias('jquery', '~/modules/backend/assets/js/vendor/jquery.min.js');
$this->registerAlias('framework', '~/modules/system/assets/js/framework.js');
$this->registerAlias('framework.extras', '~/modules/system/assets/js/framework.extras.js');
$this->registerAlias('framework.extras', '~/modules/system/assets/css/framework.extras.css');
/*
* Deferred registration
*/
foreach (static::$callbacks as $callback) {
$callback($this);
}
}
/**
* Combines JavaScript or StyleSheet file references
* to produce a page relative URL to the combined contents.
*
* $assets = [
* 'assets/vendor/mustache/mustache.js',
* 'assets/js/vendor/jquery.ui.widget.js',
* 'assets/js/vendor/canvas-to-blob.js',
* ];
*
* CombineAssets::combine($assets, base_path('plugins/acme/blog'));
*
* @param array $assets Collection of assets
* @param string $localPath Prefix all assets with this path (optional)
* @return string URL to contents.
*/
public static function combine($assets = [], $localPath = null)
{
return self::instance()->prepareRequest($assets, $localPath);
}
/**
* Combines a collection of assets files to a destination file
*
* $assets = [
* 'assets/less/header.less',
* 'assets/less/footer.less',
* ];
*
* CombineAssets::combineToFile(
* $assets,
* base_path('themes/website/assets/theme.less'),
* base_path('themes/website')
* );
*
* @param array $assets Collection of assets
* @param string $destination Write the combined file to this location
* @param string $localPath Prefix all assets with this path (optional)
* @return void
*/
public function combineToFile($assets = [], $destination, $localPath = null)
{
// Disable cache always
$this->storagePath = null;
list($assets, $extension) = $this->prepareAssets($assets);
$rewritePath = File::localToPublic(dirname($destination));
$combiner = $this->prepareCombiner($assets, $rewritePath);
$contents = $combiner->dump();
File::put($destination, $contents);
}
/**
* Returns the combined contents from a prepared cache identifier.
* @param string $cacheKey Cache identifier.
* @return string Combined file contents.
*/
public function getContents($cacheKey)
{
$cacheInfo = $this->getCache($cacheKey);
if (!$cacheInfo) {
throw new ApplicationException(Lang::get('system::lang.combiner.not_found', ['name'=>$cacheKey]));
}
$this->localPath = $cacheInfo['path'];
$this->storagePath = storage_path('cms/combiner/assets');
/*
* Analyse cache information
*/
$lastModifiedTime = gmdate("D, d M Y H:i:s \G\M\T", array_get($cacheInfo, 'lastMod'));
$etag = array_get($cacheInfo, 'etag');
$mime = (array_get($cacheInfo, 'extension') == 'css')
? 'text/css'
: 'application/javascript';
/*
* Set 304 Not Modified header, if necessary
*/
header_remove();
$response = Response::make();
$response->header('Content-Type', $mime);
$response->header('Cache-Control', 'private, max-age=604800');
$response->setLastModified(new DateTime($lastModifiedTime));
$response->setEtag($etag);
$response->setPublic();
$modified = !$response->isNotModified(App::make('request'));
/*
* Request says response is cached, no code evaluation needed
*/
if ($modified) {
$this->setHashOnCombinerFilters($cacheKey);
$combiner = $this->prepareCombiner($cacheInfo['files']);
$contents = $combiner->dump();
$response->setContent($contents);
}
return $response;
}
/**
* Prepares an array of assets by normalizing the collection
* and processing aliases.
* @param array $assets
* @return array
*/
protected function prepareAssets(array $assets)
{
if (!is_array($assets)) {
$assets = [$assets];
}
/*
* Split assets in to groups.
*/
$combineJs = [];
$combineCss = [];
foreach ($assets as $asset) {
/*
* Allow aliases to go through without an extension
*/
if (substr($asset, 0, 1) == '@') {
$combineJs[] = $asset;
$combineCss[] = $asset;
continue;
}
$extension = File::extension($asset);
if (in_array($extension, self::$jsExtensions)) {
$combineJs[] = $asset;
continue;
}
if (in_array($extension, self::$cssExtensions)) {
$combineCss[] = $asset;
continue;
}
}
/*
* Determine which group of assets to combine.
*/
if (count($combineCss) > count($combineJs)) {
$extension = 'css';
$assets = $combineCss;
}
else {
$extension = 'js';
$assets = $combineJs;
}
/*
* Apply registered aliases
*/
if ($aliasMap = $this->getAliases($extension)) {
foreach ($assets as $key => $asset) {
if (substr($asset, 0, 1) !== '@') {
continue;
}
$_asset = substr($asset, 1);
if (isset($aliasMap[$_asset])) {
$assets[$key] = $aliasMap[$_asset];
}
}
}
return [$assets, $extension];
}
/**
* Combines asset file references of a single type to produce
* a URL reference to the combined contents.
* @param array $assets List of asset files.
* @param string $localPath File extension, used for aesthetic purposes only.
* @return string URL to contents.
*/
protected function prepareRequest(array $assets, $localPath = null)
{
if (substr($localPath, -1) != '/') {
$localPath = $localPath.'/';
}
$this->localPath = $localPath;
$this->storagePath = storage_path('cms/combiner/assets');
list($assets, $extension) = $this->prepareAssets($assets);
/*
* Cache and process
*/
$cacheKey = $this->getCacheKey($assets);
$cacheInfo = $this->useCache ? $this->getCache($cacheKey) : false;
if (!$cacheInfo) {
$this->setHashOnCombinerFilters($cacheKey);
$combiner = $this->prepareCombiner($assets);
if ($this->useDeepHashing) {
$factory = new AssetFactory($this->localPath);
$lastMod = $factory->getLastModified($combiner);
}
else {
$lastMod = $combiner->getLastModified();
}
$cacheInfo = [
'version' => $cacheKey.'-'.$lastMod,
'etag' => $cacheKey,
'lastMod' => $lastMod,
'files' => $assets,
'path' => $this->localPath,
'extension' => $extension
];
$this->putCache($cacheKey, $cacheInfo);
}
return $this->getCombinedUrl($cacheInfo['version']);
}
/**
* Returns the combined contents from a prepared cache identifier.
* @param array $assets List of asset files.
* @param string $rewritePath
* @return string Combined file contents.
*/
protected function prepareCombiner(array $assets, $rewritePath = null)
{
/*
* Extensibility
*/
Event::fire('cms.combiner.beforePrepare', [$this, $assets]);
$files = [];
$filesSalt = null;
foreach ($assets as $asset) {
$filters = $this->getFilters(File::extension($asset)) ?: [];
$path = file_exists($asset) ? $asset : File::symbolizePath($asset, null) ?: $this->localPath . $asset;
$files[] = new FileAsset($path, $filters, public_path());
$filesSalt .= $this->localPath . $asset;
}
$filesSalt = md5($filesSalt);
$collection = new AssetCollection($files, [], $filesSalt);
$collection->setTargetPath($this->getTargetPath($rewritePath));
if ($this->storagePath === null) {
return $collection;
}
if (!File::isDirectory($this->storagePath)) {
@File::makeDirectory($this->storagePath);
}
$cache = new FilesystemCache($this->storagePath);
$cachedFiles = [];
foreach ($files as $file) {
$cachedFiles[] = new AssetCache($file, $cache);
}
$cachedCollection = new AssetCollection($cachedFiles, [], $filesSalt);
$cachedCollection->setTargetPath($this->getTargetPath($rewritePath));
return $cachedCollection;
}
/**
* Busts the cache based on a different cache key.
* @return void
*/
protected function setHashOnCombinerFilters($hash)
{
$allFilters = call_user_func_array('array_merge', $this->getFilters());
foreach ($allFilters as $filter) {
if (method_exists($filter, 'setHash')) {
$filter->setHash($hash);
}
}
}
/**
* Returns a deep hash on filters that support it.
* @param array $assets List of asset files.
* @return void
*/
protected function getDeepHashFromAssets($assets)
{
$key = '';
$assetFiles = array_map(function ($file) {
return file_exists($file) ? $file : File::symbolizePath($file, null) ?: $this->localPath . $file;
}, $assets);
foreach ($assetFiles as $file) {
$filters = $this->getFilters(File::extension($file));
foreach ($filters as $filter) {
if (method_exists($filter, 'hashAsset')) {
$key .= $filter->hashAsset($file, $this->localPath);
}
}
}
return $key;
}
/**
* Returns the URL used for accessing the combined files.
* @param string $outputFilename A custom file name to use.
* @return string
*/
protected function getCombinedUrl($outputFilename = 'undefined.css')
{
$combineAction = 'System\Classes\Controller@combine';
$actionExists = Route::getRoutes()->getByAction($combineAction) !== null;
if ($actionExists) {
return Url::action($combineAction, [$outputFilename], false);
}
else {
return '/combine/'.$outputFilename;
}
}
/**
* Returns the target path for use with the combiner. The target
* path helps generate relative links within CSS.
*
* /combine returns combine/
* /index.php/combine returns index-php/combine/
*
* @param string|null $path
* @return string The new target path
*/
protected function getTargetPath($path = null)
{
if ($path === null) {
$baseUri = substr(Request::getBaseUrl(), strlen(Request::getBasePath()));
$path = $baseUri.'/combine';
}
if (strpos($path, '/') === 0) {
$path = substr($path, 1);
}
$path = str_replace('.', '-', $path).'/';
return $path;
}
//
// Registration
//
/**
* Registers a callback function that defines bundles.
* The callback function should register bundles by calling the manager's
* `registerBundle` method. This instance is passed to the callback
* function as an argument. Usage:
*
* CombineAssets::registerCallback(function($combiner){
* $combiner->registerBundle('~/modules/backend/assets/less/october.less');
* });
*
* @param callable $callback A callable function.
*/
public static function registerCallback(callable $callback)
{
self::$callbacks[] = $callback;
}
//
// Filters
//
/**
* Register a filter to apply to the combining process.
* @param string|array $extension Extension name. Eg: css
* @param object $filter Collection of files to combine.
* @return self
*/
public function registerFilter($extension, $filter)
{
if (is_array($extension)) {
foreach ($extension as $_extension) {
$this->registerFilter($_extension, $filter);
}
return;
}
$extension = strtolower($extension);
if (!isset($this->filters[$extension])) {
$this->filters[$extension] = [];
}
if ($filter !== null) {
$this->filters[$extension][] = $filter;
}
return $this;
}
/**
* Clears any registered filters.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function resetFilters($extension = null)
{
if ($extension === null) {
$this->filters = [];
}
else {
$this->filters[$extension] = [];
}
return $this;
}
/**
* Returns filters.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getFilters($extension = null)
{
if ($extension === null) {
return $this->filters;
}
elseif (isset($this->filters[$extension])) {
return $this->filters[$extension];
}
else {
return null;
}
}
//
// Bundles
//
/**
* Registers bundle.
* @param string|array $files Files to be registered to bundle
* @param string $destination Destination file will be compiled to.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function registerBundle($files, $destination = null, $extension = null)
{
if (!is_array($files)) {
$files = [$files];
}
$firstFile = array_values($files)[0];
if ($extension === null) {
$extension = File::extension($firstFile);
}
$extension = strtolower(trim($extension));
if ($destination === null) {
$file = File::name($firstFile);
$path = dirname($firstFile);
$preprocessors = array_except(self::$cssExtensions, 'css');
if (in_array($extension, $preprocessors)) {
$cssPath = $path.'/../css';
if (
in_array(strtolower(basename($path)), $preprocessors) &&
File::isDirectory(File::symbolizePath($cssPath))
) {
$path = $cssPath;
}
$destination = $path.'/'.$file.'.css';
}
else {
$destination = $path.'/'.$file.'-min.'.$extension;
}
}
$this->bundles[$extension][$destination] = $files;
return $this;
}
/**
* Returns bundles.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getBundles($extension = null)
{
if ($extension === null) {
return $this->bundles;
}
elseif (isset($this->bundles[$extension])) {
return $this->bundles[$extension];
}
else {
return null;
}
}
//
// Aliases
//
/**
* Register an alias to use for a longer file reference.
* @param string $alias Alias name. Eg: framework
* @param string $file Path to file to use for alias
* @param string $extension Extension name. Eg: css
* @return self
*/
public function registerAlias($alias, $file, $extension = null)
{
if ($extension === null) {
$extension = File::extension($file);
}
$extension = strtolower($extension);
if (!isset($this->aliases[$extension])) {
$this->aliases[$extension] = [];
}
$this->aliases[$extension][$alias] = $file;
return $this;
}
/**
* Clears any registered aliases.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function resetAliases($extension = null)
{
if ($extension === null) {
$this->aliases = [];
}
else {
$this->aliases[$extension] = [];
}
return $this;
}
/**
* Returns aliases.
* @param string $extension Extension name. Eg: css
* @return self
*/
public function getAliases($extension = null)
{
if ($extension === null) {
return $this->aliases;
}
elseif (isset($this->aliases[$extension])) {
return $this->aliases[$extension];
}
else {
return null;
}
}
//
// Cache
//
/**
* Stores information about a asset collection against
* a cache identifier.
* @param string $cacheKey Cache identifier.
* @param array $cacheInfo List of asset files.
* @return bool Successful
*/
protected function putCache($cacheKey, array $cacheInfo)
{
$cacheKey = 'combiner.'.$cacheKey;
if (Cache::has($cacheKey)) {
return false;
}
$this->putCacheIndex($cacheKey);
Cache::forever($cacheKey, base64_encode(serialize($cacheInfo)));
return true;
}
/**
* Look up information about a cache identifier.
* @param string $cacheKey Cache identifier
* @return array Cache information
*/
protected function getCache($cacheKey)
{
$cacheKey = 'combiner.'.$cacheKey;
if (!Cache::has($cacheKey)) {
return false;
}
return @unserialize(@base64_decode(Cache::get($cacheKey)));
}
/**
* Builds a unique string based on assets
* @param array $assets Asset files
* @return string Unique identifier
*/
protected function getCacheKey(array $assets)
{
$cacheKey = $this->localPath . implode('|', $assets);
/*
* Deep hashing
*/
if ($this->useDeepHashing) {
$cacheKey .= $this->getDeepHashFromAssets($assets);
}
/*
* Extensibility
*/
$dataHolder = (object) ['key' => $cacheKey];
Event::fire('cms.combiner.getCacheKey', [$this, $dataHolder]);
$cacheKey = $dataHolder->key;
return md5($cacheKey);
}
/**
* Resets the combiner cache
* @return void
*/
public static function resetCache()
{
if (Cache::has('combiner.index')) {
$index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: [];
foreach ($index as $cacheKey) {
Cache::forget($cacheKey);
}
Cache::forget('combiner.index');
}
CacheHelper::instance()->clearCombiner();
}
/**
* Adds a cache identifier to the index store used for
* performing a reset of the cache.
* @param string $cacheKey Cache identifier
* @return bool Returns false if identifier is already in store
*/
protected function putCacheIndex($cacheKey)
{
$index = [];
if (Cache::has('combiner.index')) {
$index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: [];
}
if (in_array($cacheKey, $index)) {
return false;
}
$index[] = $cacheKey;
Cache::forever('combiner.index', base64_encode(serialize($index)));
return true;
}
}
| lupin72/piergorelli.com | modules/system/classes/CombineAssets.php | PHP | mit | 24,315 |
<?php
/**
* SimplePie
*
* A PHP-Based RSS and Atom Feed Framework.
* Takes the hard work out of managing a complete RSS/Atom solution.
*
* Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the SimplePie Team nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
* AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package SimplePie
* @version 1.3.2-dev
* @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue
* @author Ryan Parman
* @author Geoffrey Sneddon
* @author Ryan McCue
* @link http://simplepie.org/ SimplePie
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
/**
* SimplePie Name
*/
define('SIMPLEPIE_NAME', 'SimplePie');
/**
* SimplePie Version
*/
define('SIMPLEPIE_VERSION', '1.3.2-dev');
/**
* SimplePie Build
* @todo Hardcode for release (there's no need to have to call SimplePie_Misc::get_build() only every load of simplepie.inc)
*/
define('SIMPLEPIE_BUILD', gmdate('YmdHis', SimplePie_Misc::get_build()));
/**
* SimplePie Website URL
*/
define('SIMPLEPIE_URL', 'http://simplepie.org');
/**
* SimplePie Useragent
* @see SimplePie::set_useragent()
*/
define('SIMPLEPIE_USERAGENT', SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION . ' (Feed Parser; ' . SIMPLEPIE_URL . '; Allow like Gecko) Build/' . SIMPLEPIE_BUILD);
/**
* SimplePie Linkback
*/
define('SIMPLEPIE_LINKBACK', '<a href="' . SIMPLEPIE_URL . '" title="' . SIMPLEPIE_NAME . ' ' . SIMPLEPIE_VERSION . '">' . SIMPLEPIE_NAME . '</a>');
/**
* No Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_NONE', 0);
/**
* Feed Link Element Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_AUTODISCOVERY', 1);
/**
* Local Feed Extension Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_LOCAL_EXTENSION', 2);
/**
* Local Feed Body Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_LOCAL_BODY', 4);
/**
* Remote Feed Extension Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_REMOTE_EXTENSION', 8);
/**
* Remote Feed Body Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_REMOTE_BODY', 16);
/**
* All Feed Autodiscovery
* @see SimplePie::set_autodiscovery_level()
*/
define('SIMPLEPIE_LOCATOR_ALL', 31);
/**
* No known feed type
*/
define('SIMPLEPIE_TYPE_NONE', 0);
/**
* RSS 0.90
*/
define('SIMPLEPIE_TYPE_RSS_090', 1);
/**
* RSS 0.91 (Netscape)
*/
define('SIMPLEPIE_TYPE_RSS_091_NETSCAPE', 2);
/**
* RSS 0.91 (Userland)
*/
define('SIMPLEPIE_TYPE_RSS_091_USERLAND', 4);
/**
* RSS 0.91 (both Netscape and Userland)
*/
define('SIMPLEPIE_TYPE_RSS_091', 6);
/**
* RSS 0.92
*/
define('SIMPLEPIE_TYPE_RSS_092', 8);
/**
* RSS 0.93
*/
define('SIMPLEPIE_TYPE_RSS_093', 16);
/**
* RSS 0.94
*/
define('SIMPLEPIE_TYPE_RSS_094', 32);
/**
* RSS 1.0
*/
define('SIMPLEPIE_TYPE_RSS_10', 64);
/**
* RSS 2.0
*/
define('SIMPLEPIE_TYPE_RSS_20', 128);
/**
* RDF-based RSS
*/
define('SIMPLEPIE_TYPE_RSS_RDF', 65);
/**
* Non-RDF-based RSS (truly intended as syndication format)
*/
define('SIMPLEPIE_TYPE_RSS_SYNDICATION', 190);
/**
* All RSS
*/
define('SIMPLEPIE_TYPE_RSS_ALL', 255);
/**
* Atom 0.3
*/
define('SIMPLEPIE_TYPE_ATOM_03', 256);
/**
* Atom 1.0
*/
define('SIMPLEPIE_TYPE_ATOM_10', 512);
/**
* All Atom
*/
define('SIMPLEPIE_TYPE_ATOM_ALL', 768);
/**
* All feed types
*/
define('SIMPLEPIE_TYPE_ALL', 1023);
/**
* No construct
*/
define('SIMPLEPIE_CONSTRUCT_NONE', 0);
/**
* Text construct
*/
define('SIMPLEPIE_CONSTRUCT_TEXT', 1);
/**
* HTML construct
*/
define('SIMPLEPIE_CONSTRUCT_HTML', 2);
/**
* XHTML construct
*/
define('SIMPLEPIE_CONSTRUCT_XHTML', 4);
/**
* base64-encoded construct
*/
define('SIMPLEPIE_CONSTRUCT_BASE64', 8);
/**
* IRI construct
*/
define('SIMPLEPIE_CONSTRUCT_IRI', 16);
/**
* A construct that might be HTML
*/
define('SIMPLEPIE_CONSTRUCT_MAYBE_HTML', 32);
/**
* All constructs
*/
define('SIMPLEPIE_CONSTRUCT_ALL', 63);
/**
* Don't change case
*/
define('SIMPLEPIE_SAME_CASE', 1);
/**
* Change to lowercase
*/
define('SIMPLEPIE_LOWERCASE', 2);
/**
* Change to uppercase
*/
define('SIMPLEPIE_UPPERCASE', 4);
/**
* PCRE for HTML attributes
*/
define('SIMPLEPIE_PCRE_HTML_ATTRIBUTE', '((?:[\x09\x0A\x0B\x0C\x0D\x20]+[^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"(?:[^"]*)"|\'(?:[^\']*)\'|(?:[^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?)*)[\x09\x0A\x0B\x0C\x0D\x20]*');
/**
* PCRE for XML attributes
*/
define('SIMPLEPIE_PCRE_XML_ATTRIBUTE', '((?:\s+(?:(?:[^\s:]+:)?[^\s:]+)\s*=\s*(?:"(?:[^"]*)"|\'(?:[^\']*)\'))*)\s*');
/**
* XML Namespace
*/
define('SIMPLEPIE_NAMESPACE_XML', 'http://www.w3.org/XML/1998/namespace');
/**
* Atom 1.0 Namespace
*/
define('SIMPLEPIE_NAMESPACE_ATOM_10', 'http://www.w3.org/2005/Atom');
/**
* Atom 0.3 Namespace
*/
define('SIMPLEPIE_NAMESPACE_ATOM_03', 'http://purl.org/atom/ns#');
/**
* RDF Namespace
*/
define('SIMPLEPIE_NAMESPACE_RDF', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
/**
* RSS 0.90 Namespace
*/
define('SIMPLEPIE_NAMESPACE_RSS_090', 'http://my.netscape.com/rdf/simple/0.9/');
/**
* RSS 1.0 Namespace
*/
define('SIMPLEPIE_NAMESPACE_RSS_10', 'http://purl.org/rss/1.0/');
/**
* RSS 1.0 Content Module Namespace
*/
define('SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT', 'http://purl.org/rss/1.0/modules/content/');
/**
* RSS 2.0 Namespace
* (Stupid, I know, but I'm certain it will confuse people less with support.)
*/
define('SIMPLEPIE_NAMESPACE_RSS_20', '');
/**
* DC 1.0 Namespace
*/
define('SIMPLEPIE_NAMESPACE_DC_10', 'http://purl.org/dc/elements/1.0/');
/**
* DC 1.1 Namespace
*/
define('SIMPLEPIE_NAMESPACE_DC_11', 'http://purl.org/dc/elements/1.1/');
/**
* W3C Basic Geo (WGS84 lat/long) Vocabulary Namespace
*/
define('SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO', 'http://www.w3.org/2003/01/geo/wgs84_pos#');
/**
* GeoRSS Namespace
*/
define('SIMPLEPIE_NAMESPACE_GEORSS', 'http://www.georss.org/georss');
/**
* Media RSS Namespace
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS', 'http://search.yahoo.com/mrss/');
/**
* Wrong Media RSS Namespace. Caused by a long-standing typo in the spec.
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG', 'http://search.yahoo.com/mrss');
/**
* Wrong Media RSS Namespace #2. New namespace introduced in Media RSS 1.5.
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG2', 'http://video.search.yahoo.com/mrss');
/**
* Wrong Media RSS Namespace #3. A possible typo of the Media RSS 1.5 namespace.
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG3', 'http://video.search.yahoo.com/mrss/');
/**
* Wrong Media RSS Namespace #4. New spec location after the RSS Advisory Board takes it over, but not a valid namespace.
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG4', 'http://www.rssboard.org/media-rss');
/**
* Wrong Media RSS Namespace #5. A possible typo of the RSS Advisory Board URL.
*/
define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG5', 'http://www.rssboard.org/media-rss/');
/**
* iTunes RSS Namespace
*/
define('SIMPLEPIE_NAMESPACE_ITUNES', 'http://www.itunes.com/dtds/podcast-1.0.dtd');
/**
* XHTML Namespace
*/
define('SIMPLEPIE_NAMESPACE_XHTML', 'http://www.w3.org/1999/xhtml');
/**
* IANA Link Relations Registry
*/
define('SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY', 'http://www.iana.org/assignments/relation/');
/**
* No file source
*/
define('SIMPLEPIE_FILE_SOURCE_NONE', 0);
/**
* Remote file source
*/
define('SIMPLEPIE_FILE_SOURCE_REMOTE', 1);
/**
* Local file source
*/
define('SIMPLEPIE_FILE_SOURCE_LOCAL', 2);
/**
* fsockopen() file source
*/
define('SIMPLEPIE_FILE_SOURCE_FSOCKOPEN', 4);
/**
* cURL file source
*/
define('SIMPLEPIE_FILE_SOURCE_CURL', 8);
/**
* file_get_contents() file source
*/
define('SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS', 16);
/**
* SimplePie
*
* @package SimplePie
* @subpackage API
*/
class SimplePie
{
/**
* @var array Raw data
* @access private
*/
public $data = array();
/**
* @var mixed Error string
* @access private
*/
public $error;
/**
* @var object Instance of SimplePie_Sanitize (or other class)
* @see SimplePie::set_sanitize_class()
* @access private
*/
public $sanitize;
/**
* @var string SimplePie Useragent
* @see SimplePie::set_useragent()
* @access private
*/
public $useragent = SIMPLEPIE_USERAGENT;
/**
* @var string Feed URL
* @see SimplePie::set_feed_url()
* @access private
*/
public $feed_url;
/**
* @var object Instance of SimplePie_File to use as a feed
* @see SimplePie::set_file()
* @access private
*/
public $file;
/**
* @var string Raw feed data
* @see SimplePie::set_raw_data()
* @access private
*/
public $raw_data;
/**
* @var int Timeout for fetching remote files
* @see SimplePie::set_timeout()
* @access private
*/
public $timeout = 10;
/**
* @var bool Forces fsockopen() to be used for remote files instead
* of cURL, even if a new enough version is installed
* @see SimplePie::force_fsockopen()
* @access private
*/
public $force_fsockopen = false;
/**
* @var bool Force the given data/URL to be treated as a feed no matter what
* it appears like
* @see SimplePie::force_feed()
* @access private
*/
public $force_feed = false;
/**
* @var bool Enable/Disable Caching
* @see SimplePie::enable_cache()
* @access private
*/
public $cache = true;
/**
* @var int Cache duration (in seconds)
* @see SimplePie::set_cache_duration()
* @access private
*/
public $cache_duration = 3600;
/**
* @var int Auto-discovery cache duration (in seconds)
* @see SimplePie::set_autodiscovery_cache_duration()
* @access private
*/
public $autodiscovery_cache_duration = 604800; // 7 Days.
/**
* @var string Cache location (relative to executing script)
* @see SimplePie::set_cache_location()
* @access private
*/
public $cache_location = './cache';
/**
* @var string Function that creates the cache filename
* @see SimplePie::set_cache_name_function()
* @access private
*/
public $cache_name_function = 'md5';
/**
* @var bool Reorder feed by date descending
* @see SimplePie::enable_order_by_date()
* @access private
*/
public $order_by_date = true;
/**
* @var mixed Force input encoding to be set to the follow value
* (false, or anything type-cast to false, disables this feature)
* @see SimplePie::set_input_encoding()
* @access private
*/
public $input_encoding = false;
/**
* @var int Feed Autodiscovery Level
* @see SimplePie::set_autodiscovery_level()
* @access private
*/
public $autodiscovery = SIMPLEPIE_LOCATOR_ALL;
/**
* Class registry object
*
* @var SimplePie_Registry
*/
public $registry;
/**
* @var int Maximum number of feeds to check with autodiscovery
* @see SimplePie::set_max_checked_feeds()
* @access private
*/
public $max_checked_feeds = 10;
/**
* @var array All the feeds found during the autodiscovery process
* @see SimplePie::get_all_discovered_feeds()
* @access private
*/
public $all_discovered_feeds = array();
/**
* @var string Web-accessible path to the handler_image.php file.
* @see SimplePie::set_image_handler()
* @access private
*/
public $image_handler = '';
/**
* @var array Stores the URLs when multiple feeds are being initialized.
* @see SimplePie::set_feed_url()
* @access private
*/
public $multifeed_url = array();
/**
* @var array Stores SimplePie objects when multiple feeds initialized.
* @access private
*/
public $multifeed_objects = array();
/**
* @var array Stores the get_object_vars() array for use with multifeeds.
* @see SimplePie::set_feed_url()
* @access private
*/
public $config_settings = null;
/**
* @var integer Stores the number of items to return per-feed with multifeeds.
* @see SimplePie::set_item_limit()
* @access private
*/
public $item_limit = 0;
/**
* @var array Stores the default attributes to be stripped by strip_attributes().
* @see SimplePie::strip_attributes()
* @access private
*/
public $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc');
/**
* @var array Stores the default tags to be stripped by strip_htmltags().
* @see SimplePie::strip_htmltags()
* @access private
*/
public $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style');
/**
* The SimplePie class contains feed level data and options
*
* To use SimplePie, create the SimplePie object with no parameters. You can
* then set configuration options using the provided methods. After setting
* them, you must initialise the feed using $feed->init(). At that point the
* object's methods and properties will be available to you.
*
* Previously, it was possible to pass in the feed URL along with cache
* options directly into the constructor. This has been removed as of 1.3 as
* it caused a lot of confusion.
*
* @since 1.0 Preview Release
*/
public function __construct()
{
if (version_compare(PHP_VERSION, '5.2', '<'))
{
trigger_error('PHP 4.x, 5.0 and 5.1 are no longer supported. Please upgrade to PHP 5.2 or newer.');
die();
}
// Other objects, instances created here so we can set options on them
$this->sanitize = new SimplePie_Sanitize();
$this->registry = new SimplePie_Registry();
if (func_num_args() > 0)
{
$level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING;
trigger_error('Passing parameters to the constructor is no longer supported. Please use set_feed_url(), set_cache_location(), and set_cache_location() directly.', $level);
$args = func_get_args();
switch (count($args)) {
case 3:
$this->set_cache_duration($args[2]);
case 2:
$this->set_cache_location($args[1]);
case 1:
$this->set_feed_url($args[0]);
$this->init();
}
}
}
/**
* Used for converting object to a string
*/
public function __toString()
{
return md5(serialize($this->data));
}
/**
* Remove items that link back to this before destroying this object
*/
public function __destruct()
{
if ((version_compare(PHP_VERSION, '5.3', '<') || !gc_enabled()) && !ini_get('zend.ze1_compatibility_mode'))
{
if (!empty($this->data['items']))
{
foreach ($this->data['items'] as $item)
{
$item->__destruct();
}
unset($item, $this->data['items']);
}
if (!empty($this->data['ordered_items']))
{
foreach ($this->data['ordered_items'] as $item)
{
$item->__destruct();
}
unset($item, $this->data['ordered_items']);
}
}
}
/**
* Force the given data/URL to be treated as a feed
*
* This tells SimplePie to ignore the content-type provided by the server.
* Be careful when using this option, as it will also disable autodiscovery.
*
* @since 1.1
* @param bool $enable Force the given data/URL to be treated as a feed
*/
public function force_feed($enable = false)
{
$this->force_feed = (bool) $enable;
}
/**
* Set the URL of the feed you want to parse
*
* This allows you to enter the URL of the feed you want to parse, or the
* website you want to try to use auto-discovery on. This takes priority
* over any set raw data.
*
* You can set multiple feeds to mash together by passing an array instead
* of a string for the $url. Remember that with each additional feed comes
* additional processing and resources.
*
* @since 1.0 Preview Release
* @see set_raw_data()
* @param string|array $url This is the URL (or array of URLs) that you want to parse.
*/
public function set_feed_url($url)
{
$this->multifeed_url = array();
if (is_array($url))
{
foreach ($url as $value)
{
$this->multifeed_url[] = $this->registry->call('Misc', 'fix_protocol', array($value, 1));
}
}
else
{
$this->feed_url = $this->registry->call('Misc', 'fix_protocol', array($url, 1));
}
}
/**
* Set an instance of {@see SimplePie_File} to use as a feed
*
* @param SimplePie_File &$file
* @return bool True on success, false on failure
*/
public function set_file(&$file)
{
if ($file instanceof SimplePie_File)
{
$this->feed_url = $file->url;
$this->file =& $file;
return true;
}
return false;
}
/**
* Set the raw XML data to parse
*
* Allows you to use a string of RSS/Atom data instead of a remote feed.
*
* If you have a feed available as a string in PHP, you can tell SimplePie
* to parse that data string instead of a remote feed. Any set feed URL
* takes precedence.
*
* @since 1.0 Beta 3
* @param string $data RSS or Atom data as a string.
* @see set_feed_url()
*/
public function set_raw_data($data)
{
$this->raw_data = $data;
}
/**
* Set the the default timeout for fetching remote feeds
*
* This allows you to change the maximum time the feed's server to respond
* and send the feed back.
*
* @since 1.0 Beta 3
* @param int $timeout The maximum number of seconds to spend waiting to retrieve a feed.
*/
public function set_timeout($timeout = 10)
{
$this->timeout = (int) $timeout;
}
/**
* Force SimplePie to use fsockopen() instead of cURL
*
* @since 1.0 Beta 3
* @param bool $enable Force fsockopen() to be used
*/
public function force_fsockopen($enable = false)
{
$this->force_fsockopen = (bool) $enable;
}
/**
* Enable/disable caching in SimplePie.
*
* This option allows you to disable caching all-together in SimplePie.
* However, disabling the cache can lead to longer load times.
*
* @since 1.0 Preview Release
* @param bool $enable Enable caching
*/
public function enable_cache($enable = true)
{
$this->cache = (bool) $enable;
}
/**
* Set the length of time (in seconds) that the contents of a feed will be
* cached
*
* @param int $seconds The feed content cache duration
*/
public function set_cache_duration($seconds = 3600)
{
$this->cache_duration = (int) $seconds;
}
/**
* Set the length of time (in seconds) that the autodiscovered feed URL will
* be cached
*
* @param int $seconds The autodiscovered feed URL cache duration.
*/
public function set_autodiscovery_cache_duration($seconds = 604800)
{
$this->autodiscovery_cache_duration = (int) $seconds;
}
/**
* Set the file system location where the cached files should be stored
*
* @param string $location The file system location.
*/
public function set_cache_location($location = './cache')
{
$this->cache_location = (string) $location;
}
/**
* Set whether feed items should be sorted into reverse chronological order
*
* @param bool $enable Sort as reverse chronological order.
*/
public function enable_order_by_date($enable = true)
{
$this->order_by_date = (bool) $enable;
}
/**
* Set the character encoding used to parse the feed
*
* This overrides the encoding reported by the feed, however it will fall
* back to the normal encoding detection if the override fails
*
* @param string $encoding Character encoding
*/
public function set_input_encoding($encoding = false)
{
if ($encoding)
{
$this->input_encoding = (string) $encoding;
}
else
{
$this->input_encoding = false;
}
}
/**
* Set how much feed autodiscovery to do
*
* @see SIMPLEPIE_LOCATOR_NONE
* @see SIMPLEPIE_LOCATOR_AUTODISCOVERY
* @see SIMPLEPIE_LOCATOR_LOCAL_EXTENSION
* @see SIMPLEPIE_LOCATOR_LOCAL_BODY
* @see SIMPLEPIE_LOCATOR_REMOTE_EXTENSION
* @see SIMPLEPIE_LOCATOR_REMOTE_BODY
* @see SIMPLEPIE_LOCATOR_ALL
* @param int $level Feed Autodiscovery Level (level can be a combination of the above constants, see bitwise OR operator)
*/
public function set_autodiscovery_level($level = SIMPLEPIE_LOCATOR_ALL)
{
$this->autodiscovery = (int) $level;
}
/**
* Get the class registry
*
* Use this to override SimplePie's default classes
* @see SimplePie_Registry
* @return SimplePie_Registry
*/
public function &get_registry()
{
return $this->registry;
}
/**#@+
* Useful when you are overloading or extending SimplePie's default classes.
*
* @deprecated Use {@see get_registry()} instead
* @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation
* @param string $class Name of custom class
* @return boolean True on success, false otherwise
*/
/**
* Set which class SimplePie uses for caching
*/
public function set_cache_class($class = 'SimplePie_Cache')
{
return $this->registry->register('Cache', $class, true);
}
/**
* Set which class SimplePie uses for auto-discovery
*/
public function set_locator_class($class = 'SimplePie_Locator')
{
return $this->registry->register('Locator', $class, true);
}
/**
* Set which class SimplePie uses for XML parsing
*/
public function set_parser_class($class = 'SimplePie_Parser')
{
return $this->registry->register('Parser', $class, true);
}
/**
* Set which class SimplePie uses for remote file fetching
*/
public function set_file_class($class = 'SimplePie_File')
{
return $this->registry->register('File', $class, true);
}
/**
* Set which class SimplePie uses for data sanitization
*/
public function set_sanitize_class($class = 'SimplePie_Sanitize')
{
return $this->registry->register('Sanitize', $class, true);
}
/**
* Set which class SimplePie uses for handling feed items
*/
public function set_item_class($class = 'SimplePie_Item')
{
return $this->registry->register('Item', $class, true);
}
/**
* Set which class SimplePie uses for handling author data
*/
public function set_author_class($class = 'SimplePie_Author')
{
return $this->registry->register('Author', $class, true);
}
/**
* Set which class SimplePie uses for handling category data
*/
public function set_category_class($class = 'SimplePie_Category')
{
return $this->registry->register('Category', $class, true);
}
/**
* Set which class SimplePie uses for feed enclosures
*/
public function set_enclosure_class($class = 'SimplePie_Enclosure')
{
return $this->registry->register('Enclosure', $class, true);
}
/**
* Set which class SimplePie uses for `<media:text>` captions
*/
public function set_caption_class($class = 'SimplePie_Caption')
{
return $this->registry->register('Caption', $class, true);
}
/**
* Set which class SimplePie uses for `<media:copyright>`
*/
public function set_copyright_class($class = 'SimplePie_Copyright')
{
return $this->registry->register('Copyright', $class, true);
}
/**
* Set which class SimplePie uses for `<media:credit>`
*/
public function set_credit_class($class = 'SimplePie_Credit')
{
return $this->registry->register('Credit', $class, true);
}
/**
* Set which class SimplePie uses for `<media:rating>`
*/
public function set_rating_class($class = 'SimplePie_Rating')
{
return $this->registry->register('Rating', $class, true);
}
/**
* Set which class SimplePie uses for `<media:restriction>`
*/
public function set_restriction_class($class = 'SimplePie_Restriction')
{
return $this->registry->register('Restriction', $class, true);
}
/**
* Set which class SimplePie uses for content-type sniffing
*/
public function set_content_type_sniffer_class($class = 'SimplePie_Content_Type_Sniffer')
{
return $this->registry->register('Content_Type_Sniffer', $class, true);
}
/**
* Set which class SimplePie uses item sources
*/
public function set_source_class($class = 'SimplePie_Source')
{
return $this->registry->register('Source', $class, true);
}
/**#@-*/
/**
* Set the user agent string
*
* @param string $ua New user agent string.
*/
public function set_useragent($ua = SIMPLEPIE_USERAGENT)
{
$this->useragent = (string) $ua;
}
/**
* Set callback function to create cache filename with
*
* @param mixed $function Callback function
*/
public function set_cache_name_function($function = 'md5')
{
if (is_callable($function))
{
$this->cache_name_function = $function;
}
}
/**
* Set options to make SP as fast as possible
*
* Forgoes a substantial amount of data sanitization in favor of speed. This
* turns SimplePie into a dumb parser of feeds.
*
* @param bool $set Whether to set them or not
*/
public function set_stupidly_fast($set = false)
{
if ($set)
{
$this->enable_order_by_date(false);
$this->remove_div(false);
$this->strip_comments(false);
$this->strip_htmltags(false);
$this->strip_attributes(false);
$this->set_image_handler(false);
}
}
/**
* Set maximum number of feeds to check with autodiscovery
*
* @param int $max Maximum number of feeds to check
*/
public function set_max_checked_feeds($max = 10)
{
$this->max_checked_feeds = (int) $max;
}
public function remove_div($enable = true)
{
$this->sanitize->remove_div($enable);
}
public function strip_htmltags($tags = '', $encode = null)
{
if ($tags === '')
{
$tags = $this->strip_htmltags;
}
$this->sanitize->strip_htmltags($tags);
if ($encode !== null)
{
$this->sanitize->encode_instead_of_strip($tags);
}
}
public function encode_instead_of_strip($enable = true)
{
$this->sanitize->encode_instead_of_strip($enable);
}
public function strip_attributes($attribs = '')
{
if ($attribs === '')
{
$attribs = $this->strip_attributes;
}
$this->sanitize->strip_attributes($attribs);
}
/**
* Set the output encoding
*
* Allows you to override SimplePie's output to match that of your webpage.
* This is useful for times when your webpages are not being served as
* UTF-8. This setting will be obeyed by {@see handle_content_type()}, and
* is similar to {@see set_input_encoding()}.
*
* It should be noted, however, that not all character encodings can support
* all characters. If your page is being served as ISO-8859-1 and you try
* to display a Japanese feed, you'll likely see garbled characters.
* Because of this, it is highly recommended to ensure that your webpages
* are served as UTF-8.
*
* The number of supported character encodings depends on whether your web
* host supports {@link http://php.net/mbstring mbstring},
* {@link http://php.net/iconv iconv}, or both. See
* {@link http://simplepie.org/wiki/faq/Supported_Character_Encodings} for
* more information.
*
* @param string $encoding
*/
public function set_output_encoding($encoding = 'UTF-8')
{
$this->sanitize->set_output_encoding($encoding);
}
public function strip_comments($strip = false)
{
$this->sanitize->strip_comments($strip);
}
/**
* Set element/attribute key/value pairs of HTML attributes
* containing URLs that need to be resolved relative to the feed
*
* Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
* |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
* |q|@cite
*
* @since 1.0
* @param array|null $element_attribute Element/attribute key/value pairs, null for default
*/
public function set_url_replacements($element_attribute = null)
{
$this->sanitize->set_url_replacements($element_attribute);
}
/**
* Set the handler to enable the display of cached images.
*
* @param str $page Web-accessible path to the handler_image.php file.
* @param str $qs The query string that the value should be passed to.
*/
public function set_image_handler($page = false, $qs = 'i')
{
if ($page !== false)
{
$this->sanitize->set_image_handler($page . '?' . $qs . '=');
}
else
{
$this->image_handler = '';
}
}
/**
* Set the limit for items returned per-feed with multifeeds
*
* @param integer $limit The maximum number of items to return.
*/
public function set_item_limit($limit = 0)
{
$this->item_limit = (int) $limit;
}
/**
* Initialize the feed object
*
* This is what makes everything happen. Period. This is where all of the
* configuration options get processed, feeds are fetched, cached, and
* parsed, and all of that other good stuff.
*
* @return boolean True if successful, false otherwise
*/
public function init()
{
// Check absolute bare minimum requirements.
if (!extension_loaded('xml') || !extension_loaded('pcre'))
{
return false;
}
// Then check the xml extension is sane (i.e., libxml 2.7.x issue on PHP < 5.2.9 and libxml 2.7.0 to 2.7.2 on any version) if we don't have xmlreader.
elseif (!extension_loaded('xmlreader'))
{
static $xml_is_sane = null;
if ($xml_is_sane === null)
{
$parser_check = xml_parser_create();
xml_parse_into_struct($parser_check, '<foo>&</foo>', $values);
xml_parser_free($parser_check);
$xml_is_sane = isset($values[0]['value']);
}
if (!$xml_is_sane)
{
return false;
}
}
if (method_exists($this->sanitize, 'set_registry'))
{
$this->sanitize->set_registry($this->registry);
}
// Pass whatever was set with config options over to the sanitizer.
// Pass the classes in for legacy support; new classes should use the registry instead
$this->sanitize->pass_cache_data($this->cache, $this->cache_location, $this->cache_name_function, $this->registry->get_class('Cache'));
$this->sanitize->pass_file_data($this->registry->get_class('File'), $this->timeout, $this->useragent, $this->force_fsockopen);
if (!empty($this->multifeed_url))
{
$i = 0;
$success = 0;
$this->multifeed_objects = array();
$this->error = array();
foreach ($this->multifeed_url as $url)
{
$this->multifeed_objects[$i] = clone $this;
$this->multifeed_objects[$i]->set_feed_url($url);
$single_success = $this->multifeed_objects[$i]->init();
$success |= $single_success;
if (!$single_success)
{
$this->error[$i] = $this->multifeed_objects[$i]->error();
}
$i++;
}
return (bool) $success;
}
elseif ($this->feed_url === null && $this->raw_data === null)
{
return false;
}
$this->error = null;
$this->data = array();
$this->multifeed_objects = array();
$cache = false;
if ($this->feed_url !== null)
{
$parsed_feed_url = $this->registry->call('Misc', 'parse_url', array($this->feed_url));
// Decide whether to enable caching
if ($this->cache && $parsed_feed_url['scheme'] !== '')
{
$cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, call_user_func($this->cache_name_function, $this->feed_url), 'spc'));
}
// Fetch the data via SimplePie_File into $this->raw_data
if (($fetched = $this->fetch_data($cache)) === true)
{
return true;
}
elseif ($fetched === false) {
return false;
}
list($headers, $sniffed) = $fetched;
}
// Set up array of possible encodings
$encodings = array();
// First check to see if input has been overridden.
if ($this->input_encoding !== false)
{
$encodings[] = $this->input_encoding;
}
$application_types = array('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity');
$text_types = array('text/xml', 'text/xml-external-parsed-entity');
// RFC 3023 (only applies to sniffed content)
if (isset($sniffed))
{
if (in_array($sniffed, $application_types) || substr($sniffed, 0, 12) === 'application/' && substr($sniffed, -4) === '+xml')
{
if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset))
{
$encodings[] = strtoupper($charset[1]);
}
$encodings = array_merge($encodings, $this->registry->call('Misc', 'xml_encoding', array($this->raw_data, &$this->registry)));
$encodings[] = 'UTF-8';
}
elseif (in_array($sniffed, $text_types) || substr($sniffed, 0, 5) === 'text/' && substr($sniffed, -4) === '+xml')
{
if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset))
{
$encodings[] = $charset[1];
}
$encodings[] = 'US-ASCII';
}
// Text MIME-type default
elseif (substr($sniffed, 0, 5) === 'text/')
{
$encodings[] = 'US-ASCII';
}
}
// Fallback to XML 1.0 Appendix F.1/UTF-8/ISO-8859-1
$encodings = array_merge($encodings, $this->registry->call('Misc', 'xml_encoding', array($this->raw_data, &$this->registry)));
$encodings[] = 'UTF-8';
$encodings[] = 'ISO-8859-1';
// There's no point in trying an encoding twice
$encodings = array_unique($encodings);
// Loop through each possible encoding, till we return something, or run out of possibilities
foreach ($encodings as $encoding)
{
// Change the encoding to UTF-8 (as we always use UTF-8 internally)
if ($utf8_data = $this->registry->call('Misc', 'change_encoding', array($this->raw_data, $encoding, 'UTF-8')))
{
// Create new parser
$parser = $this->registry->create('Parser');
// If it's parsed fine
if ($parser->parse($utf8_data, 'UTF-8'))
{
$this->data = $parser->get_data();
if (!($this->get_type() & ~SIMPLEPIE_TYPE_NONE))
{
$this->error = "A feed could not be found at $this->feed_url. This does not appear to be a valid RSS or Atom feed.";
$this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__));
return false;
}
if (isset($headers))
{
$this->data['headers'] = $headers;
}
$this->data['build'] = SIMPLEPIE_BUILD;
// Cache the file if caching is enabled
if ($cache && !$cache->save($this))
{
trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
}
return true;
}
}
}
if (isset($parser))
{
// We have an error, just set SimplePie_Misc::error to it and quit
$this->error = sprintf('This XML document is invalid, likely due to invalid characters. XML error: %s at line %d, column %d', $parser->get_error_string(), $parser->get_current_line(), $parser->get_current_column());
}
else
{
$this->error = 'The data could not be converted to UTF-8. You MUST have either the iconv or mbstring extension installed. Upgrading to PHP 5.x (which includes iconv) is highly recommended.';
}
$this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__));
return false;
}
/**
* Fetch the data via SimplePie_File
*
* If the data is already cached, attempt to fetch it from there instead
* @param SimplePie_Cache|false $cache Cache handler, or false to not load from the cache
* @return array|true Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type
*/
protected function fetch_data(&$cache)
{
// If it's enabled, use the cache
if ($cache)
{
// Load the Cache
$this->data = $cache->load();
if (!empty($this->data))
{
// If the cache is for an outdated build of SimplePie
if (!isset($this->data['build']) || $this->data['build'] !== SIMPLEPIE_BUILD)
{
$cache->unlink();
$this->data = array();
}
// If we've hit a collision just rerun it with caching disabled
elseif (isset($this->data['url']) && $this->data['url'] !== $this->feed_url)
{
$cache = false;
$this->data = array();
}
// If we've got a non feed_url stored (if the page isn't actually a feed, or is a redirect) use that URL.
elseif (isset($this->data['feed_url']))
{
// If the autodiscovery cache is still valid use it.
if ($cache->mtime() + $this->autodiscovery_cache_duration > time())
{
// Do not need to do feed autodiscovery yet.
if ($this->data['feed_url'] !== $this->data['url'])
{
$this->set_feed_url($this->data['feed_url']);
return $this->init();
}
$cache->unlink();
$this->data = array();
}
}
// Check if the cache has been updated
elseif ($cache->mtime() + $this->cache_duration < time())
{
// If we have last-modified and/or etag set
if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag']))
{
$headers = array(
'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1',
);
if (isset($this->data['headers']['last-modified']))
{
$headers['if-modified-since'] = $this->data['headers']['last-modified'];
}
if (isset($this->data['headers']['etag']))
{
$headers['if-none-match'] = $this->data['headers']['etag'];
}
$file = $this->registry->create('File', array($this->feed_url, $this->timeout/10, 5, $headers, $this->useragent, $this->force_fsockopen));
if ($file->success)
{
if ($file->status_code === 304)
{
$cache->touch();
return true;
}
}
else
{
unset($file);
}
}
}
// If the cache is still valid, just return true
else
{
$this->raw_data = false;
return true;
}
}
// If the cache is empty, delete it
else
{
$cache->unlink();
$this->data = array();
}
}
// If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it.
if (!isset($file))
{
if ($this->file instanceof SimplePie_File && $this->file->url === $this->feed_url)
{
$file =& $this->file;
}
else
{
$headers = array(
'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1',
);
$file = $this->registry->create('File', array($this->feed_url, $this->timeout, 5, $headers, $this->useragent, $this->force_fsockopen));
}
}
// If the file connection has an error, set SimplePie::error to that and quit
if (!$file->success && !($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
{
$this->error = $file->error;
return !empty($this->data);
}
if (!$this->force_feed)
{
// Check if the supplied URL is a feed, if it isn't, look for it.
$locate = $this->registry->create('Locator', array(&$file, $this->timeout, $this->useragent, $this->max_checked_feeds));
if (!$locate->is_feed($file))
{
// We need to unset this so that if SimplePie::set_file() has been called that object is untouched
unset($file);
try
{
if (!($file = $locate->find($this->autodiscovery, $this->all_discovered_feeds)))
{
$this->error = "A feed could not be found at $this->feed_url. A feed with an invalid mime type may fall victim to this error, or " . SIMPLEPIE_NAME . " was unable to auto-discover it.. Use force_feed() if you are certain this URL is a real feed.";
$this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, __FILE__, __LINE__));
return false;
}
}
catch (SimplePie_Exception $e)
{
// This is usually because DOMDocument doesn't exist
$this->error = $e->getMessage();
$this->registry->call('Misc', 'error', array($this->error, E_USER_NOTICE, $e->getFile(), $e->getLine()));
return false;
}
if ($cache)
{
$this->data = array('url' => $this->feed_url, 'feed_url' => $file->url, 'build' => SIMPLEPIE_BUILD);
if (!$cache->save($this))
{
trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
}
$cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, call_user_func($this->cache_name_function, $file->url), 'spc'));
}
$this->feed_url = $file->url;
}
$locate = null;
}
$this->raw_data = $file->body;
$headers = $file->headers;
$sniffer = $this->registry->create('Content_Type_Sniffer', array(&$file));
$sniffed = $sniffer->get_type();
return array($headers, $sniffed);
}
/**
* Get the error message for the occured error
*
* @return string|array Error message, or array of messages for multifeeds
*/
public function error()
{
return $this->error;
}
/**
* Get the raw XML
*
* This is the same as the old `$feed->enable_xml_dump(true)`, but returns
* the data instead of printing it.
*
* @return string|boolean Raw XML data, false if the cache is used
*/
public function get_raw_data()
{
return $this->raw_data;
}
/**
* Get the character encoding used for output
*
* @since Preview Release
* @return string
*/
public function get_encoding()
{
return $this->sanitize->output_encoding;
}
/**
* Send the content-type header with correct encoding
*
* This method ensures that the SimplePie-enabled page is being served with
* the correct {@link http://www.iana.org/assignments/media-types/ mime-type}
* and character encoding HTTP headers (character encoding determined by the
* {@see set_output_encoding} config option).
*
* This won't work properly if any content or whitespace has already been
* sent to the browser, because it relies on PHP's
* {@link http://php.net/header header()} function, and these are the
* circumstances under which the function works.
*
* Because it's setting these settings for the entire page (as is the nature
* of HTTP headers), this should only be used once per page (again, at the
* top).
*
* @param string $mime MIME type to serve the page as
*/
public function handle_content_type($mime = 'text/html')
{
if (!headers_sent())
{
$header = "Content-type: $mime;";
if ($this->get_encoding())
{
$header .= ' charset=' . $this->get_encoding();
}
else
{
$header .= ' charset=UTF-8';
}
header($header);
}
}
/**
* Get the type of the feed
*
* This returns a SIMPLEPIE_TYPE_* constant, which can be tested against
* using {@link http://php.net/language.operators.bitwise bitwise operators}
*
* @since 0.8 (usage changed to using constants in 1.0)
* @see SIMPLEPIE_TYPE_NONE Unknown.
* @see SIMPLEPIE_TYPE_RSS_090 RSS 0.90.
* @see SIMPLEPIE_TYPE_RSS_091_NETSCAPE RSS 0.91 (Netscape).
* @see SIMPLEPIE_TYPE_RSS_091_USERLAND RSS 0.91 (Userland).
* @see SIMPLEPIE_TYPE_RSS_091 RSS 0.91.
* @see SIMPLEPIE_TYPE_RSS_092 RSS 0.92.
* @see SIMPLEPIE_TYPE_RSS_093 RSS 0.93.
* @see SIMPLEPIE_TYPE_RSS_094 RSS 0.94.
* @see SIMPLEPIE_TYPE_RSS_10 RSS 1.0.
* @see SIMPLEPIE_TYPE_RSS_20 RSS 2.0.x.
* @see SIMPLEPIE_TYPE_RSS_RDF RDF-based RSS.
* @see SIMPLEPIE_TYPE_RSS_SYNDICATION Non-RDF-based RSS (truly intended as syndication format).
* @see SIMPLEPIE_TYPE_RSS_ALL Any version of RSS.
* @see SIMPLEPIE_TYPE_ATOM_03 Atom 0.3.
* @see SIMPLEPIE_TYPE_ATOM_10 Atom 1.0.
* @see SIMPLEPIE_TYPE_ATOM_ALL Any version of Atom.
* @see SIMPLEPIE_TYPE_ALL Any known/supported feed type.
* @return int SIMPLEPIE_TYPE_* constant
*/
public function get_type()
{
if (!isset($this->data['type']))
{
$this->data['type'] = SIMPLEPIE_TYPE_ALL;
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed']))
{
$this->data['type'] &= SIMPLEPIE_TYPE_ATOM_10;
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed']))
{
$this->data['type'] &= SIMPLEPIE_TYPE_ATOM_03;
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF']))
{
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['channel'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['image'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['item'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['textinput']))
{
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_10;
}
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['channel'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['image'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['item'])
|| isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['textinput']))
{
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_090;
}
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss']))
{
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_ALL;
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version']))
{
switch (trim($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version']))
{
case '0.91':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_091;
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['skiphours']['hour'][0]['data']))
{
switch (trim($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['skiphours']['hour'][0]['data']))
{
case '0':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_NETSCAPE;
break;
case '24':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_USERLAND;
break;
}
}
break;
case '0.92':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_092;
break;
case '0.93':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_093;
break;
case '0.94':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_094;
break;
case '2.0':
$this->data['type'] &= SIMPLEPIE_TYPE_RSS_20;
break;
}
}
}
else
{
$this->data['type'] = SIMPLEPIE_TYPE_NONE;
}
}
return $this->data['type'];
}
/**
* Get the URL for the feed
*
* May or may not be different from the URL passed to {@see set_feed_url()},
* depending on whether auto-discovery was used.
*
* @since Preview Release (previously called `get_feed_url()` since SimplePie 0.8.)
* @todo If we have a perm redirect we should return the new URL
* @todo When we make the above change, let's support <itunes:new-feed-url> as well
* @todo Also, |atom:link|@rel=self
* @return string|null
*/
public function subscribe_url()
{
if ($this->feed_url !== null)
{
return $this->sanitize($this->feed_url, SIMPLEPIE_CONSTRUCT_IRI);
}
else
{
return null;
}
}
/**
* Get data for an feed-level element
*
* This method allows you to get access to ANY element/attribute that is a
* sub-element of the opening feed tag.
*
* The return value is an indexed array of elements matching the given
* namespace and tag name. Each element has `attribs`, `data` and `child`
* subkeys. For `attribs` and `child`, these contain namespace subkeys.
* `attribs` then has one level of associative name => value data (where
* `value` is a string) after the namespace. `child` has tag-indexed keys
* after the namespace, each member of which is an indexed array matching
* this same format.
*
* For example:
* <pre>
* // This is probably a bad example because we already support
* // <media:content> natively, but it shows you how to parse through
* // the nodes.
* $group = $item->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'group');
* $content = $group[0]['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'];
* $file = $content[0]['attribs']['']['url'];
* echo $file;
* </pre>
*
* @since 1.0
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
* @return array
*/
public function get_feed_tags($namespace, $tag)
{
$type = $this->get_type();
if ($type & SIMPLEPIE_TYPE_ATOM_10)
{
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag]))
{
return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag];
}
}
if ($type & SIMPLEPIE_TYPE_ATOM_03)
{
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag]))
{
return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag];
}
}
if ($type & SIMPLEPIE_TYPE_RSS_RDF)
{
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag]))
{
return $this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag];
}
}
if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION)
{
if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag]))
{
return $this->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag];
}
}
return null;
}
/**
* Get data for an channel-level element
*
* This method allows you to get access to ANY element/attribute in the
* channel/header section of the feed.
*
* See {@see SimplePie::get_feed_tags()} for a description of the return value
*
* @since 1.0
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
* @return array
*/
public function get_channel_tags($namespace, $tag)
{
$type = $this->get_type();
if ($type & SIMPLEPIE_TYPE_ATOM_ALL)
{
if ($return = $this->get_feed_tags($namespace, $tag))
{
return $return;
}
}
if ($type & SIMPLEPIE_TYPE_RSS_10)
{
if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'channel'))
{
if (isset($channel[0]['child'][$namespace][$tag]))
{
return $channel[0]['child'][$namespace][$tag];
}
}
}
if ($type & SIMPLEPIE_TYPE_RSS_090)
{
if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'channel'))
{
if (isset($channel[0]['child'][$namespace][$tag]))
{
return $channel[0]['child'][$namespace][$tag];
}
}
}
if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION)
{
if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel'))
{
if (isset($channel[0]['child'][$namespace][$tag]))
{
return $channel[0]['child'][$namespace][$tag];
}
}
}
return null;
}
/**
* Get data for an channel-level element
*
* This method allows you to get access to ANY element/attribute in the
* image/logo section of the feed.
*
* See {@see SimplePie::get_feed_tags()} for a description of the return value
*
* @since 1.0
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
* @return array
*/
public function get_image_tags($namespace, $tag)
{
$type = $this->get_type();
if ($type & SIMPLEPIE_TYPE_RSS_10)
{
if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'image'))
{
if (isset($image[0]['child'][$namespace][$tag]))
{
return $image[0]['child'][$namespace][$tag];
}
}
}
if ($type & SIMPLEPIE_TYPE_RSS_090)
{
if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'image'))
{
if (isset($image[0]['child'][$namespace][$tag]))
{
return $image[0]['child'][$namespace][$tag];
}
}
}
if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION)
{
if ($image = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'image'))
{
if (isset($image[0]['child'][$namespace][$tag]))
{
return $image[0]['child'][$namespace][$tag];
}
}
}
return null;
}
/**
* Get the base URL value from the feed
*
* Uses `<xml:base>` if available, otherwise uses the first link in the
* feed, or failing that, the URL of the feed itself.
*
* @see get_link
* @see subscribe_url
*
* @param array $element
* @return string
*/
public function get_base($element = array())
{
if (!($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION) && !empty($element['xml_base_explicit']) && isset($element['xml_base']))
{
return $element['xml_base'];
}
elseif ($this->get_link() !== null)
{
return $this->get_link();
}
else
{
return $this->subscribe_url();
}
}
/**
* Sanitize feed data
*
* @access private
* @see SimplePie_Sanitize::sanitize()
* @param string $data Data to sanitize
* @param int $type One of the SIMPLEPIE_CONSTRUCT_* constants
* @param string $base Base URL to resolve URLs against
* @return string Sanitized data
*/
public function sanitize($data, $type, $base = '')
{
return $this->sanitize->sanitize($data, $type, $base);
}
/**
* Get the title of the feed
*
* Uses `<atom:title>`, `<title>` or `<dc:title>`
*
* @since 1.0 (previously called `get_feed_title` since 0.8)
* @return string|null
*/
public function get_title()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
else
{
return null;
}
}
/**
* Get a category for the feed
*
* @since Unknown
* @param int $key The category that you want to return. Remember that arrays begin with 0, not 1
* @return SimplePie_Category|null
*/
public function get_category($key = 0)
{
$categories = $this->get_categories();
if (isset($categories[$key]))
{
return $categories[$key];
}
else
{
return null;
}
}
/**
* Get all categories for the feed
*
* Uses `<atom:category>`, `<category>` or `<dc:subject>`
*
* @since Unknown
* @return array|null List of {@see SimplePie_Category} objects
*/
public function get_categories()
{
$categories = array();
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category)
{
$term = null;
$scheme = null;
$label = null;
if (isset($category['attribs']['']['term']))
{
$term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($category['attribs']['']['scheme']))
{
$scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($category['attribs']['']['label']))
{
$label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT);
}
$categories[] = $this->registry->create('Category', array($term, $scheme, $label));
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'category') as $category)
{
// This is really the label, but keep this as the term also for BC.
// Label will also work on retrieving because that falls back to term.
$term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT);
if (isset($category['attribs']['']['domain']))
{
$scheme = $this->sanitize($category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT);
}
else
{
$scheme = null;
}
$categories[] = $this->registry->create('Category', array($term, $scheme, null));
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category)
{
$categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category)
{
$categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
}
if (!empty($categories))
{
return array_unique($categories);
}
else
{
return null;
}
}
/**
* Get an author for the feed
*
* @since 1.1
* @param int $key The author that you want to return. Remember that arrays begin with 0, not 1
* @return SimplePie_Author|null
*/
public function get_author($key = 0)
{
$authors = $this->get_authors();
if (isset($authors[$key]))
{
return $authors[$key];
}
else
{
return null;
}
}
/**
* Get all authors for the feed
*
* Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>`
*
* @since 1.1
* @return array|null List of {@see SimplePie_Author} objects
*/
public function get_authors()
{
$authors = array();
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author)
{
$name = null;
$uri = null;
$email = null;
if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']))
{
$name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']))
{
$uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]));
}
if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data']))
{
$email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if ($name !== null || $email !== null || $uri !== null)
{
$authors[] = $this->registry->create('Author', array($name, $uri, $email));
}
}
if ($author = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author'))
{
$name = null;
$url = null;
$email = null;
if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data']))
{
$name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data']))
{
$url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]));
}
if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data']))
{
$email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if ($name !== null || $email !== null || $url !== null)
{
$authors[] = $this->registry->create('Author', array($name, $url, $email));
}
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author)
{
$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author)
{
$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author)
{
$authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null));
}
if (!empty($authors))
{
return array_unique($authors);
}
else
{
return null;
}
}
/**
* Get a contributor for the feed
*
* @since 1.1
* @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1
* @return SimplePie_Author|null
*/
public function get_contributor($key = 0)
{
$contributors = $this->get_contributors();
if (isset($contributors[$key]))
{
return $contributors[$key];
}
else
{
return null;
}
}
/**
* Get all contributors for the feed
*
* Uses `<atom:contributor>`
*
* @since 1.1
* @return array|null List of {@see SimplePie_Author} objects
*/
public function get_contributors()
{
$contributors = array();
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor)
{
$name = null;
$uri = null;
$email = null;
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']))
{
$name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']))
{
$uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]));
}
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data']))
{
$email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if ($name !== null || $email !== null || $uri !== null)
{
$contributors[] = $this->registry->create('Author', array($name, $uri, $email));
}
}
foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor)
{
$name = null;
$url = null;
$email = null;
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data']))
{
$name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data']))
{
$url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]));
}
if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data']))
{
$email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
if ($name !== null || $email !== null || $url !== null)
{
$contributors[] = $this->registry->create('Author', array($name, $url, $email));
}
}
if (!empty($contributors))
{
return array_unique($contributors);
}
else
{
return null;
}
}
/**
* Get a single link for the feed
*
* @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8)
* @param int $key The link that you want to return. Remember that arrays begin with 0, not 1
* @param string $rel The relationship of the link to return
* @return string|null Link URL
*/
public function get_link($key = 0, $rel = 'alternate')
{
$links = $this->get_links($rel);
if (isset($links[$key]))
{
return $links[$key];
}
else
{
return null;
}
}
/**
* Get the permalink for the item
*
* Returns the first link available with a relationship of "alternate".
* Identical to {@see get_link()} with key 0
*
* @see get_link
* @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8)
* @internal Added for parity between the parent-level and the item/entry-level.
* @return string|null Link URL
*/
public function get_permalink()
{
return $this->get_link(0);
}
/**
* Get all links for the feed
*
* Uses `<atom:link>` or `<link>`
*
* @since Beta 2
* @param string $rel The relationship of links to return
* @return array|null Links found for the feed (strings)
*/
public function get_links($rel = 'alternate')
{
if (!isset($this->data['links']))
{
$this->data['links'] = array();
if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link'))
{
foreach ($links as $link)
{
if (isset($link['attribs']['']['href']))
{
$link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
$this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link));
}
}
}
if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link'))
{
foreach ($links as $link)
{
if (isset($link['attribs']['']['href']))
{
$link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
$this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link));
}
}
}
if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link'))
{
$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
}
if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link'))
{
$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
}
if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link'))
{
$this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0]));
}
$keys = array_keys($this->data['links']);
foreach ($keys as $key)
{
if ($this->registry->call('Misc', 'is_isegment_nz_nc', array($key)))
{
if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]))
{
$this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]);
$this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key];
}
else
{
$this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key];
}
}
elseif (substr($key, 0, 41) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY)
{
$this->data['links'][substr($key, 41)] =& $this->data['links'][$key];
}
$this->data['links'][$key] = array_unique($this->data['links'][$key]);
}
}
if (isset($this->data['links'][$rel]))
{
return $this->data['links'][$rel];
}
else
{
return null;
}
}
public function get_all_discovered_feeds()
{
return $this->all_discovered_feeds;
}
/**
* Get the content for the item
*
* Uses `<atom:subtitle>`, `<atom:tagline>`, `<description>`,
* `<dc:description>`, `<itunes:summary>` or `<itunes:subtitle>`
*
* @since 1.0 (previously called `get_feed_description()` since 0.8)
* @return string|null
*/
public function get_description()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0]));
}
else
{
return null;
}
}
/**
* Get the copyright info for the feed
*
* Uses `<atom:rights>`, `<atom:copyright>` or `<dc:rights>`
*
* @since 1.0 (previously called `get_feed_copyright()` since 0.8)
* @return string|null
*/
public function get_copyright()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'copyright'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
else
{
return null;
}
}
/**
* Get the language for the feed
*
* Uses `<language>`, `<dc:language>`, or @xml_lang
*
* @since 1.0 (previously called `get_feed_language()` since 0.8)
* @return string|null
*/
public function get_language()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'language'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang']))
{
return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang']))
{
return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang']))
{
return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (isset($this->data['headers']['content-language']))
{
return $this->sanitize($this->data['headers']['content-language'], SIMPLEPIE_CONSTRUCT_TEXT);
}
else
{
return null;
}
}
/**
* Get the latitude coordinates for the item
*
* Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
*
* Uses `<geo:lat>` or `<georss:point>`
*
* @since 1.0
* @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
* @link http://www.georss.org/ GeoRSS
* @return string|null
*/
public function get_latitude()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat'))
{
return (float) $return[0]['data'];
}
elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match))
{
return (float) $match[1];
}
else
{
return null;
}
}
/**
* Get the longitude coordinates for the feed
*
* Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
*
* Uses `<geo:long>`, `<geo:lon>` or `<georss:point>`
*
* @since 1.0
* @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
* @link http://www.georss.org/ GeoRSS
* @return string|null
*/
public function get_longitude()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long'))
{
return (float) $return[0]['data'];
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon'))
{
return (float) $return[0]['data'];
}
elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match))
{
return (float) $match[2];
}
else
{
return null;
}
}
/**
* Get the feed logo's title
*
* RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" title.
*
* Uses `<image><title>` or `<image><dc:title>`
*
* @return string|null
*/
public function get_image_title()
{
if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
else
{
return null;
}
}
/**
* Get the feed logo's URL
*
* RSS 0.9.0, 2.0, Atom 1.0, and feeds with iTunes RSS tags are allowed to
* have a "feed logo" URL. This points directly to the image itself.
*
* Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`,
* `<image><title>` or `<image><dc:title>`
*
* @return string|null
*/
public function get_image_url()
{
if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image'))
{
return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI);
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'url'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'url'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
else
{
return null;
}
}
/**
* Get the feed logo's link
*
* RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" link. This
* points to a human-readable page that the image should link to.
*
* Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`,
* `<image><title>` or `<image><dc:title>`
*
* @return string|null
*/
public function get_image_link()
{
if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0]));
}
else
{
return null;
}
}
/**
* Get the feed logo's link
*
* RSS 2.0 feeds are allowed to have a "feed logo" width.
*
* Uses `<image><width>` or defaults to 88.0 if no width is specified and
* the feed is an RSS 2.0 feed.
*
* @return int|float|null
*/
public function get_image_width()
{
if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'width'))
{
return round($return[0]['data']);
}
elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url'))
{
return 88.0;
}
else
{
return null;
}
}
/**
* Get the feed logo's height
*
* RSS 2.0 feeds are allowed to have a "feed logo" height.
*
* Uses `<image><height>` or defaults to 31.0 if no height is specified and
* the feed is an RSS 2.0 feed.
*
* @return int|float|null
*/
public function get_image_height()
{
if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'height'))
{
return round($return[0]['data']);
}
elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'url'))
{
return 31.0;
}
else
{
return null;
}
}
/**
* Get the number of items in the feed
*
* This is well-suited for {@link http://php.net/for for()} loops with
* {@see get_item()}
*
* @param int $max Maximum value to return. 0 for no limit
* @return int Number of items in the feed
*/
public function get_item_quantity($max = 0)
{
$max = (int) $max;
$qty = count($this->get_items());
if ($max === 0)
{
return $qty;
}
else
{
return ($qty > $max) ? $max : $qty;
}
}
/**
* Get a single item from the feed
*
* This is better suited for {@link http://php.net/for for()} loops, whereas
* {@see get_items()} is better suited for
* {@link http://php.net/foreach foreach()} loops.
*
* @see get_item_quantity()
* @since Beta 2
* @param int $key The item that you want to return. Remember that arrays begin with 0, not 1
* @return SimplePie_Item|null
*/
public function get_item($key = 0)
{
$items = $this->get_items();
if (isset($items[$key]))
{
return $items[$key];
}
else
{
return null;
}
}
/**
* Get all items from the feed
*
* This is better suited for {@link http://php.net/for for()} loops, whereas
* {@see get_items()} is better suited for
* {@link http://php.net/foreach foreach()} loops.
*
* @see get_item_quantity
* @since Beta 2
* @param int $start Index to start at
* @param int $end Number of items to return. 0 for all items after `$start`
* @return array|null List of {@see SimplePie_Item} objects
*/
public function get_items($start = 0, $end = 0)
{
if (!isset($this->data['items']))
{
if (!empty($this->multifeed_objects))
{
$this->data['items'] = SimplePie::merge_items($this->multifeed_objects, $start, $end, $this->item_limit);
}
else
{
$this->data['items'] = array();
if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'entry'))
{
$keys = array_keys($items);
foreach ($keys as $key)
{
$this->data['items'][] = $this->registry->create('Item', array($this, $items[$key]));
}
}
if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'entry'))
{
$keys = array_keys($items);
foreach ($keys as $key)
{
$this->data['items'][] = $this->registry->create('Item', array($this, $items[$key]));
}
}
if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'item'))
{
$keys = array_keys($items);
foreach ($keys as $key)
{
$this->data['items'][] = $this->registry->create('Item', array($this, $items[$key]));
}
}
if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'item'))
{
$keys = array_keys($items);
foreach ($keys as $key)
{
$this->data['items'][] = $this->registry->create('Item', array($this, $items[$key]));
}
}
if ($items = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'item'))
{
$keys = array_keys($items);
foreach ($keys as $key)
{
$this->data['items'][] = $this->registry->create('Item', array($this, $items[$key]));
}
}
}
}
if (!empty($this->data['items']))
{
// If we want to order it by date, check if all items have a date, and then sort it
if ($this->order_by_date && empty($this->multifeed_objects))
{
if (!isset($this->data['ordered_items']))
{
$do_sort = true;
foreach ($this->data['items'] as $item)
{
if (!$item->get_date('U'))
{
$do_sort = false;
break;
}
}
$item = null;
$this->data['ordered_items'] = $this->data['items'];
if ($do_sort)
{
usort($this->data['ordered_items'], array(get_class($this), 'sort_items'));
}
}
$items = $this->data['ordered_items'];
}
else
{
$items = $this->data['items'];
}
// Slice the data as desired
if ($end === 0)
{
return array_slice($items, $start);
}
else
{
return array_slice($items, $start, $end);
}
}
else
{
return array();
}
}
/**
* Set the favicon handler
*
* @deprecated Use your own favicon handling instead
*/
public function set_favicon_handler($page = false, $qs = 'i')
{
$level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING;
trigger_error('Favicon handling has been removed, please use your own handling', $level);
return false;
}
/**
* Get the favicon for the current feed
*
* @deprecated Use your own favicon handling instead
*/
public function get_favicon()
{
$level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING;
trigger_error('Favicon handling has been removed, please use your own handling', $level);
if (($url = $this->get_link()) !== null)
{
return 'http://g.etfv.co/' . urlencode($url);
}
return false;
}
/**
* Magic method handler
*
* @param string $method Method name
* @param array $args Arguments to the method
* @return mixed
*/
public function __call($method, $args)
{
if (strpos($method, 'subscribe_') === 0)
{
$level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING;
trigger_error('subscribe_*() has been deprecated, implement the callback yourself', $level);
return '';
}
if ($method === 'enable_xml_dump')
{
$level = defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_WARNING;
trigger_error('enable_xml_dump() has been deprecated, use get_raw_data() instead', $level);
return false;
}
$class = get_class($this);
$trace = debug_backtrace();
$file = $trace[0]['file'];
$line = $trace[0]['line'];
trigger_error("Call to undefined method $class::$method() in $file on line $line", E_USER_ERROR);
}
/**
* Sorting callback for items
*
* @access private
* @param SimplePie $a
* @param SimplePie $b
* @return boolean
*/
public static function sort_items($a, $b)
{
return $a->get_date('U') <= $b->get_date('U');
}
/**
* Merge items from several feeds into one
*
* If you're merging multiple feeds together, they need to all have dates
* for the items or else SimplePie will refuse to sort them.
*
* @link http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date#if_feeds_require_separate_per-feed_settings
* @param array $urls List of SimplePie feed objects to merge
* @param int $start Starting item
* @param int $end Number of items to return
* @param int $limit Maximum number of items per feed
* @return array
*/
public static function merge_items($urls, $start = 0, $end = 0, $limit = 0)
{
if (is_array($urls) && sizeof($urls) > 0)
{
$items = array();
foreach ($urls as $arg)
{
if ($arg instanceof SimplePie)
{
$items = array_merge($items, $arg->get_items(0, $limit));
}
else
{
trigger_error('Arguments must be SimplePie objects', E_USER_WARNING);
}
}
$do_sort = true;
foreach ($items as $item)
{
if (!$item->get_date('U'))
{
$do_sort = false;
break;
}
}
$item = null;
if ($do_sort)
{
usort($items, array(get_class($urls[0]), 'sort_items'));
}
if ($end === 0)
{
return array_slice($items, $start);
}
else
{
return array_slice($items, $start, $end);
}
}
else
{
trigger_error('Cannot merge zero SimplePie objects', E_USER_WARNING);
return array();
}
}
}
| b13/t3ext-newsfeedimport | Classes/SimplePie/library/SimplePie.php | PHP | mit | 88,133 |
#include "ObservationSequences.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include "boost\filesystem.hpp"
using namespace std;
namespace bst = boost::filesystem;
ObservationSequences::~ObservationSequences()
{
}
ObservationSequences::ObservationSequences(std::string folderName)
{
noOfFiles = 0;
noOfTrainingFiles = 0;
noOfScoringFiles = 0;
this->malwareFamilyName = folderName;
}
void ObservationSequences::getFileList() {
string folderName = "D:/Aditya/CS_266/Project/Dataset/" + this->malwareFamilyName + "/";
cout << folderName << endl;
bst::path p(folderName);
for (auto i = bst::directory_iterator(p); i != bst::directory_iterator(); i++)
{
if (!bst::is_directory(i->path()))
{
string fullFileName = folderName + i->path().filename().string();
this->fileNameList.push_back(fullFileName);
}
}
}
void ObservationSequences::getFileStream()
{
this->noOfFiles = this->fileNameList.size();
for (int index = 0; index < this->noOfFiles; index++)
{
vector<int> tempFileStream;
vector<string> opCodeStream;
string tempFileName = this->fileNameList.at(index);
ifstream tempReadFile;
tempReadFile.open(tempFileName);
string line;
while (getline(tempReadFile, line))
{
int opCodeIndex = find(this->distinctOpCodesList.begin(), this->distinctOpCodesList.end(), line) - this->distinctOpCodesList.begin();
int endIndex = this->distinctOpCodesList.size();
if (opCodeIndex != endIndex)
{
tempFileStream.push_back(opCodeIndex);
}
else
{
this->distinctOpCodesList.push_back(line);
int newOpCodeIndex = this->distinctOpCodesList.size()-1;
tempFileStream.push_back(newOpCodeIndex);
}
opCodeStream.push_back(line);
}
this->obsSequenceList.push_back(tempFileStream);
}
cout << this->distinctOpCodesList.size();
} | anish-shekhawat/hmm-adaboost | src/ObservationSequences.cpp | C++ | mit | 1,824 |
'use strict'
angular
.module('softvApp')
.controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) {
function init() {
if (opcion.opcion === 1) {
vm.blockForm2 = true;
muestraColonias();
muestrarelaciones();
vm.Titulo = 'Nuevo HUB';
} else if (opcion.opcion === 2) {
areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) {
console.log();
vm.blockForm2 = false;
var hub = data.GetConHubResult[0];
vm.Clv_Txt = hub.Clv_txt;
vm.Titulo = 'Editar HUB - '+hub.Clv_txt;
vm.Descripcion = hub.Descripcion;
vm.clv_hub = hub.Clv_Sector;
muestraColonias();
muestrarelaciones();
});
}
else if (opcion.opcion === 3) {
areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) {
vm.blockForm2 = true;
vm.blocksave = true;
var hub = data.GetConHubResult[0];
vm.Clv_Txt = hub.Clv_txt;
vm.Titulo = 'Consultar HUB - '+hub.Clv_txt;
vm.Descripcion = hub.Descripcion;
vm.clv_hub = hub.Clv_Sector;
muestraColonias();
muestrarelaciones();
});
}
}
function muestraColonias() {
areaTecnicaFactory.GetMuestraColoniaHub(0, 0, 0)
.then(function (data) {
vm.colonias = data.GetMuestraColoniaHubResult;
});
}
function AddSector() {
if (opcion.opcion === 1) {
areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) {
if (data.GetNueHubResult > 0) {
vm.clv_hub = data.GetNueHubResult;
ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success');
$rootScope.$broadcast('reloadlista');
vm.blockForm2 = false;
vm.blocksave = true;
} else {
ngNotify.set('La clave del HUB ya existe', 'error');
}
});
} else if (opcion.opcion === 2) {
areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) {
console.log(data);
ngNotify.set('El HUB se ha editado correctamente', 'success');
$rootScope.$broadcast('reloadlista');
$uibModalInstance.dismiss('cancel');
});
}
}
function cancel() {
$uibModalInstance.dismiss('cancel');
}
function validaRelacion(clv) {
var count = 0;
vm.RelColonias.forEach(function (item) {
count += (item.IdColonia === clv) ? 1 : 0;
});
return (count > 0) ? true : false;
}
function NuevaRelacionSecColonia() {
if (validaRelacion(vm.Colonia.IdColonia) === true) {
ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn');
return;
}
areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia)
.then(function (data) {
muestrarelaciones();
ngNotify.set('se agrego la relación correctamente', 'success');
});
}
function muestrarelaciones() {
areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub)
.then(function (rel) {
console.log(rel);
vm.RelColonias = rel.GetConRelHubColoniaResult;
});
}
function deleterelacion(clv) {
clusterFactory.GetQuitarEliminarRelClusterSector(2, vm.clv_cluster, clv).then(function (data) {
ngNotify.set('Se eliminó la relación correctamente', 'success');
muestrarelaciones();
});
}
var vm = this;
init();
vm.cancel = cancel;
vm.clv_hub = 0;
vm.RelColonias = [];
vm.AddSector = AddSector;
vm.NuevaRelacionSecColonia = NuevaRelacionSecColonia;
});
| alesabas/Softv | app/scripts/controllers/areatecnica/ModalAddhubCtrl.js | JavaScript | mit | 3,930 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Lachlan Dowding
*
* 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 permafrost.tundra.math;
import java.text.MessageFormat;
/**
* A collection of convenience methods for working with integers.
*/
public final class IntegerHelper {
/**
* The default value used when parsing a null string.
*/
private static int DEFAULT_INT_VALUE = 0;
/**
* Disallow instantiation of this class.
*/
private IntegerHelper() {}
/**
* Converts the given object to a Integer.
*
* @param object The object to be converted.
* @return The converted object.
*/
public static Integer normalize(Object object) {
Integer value = null;
if (object instanceof Number) {
value = ((Number)object).intValue();
} else if (object instanceof String) {
value = parse((String)object);
}
return value;
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @return Integer representing the given string, or 0 if the given string was null.
*/
public static int parse(String input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @param defaultValue The value returned if the given string is null.
* @return Integer representing the given string, or defaultValue if the given string is null.
*/
public static int parse(String input, int defaultValue) {
if (input == null) return defaultValue;
return Integer.parseInt(input);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @param defaultValue The value returned if a string in the list is null.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input, int defaultValue) {
if (input == null) return null;
int[] output = new int[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = parse(input[i], defaultValue);
}
return output;
}
/**
* Serializes the given integer as a string.
*
* @param input The integer to be serialized.
* @return A string representation of the given integer.
*/
public static String emit(int input) {
return Integer.toString(input);
}
/**
* Serializes the given integers as strings.
*
* @param input A list of integers to be serialized.
* @return A list of string representations of the given integers.
*/
public static String[] emit(int[] input) {
if (input == null) return null;
String[] output = new String[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = emit(input[i]);
}
return output;
}
}
| Permafrost/Tundra.java | src/main/java/permafrost/tundra/math/IntegerHelper.java | Java | mit | 4,471 |
require 'asciidoctor/extensions'
Asciidoctor::Extensions.register do
treeprocessor do
process do |doc|
doc
end
end
end
| feelpp/www.feelpp.org | _plugins/asciidoctor-extensions.rb | Ruby | mit | 138 |
package com.artfulbits.utils;
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
/** Common string routine. */
public final class StringUtils {
/* [ CONSTANTS ] ======================================================================================================================================= */
/** Our own class Logger instance. */
private final static Logger _log = LogEx.getLogger(StringUtils.class);
/** Default strings encoding. */
public final static String UTF8 = "UTF-8";
/* [ CONSTRUCTORS ] ==================================================================================================================================== */
/** Hidden constructor. */
private StringUtils() {
throw new AssertionError();
}
/* [ STATIC METHODS ] ================================================================================================================================== */
/**
* Convert string to utf 8 bytes.
*
* @param value the value to convert
* @return the bytes in UTF8 encoding.
*/
public static byte[] toUtf8Bytes(final String value) {
ValidUtils.isEmpty(value, "Expected not null value.");
// try to avoid NULL values, better to return empty array
byte[] buffer = new byte[]{};
if (!TextUtils.isEmpty(value)) {
try {
buffer = value.getBytes(StringUtils.UTF8);
} catch (final UnsupportedEncodingException e) {
_log.severe(LogEx.dump(e));
}
}
return buffer;
}
}
| OleksandrKucherenko/spacefish | _libs/artfulbits-sdk/src/main/com/artfulbits/utils/StringUtils.java | Java | mit | 1,547 |
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.management import call_command
from django.db import models, connections, transaction
from django.urls import reverse
from django_tenants.clone import CloneSchema
from .postgresql_backend.base import _check_schema_name
from .signals import post_schema_sync, schema_needs_to_be_sync
from .utils import get_creation_fakes_migrations, get_tenant_base_schema
from .utils import schema_exists, get_tenant_domain_model, get_public_schema_name, get_tenant_database_alias
class TenantMixin(models.Model):
"""
All tenant models must inherit this class.
"""
auto_drop_schema = False
"""
USE THIS WITH CAUTION!
Set this flag to true on a parent class if you want the schema to be
automatically deleted if the tenant row gets deleted.
"""
auto_create_schema = True
"""
Set this flag to false on a parent class if you don't want the schema
to be automatically created upon save.
"""
schema_name = models.CharField(max_length=63, unique=True, db_index=True,
validators=[_check_schema_name])
domain_url = None
"""
Leave this as None. Stores the current domain url so it can be used in the logs
"""
domain_subfolder = None
"""
Leave this as None. Stores the subfolder in subfolder routing was used
"""
_previous_tenant = []
class Meta:
abstract = True
def __enter__(self):
"""
Syntax sugar which helps in celery tasks, cron jobs, and other scripts
Usage:
with Tenant.objects.get(schema_name='test') as tenant:
# run some code in tenant test
# run some code in previous tenant (public probably)
"""
connection = connections[get_tenant_database_alias()]
self._previous_tenant.append(connection.tenant)
self.activate()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
connection = connections[get_tenant_database_alias()]
connection.set_tenant(self._previous_tenant.pop())
def activate(self):
"""
Syntax sugar that helps at django shell with fast tenant changing
Usage:
Tenant.objects.get(schema_name='test').activate()
"""
connection = connections[get_tenant_database_alias()]
connection.set_tenant(self)
@classmethod
def deactivate(cls):
"""
Syntax sugar, return to public schema
Usage:
test_tenant.deactivate()
# or simpler
Tenant.deactivate()
"""
connection = connections[get_tenant_database_alias()]
connection.set_schema_to_public()
def save(self, verbosity=1, *args, **kwargs):
connection = connections[get_tenant_database_alias()]
is_new = self.pk is None
has_schema = hasattr(connection, 'schema_name')
if has_schema and is_new and connection.schema_name != get_public_schema_name():
raise Exception("Can't create tenant outside the public schema. "
"Current schema is %s." % connection.schema_name)
elif has_schema and not is_new and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't update tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
super().save(*args, **kwargs)
if has_schema and is_new and self.auto_create_schema:
try:
self.create_schema(check_if_exists=True, verbosity=verbosity)
post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields())
except Exception:
# We failed creating the tenant, delete what we created and
# re-raise the exception
self.delete(force_drop=True)
raise
elif is_new:
# although we are not using the schema functions directly, the signal might be registered by a listener
schema_needs_to_be_sync.send(sender=TenantMixin, tenant=self.serializable_fields())
elif not is_new and self.auto_create_schema and not schema_exists(self.schema_name):
# Create schemas for existing models, deleting only the schema on failure
try:
self.create_schema(check_if_exists=True, verbosity=verbosity)
post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields())
except Exception:
# We failed creating the schema, delete what we created and
# re-raise the exception
self._drop_schema()
raise
def serializable_fields(self):
""" in certain cases the user model isn't serializable so you may want to only send the id """
return self
def _drop_schema(self, force_drop=False):
""" Drops the schema"""
connection = connections[get_tenant_database_alias()]
has_schema = hasattr(connection, 'schema_name')
if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't delete tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):
self.pre_drop()
cursor = connection.cursor()
cursor.execute('DROP SCHEMA "%s" CASCADE' % self.schema_name)
def pre_drop(self):
"""
This is a routine which you could override to backup the tenant schema before dropping.
:return:
"""
def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
"""
self._drop_schema(force_drop)
super().delete(*args, **kwargs)
def create_schema(self, check_if_exists=False, sync_schema=True,
verbosity=1):
"""
Creates the schema 'schema_name' for this tenant. Optionally checks if
the schema already exists before creating it. Returns true if the
schema was created, false otherwise.
"""
# safety check
connection = connections[get_tenant_database_alias()]
_check_schema_name(self.schema_name)
cursor = connection.cursor()
if check_if_exists and schema_exists(self.schema_name):
return False
fake_migrations = get_creation_fakes_migrations()
if sync_schema:
if fake_migrations:
# copy tables and data from provided model schema
base_schema = get_tenant_base_schema()
clone_schema = CloneSchema()
clone_schema.clone_schema(base_schema, self.schema_name)
call_command('migrate_schemas',
tenant=True,
fake=True,
schema_name=self.schema_name,
interactive=False,
verbosity=verbosity)
else:
# create the schema
cursor.execute('CREATE SCHEMA "%s"' % self.schema_name)
call_command('migrate_schemas',
tenant=True,
schema_name=self.schema_name,
interactive=False,
verbosity=verbosity)
connection.set_schema_to_public()
def get_primary_domain(self):
"""
Returns the primary domain of the tenant
"""
try:
domain = self.domains.get(is_primary=True)
return domain
except get_tenant_domain_model().DoesNotExist:
return None
def reverse(self, request, view_name):
"""
Returns the URL of this tenant.
"""
http_type = 'https://' if request.is_secure() else 'http://'
domain = get_current_site(request).domain
url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name)))
return url
def get_tenant_type(self):
"""
Get the type of tenant. Will only work for multi type tenants
:return: str
"""
return getattr(self, settings.MULTI_TYPE_DATABASE_FIELD)
class DomainMixin(models.Model):
"""
All models that store the domains must inherit this class
"""
domain = models.CharField(max_length=253, unique=True, db_index=True)
tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains',
on_delete=models.CASCADE)
# Set this to true if this is the primary domain
is_primary = models.BooleanField(default=True, db_index=True)
@transaction.atomic
def save(self, *args, **kwargs):
# Get all other primary domains with the same tenant
domain_list = self.__class__.objects.filter(tenant=self.tenant, is_primary=True).exclude(pk=self.pk)
# If we have no primary domain yet, set as primary domain by default
self.is_primary = self.is_primary or (not domain_list.exists())
if self.is_primary:
# Remove primary status of existing domains for tenant
domain_list.update(is_primary=False)
super().save(*args, **kwargs)
class Meta:
abstract = True
| tomturner/django-tenants | django_tenants/models.py | Python | mit | 9,732 |
package server
import (
"io"
"io/ioutil"
"log"
"net/http"
)
type Rest struct {
channels map[string]*Channel
}
func NewRestServer(server *Server) *Rest {
return &Rest{server.channels}
}
func (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h(w, r)
return
}
http.Error(w, "post only", http.StatusMethodNotAllowed)
}
}
func (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
channel := r.URL.Query().Get("channel")
//get the session id from header
session := r.Header.Get("session");
log.Printf("SessionID: %s", session)
msg := &Message{Channel: channel, Body: string(body), session: session}
if ch, ok := self.channels[channel]; ok {
ch.sendAll <- msg
}
log.Printf("[REST] body: %s, channel: %s", body, channel)
}
func (self *Rest) ListenRest() {
log.Println("Listening server(REST)...")
http.HandleFunc("/rest", self.PostOnly(self.restHandler))
}
| nkostadinov/websocket | server/rest.go | GO | mit | 1,150 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class HistorialC extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('date');
$this->load->model('HistorialM');
if (!$this->session->userdata("login")) {
redirect(base_url());
}
}
public function index(){
$data['regs'] = $this->HistorialM->lista();
$this->load->view('historialV', $data);
}
}
| euphoz/correosusers | application/controllers/HistorialC.php | PHP | mit | 506 |
using System;
using System.Collections.Generic;
using System.Linq;
using RiotSharp.MatchEndpoint.Enums;
namespace RiotSharp.Misc
{
static class Util
{
public static DateTime BaseDateTime = new DateTime(1970, 1, 1);
public static DateTime ToDateTimeFromMilliSeconds(this long millis)
{
return BaseDateTime.AddMilliseconds(millis);
}
public static long ToLong(this DateTime dateTime)
{
var span = dateTime - BaseDateTime;
return (long)span.TotalMilliseconds;
}
public static string BuildIdsString(List<int> ids)
{
return string.Join(",", ids);
}
public static string BuildIdsString(List<long> ids)
{
return string.Join(",", ids);
}
public static string BuildNamesString(List<string> names)
{
return string.Join(",", names.Select(Uri.EscapeDataString));
}
public static string BuildQueuesString(List<string> queues)
{
return string.Join(",", queues);
}
public static string BuildSeasonString(List<Season> seasons)
{
return string.Join(",", seasons.Select(s => s.ToCustomString()));
}
}
}
| frederickrogan/RiotSharp | RiotSharp/Misc/Util.cs | C# | mit | 1,281 |
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('pillzApp'));
var MainCtrl,
scope,
$httpBackend;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/awesomeThings')
.respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings).toBeUndefined();
$httpBackend.flush();
expect(scope.awesomeThings.length).toBe(4);
});
});
| captDaylight/pillz | test/client/spec/controllers/main.js | JavaScript | mit | 769 |
<?php
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// _profiler_search_bar
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',);
}
}
// _profiler_purge
if ($pathinfo === '/_profiler/purge') {
return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',);
}
if (0 === strpos($pathinfo, '/_profiler/i')) {
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_import
if ($pathinfo === '/_profiler/import') {
return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',);
}
}
// _profiler_export
if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// _profiler_search_results
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// _profiler_exception_css
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
if (0 === strpos($pathinfo, '/_configurator')) {
// _configurator_home
if (rtrim($pathinfo, '/') === '/_configurator') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_configurator_home');
}
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',);
}
// _configurator_step
if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',));
}
// _configurator_final
if ($pathinfo === '/_configurator/final') {
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',);
}
}
}
if (0 === strpos($pathinfo, '/collection')) {
// lien_collection
if (rtrim($pathinfo, '/') === '/collection') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_collection');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::indexAction', '_route' => 'lien_collection',);
}
// lien_collection_show
if (preg_match('#^/collection/(?P<id>[^/]++)/(?P<slug>[^/]++)(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_collection_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::showAction', 'page' => 1,));
}
// lien_collection_new
if ($pathinfo === '/collection/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::newAction', '_route' => 'lien_collection_new',);
}
// lien_collection_create
if ($pathinfo === '/collection/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_collection_create;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::createAction', '_route' => 'lien_collection_create',);
}
not_lien_collection_create:
// lien_collection_edit
if (0 === strpos($pathinfo, '/collection/edit') && preg_match('#^/collection/edit/(?P<id>[^/]++)/?$#s', $pathinfo, $matches)) {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_collection_edit');
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_collection_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::editAction',));
}
// lien_collection_update
if (preg_match('#^/collection/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_lien_collection_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_collection_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::updateAction',));
}
not_lien_collection_update:
// lien_collection_delete
if (preg_match('#^/collection/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_lien_collection_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_collection_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\CollectionController::deleteAction',));
}
not_lien_collection_delete:
}
if (0 === strpos($pathinfo, '/avis')) {
// lien_avis
if (rtrim($pathinfo, '/') === '/avis') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_avis');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::indexAction', '_route' => 'lien_avis',);
}
// lien_avis_show
if (preg_match('#^/avis/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::showAction',));
}
// lien_avis_new
if ($pathinfo === '/avis/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::newAction', '_route' => 'lien_avis_new',);
}
// lien_avis_create
if ($pathinfo === '/avis/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_avis_create;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::createAction', '_route' => 'lien_avis_create',);
}
not_lien_avis_create:
// lien_avis_edit
if (preg_match('#^/avis/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::editAction',));
}
// lien_avis_update
if (preg_match('#^/avis/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_lien_avis_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::updateAction',));
}
not_lien_avis_update:
// lien_avis_delete
if (preg_match('#^/avis/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_lien_avis_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_avis_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\AvisUserLivreController::deleteAction',));
}
not_lien_avis_delete:
}
if (0 === strpos($pathinfo, '/livre')) {
// lien_livre
if (rtrim($pathinfo, '/') === '/livre') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_livre');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::indexAction', '_route' => 'lien_livre',);
}
// lien_livre_read
if (0 === strpos($pathinfo, '/livre/read') && preg_match('#^/livre/read/(?P<collection>[^/]++)/(?P<auteur>[^/]++)/(?P<id>\\d+)/(?P<titre>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_read')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::readAction',));
}
// lien_livre_show
if (preg_match('#^/livre/(?P<collection>[^/]++)/(?P<auteur>[^/]++)/(?P<id>\\d+)/(?P<titre>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::showAction',));
}
// lien_livre_all
if (0 === strpos($pathinfo, '/livre/liste') && preg_match('#^/livre/liste(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_all')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::allAction', 'page' => 1,));
}
// lien_livre_show_all
if (0 === strpos($pathinfo, '/livre/catalogue') && preg_match('#^/livre/catalogue(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_show_all')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::showAllAction', 'page' => 1,));
}
// lien_livre_find
if ($pathinfo === '/livre/recherche') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_livre_find;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::findAction', '_route' => 'lien_livre_find',);
}
not_lien_livre_find:
// lien_livre_new
if ($pathinfo === '/livre/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::newAction', '_route' => 'lien_livre_new',);
}
// lien_livre_create
if ($pathinfo === '/livre/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_livre_create;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::createAction', '_route' => 'lien_livre_create',);
}
not_lien_livre_create:
// lien_livre_edit
if (preg_match('#^/livre/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::editAction',));
}
// lien_livre_update
if (preg_match('#^/livre/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_lien_livre_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::updateAction',));
}
not_lien_livre_update:
// lien_livre_delete
if (preg_match('#^/livre/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_lien_livre_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_livre_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\LivreController::deleteAction',));
}
not_lien_livre_delete:
}
if (0 === strpos($pathinfo, '/user')) {
// lien_user
if (rtrim($pathinfo, '/') === '/user') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_user');
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::indexAction', '_route' => 'lien_user',);
}
// lien_user_show
if (preg_match('#^/user/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_show')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::showAction',));
}
// lien_user_new
if ($pathinfo === '/user/new') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::newAction', '_route' => 'lien_user_new',);
}
// lien_user_create
if ($pathinfo === '/user/create') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_user_create;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::createAction', '_route' => 'lien_user_create',);
}
not_lien_user_create:
// lien_user_modif
if ($pathinfo === '/user/modif') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_user_modif;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::modifAction', '_route' => 'lien_user_modif',);
}
not_lien_user_modif:
// lien_user_edit
if (0 === strpos($pathinfo, '/user/edit') && preg_match('#^/user/edit/(?P<id>[^/]++)/?$#s', $pathinfo, $matches)) {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'lien_user_edit');
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_edit')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::editAction',));
}
// lien_user_edit_admin
if (preg_match('#^/user/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_edit_admin')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::editAdminAction',));
}
// lien_user_update
if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_lien_user_update;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_update')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::updateAction',));
}
not_lien_user_update:
// lien_user_update_admin
if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
$allow = array_merge($allow, array('POST', 'PUT'));
goto not_lien_user_update_admin;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_update_admin')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::updateAdminAction',));
}
not_lien_user_update_admin:
// lien_user_delete
if (preg_match('#^/user/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
$allow = array_merge($allow, array('POST', 'DELETE'));
goto not_lien_user_delete;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lien_user_delete')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::deleteAction',));
}
not_lien_user_delete:
if (0 === strpos($pathinfo, '/user/log')) {
// lien_user_login
if ($pathinfo === '/user/login') {
if ($this->context->getMethod() != 'POST') {
$allow[] = 'POST';
goto not_lien_user_login;
}
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::loginAction', '_route' => 'lien_user_login',);
}
not_lien_user_login:
// lien_user_logout
if ($pathinfo === '/user/logout') {
return array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\UserController::logoutAction', '_route' => 'lien_user_logout',);
}
}
}
// lsi_biblio_homepage
if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'lsi_biblio_homepage')), array ( '_controller' => 'Lsi\\BiblioBundle\\Controller\\DefaultController::indexAction',));
}
// _welcome
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_welcome');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',);
}
if (0 === strpos($pathinfo, '/demo')) {
if (0 === strpos($pathinfo, '/demo/secured')) {
if (0 === strpos($pathinfo, '/demo/secured/log')) {
if (0 === strpos($pathinfo, '/demo/secured/login')) {
// _demo_login
if ($pathinfo === '/demo/secured/login') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',);
}
// _security_check
if ($pathinfo === '/demo/secured/login_check') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',);
}
}
// _demo_logout
if ($pathinfo === '/demo/secured/logout') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',);
}
}
if (0 === strpos($pathinfo, '/demo/secured/hello')) {
// acme_demo_secured_hello
if ($pathinfo === '/demo/secured/hello') {
return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',);
}
// _demo_secured_hello
if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',));
}
// _demo_secured_hello_admin
if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',));
}
}
}
// _demo
if (rtrim($pathinfo, '/') === '/demo') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_demo');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',);
}
// _demo_hello
if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',));
}
// _demo_contact
if ($pathinfo === '/demo/contact') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',);
}
}
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
}
}
| sekouzed/Libraire-biblioth-ques-en-ligne-avec-Symfony | app/cache/dev/appDevUrlMatcher.php | PHP | mit | 27,519 |
'use strict';
var assert = require('power-assert');
var resetStorage = require('./');
var dbName = 'test-item';
describe('#localStorage', function () {
beforeEach(function (done) {
localStorage.clear();
done();
});
it('should save value', function () {
var expected = { foo: 'bar', goo: 'nuu' };
localStorage.setItem('item', JSON.stringify(expected));
assert.deepEqual(expected, JSON.parse(localStorage.getItem('item')));
});
it('should clear value', function (done) {
var input = { foo: 'bar', goo: 'nuu' };
localStorage.setItem('item', JSON.stringify(input));
resetStorage
.localStorage()
.then(function () {
assert.equal(null, localStorage.getItem('item'));
done();
});
});
});
describe('#indexedDB', function () {
var db;
beforeEach(function (done) {
var req = indexedDB.deleteDatabase('test-item');
req.onsuccess = function() {
done();
};
});
// http://dev.classmethod.jp/ria/html5/html5-indexed-database-api/
it('should save value', function (done) {
if (!indexedDB) {
throw new Error('Your browser doesn\'t support a stable version of IndexedDB.');
}
var openRequest = indexedDB.open(dbName, 2);
var key = 'foo';
var value = 'bar';
var expected = {};
expected[key] = value;
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore('mystore', { keyPath: 'mykey'});
store.createIndex('myvalueIndex', 'myvalue');
};
openRequest.onsuccess = function() {
db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.put({ mykey: key, myvalue: value });
request.onsuccess = function () {
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.get(key);
request.onsuccess = function (event) {
assert.equal(value, event.target.result.myvalue);
db.close();
done();
};
request.onerror = function (event) {
db.close();
throw new Error(event.toString);
};
};
request.onerror = function(event) {
db.close();
throw new Error(event.toString);
};
};
});
it.skip('should clear value. Writing this test is too hard for me.', function (done) {
if (true) {// eslint-disable-line no-constant-condition
throw new Error();
}
if (!indexedDB) {
throw new Error('Your browser doesn\'t support a stable version of IndexedDB.');
}
var openRequest = indexedDB.open(dbName, 2);
var key = 'foo';
var value = 'bar';
var expected = {};
expected[key] = value;
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore('mystore', { keyPath: 'mykey'});
store.createIndex('myvalueIndex', 'myvalue');
};
openRequest.onsuccess = function() {
db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.put({ mykey: key, myvalue: value });
request.onsuccess = function () {
db.close();
var openRequest = indexedDB.open(dbName, 2);
openRequest.onerror = function(event) {
throw new Error(event.toString);
};
openRequest.onsuccess = function() {
var db = openRequest.result;
var transaction = db.transaction(['mystore'], 'readwrite');
var store = transaction.objectStore('mystore');
var request = store.get(key);
request.onsuccess = function (event) {
assert.equal(value, event.target.result.myvalue);
db.close();
done();
};
request.onerror = function (event) {
db.close();
throw new Error(event.toString);
};
};
};
request.onerror = function(event) {
db.close();
throw new Error(event.toString);
};
};
});
});
| pandawing/node-reset-storage | test.js | JavaScript | mit | 4,421 |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using alby.core.threadpool ;
namespace alby.codegen.generator
{
public partial class ViewGeneratorParameters
{
public Program p ;
public string fqview ;
public Exception exception ;
} // end class
public partial class ViewGeneratorThreadPoolItem : MyThreadPoolItemBase
{
protected ViewGeneratorParameters _vgp ;
public ViewGeneratorThreadPoolItem( ViewGeneratorParameters vgp )
{
_vgp = vgp ;
}
public override void Run()
{
Helper h = new Helper() ;
try
{
DoView( _vgp.p, _vgp.fqview ) ;
}
catch( Exception ex )
{
_vgp.exception = ex ;
h.Message( "[DoTable() EXCEPTION]\n{0}", ex ) ;
}
}
protected void DoView( Program p, string fqview )
{
Helper h = new Helper() ;
ColumnInfo ci = new ColumnInfo() ;
Tuple<string,string> schemaview = h.SplitSchemaFromTable( fqview ) ;
string thedatabase = h.GetCsharpClassName( null, null, p._databaseName ) ;
string csharpnamespace = p._namespace + "." + p._viewSubDirectory;
string resourcenamespace = p._resourceNamespace + "." + p._viewSubDirectory;
string theclass = h.GetCsharpClassName( p._prefixObjectsWithSchema, schemaview.Item1, schemaview.Item2);
string csharpfile = p._directory + @"\" + p._viewSubDirectory + @"\" + theclass + ".cs" ;
string csharpfactoryfile = csharpfile.Replace(".cs", "Factory.cs");
string thefactoryclass = theclass + "Factory";
// config for this view, if any
string xpath = "/CodeGen/Views/View[@Class='" + theclass + "']" ;
XmlNode view = p._codegen.SelectSingleNode(xpath);
// select sql
string selectsql = "select * from {0} t ";
// do class
h.MessageVerbose( "[{0}]", csharpfile );
using ( StreamWriter sw = new StreamWriter( csharpfile, false, UTF8Encoding.UTF8 ) )
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw);
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, theclass, "acr.RowBase"))
{
List< Tuple<string,string> > columns = ci.GetViewColumns( fqview ) ;
// properties and constructor
using (RowConstructorBlock conb = new RowConstructorBlock(sw, tab, theclass, columns, null, ""))
{}
} // end class
} // end namespace
} // eof
// do class factory
h.MessageVerbose( "[{0}]", csharpfactoryfile );
using (StreamWriter sw = new StreamWriter(csharpfactoryfile, false, UTF8Encoding.UTF8))
{
int tab = 0;
// header
h.WriteCodeGenHeader(sw);
h.WriteUsing(sw, p._namespace );
// namespace
using (NamespaceBlock nsb = new NamespaceBlock(sw, tab++, csharpnamespace))
{
using (ClassBlock cb = new ClassBlock(sw, tab++, thefactoryclass,
"acr.FactoryBase< " +
theclass + ", " +
"ns." + p._databaseSubDirectory + "." + thedatabase + "DatabaseSingletonHelper, " +
"ns." + p._databaseSubDirectory + "." + thedatabase + "Database >"
) )
{
// constructor
using (ViewFactoryConstructorBlock conb = new ViewFactoryConstructorBlock( sw, tab, fqview, selectsql, thefactoryclass))
{}
// default load all method
List<string> parameters = new List<string>();
Dictionary<string, string> parameterdictionary = new Dictionary<string, string>();
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "Loadˡ");
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, "Loadˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// load by where
parameters = new List<string>() ;
parameters.Add("connˡ" );
parameters.Add("whereˡ" );
parameters.Add("parametersˡ" );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
parameterdictionary.Add("whereˡ", "string");
parameterdictionary.Add("parametersˡ", "scg.List<sds.SqlParameter>");
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
h.MessageVerbose("[{0}].[{1}].[{2}]", csharpnamespace, theclass, "LoadByWhereˡ");
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, "LoadByWhereˡ", parameters, parameterdictionary, "", theclass, resourcenamespace))
{}
// other methods
if ( view != null )
{
XmlNodeList xmlmethods = view.SelectNodes("Methods/Method");
foreach ( XmlNode xmlmethod in xmlmethods )
{
string themethod = xmlmethod.SelectSingleNode("@Name").InnerText;
// where resource
string whereresource = xmlmethod.SelectSingleNode("@Where").InnerText;
// parameters
parameters = new List<string>() ;
parameters.Add("connˡ" );
XmlNodeList xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameters.Add( xmlparameter.SelectSingleNode("@Name").InnerText );
parameters.Add("topNˡ" );
parameters.Add("orderByˡ" );
parameters.Add("tranˡ" );
parameterdictionary = new Dictionary<string, string>();
parameterdictionary.Add("connˡ", "sds.SqlConnection");
xmlparameters = xmlmethod.SelectNodes("Parameters/Parameter");
foreach ( XmlNode xmlparameter in xmlparameters )
parameterdictionary.Add( xmlparameter.SelectSingleNode("@Name").InnerText,
xmlparameter.SelectSingleNode("@Type").InnerText );
parameterdictionary.Add("topNˡ", "int?");
parameterdictionary.Add("orderByˡ", "scg.List<acr.CodeGenOrderBy>");
parameterdictionary.Add("tranˡ", "sds.SqlTransaction");
// method
h.MessageVerbose( "[{0}].[{1}].method [{2}]", csharpnamespace, theclass, themethod );
using (ViewFactoryMethodBlock mb = new ViewFactoryMethodBlock(sw, tab, themethod, parameters, parameterdictionary, whereresource, theclass, resourcenamespace))
{}
}
}
} // end class
} // end namespace
} // eof
} // end do view
} // end class
} | casaletto/alby.codegen.2015 | alby.codegen.generator/ViewGeneratorThreadPoolItem.cs | C# | mit | 7,334 |
// Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <chainparams.h>
#include <chainparamsbase.h>
#include <logging.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/url.h>
#include <wallet/wallettool.h>
#include <functional>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
UrlDecodeFn* const URL_DECODE = nullptr;
static void SetupWalletToolArgs(ArgsManager& argsman)
{
SetupHelpOptions(argsman);
SetupChainParamsBaseOptions(argsman);
argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
argsman.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
argsman.AddArg("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
}
static bool WalletAppInit(int argc, char* argv[])
{
SetupWalletToolArgs(gArgs);
std::string error_message;
if (!gArgs.ParseParameters(argc, argv, error_message)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
return false;
}
if (argc < 2 || HelpRequested(gArgs)) {
std::string usage = strprintf("%s elements-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" +
"elements-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n" +
"By default elements-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" +
"To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" +
"Usage:\n" +
" elements-wallet [options] <command>\n\n" +
gArgs.GetHelpMessage();
tfm::format(std::cout, "%s", usage);
return false;
}
// check for printtoconsole, allow -debug
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false));
if (!CheckDataDirOption()) {
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""));
return false;
}
// Check for chain settings (Params() calls are only valid after this clause)
SelectParams(gArgs.GetChainName());
return true;
}
int main(int argc, char* argv[])
{
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
RandomInit();
try {
if (!WalletAppInit(argc, argv)) return EXIT_FAILURE;
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "WalletAppInit()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "WalletAppInit()");
return EXIT_FAILURE;
}
std::string method {};
for(int i = 1; i < argc; ++i) {
if (!IsSwitchChar(argv[i][0])) {
if (!method.empty()) {
tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]);
return EXIT_FAILURE;
}
method = argv[i];
}
}
if (method.empty()) {
tfm::format(std::cerr, "No method provided. Run `elements-wallet -help` for valid methods.\n");
return EXIT_FAILURE;
}
// A name must be provided when creating a file
if (method == "create" && !gArgs.IsArgSet("-wallet")) {
tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n");
return EXIT_FAILURE;
}
std::string name = gArgs.GetArg("-wallet", "");
ECCVerifyHandle globalVerifyHandle;
ECC_Start();
if (!WalletTool::ExecuteWalletToolFunc(method, name))
return EXIT_FAILURE;
ECC_Stop();
return EXIT_SUCCESS;
}
| ElementsProject/elements | src/bitcoin-wallet.cpp | C++ | mit | 4,831 |
<?php
namespace App\Common\Models\Order\Mysql;
use App\Common\Models\Base\Mysql\Base;
class OrderCommon extends Base
{
/**
* 订单-订单扩展信息表管理
* This model is mapped to the table iorder_common
*/
public function getSource()
{
return 'iorder_common';
}
public function reorganize(array $data)
{
$data = parent::reorganize($data);
// $data['is_smtp'] = $this->changeToBoolean($data['is_smtp']);
// $data['access_token_expire'] = $this->changeToValidDate($data['access_token_expire']);
return $data;
}
} | handsomegyr/models | lib/App/Common/Models/Order/Mysql/OrderCommon.php | PHP | mit | 613 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Treorisoft.Net.Utilities
{
/// <summary>
/// Provides properties and instance methods for sending files over a <see cref="Winsock"/> objects.
/// </summary>
[Serializable]
public class FileData : ISerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="FileData"/> class.
/// </summary>
/// <param name="info">A <see cref="FileInfo"/> object that contains data about the file.</param>
public FileData(FileInfo info)
{
Guid = Guid.NewGuid();
FileName = info.Name;
FileSize = info.Length;
Info = info;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileData"/> class with serialized data.
/// </summary>
/// <param name="info">The object that holds the serialized object data.</param>
/// <param name="context">The contextual information about the source or destination.</param>
protected FileData(SerializationInfo info, StreamingContext context)
{
Guid = (Guid)info.GetValue("guid", typeof(Guid));
FileName = info.GetString("filename");
FileSize = info.GetInt64("filesize");
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and returns the data needed to serialize the <see cref="FileData"/> object.
/// </summary>
/// <param name="info">A SerializationInfo object containing information required to serialize the FileData object.</param>
/// <param name="context">A StreamingContext object containing the source and destination of the serialized stream associated with the FileData object.</param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("guid", Guid);
info.AddValue("filename", FileName);
info.AddValue("filesize", FileSize);
}
/// <summary>
/// Gets a <see cref="Guid"/> identifier for the file.
/// </summary>
public Guid Guid { get; private set; }
/// <summary>
/// Gets the name of the file.
/// </summary>
public string FileName { get; private set; }
/// <summary>
/// Gets the size, in bytes, of the file.
/// </summary>
public long FileSize { get; private set; }
/// <summary>
/// Gets the <see cref="FileInfo"/> of the file being transmitted.
/// </summary>
/// <remarks>
/// During sending this contains the details of the actual file being transmitted.
/// During receiving this contains the details of a temporary file, that upon arrival can be moved to another location.
/// </remarks>
public FileInfo Info { get; internal set; }
#region Sending/Receiving Helpers
/// <summary>
/// Field backing the SyncRoot property.
/// </summary>
internal object _syncRoot = null;
/// <summary>
/// Field backing the MetaSize property.
/// </summary>
internal static int _fileDataMetaSize = -1;
/// <summary>
/// Gets an object that can be used to synchronize access to the file being read/written.
/// </summary>
private object SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
/// <summary>
/// Gets a value the estimates the size of an empty <see cref="FileDataPart"/> object.
/// </summary>
internal static int MetaSize
{
get
{
if (_fileDataMetaSize < 0)
_fileDataMetaSize = EstimatePartSize(0) + 1;
return _fileDataMetaSize;
}
}
/// <summary>
/// Gets an estimate of a <see cref="FileDataPart"/> object of the specified data size.
/// </summary>
/// <param name="size">The size of the data that should be used in the size estimate.</param>
/// <returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(int size)
{
return EstimatePartSize(Guid.Empty, long.MaxValue, size);
}
/// <summary>
/// Gets an estimate of a <see cref="FileDataPart"/>.
/// </summary>
/// <param name="guid">The <see cref="Guid"/> that should be used in the size estimate.</param>
/// <param name="start">The start position that should be used in the size estimate.</param>
/// <param name="size">The size of the data that should be used in the size estimate.</param>
/// <returns>The estimated size, in bytes, of a serialized <see cref="FileDataPart"/>.</returns>
internal static int EstimatePartSize(Guid guid, long start, int size)
{
var part = new FileDataPart(guid, start, new byte[size]);
var bytes = ObjectPacker.Pack(part);
return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
}
#endregion
#region Sending
/// <summary>
/// Gets the total number of bytes sent.
/// </summary>
internal long SentBytes { get; set; } = 0;
/// <summary>
/// Gets a boolean value indicating whether if the file has been completely sent or not.
/// </summary>
internal bool SendCompleted { get { return (SentBytes == FileSize); } }
/// <summary>
/// Gets the next <see cref="FileDataPart"/> that will be sent over the network.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to return.</param>
/// <returns>The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.</returns>
internal FileDataPart GetNextPart(int bufferSize)
{
if (SendCompleted) return null;
if (Info == null) throw new NullReferenceException("File information not found.");
if (!Info.Exists) throw new FileNotFoundException(Info.FullName);
bufferSize -= MetaSize;
byte[] buffer = new byte[bufferSize];
lock (SyncRoot)
{
using (FileStream fs = new FileStream(Info.FullName, FileMode.Open, FileAccess.Read))
{
fs.Seek(SentBytes, SeekOrigin.Begin);
int readSize = fs.Read(buffer, 0, bufferSize);
byte[] sizedBuffer = ArrayMethods.Shrink(ref buffer, readSize);
var part = new FileDataPart(Guid, SentBytes, sizedBuffer);
SentBytes += readSize;
return part;
}
}
}
/// <summary>
/// Gets the total size of all the parts of the file at the given buffer size.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
/// <returns>
/// This routine is used by <see cref="SendProgress"/> to help determine the total number of bytes to send, and therefore also the percent completed.
/// The bufferSize is adjusted by an estimate of how large the metadata would be, so that the size of the serialized <see cref="FileDataPart"/> should be the same as the bufferSize.
/// </returns>
internal long GetTotalPartSize(int bufferSize)
{
long sum = 0;
foreach (int size in GetPartSizes(bufferSize))
sum += size;
return sum;
}
/// <summary>
/// Gets the sizes of all the parts of the file at the given buffer size.
/// </summary>
/// <param name="bufferSize">The size of the buffer and amount of data to estimate with.</param>
/// <returns>
/// Returns an IEnumerable containing the sizes of all the different parts of the file - including the <see cref="FileData"/> header.
/// </returns>
internal IEnumerable<int> GetPartSizes(int bufferSize)
{
if (Info == null) throw new NullReferenceException("File information not found.");
if (!Info.Exists) throw new FileNotFoundException(Info.FullName);
var bytes = ObjectPacker.Pack(this);
yield return bytes.Length + PacketHeader.HeaderSize(bytes.Length);
bufferSize -= MetaSize;
long fileSize = Info.Length;
long start = 0;
while (fileSize > 0)
{
if (fileSize > bufferSize)
{
yield return EstimatePartSize(Guid, start, bufferSize);
fileSize -= bufferSize;
start += bufferSize;
}
else
{
yield return EstimatePartSize(Guid, start, (int)fileSize);
fileSize = 0;
}
}
}
#endregion
#region Receiving
/// <summary>
/// Gets the total number of received bytes.
/// </summary>
public long ReceivedBytes { get; private set; } = 0;
/// <summary>
/// Gets a boolean value indicating if the file has been completely received or not.
/// </summary>
public bool ReceiveCompleted { get { return (ReceivedBytes == FileSize); } }
/// <summary>
/// Gets the size of the last received <see cref="FileDataPart"/>.
/// </summary>
/// <remarks>This is used to help setup the <see cref="ReceiveProgressEventArgs"/> that is raised.</remarks>
internal int LastReceivedSize { get; set; }
/// <summary>
/// Receives the <see cref="FileDataPart"/> into the specified file.
/// </summary>
/// <param name="fileName">The fully qualified name of the file, or the relative file name. Do not end the path with the directory separator character.</param>
/// <param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(string fileName, FileDataPart part)
{
ReceivePart(new FileInfo(fileName), part);
}
/// <summary>
/// Receives the <see cref="FileDataPart"/> into the specified file.
/// </summary>
/// <param name="file">A <see cref="FileInfo"/> object containing the fully qualified name of the file to receiving the data to.</param>
/// <param name="part">The <see cref="FileDataPart"/> to be received.</param>
internal void ReceivePart(FileInfo file, FileDataPart part)
{
if (ReceiveCompleted)
throw new InvalidOperationException("Receive operation for this file has already been completed.");
lock (SyncRoot)
{
using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Seek(part.Start, SeekOrigin.Begin);
fs.Write(part.Data, 0, part.Data.Length);
}
LastReceivedSize = part.Data.Length;
ReceivedBytes += part.Data.Length;
}
}
#endregion
}
}
| Borvik/Winsock.Net | Winsock/Utilities/FileData.cs | C# | mit | 11,804 |
package main
import "fmt"
func main() {
fmt.Println("go" + "lang")
fmt.Println("1+1 =", 1+1)
fmt.Println("7.0/3.0 =", 7.0/3.0)
fmt.Println(true && false)
fmt.Println(true || false)
fmt.Println(!true)
}
| csaura/go_examples | values/values.go | GO | mit | 217 |
import React from 'react'
import DocumentTitle from 'react-document-title'
import ReactHeight from 'react-height'
import Header from './header/header'
import Content from './content/content'
import Footer from './footer/footer'
import { APP_NAME } from '../constants'
class Layout extends React.Component {
render() {
const hfStyle = {
flex: 'none'
}
const contentStyle = {
flex: 1
}
const containerStyle = {
display: 'flex',
minHeight: window.innerHeight,
flexDirection: 'column'
}
return (
<div style={containerStyle}>
<DocumentTitle title={APP_NAME}/>
<Header style={hfStyle}/>
<Content style={contentStyle}/>
<Footer style={hfStyle}/>
</div>
)
}
}
export default Layout
| HendrikCrause/crossword-creator | src/components/layout.js | JavaScript | mit | 792 |
import Graph from 'graphology-types';
export default function mergePath(graph: Graph, nodes: Array<unknown>): void;
| graphology/graphology | src/utils/merge-path.d.ts | TypeScript | mit | 117 |
var i18n = require('i18n');
var _ = require('lodash');
exports.register = function (plugin, options, next) {
i18n.configure(options);
plugin.ext('onPreResponse', function (request, extNext) {
// If is an error message
if(request.response.isBoom) {
i18n.setLocale(getLocale(request, options));
request.response.output.payload.message = i18n.__(request.response.output.payload.message);
return extNext(request.response);
}
extNext();
});
next();
};
var getLocale = function(request, options) {
i18n.init(request.raw.req);
if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) {
return request.raw.req.language;
} else {
return options.defaultLocale;
}
}; | jozzhart/josepoo | lib/index.js | JavaScript | mit | 731 |
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
| Kinnay/NintendoClients | tests/test_dauth.py | Python | mit | 2,095 |
package com.jxtech.distributed.zookeeper.pool;
import java.util.NoSuchElementException;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.StackObjectPool;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jxtech.distributed.Configuration;
/**
* ZK实例池管理器
*
* @author wmzsoft@gmail.com
*/
public class ZookeeperPoolManager {
private static final Logger LOG = LoggerFactory.getLogger(ZookeeperPoolManager.class);
/** 单例 */
protected static ZookeeperPoolManager instance;
private ObjectPool pool;
/**
* 构造方法
*/
private ZookeeperPoolManager() {
init();
}
/**
* 返回单例的对象
*
* @return
*/
public static ZookeeperPoolManager getInstance() {
if (instance == null) {
instance = new ZookeeperPoolManager();
}
return instance;
}
/**
* 初始化方法zookeeper连接池
*
* @param config
*/
private void init() {
if (pool != null) {
LOG.debug("pool is already init");
return;
}
Configuration config = Configuration.getInstance();
if (!config.isDeploy()) {
LOG.info("Can't init , deploy = false.");
return;
}
PoolableObjectFactory factory = new ZookeeperPoolableObjectFactory(config);
// 初始化ZK对象池
int maxIdle = config.getMaxIdle();
int initIdleCapacity = config.getInitIdleCapacity();
pool = new StackObjectPool(factory, maxIdle, initIdleCapacity);
// 初始化池
for (int i = 0; i < initIdleCapacity; i++) {
try {
pool.addObject();
} catch (IllegalStateException | UnsupportedOperationException ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* 将ZK对象从对象池中取出
*
* @return
*/
public ZooKeeper borrowObject() {
if (pool != null) {
try {
return (ZooKeeper) pool.borrowObject();
} catch (NoSuchElementException | IllegalStateException ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
return null;
}
/**
* 将ZK实例返回对象池
*
* @param zk
*/
public void returnObject(ZooKeeper zk) {
if (pool != null && zk != null) {
try {
pool.returnObject(zk);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* 关闭对象池
*/
public void close() {
if (pool != null) {
try {
pool.close();
LOG.info("关闭ZK对象池完成");
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
}
| wmzsoft/JXADF | Source/JxADF/JxPlatform/src/main/java/com/jxtech/distributed/zookeeper/pool/ZookeeperPoolManager.java | Java | mit | 3,203 |
<div class="page-actions">
<!-- AUDIO CONTAINER (conditional) -->
<?php if ($page->episode_file()->isNotEmpty()) { ?>
<div class="audio-holder" itemprop="audio">
<audio preload="none" controls>
<source src="/podcasts/<?php echo $page->episode_file() ?>" type="audio/mpeg" />
</audio>
</div>
<?php } ?>
<!-- DOWNLOAD FILE -->
<?php if ($page->episode_file() != ""): ?>
<a itemprop="audio" class="action download" href="<?= $site->url(); ?>/podcasts/<?php echo $page->episode_file() ?>" download title="Download episode">
<svg viewBox="0 0 100 100">
<path d="M81.2 49.4c0 7.7-6.3 13.9-13.9 13.9h-5.6v-6.1h5.6c4.4 0 7.9-3.6 7.9-7.9 0-5.4-3.6-8.2-7.5-8.2-.2-9-6.1-12.9-11.9-12.9-7.6 0-10.8 5.8-11.5 8-3.1-4.5-11.5-1.1-9.8 4.9-5.3-.9-9.4 3-9.4 8.2 0 4.4 3.6 7.9 8.1 7.9h7.7v6.1h-7.7C25.3 63.3 19 57 19 49.4c0-6.3 4.2-11.7 10-13.4 1.6-5.6 7.5-8.9 13.1-7.4 3.4-4 8.3-6.3 13.6-6.3 8.6 0 16 6.2 17.5 14.5 4.9 2.3 8 7.1 8 12.6zM62.3 68.8h-5.1V57.3H45.1v11.5H40L51.1 80l11.2-11.2z"/>
</svg>
<span class="label go-right">Download this episode</span>
</a>
<?php endif; ?>
<!-- READ DOCUMENT -->
<?php if ($page->document_link() != ""): ?>
<a itemprop="citation" class="action read" href="<?php echo $page->document_link() ?>" title="Read <?php echo $page->provider() ?>'s document" target="_blank">
<svg viewBox="0 0 100 100">
<path d="M65.3 57H44.2v-4.6h21l.1 4.6zm0-10H44.2v-4.6h21l.1 4.6zm0-10H44.2v-4.6h21l.1 4.6zM29.1 75.3V24.4h42.8v33.4c0 9.7-11.9 5.8-11.9 5.8s3.6 11.7-5.4 11.7H29.1zM78 58.4V18.3H23v63.1h31.7c10.4 0 23.3-13.6 23.3-23zM37.8 32c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7zm0 10.1c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7zm0 9.9c-1.5 0-2.7 1.2-2.7 2.7 0 1.5 1.2 2.7 2.7 2.7s2.7-1.2 2.7-2.7c-.1-1.5-1.3-2.7-2.7-2.7z"/>
</svg>
<span class="label go-right">Read <?php echo $page->provider() ?>'s document</span>
</a>
<?php endif ?>
<!-- Contribute To The F Plus -->
<a class="social contribute" href="/contribute/" title="Contribute To The Podcast">
<svg viewBox="0 0 100 100">
<path d="M50.6 28.3l10.2-3.6L50 20.9l-10.7 3.7M32 36v-1.2l2.3-.7 9.5-3.4L32.7 27l-11.8 4.1v8.2L32 43.6M67.5 27l-9.7 3.6 8.9 2.9 3 1v7.6l9.4-4.1v-6.9M62.1 36.9L51 33.1l-11.4 4.2v9.2l10.4 4 12.1-5.2"/>
<path d="M60.9 47.4L50 52.2l-9.2-3.6v24.9l9.2 5.6L60.9 72M33.2 45.6l-10.9-4.2v21L33.2 69M68.5 44v23.1l9.2-6V39.9" />
</svg>
<span class="label">Contribute to the Podcast</span>
</a>
<!-- TWEET THIS -->
<a class="social twitter" href="https://twitter.com/intent/tweet?text=<?php echo rawurlencode($page->title()); ?>%0A&url=<?php echo rawurlencode($page->url()); ?>&via=TheFPlus" target="_blank" title="Tweet this">
<svg viewBox="0 0 100 100">
<path d="M80.2 30.5c-2.3 1-4.8 1.8-7.4 2 2.6-1.6 4.7-4.1 5.7-7.1-2.5 1.5-5.2 2.6-8.2 3.2-2.3-2.5-5.7-4.1-9.5-4.1-7.1 0-13 5.8-13 13 0 1 .1 2 .3 2.9-10.8-.6-20.3-5.7-26.7-13.6-1.2 1.9-1.8 4.1-1.8 6.6 0 4.5 2.3 8.5 5.8 10.8-2 0-4.1-.7-5.8-1.6v.1c0 6.3 4.5 11.5 10.4 12.7-1.2.3-2.2.4-3.4.4-.9 0-1.6 0-2.5-.3 1.6 5.1 6.4 8.9 12.1 9-4.5 3.5-10.1 5.5-16 5.5-1 0-2 0-3.1-.1 5.7 3.7 12.6 5.8 20 5.8C61 75.7 74 55.9 74 38.8V37c2.3-1.6 4.5-4 6.2-6.5z"/>
</svg>
<span class="label">Tweet this episode</span>
</a>
<!-- FACEBOOK SHARE -->
<a class="social facebook" href="https://www.facebook.com/sharer.php?u=<?php echo rawurlencode ($page->url()); ?>" title="Share on Facebook">
<svg viewBox="0 0 100 100">
<path d="M76.8 18.3H21.9c-1.9 0-3.4 1.5-3.4 3.4v54.9c0 1.9 1.5 3.4 3.4 3.4h29.5V56.1h-8v-9.3h8V40c0-7.9 4.9-12.3 12-12.3 3.4 0 6.3.3 7.2.4v8.3h-4.9c-3.9 0-4.6 1.8-4.6 4.5v6h9.2L69 56.3h-7.9v23.9h15.7c1.9 0 3.4-1.5 3.4-3.4v-55c0-1.9-1.5-3.5-3.4-3.5z"/>
</svg>
<span class="label">Share on Facebook</span>
</a>
<!-- REDDIT SHARE -->
<a class="social reddit" href="https://reddit.com/submit/?<?php echo rawurlencode ($page->url()); ?>" target="_blank" title="Share on Reddit">
<svg viewBox="0 0 100 100">
<path d="M82.7 47.1c0-4.7-3.8-8.5-8.5-8.5-2.7 0-5.3 1.4-6.9 3.5-4.7-2.9-10.6-4.7-17.2-4.9.2-3.2 1.1-8.7 4.3-10.5 2-1.2 4.9-.7 8.6 1.4.4 4.3 4 7.6 8.4 7.6 4.7 0 8.5-3.8 8.5-8.5s-3.8-8.5-8.5-8.5c-3.9 0-7.2 2.7-8.2 6.3-4.1-2-7.5-2.3-10.2-.7-4.7 2.7-5.5 9.9-5.7 12.9-6.6.2-12.6 2-17.3 4.9-1.6-2.2-4.1-3.5-6.9-3.5-4.7 0-8.5 3.8-8.5 8.5 0 3.7 2.4 6.9 5.8 8.1-.1.6-.1 1.2-.1 1.9C20.3 68.1 33 77 48.7 77S77 68 77 57c0-.6-.1-1.3-.1-1.9 3.4-1.1 5.8-4.3 5.8-8zM21 52.4c-2.2-.8-3.7-2.9-3.7-5.3 0-3.1 2.5-5.7 5.7-5.7 1.8 0 3.5.9 4.5 2.3-3.1 2.4-5.4 5.4-6.5 8.7zm10.6.4c0-3.1 2.5-5.7 5.7-5.7 3.1 0 5.7 2.5 5.7 5.7s-2.5 5.7-5.7 5.7-5.7-2.6-5.7-5.7zm27.8 13.6c-3 1.7-6.8 2.7-10.8 2.7-3.9 0-7.8-1-10.8-2.7-.7-.4-.9-1.3-.5-1.9.4-.7 1.3-.9 1.9-.5 5.2 3 13.5 3 18.7 0 .7-.4 1.5-.2 1.9.5.5.7.2 1.5-.4 1.9zm.6-8c-3.1 0-5.7-2.5-5.7-5.7S56.8 47 60 47c3.1 0 5.7 2.5 5.7 5.7s-2.6 5.7-5.7 5.7zm16.2-6c-1.1-3.3-3.4-6.2-6.5-8.7 1.1-1.4 2.7-2.3 4.5-2.3 3.1 0 5.7 2.5 5.7 5.7 0 2.4-1.6 4.4-3.7 5.3z" />
</svg>
<span class="label">Share on Reddit</span>
</a>
<!-- TUMBLR SHARE -->
<a class="social tumblr" href="http://www.tumblr.com/share/link?url=<?php echo rawurlencode ($page->url()); ?>&name=<?php echo rawurlencode ($page->title()); ?>&description=<?php echo excerpt($page->text()->xml(), 180) ?>">
<svg viewBox="0 0 100 100">
<path d="M57.3 81.4c6.5 0 13-2.3 15.1-5.1l.4-.6-4-12c0-.1-.1-.2-.3-.2h-9c-.1 0-.2-.1-.3-.2-.1-.4-.2-.9-.2-1.5V47.2c0-.2.1-.3.3-.3H70c.2 0 .3-.1.3-.3v-15c0-.2-.1-.3-.3-.3H59.4c-.2 0-.3-.1-.3-.3V16.5c0-.2-.1-.3-.3-.3H40.2c-1.3 0-2.9 1-3.1 2.8-.9 7.5-4.4 12.1-10.9 14.2l-.7.2c-.1 0-.2.1-.2.3v12.9c0 .2.1.3.3.3H32.3v15.9c0 12.7 8.8 18.6 25 18.6zm12.4-6.1c-2 2-6.2 3.4-10.2 3.5h-.4c-13.2 0-16.7-10.1-16.7-16V44.6c0-.2-.1-.3-.3-.3h-6.4c-.2 0-.3-.1-.3-.3v-8.3c0-.1.1-.2.2-.3 6.8-2.6 10.6-7.9 11.6-16.1.1-.5.4-.5.4-.5h8.5c.2 0 .3.1.3.3v14.6c0 .2.1.3.3.3h10.6c.2 0 .3.1.3.3V44c0 .2-.1.3-.3.3H56.7c-.2 0-.3.1-.3.3v17.3c.1 3.9 2 5.9 5.6 5.9 1.5 0 3.2-.3 4.7-.9.1-.1.3 0 .4.2l2.7 8s0 .1-.1.2z" />
</svg>
<span class="label">Post to Tumblr</span>
</a>
<!-- Save To Pocket -->
<?php if ($page->episode_file()->isEmpty()) { ?>
<a class="social pocket" href="https://getpocket.com/edit?url=<?=rawurlencode ($page->url()); ?>">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M67.1 47.8L53.2 61.2c-.8.8-1.8 1.1-2.8 1.1-1 0-2-.4-2.8-1.1l-14-13.4c-1.6-1.5-1.7-4.1-.1-5.7 1.6-1.6 4.1-1.7 5.7-.1l11.1 10.7L61.4 42c1.6-1.6 4.2-1.5 5.7.1 1.7 1.6 1.7 4.1 0 5.7zm12.5-18.6c-.7-2.1-2.8-3.5-5-3.5H26.1c-2.2 0-4.2 1.4-5 3.5-.2.6-.3 1.3-.3 1.9V49l.2 3.6c.9 8.1 5 15.1 11.5 20.1.1.1.2.2.4.3l.1.1c3.5 2.5 7.4 4.3 11.6 5.1 1.9.4 3.9.6 5.9.6 1.8 0 3.7-.2 5.4-.5.2-.1.4-.1.7-.1.1 0 .1 0 .2-.1 4-.9 7.8-2.6 11.1-5l.1-.1.3-.3c6.5-4.9 10.7-12 11.5-20.1L80 49V31c-.1-.6-.2-1.2-.4-1.8z" />
</svg>
<span class="label">Save to Pocket</span>
</a>
<?php } ?>
<!-- GitHub Repo -->
<?php if ($page->github_repo()->isNotEmpty()) { ?>
<a class="social github" href="<?= $page->github_repo(); ?>" title="Fork on GitHub">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M50 15.3c-19 0-34.3 15.4-34.3 34.3 0 15.2 9.8 28 23.5 32.6 1.7.3 2.3-.7 2.3-1.7v-5.8c-9.5 2.1-11.6-4.6-11.6-4.6-1.6-4-3.8-5-3.8-5-3.1-2.1.2-2.1.2-2.1 3.4.2 5.3 3.5 5.3 3.5 3.1 5.2 8 3.7 10 2.9.3-2.2 1.2-3.7 2.2-4.6-7.6-.9-15.6-3.8-15.6-17 0-3.7 1.3-6.8 3.5-9.2-.4-.9-1.5-4.4.3-9.1 0 0 2.9-.9 9.4 3.5 2.7-.8 5.7-1.1 8.6-1.2 2.9 0 5.9.4 8.6 1.2 6.6-4.4 9.4-3.5 9.4-3.5 1.9 4.7.7 8.2.3 9.1 2.2 2.4 3.5 5.5 3.5 9.2 0 13.2-8 16.1-15.7 16.9 1.2 1.1 2.3 3.2 2.3 6.4v9.4c0 .9.6 2 2.4 1.7 13.6-4.5 23.5-17.4 23.5-32.6C84.3 30.7 69 15.3 50 15.3z"/>
</svg>
<span class="label">Fork on GitHub</span>
</a>
<?php } ?>
</div> | AhoyLemon/TheFPlus | site/snippets/page-actions.php | PHP | mit | 7,943 |
<?php
namespace Braintree\Error;
/**
*
* Validation Error codes and messages
*
* ErrorCodes class provides constants for validation errors.
* The constants should be used to check for a specific validation
* error in a ValidationErrorCollection.
* The error messages returned from the server may change;
* but the codes will remain the same.
*
* @package Braintree
* @subpackage Errors
* @category Validation
*/
class Codes
{
const ADDRESS_CANNOT_BE_BLANK = '81801';
const ADDRESS_COMPANY_IS_INVALID = '91821';
const ADDRESS_COMPANY_IS_TOO_LONG = '81802';
const ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = '91814';
const ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = '91816';
const ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = '91817';
const ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED = '91803';
const ADDRESS_EXTENDED_ADDRESS_IS_INVALID = '91823';
const ADDRESS_EXTENDED_ADDRESS_IS_TOO_LONG = '81804';
const ADDRESS_FIRST_NAME_IS_INVALID = '91819';
const ADDRESS_FIRST_NAME_IS_TOO_LONG = '81805';
const ADDRESS_INCONSISTENT_COUNTRY = '91815';
const ADDRESS_LAST_NAME_IS_INVALID = '91820';
const ADDRESS_LAST_NAME_IS_TOO_LONG = '81806';
const ADDRESS_LOCALITY_IS_INVALID = '91824';
const ADDRESS_LOCALITY_IS_TOO_LONG = '81807';
const ADDRESS_POSTAL_CODE_INVALID_CHARACTERS = '81813';
const ADDRESS_POSTAL_CODE_IS_INVALID = '91826';
const ADDRESS_POSTAL_CODE_IS_REQUIRED = '81808';
const ADDRESS_POSTAL_CODE_IS_TOO_LONG = '81809';
const ADDRESS_REGION_IS_INVALID = '91825';
const ADDRESS_REGION_IS_TOO_LONG = '81810';
const ADDRESS_STATE_IS_INVALID_FOR_SELLER_PROTECTION = '81827';
const ADDRESS_STREET_ADDRESS_IS_INVALID = '91822';
const ADDRESS_STREET_ADDRESS_IS_REQUIRED = '81811';
const ADDRESS_STREET_ADDRESS_IS_TOO_LONG = '81812';
const ADDRESS_TOO_MANY_ADDRESSES_PER_CUSTOMER = '91818';
const APPLE_PAY_CARDS_ARE_NOT_ACCEPTED = '83501';
const APPLE_PAY_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = '83502';
const APPLE_PAY_TOKEN_IS_IN_USE = '93503';
const APPLE_PAY_PAYMENT_METHOD_NONCE_CONSUMED = '93504';
const APPLE_PAY_PAYMENT_METHOD_NONCE_UNKNOWN = '93505';
const APPLE_PAY_PAYMENT_METHOD_NONCE_UNLOCKED = '93506';
const APPLE_PAY_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = '83518';
const APPLE_PAY_CANNOT_UPDATE_APPLE_PAY_CARD_USING_PAYMENT_METHOD_NONCE = '93507';
const APPLE_PAY_NUMBER_IS_REQUIRED = '93508';
const APPLE_PAY_EXPIRATION_MONTH_IS_REQUIRED = '93509';
const APPLE_PAY_EXPIRATION_YEAR_IS_REQUIRED = '93510';
const APPLE_PAY_CRYPTOGRAM_IS_REQUIRED = '93511';
const APPLE_PAY_DECRYPTION_FAILED = '83512';
const APPLE_PAY_DISABLED = '93513';
const APPLE_PAY_MERCHANT_NOT_CONFIGURED = '93514';
const APPLE_PAY_MERCHANT_KEYS_ALREADY_CONFIGURED = '93515';
const APPLE_PAY_MERCHANT_KEYS_NOT_CONFIGURED = '93516';
const APPLE_PAY_CERTIFICATE_INVALID = '93517';
const APPLE_PAY_CERTIFICATE_MISMATCH = '93519';
const APPLE_PAY_INVALID_TOKEN = '83520';
const APPLE_PAY_PRIVATE_KEY_MISMATCH = '93521';
const APPLE_PAY_KEY_MISMATCH_STORING_CERTIFICATE = '93522';
const AUTHORIZATION_FINGERPRINT_INVALID_CREATED_AT = '93204';
const AUTHORIZATION_FINGERPRINT_INVALID_FORMAT = '93202';
const AUTHORIZATION_FINGERPRINT_INVALID_PUBLIC_KEY = '93205';
const AUTHORIZATION_FINGERPRINT_INVALID_SIGNATURE = '93206';
const AUTHORIZATION_FINGERPRINT_MISSING_FINGERPRINT = '93201';
const AUTHORIZATION_FINGERPRINT_OPTIONS_NOT_ALLOWED_WITHOUT_CUSTOMER = '93207';
const AUTHORIZATION_FINGERPRINT_SIGNATURE_REVOKED = '93203';
const CLIENT_TOKEN_CUSTOMER_DOES_NOT_EXIST = '92804';
const CLIENT_TOKEN_FAIL_ON_DUPLICATE_PAYMENT_METHOD_REQUIRES_CUSTOMER_ID = '92803';
const CLIENT_TOKEN_MAKE_DEFAULT_REQUIRES_CUSTOMER_ID = '92801';
const CLIENT_TOKEN_PROXY_MERCHANT_DOES_NOT_EXIST = '92805';
const CLIENT_TOKEN_UNSUPPORTED_VERSION = '92806';
const CLIENT_TOKEN_VERIFY_CARD_REQUIRES_CUSTOMER_ID = '92802';
const CLIENT_TOKEN_MERCHANT_ACCOUNT_DOES_NOT_EXIST = '92807';
const CREDIT_CARD_BILLING_ADDRESS_CONFLICT = '91701';
const CREDIT_CARD_BILLING_ADDRESS_FORMAT_IS_INVALID = '91744';
const CREDIT_CARD_BILLING_ADDRESS_ID_IS_INVALID = '91702';
const CREDIT_CARD_CANNOT_UPDATE_CARD_USING_PAYMENT_METHOD_NONCE = '91735';
const CREDIT_CARD_CARDHOLDER_NAME_IS_TOO_LONG = '81723';
const CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED = '81703';
const CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED_BY_SUBSCRIPTION_MERCHANT_ACCOUNT = '81718';
const CREDIT_CARD_CUSTOMER_ID_IS_INVALID = '91705';
const CREDIT_CARD_CUSTOMER_ID_IS_REQUIRED = '91704';
const CREDIT_CARD_CVV_IS_INVALID = '81707';
const CREDIT_CARD_CVV_IS_REQUIRED = '81706';
const CREDIT_CARD_CVV_VERIFICATION_FAILED = '81736';
const CREDIT_CARD_DUPLICATE_CARD_EXISTS = '81724';
const CREDIT_CARD_EXPIRATION_DATE_CONFLICT = '91708';
const CREDIT_CARD_EXPIRATION_DATE_IS_INVALID = '81710';
const CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED = '81709';
const CREDIT_CARD_EXPIRATION_DATE_YEAR_IS_INVALID = '81711';
const CREDIT_CARD_EXPIRATION_MONTH_IS_INVALID = '81712';
const CREDIT_CARD_EXPIRATION_YEAR_IS_INVALID = '81713';
const CREDIT_CARD_INVALID_PARAMS_FOR_CREDIT_CARD_UPDATE = '91745';
const CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE = '91727';
const CREDIT_CARD_NUMBER_INVALID_LENGTH = '81716';
const CREDIT_CARD_NUMBER_IS_INVALID = '81715';
const CREDIT_CARD_NUMBER_IS_PROHIBITED = '81750';
const CREDIT_CARD_NUMBER_IS_REQUIRED = '81714';
const CREDIT_CARD_NUMBER_LENGTH_IS_INVALID = '81716';
const CREDIT_CARD_NUMBER_MUST_BE_TEST_NUMBER = '81717';
const CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_IS_INVALID = '91723';
const CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_NOT_ALLOWED = '91729';
const CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_CANNOT_BE_NEGATIVE = '91739';
const CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_FORMAT_IS_INVALID = '91740';
const CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_IS_TOO_LARGE = '91752';
const CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = '91741';
const CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_ID_IS_INVALID = '91728';
const CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_FORBIDDEN = '91743';
const CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_SUSPENDED = '91742';
const CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_CANNOT_BE_SUB_MERCHANT_ACCOUNT = '91755';
const CREDIT_CARD_PAYMENT_METHOD_CONFLICT = '81725';
const CREDIT_CARD_PAYMENT_METHOD_IS_NOT_A_CREDIT_CARD = '91738';
const CREDIT_CARD_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = '91734';
const CREDIT_CARD_PAYMENT_METHOD_NONCE_CONSUMED = '91731';
const CREDIT_CARD_PAYMENT_METHOD_NONCE_LOCKED = '91733';
const CREDIT_CARD_PAYMENT_METHOD_NONCE_UNKNOWN = '91732';
const CREDIT_CARD_POSTAL_CODE_VERIFICATION_FAILED = '81737';
const CREDIT_CARD_TOKEN_FORMAT_IS_INVALID = '91718';
const CREDIT_CARD_TOKEN_INVALID = '91718';
const CREDIT_CARD_TOKEN_IS_IN_USE = '91719';
const CREDIT_CARD_TOKEN_IS_NOT_ALLOWED = '91721';
const CREDIT_CARD_TOKEN_IS_REQUIRED = '91722';
const CREDIT_CARD_TOKEN_IS_TOO_LONG = '91720';
const CREDIT_CARD_VENMO_SDK_PAYMENT_METHOD_CODE_CARD_TYPE_IS_NOT_ACCEPTED = '91726';
const CREDIT_CARD_VERIFICATION_NOT_SUPPORTED_ON_THIS_MERCHANT_ACCOUNT = '91730';
const CUSTOMER_COMPANY_IS_TOO_LONG = '81601';
const CUSTOMER_CUSTOM_FIELD_IS_INVALID = '91602';
const CUSTOMER_CUSTOM_FIELD_IS_TOO_LONG = '81603';
const CUSTOMER_EMAIL_FORMAT_IS_INVALID = '81604';
const CUSTOMER_EMAIL_IS_INVALID = '81604';
const CUSTOMER_EMAIL_IS_REQUIRED = '81606';
const CUSTOMER_EMAIL_IS_TOO_LONG = '81605';
const CUSTOMER_FAX_IS_TOO_LONG = '81607';
const CUSTOMER_FIRST_NAME_IS_TOO_LONG = '81608';
const CUSTOMER_ID_IS_INVAILD = '91610'; //Deprecated
const CUSTOMER_ID_IS_INVALID = '91610';
const CUSTOMER_ID_IS_IN_USE = '91609';
const CUSTOMER_ID_IS_NOT_ALLOWED = '91611';
const CUSTOMER_ID_IS_REQUIRED = '91613';
const CUSTOMER_ID_IS_TOO_LONG = '91612';
const CUSTOMER_LAST_NAME_IS_TOO_LONG = '81613';
const CUSTOMER_PHONE_IS_TOO_LONG = '81614';
const CUSTOMER_VAULTED_PAYMENT_INSTRUMENT_NONCE_BELONGS_TO_DIFFERENT_CUSTOMER = '91617';
const CUSTOMER_WEBSITE_FORMAT_IS_INVALID = '81616';
const CUSTOMER_WEBSITE_IS_INVALID = '81616';
const CUSTOMER_WEBSITE_IS_TOO_LONG = '81615';
const DESCRIPTOR_NAME_FORMAT_IS_INVALID = '92201';
const DESCRIPTOR_PHONE_FORMAT_IS_INVALID = '92202';
const DESCRIPTOR_INTERNATIONAL_NAME_FORMAT_IS_INVALID = '92204';
const DESCRIPTOR_DYNAMIC_DESCRIPTORS_DISABLED = '92203';
const DESCRIPTOR_INTERNATIONAL_PHONE_FORMAT_IS_INVALID = '92205';
const DESCRIPTOR_URL_FORMAT_IS_INVALID = '92206';
const DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE = '95701';
const DISPUTE_CAN_ONLY_REMOVE_EVIDENCE_FROM_OPEN_DISPUTE = '95702';
const DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_DISPUTE = '95703';
const DISPUTE_CAN_ONLY_ACCEPT_OPEN_DISPUTE = '95704';
const DISPUTE_CAN_ONLY_FINALIZE_OPEN_DISPUTE = '95705';
const DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY = '95706';
const DISPUTE_EVIDENCE_CONTENT_DATE_INVALID = '95707';
const DISPUTE_EVIDENCE_CONTENT_TOO_LONG = '95708';
const DISPUTE_EVIDENCE_CONTENT_ARN_TOO_LONG = '95709';
const DISPUTE_EVIDENCE_CONTENT_PHONE_TOO_LONG = '95710';
const DISPUTE_EVIDENCE_CATEGORY_TEXT_ONLY = '95711';
const DISPUTE_EVIDENCE_CATEGORY_DOCUMENT_ONLY = '95712';
const DISPUTE_EVIDENCE_CATEGORY_NOT_FOR_REASON_CODE = '95713';
const DISPUTE_EVIDENCE_CATEGORY_DUPLICATE = '95713';
const DISPUTE_EVIDENCE_CATEGORY_EMAIL_INVALID = '95713';
const DISPUTE_DIGITAL_GOODS_MISSING_EVIDENCE = '95720';
const DISPUTE_DIGITAL_GOODS_MISSING_DOWNLOAD_DATE = '95721';
const DISPUTE_PRIOR_NON_DISPUTED_TRANSACTION_MISSING_ARN = '95722';
const DISPUTE_PRIOR_NON_DISPUTED_TRANSACTION_MISSING_DATE = '95723';
const DISPUTE_RECURRING_TRANSACTION_MISSING_DATE = '95724';
const DISPUTE_RECURRING_TRANSACTION_MISSING_ARN = '95725';
const DISPUTE_VALID_EVIDENCE_REQUIRED_TO_FINALIZE = '95726';
const DOCUMENT_UPLOAD_KIND_IS_INVALID = '84901';
const DOCUMENT_UPLOAD_FILE_IS_TOO_LARGE = '84902';
const DOCUMENT_UPLOAD_FILE_TYPE_IS_INVALID = '84903';
const DOCUMENT_UPLOAD_FILE_IS_MALFORMED_OR_ENCRYPTED = '84904';
const FAILED_AUTH_ADJUSTMENT_ALLOW_RETRY = '95603';
const FAILED_AUTH_ADJUSTMENT_HARD_DECLINE = '95602';
const FINAL_AUTH_SUBMIT_FOR_SETTLEMENT_FOR_DIFFERENT_AMOUNT = '95601';
const INDUSTRY_DATA_INDUSTRY_TYPE_IS_INVALID = '93401';
const INDUSTRY_DATA_LODGING_EMPTY_DATA = '93402';
const INDUSTRY_DATA_LODGING_FOLIO_NUMBER_IS_INVALID = '93403';
const INDUSTRY_DATA_LODGING_CHECK_IN_DATE_IS_INVALID = '93404';
const INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_IS_INVALID = '93405';
const INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_MUST_FOLLOW_CHECK_IN_DATE = '93406';
const INDUSTRY_DATA_LODGING_UNKNOWN_DATA_FIELD = '93407';
const INDUSTRY_DATA_TRAVEL_CRUISE_EMPTY_DATA = '93408';
const INDUSTRY_DATA_TRAVEL_CRUISE_UNKNOWN_DATA_FIELD = '93409';
const INDUSTRY_DATA_TRAVEL_CRUISE_TRAVEL_PACKAGE_IS_INVALID = '93410';
const INDUSTRY_DATA_TRAVEL_CRUISE_DEPARTURE_DATE_IS_INVALID = '93411';
const INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_IN_DATE_IS_INVALID = '93412';
const INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_OUT_DATE_IS_INVALID = '93413';
const TRANSACTION_LINE_ITEM_COMMODITY_CODE_IS_TOO_LONG = '95801';
const TRANSACTION_LINE_ITEM_DESCRIPTION_IS_TOO_LONG = '95803';
const TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_FORMAT_IS_INVALID = '95804';
const TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_IS_TOO_LARGE = '95805';
const TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_MUST_BE_GREATER_THAN_ZERO = '95806'; // Deprecated as the amount may be zero. Use TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_CANNOT_BE_ZERO.
const TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_CANNOT_BE_NEGATIVE = '95806';
const TRANSACTION_LINE_ITEM_KIND_IS_INVALID = '95807';
const TRANSACTION_LINE_ITEM_KIND_IS_REQUIRED = '95808';
const TRANSACTION_LINE_ITEM_NAME_IS_REQUIRED = '95822';
const TRANSACTION_LINE_ITEM_NAME_IS_TOO_LONG = '95823';
const TRANSACTION_LINE_ITEM_PRODUCT_CODE_IS_TOO_LONG = '95809';
const TRANSACTION_LINE_ITEM_QUANTITY_FORMAT_IS_INVALID = '95810';
const TRANSACTION_LINE_ITEM_QUANTITY_IS_REQUIRED = '95811';
const TRANSACTION_LINE_ITEM_QUANTITY_IS_TOO_LARGE = '95812';
const TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_FORMAT_IS_INVALID = '95813';
const TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_IS_REQUIRED = '95814';
const TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_IS_TOO_LARGE = '95815';
const TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_MUST_BE_GREATER_THAN_ZERO = '95816';
const TRANSACTION_LINE_ITEM_UNIT_AMOUNT_FORMAT_IS_INVALID = '95817';
const TRANSACTION_LINE_ITEM_UNIT_AMOUNT_IS_REQUIRED = '95818';
const TRANSACTION_LINE_ITEM_UNIT_AMOUNT_IS_TOO_LARGE = '95819';
const TRANSACTION_LINE_ITEM_UNIT_AMOUNT_MUST_BE_GREATER_THAN_ZERO = '95820';
const TRANSACTION_LINE_ITEM_UNIT_OF_MEASURE_IS_TOO_LONG = '95821';
const TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_FORMAT_IS_INVALID = '95824';
const TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_IS_TOO_LARGE = '95825';
const TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_MUST_BE_GREATER_THAN_ZERO = '95826'; // Deprecated as the amount may be zero. Use TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_CANNOT_BE_ZERO.
const TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_CANNOT_BE_NEGATIVE = '95826';
const TRANSACTION_LINE_ITEM_TAX_AMOUNT_FORMAT_IS_INVALID = '95827';
const TRANSACTION_LINE_ITEM_TAX_AMOUNT_IS_TOO_LARGE = '95828';
const TRANSACTION_LINE_ITEM_TAX_AMOUNT_CANNOT_BE_NEGATIVE = '95829';
const MERCHANT_COUNTRY_CANNOT_BE_BLANK = '83603';
const MERCHANT_COUNTRY_CODE_ALPHA2_IS_INVALID = '93607';
const MERCHANT_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = '93606';
const MERCHANT_COUNTRY_CODE_ALPHA3_IS_INVALID = '93605';
const MERCHANT_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = '93604';
const MERCHANT_COUNTRY_CODE_NUMERIC_IS_INVALID = '93609';
const MERCHANT_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = '93608';
const MERCHANT_COUNTRY_NAME_IS_INVALID = '93611';
const MERCHANT_COUNTRY_NAME_IS_NOT_ACCEPTED = '93610';
const MERCHANT_CURRENCIES_ARE_INVALID = '93614';
const MERCHANT_EMAIL_FORMAT_IS_INVALID = '93602';
const MERCHANT_EMAIL_IS_REQUIRED = '83601';
const MERCHANT_INCONSISTENT_COUNTRY = '93612';
const MERCHANT_ACCOUNT_PAYMENT_METHODS_ARE_INVALID = '93613';
const MERCHANT_PAYMENT_METHODS_ARE_NOT_ALLOWED = '93615';
const MERCHANT_MERCHANT_ACCOUNT_EXISTS_FOR_CURRENCY = '93616';
const MERCHANT_CURRENCY_IS_REQUIRED = '93617';
const MERCHANT_CURRENCY_IS_INVALID = '93618';
const MERCHANT_NO_MERCHANT_ACCOUNTS = '93619';
const MERCHANT_MERCHANT_ACCOUNT_EXISTS_FOR_ID = '93620';
const MERCHANT_MERCHANT_ACCOUNT_NOT_AUTH_ONBOARDED = '93621';
const MERCHANT_ACCOUNT_ID_FORMAT_IS_INVALID = '82603';
const MERCHANT_ACCOUNT_ID_IS_IN_USE = '82604';
const MERCHANT_ACCOUNT_ID_IS_NOT_ALLOWED = '82605';
const MERCHANT_ACCOUNT_ID_IS_TOO_LONG = '82602';
const MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_INVALID = '82607';
const MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED = '82606';
const MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_MUST_BE_ACTIVE = '82608';
const MERCHANT_ACCOUNT_TOS_ACCEPTED_IS_REQUIRED = '82610';
const MERCHANT_ACCOUNT_CANNOT_BE_UPDATED = '82674';
const MERCHANT_ACCOUNT_DECLINED = '82626';
const MERCHANT_ACCOUNT_DECLINED_MASTER_CARD_MATCH = '82622';
const MERCHANT_ACCOUNT_DECLINED_OFAC = '82621';
const MERCHANT_ACCOUNT_DECLINED_FAILED_KYC = '82623';
const MERCHANT_ACCOUNT_DECLINED_SSN_INVALID = '82624';
const MERCHANT_ACCOUNT_DECLINED_SSN_MATCHES_DECEASED = '82625';
const MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = '82675';
const MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = '82676';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_REQUIRED = '82614';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_INVALID = '82631';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_REQUIRED_WITH_TAX_ID = '82633';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_REQUIRED = '82612';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED = '82626'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_MASTER_CARD_MATCH = '82622'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_OFAC = '82621'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_FAILED_KYC = '82623'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_INVALID = '82624'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_MATCHES_DECEASED = '82625'; // Keep for backwards compatibility
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_INVALID = '82616';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_INVALID = '82627';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_REQUIRED = '82609';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_INVALID = '82628';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_REQUIRED = '82611';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_PHONE_IS_INVALID = '82636';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_INVALID = '82635';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_REQUIRED = '82613';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_SSN_IS_INVALID = '82615';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_INVALID = '82632';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_REQUIRED_WITH_COMPANY_NAME = '82634';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_INVALID = '82663';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_INVALID = '82664';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_REQUIRED = '82665';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_INVALID = '82670';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_MUST_BE_BLANK = '82673';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_LOCALITY_IS_REQUIRED = '82618';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_INVALID = '82630';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_REQUIRED = '82619';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_REQUIRED = '82620';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_INVALID = '82629';
const MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_REQUIRED = '82617';
const MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID = '82646';
const MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID = '82647';
const MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_REQUIRED_WITH_LEGAL_NAME = '82648';
const MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_REQUIRED_WITH_TAX_ID = '82669';
const MERCHANT_ACCOUNT_BUSINESS_TAX_ID_MUST_BE_BLANK = '82672';
const MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID = '82677';
const MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID = '82684';
const MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID = '82685';
const MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID = '82686';
const MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED = '82637';
const MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED = '82638';
const MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED = '82639';
const MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID = '82642';
const MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID = '82643';
const MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID = '82644';
const MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID = '82645';
const MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID = '82656';
const MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID = '82666';
const MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED = '82667';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED = '82657';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED = '82658';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED = '82659';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED = '82660';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID = '82661';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID = '82662';
const MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID = '82668';
const MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_REQUIRED = '82640';
const MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_REQUIRED = '82641';
const MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID = '82649';
const MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID = '82671';
const MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED = '82678';
const MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID = '82679';
const MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_REQUIRED = '82680';
const MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID = '82681';
const MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_REQUIRED = '82682';
const MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID = '82683';
const OAUTH_INVALID_GRANT = '93801';
const OAUTH_INVALID_CREDENTIALS = '93802';
const OAUTH_INVALID_SCOPE = '93803';
const OAUTH_INVALID_REQUEST = '93804';
const OAUTH_UNSUPPORTED_GRANT_TYPE = '93805';
const PAYMENT_METHOD_CANNOT_FORWARD_PAYMENT_METHOD_TYPE = '93106';
const PAYMENT_METHOD_CUSTOMER_ID_IS_INVALID = '93105';
const PAYMENT_METHOD_CUSTOMER_ID_IS_REQUIRED = '93104';
const PAYMENT_METHOD_NONCE_IS_INVALID = '93102';
const PAYMENT_METHOD_NONCE_IS_REQUIRED = '93103';
const PAYMENT_METHOD_PAYMENT_METHOD_NONCE_CONSUMED = '93107';
const PAYMENT_METHOD_PAYMENT_METHOD_NONCE_UNKNOWN = '93108';
const PAYMENT_METHOD_PAYMENT_METHOD_NONCE_LOCKED = '93109';
const PAYMENT_METHOD_PAYMENT_METHOD_PARAMS_ARE_REQUIRED = '93101';
const PAYMENT_METHOD_NO_LONGER_SUPPORTED = '93117';
const PAYMENT_METHOD_OPTIONS_US_BANK_ACCOUNT_VERIFICATION_METHOD_IS_INVALID = '93121';
const PAYPAL_ACCOUNT_AUTH_EXPIRED = '92911';
const PAYPAL_ACCOUNT_CANNOT_HAVE_BOTH_ACCESS_TOKEN_AND_CONSENT_CODE = '82903';
const PAYPAL_ACCOUNT_CANNOT_HAVE_FUNDING_SOURCE_WITHOUT_ACCESS_TOKEN = '92912';
const PAYPAL_ACCOUNT_CANNOT_UPDATE_PAYPAL_ACCOUNT_USING_PAYMENT_METHOD_NONCE = '92914';
const PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT = '82902';
const PAYPAL_ACCOUNT_CONSENT_CODE_OR_ACCESS_TOKEN_IS_REQUIRED = '82901';
const PAYPAL_ACCOUNT_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = '82905';
const PAYPAL_ACCOUNT_INVALID_FUNDING_SOURCE_SELECTION = '92913';
const PAYPAL_ACCOUNT_INVALID_PARAMS_FOR_PAYPAL_ACCOUNT_UPDATE = '92915';
const PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_CONSUMED = '92907';
const PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_LOCKED = '92909';
const PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_UNKNOWN = '92908';
const PAYPAL_ACCOUNT_PAYPAL_ACCOUNTS_ARE_NOT_ACCEPTED = '82904';
const PAYPAL_ACCOUNT_PAYPAL_COMMUNICATION_ERROR = '92910';
const PAYPAL_ACCOUNT_TOKEN_IS_IN_USE = '92906';
const SEPA_BANK_ACCOUNT_ACCOUNT_HOLDER_NAME_IS_REQUIRED = '93003';
const SEPA_BANK_ACCOUNT_BIC_IS_REQUIRED = '93002';
const SEPA_BANK_ACCOUNT_IBAN_IS_REQUIRED = '93001';
const SEPA_MANDATE_ACCOUNT_HOLDER_NAME_IS_REQUIRED = '83301';
const SEPA_MANDATE_BIC_INVALID_CHARACTER = '83306';
const SEPA_MANDATE_BIC_IS_REQUIRED = '83302';
const SEPA_MANDATE_BIC_LENGTH_IS_INVALID = '83307';
const SEPA_MANDATE_BIC_UNSUPPORTED_COUNTRY = '83308';
const SEPA_MANDATE_BILLING_ADDRESS_CONFLICT = '93311';
const SEPA_MANDATE_BILLING_ADDRESS_ID_IS_INVALID = '93312';
const SEPA_MANDATE_IBAN_INVALID_CHARACTER = '83305';
const SEPA_MANDATE_IBAN_INVALID_FORMAT = '83310';
const SEPA_MANDATE_IBAN_IS_REQUIRED = '83303';
const SEPA_MANDATE_IBAN_UNSUPPORTED_COUNTRY = '83309';
const SEPA_MANDATE_TYPE_IS_REQUIRED = '93304';
const SEPA_MANDATE_TYPE_IS_INVALID = '93313';
const SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_INVALID = '82302';
const SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_REQUIRED = '82301';
const SETTLEMENT_BATCH_SUMMARY_CUSTOM_FIELD_IS_INVALID = '82303';
const SUBSCRIPTION_BILLING_DAY_OF_MONTH_CANNOT_BE_UPDATED = '91918';
const SUBSCRIPTION_BILLING_DAY_OF_MONTH_IS_INVALID = '91914';
const SUBSCRIPTION_BILLING_DAY_OF_MONTH_MUST_BE_NUMERIC = '91913';
const SUBSCRIPTION_CANNOT_ADD_DUPLICATE_ADDON_OR_DISCOUNT = '91911';
const SUBSCRIPTION_CANNOT_EDIT_CANCELED_SUBSCRIPTION = '81901';
const SUBSCRIPTION_CANNOT_EDIT_EXPIRED_SUBSCRIPTION = '81910';
const SUBSCRIPTION_CANNOT_EDIT_PRICE_CHANGING_FIELDS_ON_PAST_DUE_SUBSCRIPTION = '91920';
const SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_IN_THE_PAST = '91916';
const SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_UPDATED = '91919';
const SUBSCRIPTION_FIRST_BILLING_DATE_IS_INVALID = '91915';
const SUBSCRIPTION_ID_IS_IN_USE = '81902';
const SUBSCRIPTION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = '91908';
const SUBSCRIPTION_INCONSISTENT_START_DATE = '91917';
const SUBSCRIPTION_INVALID_REQUEST_FORMAT = '91921';
const SUBSCRIPTION_MERCHANT_ACCOUNT_ID_IS_INVALID = '91901';
const SUBSCRIPTION_MISMATCH_CURRENCY_ISO_CODE = '91923';
const SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = '91912';
const SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_IS_TOO_SMALL = '91909';
const SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = '91907';
const SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_NUMERIC = '91906';
const SUBSCRIPTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = '91924';
const SUBSCRIPTION_PAYMENT_METHOD_NONCE_IS_INVALID = '91925';
const SUBSCRIPTION_PAYMENT_METHOD_NONCE_NOT_ASSOCIATED_WITH_CUSTOMER = '91926';
const SUBSCRIPTION_PAYMENT_METHOD_NONCE_UNVAULTED_CARD_IS_NOT_ACCEPTED = '91927';
const SUBSCRIPTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = '91902';
const SUBSCRIPTION_PAYMENT_METHOD_TOKEN_IS_INVALID = '91903';
const SUBSCRIPTION_PAYMENT_METHOD_TOKEN_NOT_ASSOCIATED_WITH_CUSTOMER = '91905';
const SUBSCRIPTION_PLAN_BILLING_FREQUENCY_CANNOT_BE_UPDATED = '91922';
const SUBSCRIPTION_PLAN_ID_IS_INVALID = '91904';
const SUBSCRIPTION_PRICE_CANNOT_BE_BLANK = '81903';
const SUBSCRIPTION_PRICE_FORMAT_IS_INVALID = '81904';
const SUBSCRIPTION_PRICE_IS_TOO_LARGE = '81923';
const SUBSCRIPTION_STATUS_IS_CANCELED = '81905';
const SUBSCRIPTION_TOKEN_FORMAT_IS_INVALID = '81906';
const SUBSCRIPTION_TRIAL_DURATION_FORMAT_IS_INVALID = '81907';
const SUBSCRIPTION_TRIAL_DURATION_IS_REQUIRED = '81908';
const SUBSCRIPTION_TRIAL_DURATION_UNIT_IS_INVALID = '81909';
const SUBSCRIPTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_INSTRUMENT_TYPE = '91930';
const SUBSCRIPTION_PAYMENT_METHOD_NONCE_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = '91929';
const SUBSCRIPTION_PAYMENT_METHOD_TOKEN_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = '91928';
const SUBSCRIPTION_MODIFICATION_AMOUNT_CANNOT_BE_BLANK = '92003';
const SUBSCRIPTION_MODIFICATION_AMOUNT_IS_INVALID = '92002';
const SUBSCRIPTION_MODIFICATION_AMOUNT_IS_TOO_LARGE = '92023';
const SUBSCRIPTION_MODIFICATION_CANNOT_EDIT_MODIFICATIONS_ON_PAST_DUE_SUBSCRIPTION = '92022';
const SUBSCRIPTION_MODIFICATION_CANNOT_UPDATE_AND_REMOVE = '92015';
const SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INCORRECT_KIND = '92020';
const SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INVALID = '92011';
const SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_REQUIRED = '92012';
const SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INCORRECT_KIND = '92021';
const SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INVALID = '92025';
const SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_NOT_PRESENT = '92016';
const SUBSCRIPTION_MODIFICATION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = '92018';
const SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_INVALID = '92013';
const SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_REQUIRED = '92014';
const SUBSCRIPTION_MODIFICATION_MISSING = '92024';
const SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = '92017';
const SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_IS_INVALID = '92005';
const SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = '92019';
const SUBSCRIPTION_MODIFICATION_QUANTITY_CANNOT_BE_BLANK = '92004';
const SUBSCRIPTION_MODIFICATION_QUANTITY_IS_INVALID = '92001';
const SUBSCRIPTION_MODIFICATION_QUANTITY_MUST_BE_GREATER_THAN_ZERO = '92010';
const TRANSACTION_AMOUNT_CANNOT_BE_NEGATIVE = '81501';
const TRANSACTION_AMOUNT_DOES_NOT_MATCH3_D_SECURE_AMOUNT = '91585';
const TRANSACTION_AMOUNT_DOES_NOT_MATCH_IDEAL_PAYMENT_AMOUNT = '915144';
const TRANSACTION_AMOUNT_FORMAT_IS_INVALID = '81503';
const TRANSACTION_AMOUNT_IS_INVALID = '81503';
const TRANSACTION_AMOUNT_IS_REQUIRED = '81502';
const TRANSACTION_AMOUNT_IS_TOO_LARGE = '81528';
const TRANSACTION_AMOUNT_MUST_BE_GREATER_THAN_ZERO = '81531';
const TRANSACTION_BILLING_ADDRESS_CONFLICT = '91530';
const TRANSACTION_CANNOT_BE_VOIDED = '91504';
const TRANSACTION_CANNOT_CANCEL_RELEASE = '91562';
const TRANSACTION_CANNOT_CLONE_CREDIT = '91543';
const TRANSACTION_CANNOT_CLONE_MARKETPLACE_TRANSACTION = '915137';
const TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_PAYPAL_ACCOUNT = '91573';
const TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_VAULT_CREDIT_CARD = '91540';
const TRANSACTION_CANNOT_CLONE_UNSUCCESSFUL_TRANSACTION = '91542';
const TRANSACTION_CANNOT_CLONE_VOICE_AUTHORIZATIONS = '91541';
const TRANSACTION_CANNOT_HOLD_IN_ESCROW = '91560';
const TRANSACTION_CANNOT_PARTIALLY_REFUND_ESCROWED_TRANSACTION = '91563';
const TRANSACTION_CANNOT_REFUND_CREDIT = '91505';
const TRANSACTION_CANNOT_REFUND_SETTLING_TRANSACTION = '91574';
const TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED = '91506';
const TRANSACTION_CANNOT_REFUND_WITH_PENDING_MERCHANT_ACCOUNT = '91559';
const TRANSACTION_CANNOT_REFUND_WITH_SUSPENDED_MERCHANT_ACCOUNT = '91538';
const TRANSACTION_CANNOT_RELEASE_FROM_ESCROW = '91561';
const TRANSACTION_CANNOT_SIMULATE_SETTLEMENT = '91575';
const TRANSACTION_CANNOT_SUBMIT_FOR_PARTIAL_SETTLEMENT = '915103';
const TRANSACTION_CANNOT_SUBMIT_FOR_SETTLEMENT = '91507';
const TRANSACTION_CANNOT_UPDATE_DETAILS_NOT_SUBMITTED_FOR_SETTLEMENT = '915129';
const TRANSACTION_CHANNEL_IS_TOO_LONG = '91550';
const TRANSACTION_CREDIT_CARD_IS_REQUIRED = '91508';
const TRANSACTION_CUSTOMER_DEFAULT_PAYMENT_METHOD_CARD_TYPE_IS_NOT_ACCEPTED = '81509';
const TRANSACTION_CUSTOMER_DOES_NOT_HAVE_CREDIT_CARD = '91511';
const TRANSACTION_CUSTOMER_ID_IS_INVALID = '91510';
const TRANSACTION_CUSTOM_FIELD_IS_INVALID = '91526';
const TRANSACTION_CUSTOM_FIELD_IS_TOO_LONG = '81527';
const TRANSACTION_HAS_ALREADY_BEEN_REFUNDED = '91512';
const TRANSACTION_IDEAL_PAYMENT_NOT_COMPLETE = '815141';
const TRANSACTION_IDEAL_PAYMENTS_CANNOT_BE_VAULTED = '915150';
const TRANSACTION_LINE_ITEMS_EXPECTED = '915158';
const TRANSACTION_TOO_MANY_LINE_ITEMS = '915157';
const TRANSACTION_DISCOUNT_AMOUNT_FORMAT_IS_INVALID = '915159';
const TRANSACTION_DISCOUNT_AMOUNT_CANNOT_BE_NEGATIVE = '915160';
const TRANSACTION_DISCOUNT_AMOUNT_IS_TOO_LARGE = '915161';
const TRANSACTION_SHIPPING_AMOUNT_FORMAT_IS_INVALID = '915162';
const TRANSACTION_SHIPPING_AMOUNT_CANNOT_BE_NEGATIVE = '915163';
const TRANSACTION_SHIPPING_AMOUNT_IS_TOO_LARGE = '915164';
const TRANSACTION_SHIPS_FROM_POSTAL_CODE_IS_TOO_LONG = '915165';
const TRANSACTION_SHIPS_FROM_POSTAL_CODE_IS_INVALID = '915166';
const TRANSACTION_SHIPS_FROM_POSTAL_CODE_INVALID_CHARACTERS = '915167';
const TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_MATCH3_D_SECURE_MERCHANT_ACCOUNT = '91584';
const TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_MATCH_IDEAL_PAYMENT_MERCHANT_ACCOUNT = '915143';
const TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_MOTO = '91558';
const TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_REFUNDS = '91547';
const TRANSACTION_MERCHANT_ACCOUNT_ID_IS_INVALID = '91513';
const TRANSACTION_MERCHANT_ACCOUNT_IS_SUSPENDED = '91514';
const TRANSACTION_MERCHANT_ACCOUNT_NAME_IS_INVALID = '91513'; //Deprecated
const TRANSACTION_OPTIONS_PAY_PAL_CUSTOM_FIELD_TOO_LONG = '91580';
const TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_CLONING = '91544';
const TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_PAYPAL_UNILATERAL = '91582';
const TRANSACTION_OPTIONS_USE_BILLING_FOR_SHIPPING_DISABLED = '91572';
const TRANSACTION_OPTIONS_VAULT_IS_DISABLED = '91525';
const TRANSACTION_ORDER_ID_DOES_NOT_MATCH_IDEAL_PAYMENT_ORDER_ID = '91503';
const TRANSACTION_ORDER_ID_IS_REQUIRED_WITH_IDEAL_PAYMENT = '91502';
const TRANSACTION_ORDER_ID_IS_TOO_LONG = '91501';
const TRANSACTION_PAYMENT_INSTRUMENT_NOT_SUPPORTED_BY_MERCHANT_ACCOUNT = '91577';
const TRANSACTION_PAYMENT_INSTRUMENT_TYPE_IS_NOT_ACCEPTED = '915101';
const TRANSACTION_PAYMENT_METHOD_CONFLICT = '91515';
const TRANSACTION_PAYMENT_METHOD_CONFLICT_WITH_VENMO_SDK = '91549';
const TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_CUSTOMER = '91516';
const TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_SUBSCRIPTION = '91527';
const TRANSACTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = '91567';
const TRANSACTION_PAYMENT_METHOD_NONCE_CONSUMED = '91564';
const TRANSACTION_PAYMENT_METHOD_NONCE_HAS_NO_VALID_PAYMENT_INSTRUMENT_TYPE = '91569';
const TRANSACTION_PAYMENT_METHOD_NONCE_LOCKED = '91566';
const TRANSACTION_PAYMENT_METHOD_NONCE_UNKNOWN = '91565';
const TRANSACTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = '91517';
const TRANSACTION_PAYMENT_METHOD_TOKEN_IS_INVALID = '91518';
const TRANSACTION_PAYPAL_NOT_ENABLED = '91576';
const TRANSACTION_PAY_PAL_AUTH_EXPIRED = '91579';
const TRANSACTION_PAY_PAL_VAULT_RECORD_MISSING_DATA = '91583';
const TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_CANNOT_BE_SET = '91519';
const TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_IS_INVALID = '81520';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_AUTHS = '915104';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_CREDITS = '91546';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_PARTIAL_SETTLEMENT = '915102';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_UPDATING_ORDER_ID = '915107';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_UPDATING_DESCRIPTOR = '915108';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_UPDATING_DETAILS = '915130';
const TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_VOICE_AUTHORIZATIONS = '91545';
const TRANSACTION_PURCHASE_ORDER_NUMBER_IS_INVALID = '91548';
const TRANSACTION_PURCHASE_ORDER_NUMBER_IS_TOO_LONG = '91537';
const TRANSACTION_REFUND_AMOUNT_IS_TOO_LARGE = '91521';
const TRANSACTION_SERVICE_FEE_AMOUNT_CANNOT_BE_NEGATIVE = '91554';
const TRANSACTION_SERVICE_FEE_AMOUNT_FORMAT_IS_INVALID = '91555';
const TRANSACTION_SERVICE_FEE_AMOUNT_IS_TOO_LARGE = '91556';
const TRANSACTION_SERVICE_FEE_AMOUNT_NOT_ALLOWED_ON_MASTER_MERCHANT_ACCOUNT = '91557';
const TRANSACTION_SERVICE_FEE_IS_NOT_ALLOWED_ON_CREDITS = '91552';
const TRANSACTION_SERVICE_FEE_NOT_ACCEPTED_FOR_PAYPAL = '91578';
const TRANSACTION_SETTLEMENT_AMOUNT_IS_LESS_THAN_SERVICE_FEE_AMOUNT = '91551';
const TRANSACTION_SETTLEMENT_AMOUNT_IS_TOO_LARGE = '91522';
const TRANSACTION_SHIPPING_ADDRESS_DOESNT_MATCH_CUSTOMER = '91581';
const TRANSACTION_SUBSCRIPTION_DOES_NOT_BELONG_TO_CUSTOMER = '91529';
const TRANSACTION_SUBSCRIPTION_ID_IS_INVALID = '91528';
const TRANSACTION_SUBSCRIPTION_STATUS_MUST_BE_PAST_DUE = '91531';
const TRANSACTION_SUB_MERCHANT_ACCOUNT_REQUIRES_SERVICE_FEE_AMOUNT = '91553';
const TRANSACTION_TAX_AMOUNT_CANNOT_BE_NEGATIVE = '81534';
const TRANSACTION_TAX_AMOUNT_FORMAT_IS_INVALID = '81535';
const TRANSACTION_TAX_AMOUNT_IS_TOO_LARGE = '81536';
const TRANSACTION_THREE_D_SECURE_AUTHENTICATION_FAILED = '81571';
const TRANSACTION_THREE_D_SECURE_TOKEN_IS_INVALID = '91568';
const TRANSACTION_THREE_D_SECURE_TRANSACTION_DATA_DOESNT_MATCH_VERIFY = '91570';
const TRANSACTION_THREE_D_SECURE_ECI_FLAG_IS_REQUIRED = '915113';
const TRANSACTION_THREE_D_SECURE_CAVV_IS_REQUIRED = '915116';
const TRANSACTION_THREE_D_SECURE_XID_IS_REQUIRED = '915115';
const TRANSACTION_THREE_D_SECURE_ECI_FLAG_IS_INVALID = '915114';
const TRANSACTION_THREE_D_SECURE_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_CARD_TYPE = '915131';
const TRANSACTION_TYPE_IS_INVALID = '91523';
const TRANSACTION_TYPE_IS_REQUIRED = '91524';
const TRANSACTION_UNSUPPORTED_VOICE_AUTHORIZATION = '91539';
const TRANSACTION_US_BANK_ACCOUNT_NONCE_MUST_BE_PLAID_VERIFIED = '915171';
const TRANSACTION_US_BANK_ACCOUNT_NOT_VERIFIED = '915172';
const TRANSACTION_TRANSACTION_SOURCE_IS_INVALID = '915133';
const US_BANK_ACCOUNT_VERIFICATION_NOT_CONFIRMABLE = '96101';
const US_BANK_ACCOUNT_VERIFICATION_MUST_BE_MICRO_TRANSFERS_VERIFICATION = '96102';
const US_BANK_ACCOUNT_VERIFICATION_AMOUNTS_DO_NOT_MATCH = '96103';
const US_BANK_ACCOUNT_VERIFICATION_TOO_MANY_CONFIRMATION_ATTEMPTS = '96104';
const US_BANK_ACCOUNT_VERIFICATION_UNABLE_TO_CONFIRM_DEPOSIT_AMOUNTS = '96105';
const US_BANK_ACCOUNT_VERIFICATION_INVALID_DEPOSIT_AMOUNTS = '96106';
const VERIFICATION_OPTIONS_AMOUNT_CANNOT_BE_NEGATIVE = '94201';
const VERIFICATION_OPTIONS_AMOUNT_FORMAT_IS_INVALID = '94202';
const VERIFICATION_OPTIONS_AMOUNT_IS_TOO_LARGE = '94207';
const VERIFICATION_OPTIONS_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = '94203';
const VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_ID_IS_INVALID = '94204';
const VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_SUSPENDED = '94205';
const VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_FORBIDDEN = '94206';
const VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_CANNOT_BE_SUB_MERCHANT_ACCOUNT = '94208';
}
class_alias('Braintree\Error\Codes', 'Braintree_Error_Codes');
| priyankamackwan/fit.lara | app/Libraries/vendor/braintree/braintree_php/lib/Braintree/Error/Codes.php | PHP | mit | 50,875 |
var xml = require('xmlbuilder');
var fs = require('fs');
/**
* Function is used to create plis file which is required for downloading ios app.
* @param {string} name app name
* @param {string} path path to application
* @param {string} title title for alert
* @param {Function} callback function which will be called when plist file is created
*/
function creatPlist(name, path, title, callback){
var d = xml.create('plist', {'version':'1.0'})
.ele('dict')
.ele('key','items').up()
.ele('array')
.ele('dict')
.ele('key','assets').up()
.ele('array')
.ele('dict')
.ele('key','kind').up()
.ele('string','software-package').up()
.ele('key','url').up()
.ele('string',path).up()
.up()
.up()
.ele('key','metadata').up()
.ele('dict')
.ele('key','bundle-identifier').up()
.ele('string', name).up()
.ele('key', 'kind').up()
.ele('string','software').up()
.ele('key','title').up()
.ele('string', title)
.up()
.up()
.up()
.up()
.up()
.end({ pretty: true});
//generate unique file path:) use this for now.
var filePath = './processing/file' + new Date().getMilliseconds() + '.plist';
fs.writeFile(filePath, d, function(err){
callback(err,filePath);
});
console.log(xml);
}
//--------------EXPORTS---------------//
exports.creatPlist = creatPlist;
| dimko1/ohmystore | server/utils/utils.xml.js | JavaScript | mit | 1,412 |
package math;
import util.IReplicable;
public class Vector3 implements IReplicable<Vector3> {
private static final float MIN_TOLERANCE = (float) 1E-9;
public float x;
public float y;
public float z;
public static Vector3 of(float x, float y, float z) {
Vector3 vector = new Vector3();
vector.x = x;
vector.y = y;
vector.z = z;
return vector;
}
public static Vector3 getUnitX() {
Vector3 vector = new Vector3();
vector.x = 1;
return vector;
}
public static Vector3 getUnitY() {
Vector3 vector = new Vector3();
vector.y = 1;
return vector;
}
public static Vector3 getUnitZ() {
Vector3 vector = new Vector3();
vector.z = 1;
return vector;
}
public static Vector3 getUnit() {
Vector3 vector = new Vector3();
vector.x = 1;
vector.y = 1;
vector.z = 1;
return vector;
}
public boolean isUnitX() {
return (x == 1) && (y == 0) && (z == 0);
}
public boolean isUnitY() {
return (x == 0) && (y == 1) && (z == 0);
}
public boolean isUnitZ() {
return (x == 0) && (y == 0) && (z == 1);
}
public boolean isUnit() {
return (x == 1) && (y == 1) && (z == 1);
}
public float lengthSquared() {
return (x * x) + (y * y) + (z * z);
}
public float length() {
return (float) Math.sqrt(lengthSquared());
}
public float inverseLength() {
return 1f / length();
}
public static Vector3 add(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
add(result, a, b);
return result;
}
public static void add(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x + b.x;
result.y = a.y + b.y;
result.z = a.z + b.z;
}
public static Vector3 subtract(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
subtract(result, a, b);
return result;
}
public static void subtract(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x - b.x;
result.y = a.y - b.y;
result.z = a.z - b.z;
}
public static Vector3 multiply(Vector3 a, float scalar) {
Vector3 result = new Vector3();
multiply(result, a, scalar);
return result;
}
public static void multiply(Vector3 result, Vector3 a, float scalar) {
result.x = a.x * scalar;
result.y = a.y * scalar;
result.z = a.z * scalar;
}
public static Vector3 divide(Vector3 a, float scalar) {
Vector3 result = new Vector3();
divide(result, a, scalar);
return result;
}
public static void divide(Vector3 result, Vector3 a, float scalar) {
float multiplier = (scalar <= MIN_TOLERANCE)
? 0
: 1f / scalar;
multiply(result, a, multiplier);
}
public static float dot(Vector3 a, Vector3 b) {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
public static Vector3 cross(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
cross(result, a, b);
return result;
}
public static void cross(Vector3 result, Vector3 a, Vector3 b) {
float x = (a.y * b.z) - (a.z * b.y);
float y = (a.z * b.x) - (a.x * b.z);
float z = (a.x * b.y) - (a.y * b.x);
result.x = x;
result.y = y;
result.z = z;
}
public static Vector3 negate(Vector3 a) {
Vector3 result = new Vector3();
negate(result, a);
return result;
}
public static void negate(Vector3 result, Vector3 a) {
result.x = -a.x;
result.y = -a.y;
result.z = -a.z;
}
public static Vector3 normalise(Vector3 a) {
Vector3 result = new Vector3();
normalise(result, a);
return result;
}
public static void normalise(Vector3 result, Vector3 a) {
float sumSq = (a.x * a.x) + (a.y * a.y) + (a.z * a.z);
if (sumSq <= MIN_TOLERANCE) {
result.x = 0;
result.y = 1;
result.z = 0;
} else {
double sum = Math.sqrt(sumSq);
multiply(result, a, (float) (1.0 / sum));
}
}
@Override
public Vector3 createBlank() {
return new Vector3();
}
@Override
public void copyFrom(Vector3 master) {
this.x = master.x;
this.y = master.y;
this.z = master.z;
}
}
| NathanJAdams/verJ | src/math/Vector3.java | Java | mit | 4,539 |
using Phaxio.Examples.ReceiveCallback.Models;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Web.Mvc;
namespace Phaxio.Examples.ReceiveCallback.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ObjectCache cache = MemoryCache.Default;
var faxList = cache["Callbacks"] as List<FaxReceipt>;
return View(faxList);
}
}
} | phaxio/phaxio-dotnet | Phaxio.Examples.ReceiveCallback/Controllers/HomeController.cs | C# | mit | 461 |
'use strict';
define([],
function($) {
var Util = class {
static charToLineCh(string, char) {
var stringUpToChar = string.substr(0, char);
var lines = stringUpToChar.split("\n");
return {
line: lines.length - 1,
ch: lines[lines.length - 1].length
};
}
};
return Util;
}); | pixelmaid/DynamicBrushes | javascript/app/Util.js | JavaScript | mit | 319 |
package org.usfirst.frc.team5518.robot.subsystems;
import org.usfirst.frc.team5518.robot.RobotMap;
import org.usfirst.frc.team5518.robot.commands.ArcadeDriveJoystick;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class DrivingSys extends Subsystem {
private RobotDrive robotDrive;
public DrivingSys() {
super();
robotDrive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR,
RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(new ArcadeDriveJoystick());
}
public void drive(GenericHID moveStick, final int moveAxis,
GenericHID rotateStick, final int rotateAxis) {
robotDrive.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis);
}
public void drive(double moveValue, double rotateValue) {
robotDrive.arcadeDrive(moveValue, rotateValue);
}
public void log() {
}
}
| TechnoWolves5518/2015RobotCode | JoystickDemo2/src/org/usfirst/frc/team5518/robot/subsystems/DrivingSys.java | Java | mit | 1,232 |
<?php
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
$veza = new PDO('mysql:host=' . getenv('MYSQL_SERVICE_HOST') . ';port=3306;dbname=developer_blog', 'admin', 'user');
$veza->exec("set names utf8");
if (isset($_POST['update'])) {
$title = $_POST['title'];
$paragraph = $_POST['paragraph'];
try {
$problem_id = $_GET['id'];
$upit = $veza->prepare("UPDATE part SET title = '$title', text = '$paragraph' WHERE id=?");
$upit->bindValue(1, $problem_id, PDO::PARAM_INT);
$upit->execute();
} catch (Exception $e) {
}
header("location: problems.php");
exit();
}
?>
<!doctype HTML>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Developer Blog</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/grid.css">
</head>
<body>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item"><a id="problems" href="problems.php">Problems</a></li>
<li class="nav-item"><a id="tasks" href="tasks.php">Tasks</a></li>
<li class="nav-item"><a id="articles" href="articles.php">Articles</a></li>
<li class="nav-item"><a id="ideas" href="ideas.php">Ideas</a></li>
<?php
if (isset($_SESSION['username'])) {
echo '<li class="nav-item right"><a id="login" href="logout.php">Log Out</a></li>';
echo '<li class="nav-item right"><a id="profile" href="javascript:loadPartialProfile()">Profile</a></li>';
}
else {
echo '<li class="nav-item right"><a id="login" href="login.php">Log In</a></li>';
}
?>
</ul>
</nav>
<!--Content-->
<div class="content" id="content">
<?php
if (isset($_GET['id'])) {
$problem_id = $_GET['id'];
$title = "";
$paragraph = "";
$upit = $veza->prepare("SELECT * FROM part WHERE id=?");
$upit->bindValue(1, $problem_id, PDO::PARAM_INT);
$upit->execute();
foreach($upit as $childrens) {
if ($childrens['id'] == $problem_id) {
$title = $childrens['title'];
$paragraph = $childrens['text'];
}
}
echo '<form action="shareProblem.php?id=' . $_GET['id'] . '" method="POST">
<div class="row creatingForms">
<h1>Share problem</h1>
<h2>Title</h2>
<input type="text" name="title" id="title" value="' . $title . '">
<h2>Paragraph</h2>
<textarea name="paragraph" id="paragraph" >' . $paragraph . '</textarea>
<div class="centerAlign">
<button type="Submit" name="update" value="problem">Submit Problem</button>
</div>
</div>
</form>';
}
else
echo '<form action="index.php" method="POST">
<div class="row creatingForms">
<h1>Share problem</h1>
<h2>Title</h2>
<input type="text" name="title" id="title">
<h2>Paragraph</h2>
<textarea name="paragraph" id="paragraph"></textarea>
<div class="centerAlign">
<button type="Submit" name="file" value="problem">Submit Problem</button>
</div>
</div>
</form>';
?>
</div>
<script src="js/validations/loginValidation.js"></script>
<script src="js/validations/signupValidation.js"></script>
<script src="js/dropdownmenu.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
| NerminImamovic/developer-Blog | shareProblem.php | PHP | mit | 4,871 |
#if !NOT_UNITY3D
namespace Zenject
{
public class GameObjectNameGroupNameScopeArgBinder : GameObjectGroupNameScopeArgBinder
{
public GameObjectNameGroupNameScopeArgBinder(
BindInfo bindInfo,
GameObjectCreationParameters gameObjectInfo)
: base(bindInfo, gameObjectInfo)
{
}
public GameObjectGroupNameScopeArgBinder WithGameObjectName(string gameObjectName)
{
GameObjectInfo.Name = gameObjectName;
return this;
}
}
}
#endif
| austinmao/reduxity | Assets/Packages/Zenject/Source/Binding/Binders/GameObject/GameObjectNameGroupNameScopeArgBinder.cs | C# | mit | 567 |
<?php
namespace Hautelook\ExactTargetBundle\Services;
use ET_Subscriber;
use Hautelook\ExactTargetBundle\Model\Subscriber as SubscriberProperties;
class SubscriberService extends AbstractService
{
public function __construct($appSignature, $clientId, $clientSecret, $defaultWsdl)
{
parent::__construct($appSignature, $clientId, $clientSecret, $defaultWsdl);
$this->service = new ET_Subscriber();
$this->service->authStub = $this->client;
$this->properties = new SubscriberProperties();
}
}
| BradLook/ExactTargetBundle | Services/SubscriberService.php | PHP | mit | 541 |
function initBtnStartAlgo(){
$('#btn_startDispatch').bind('click', function(event) {
event.preventDefault();
initAlgo();
createResultPanel("div_resultPanel");
doRound();
printRound("resultRegion");
printResultPersonal("resultPersonal");
createDownloadableContent();
});
}
// 初始化變數、將 html 清空
function initAlgo(){
// 有時會發生役男進來後,才臨時驗退的情形,我們會在其分數欄位填入 "NA" ,在算平均成績時不把他算進去
// 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代
// Fixed: 2014, Dec, 11
var not_here_student = 0;
students = new Array();
avgScore = 0.0;
for(x in regionDatas){
regionDatas[x].queue = new Array();
regionDatas[x].resultArray = new Array();
}
for(var i=1;i<=TOTAL_STUDENT;i++){
var student = new Student();
student.id = i;
student.score = $('#score'+i).val();
student.home = $('#wishList'+i+'_0').val();
student.wish1 = $('#wishList'+i+'_1').val();
student.result = NO_REGION_RESULT;
student.homeFirst = $('#homeFirst'+i).is(':checked');
// Add to lists
students[i-1] = student;
// 處理臨時被驗退的
if($('#score'+i).val()==="NA"){
students[i-1].result = "NA"; // 要給予跟 NO_REGION_RESULT 不一樣的值
not_here_student++;
continue;
}
// parserInt() used to cause lost of digits. Fixed: 2014, Oct 29
avgScore += parseFloat(student.score);
}
avgScore = avgScore/(TOTAL_STUDENT-not_here_student);
var size = Math.pow(10, 2);
avgScore = Math.round(avgScore * size) / size;
}
// 畫出 平均分數、Round1、Round2、Round3、分發結果(依個人)的那個 nav-tabs
function createResultPanel(printToDivID){
var str = '<div class="panel panel-info">';
str += '<div class="panel-heading">';
str += '<h3 class="panel-title">第 ' + WHAT_T + ' 梯 預排結果 ( 平均分數:'+avgScore+' )</h3>';
str += '</div>';
str += '<div class="panel-body" id="div_dispatchResult">';
str += '<ul class="nav nav-tabs">';
str += '<li class="active"><a href="#resultRegion" data-toggle="tab">地區</a></li>';
str += '<li><a href="#resultPersonal" data-toggle="tab">個人</a></li>';
// color block 色塊
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeHome + ';"></canvas> 家因</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type1 + ';"></canvas> 高均+戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type2 + ';"></canvas> 高均+非戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type3 + ';"></canvas> 低均+戶籍地</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type4 + ';"></canvas> 低均+非戶籍</li>';
str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeKicked + ';"></canvas> 被擠掉</li>';
str += '</ul>';
str += '<div id="resultTabContent" class="tab-content">';
str += ' <div class="tab-pane fade active in" id="resultRegion"></div>';
str += ' <div class="tab-pane fade" id="resultPersonal"></div>';
str += '</div>';
str += '</div>';
str += '<div class="panel-fotter">';
str += ' <div class="btn-group btn-group-justified">';
str += ' <a href="" class="btn btn-primary" id="btn_downloadTXT">下載程式可讀取的格式(.txt)</a>';
str += ' <a href="" class="btn btn-info" id="btn_downloadCSVRegion">給輔導組(照地區.csv)</a>';
str += ' <a href="" class="btn btn-success" id="btn_downloadCSVPersonnel">給輔導組(照個人.csv)</a>';
str += ' </div>';
str += '</div>';
str += '</div>';
$("#"+printToDivID).html(str);
}
// 將 分發規則 用演算法實作
function doRound(){
// 可以清空 queue,因為我們可以直接從 student.result 的內容來找出還沒被分發的學生,送進下一 round
for(var i=0;i<regionDatas.length;i++){
regionDatas[i].queue = new Array();
}
// Step 1: 將學生加入其第N志願的 queue (N depend on round)
var regionDatasLength = regionDatas.length;
for(var k=0;k<TOTAL_STUDENT;k++){
// 如果學生已經分發到某的地點,就不須再分發,可跳過直接看下個學生。
if(students[k].result != NO_REGION_RESULT){
continue;
}
// TODO: 這邊改用 key hash 應該會漂亮、效能也更好
for(var i=0;i<regionDatasLength;i++){
if(students[k].wish1 == regionDatas[i].name){
regionDatas[i].queue.push(students[k]);
}
}
}
// Step 2: 將每個單位的 queue 裡面的學生互相比較,取出最適合此單位的學生放入此單位的 resultArray
for(var i=0;i<regionDatasLength;i++){
var region = regionDatas[i];
// 此單位名額已經滿,跳過
if(region.resultArray.length == region.available){
continue;
}
// 要去的人數 小於等於 開放的名額,每個人都錄取
else if(region.queue.length <= region.available){
// 其實可以不用排序,但是排序之後印出來比較好看
region.queue.sort(function(a, b){return a.score-b.score});
popItemFromQueueAndPushToResultArray(region, region.queue.length);
}
// 要去的人數 大於 開放的名額,依照 分發規則 找出最適合此單位的學生放入此單位的 resultArray
else{
// 不管是中央還是地方,都要比較成績,所以先依照成績排序
region.queue.sort(function(a, b){return a.score-b.score});
// 依照成績排序後是"由小到大",亦即 [30分, 40分, 60分, 90分, 100分]
// 考慮到之後的 Array.pop() 是 pop 出"最後一個"物件,這樣排列比較方便之後的處理
cruelFunction(i, region);
}
}
}
// This function is so cruel that I cannot even look at it.
function cruelFunction(regionID, region){
if(regionID<=3){
// 中央只有比成績,不考慮戶籍地,因此可直接依成績排序找出錄取的學生
popItemFromQueueAndPushToResultArray(region, region.available);
}else{
// 地方單位在依照成績排序後,再把 "過均標" 且 "符合戶籍地" 的往前排
// 剛剛已經過成績順序了,現在要分別對“過均標”跟“沒過均標”的做戶籍地優先的排序
region.queue.sort(function(a, b){
if((a.score >= avgScore && b.score >= avgScore) || (a.score < avgScore && b.score < avgScore)){
if(a.home == region.homeName && b.home != region.homeName){
return 1;
}else if(b.home == region.homeName && a.home != region.homeName){
return -1;
}
}
return 0;
});
// 接下來,把家因的抓出來,要優先分發,所以丟到 queue 最後面。(等等 pop()時會變成最前面 )
region.queue.sort(function(a, b){
if(a.homeFirst==true){
return 1;
}
return 0;
});
// 排完後再依照順序找出錄取的學生
popItemFromQueueAndPushToResultArray(region, region.available);
}
}
// 從 region 的排序過後的 queue 裡面,抓出 numberOfItems 個學生,丟進 resultArray 裡面
function popItemFromQueueAndPushToResultArray(region, numberOfItems){
for(var k=0;k<numberOfItems;k++){
region.resultArray.push(region.queue.pop());
}
assignStudentToRegion(region.homeName, region.resultArray);
}
// 將已經被分配到某地區的學生的 result attribute 指定為該地區。(resultArray[] 的 items 為學生,擁有 result )
function assignStudentToRegion(regionName, resultArray){
var length = resultArray.length;
for(var i=0;i<length;i++){
resultArray[i].result = regionName;
}
}
| johnyluyte/EPA-SMS-Dispatcher | js/algo.js | JavaScript | mit | 7,887 |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using QEngine.Physics.Shared;
using QEngine.Physics.Tools.Triangulation.Delaunay.Delaunay;
using QEngine.Physics.Tools.Triangulation.Delaunay.Delaunay.Sweep;
namespace QEngine.Physics.Tools.Triangulation.Delaunay
{
/// <summary>
/// 2D constrained Delaunay triangulation algorithm.
/// Based on the paper "Sweep-line algorithm for constrained Delaunay triangulation" by V. Domiter and and B. Zalik
///
/// Properties:
/// - Creates triangles with a large interior angle.
/// - Supports holes
/// - Generate a lot of garbage due to incapsulation of the Poly2Tri library.
/// - Running time is O(n^2), n = number of vertices.
/// - Does not care about winding order.
///
/// Source: http://code.google.com/p/poly2tri/
/// </summary>
internal static class CDTDecomposer
{
/// <summary>
/// Decompose the polygon into several smaller non-concave polygon.
/// </summary>
public static List<Vertices> ConvexPartition(Vertices vertices)
{
System.Diagnostics.Debug.Assert(vertices.Count > 3);
Polygon.Polygon poly = new Polygon.Polygon();
foreach (Vector2 vertex in vertices)
poly.Points.Add(new TriangulationPoint(vertex.X, vertex.Y));
if (vertices.Holes != null)
{
foreach (Vertices holeVertices in vertices.Holes)
{
Polygon.Polygon hole = new Polygon.Polygon();
foreach (Vector2 vertex in holeVertices)
hole.Points.Add(new TriangulationPoint(vertex.X, vertex.Y));
poly.AddHole(hole);
}
}
DTSweepContext tcx = new DTSweepContext();
tcx.PrepareTriangulation(poly);
DTSweep.Triangulate(tcx);
List<Vertices> results = new List<Vertices>();
foreach (DelaunayTriangle triangle in poly.Triangles)
{
Vertices v = new Vertices();
foreach (TriangulationPoint p in triangle.Points)
{
v.Add(new Vector2((float)p.X, (float)p.Y));
}
results.Add(v);
}
return results;
}
}
} | Quincy9000/QEngine.Framework | QEngine/Code/Physics/Tools/Triangulation/Delaunay/CDTDecomposer.cs | C# | mit | 2,417 |
<?php
namespace Sf\TodoBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SfTodoBundle extends Bundle
{
}
| a1092/pa8 | src/Sf/TodoBundle/SfTodoBundle.php | PHP | mit | 120 |
import * as _ from 'lodash';
import Vuex from 'vuex';
import {Deck} from '../models/Deck'
import DeckState from '../models/state/DeckState'
const store =
{
state: new DeckState(),
mutations:
{
addToDeck(state, card)
{
if (!card) { return; }
state.currentDeck.cards.push(card);
if (!_.some(state.allDecks, thatDeck => thatDeck == state.currentDeck))
{
state.allDecks.push(state.currentDeck);
}
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeFromDeck(state, card)
{
if (card == undefined) { return; }
let cardIndex = state.currentDeck.cards.indexOf(card);
if (cardIndex < 0) { return; }
state.currentDeck.cards.splice(cardIndex, 1);
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeAllFromDeck(state, card)
{
if (card == undefined) { return; }
var filtered = state.currentDeck.cards.filter(c => c.multiverseid != card.multiverseid);
state.currentDeck.cards = filtered;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
loadDeck(state, deck)
{
if (deck == undefined) { return; }
state.allDecks.push(deck);
state.currentDeck = state.allDecks[state.allDecks.length - 1];
},
deleteCurrentDeck(state)
{
var deckIndex = state.allDecks.indexOf(state.currentDeck);
state.allDecks.splice(deckIndex, 1);
},
clearDeck(state)
{
state.currentDeck.cards = [];
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
setCurrentDeck(state, deck)
{
if (deck == undefined) { return; }
state.currentDeck = deck;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
}
}
};
export default store | jmazouri/Deckard | Deckard/Frontend/src/deckard/state/DeckModule.ts | TypeScript | mit | 2,091 |
namespace _01.SchoolClasses
{
// Disciplines have name, number of lectures and number of exercises
using System;
class Disciplines : BasicInfoPeopleAndObjects
{
private int lecturesNumber;
private int exercisesNumber;
public Disciplines(string name, int lecturesNumber, int exercisesNumber)
:base(name)
{
this.LecturesNumber = lecturesNumber;
this.ExercisesNumber = exercisesNumber;
}
public int LecturesNumber
{
get
{
return this.lecturesNumber;
}
private set
{
if (CheckForValidValue(value))
{
this.lecturesNumber = value;
}
}
}
public int ExercisesNumber
{
get
{
return this.exercisesNumber;
}
private set
{
if (CheckForValidValue(value))
{
this.exercisesNumber = value;
}
}
}
private static bool CheckForValidValue(int value)
{
if (value < 1 || value > 10)
{
throw new ArgumentOutOfRangeException("THe number of Lectures Or Exercises should be bewtween 1 and 10");
}
return true;
}
}
}
| clangelov/TelerikAcademyHomework | 03_CSharp-OOP/OOP-Principles-Part1-Homework/01.SchoolClasses/Disciplines.cs | C# | mit | 1,440 |
# == Schema Information
#
# Table name: github_stargazers
#
# id :integer not null, primary key
# linked_account_id :integer not null
# tracker_id :integer not null
# stargazer :boolean
# subscriber :boolean
# forker :boolean
# synced_at :datetime
# created_at :datetime
# updated_at :datetime
#
class GithubStargazer < ApplicationRecord
belongs_to :linked_account, class_name: 'LinkedAccount::Github::User'
belongs_to :tracker, class_name: 'Github::Repository'
# options
# - oauth_token
# - tracker_ids:[123,456] | tracker_id:123
def self.sync_stargazers_for(options)
# require trackers
return if options[:tracker_ids].blank?
# get array of all stargazers, watchers, and forkers
start_time = Time.now
responses = get_responses_from_github_api(options)
logger.error "STARGAZER API TIME: #{Time.now-start_time}"
# # delete existing stargazers
GithubStargazer.where(tracker_id: options[:tracker_ids]).delete_all
# translate array into hash and group by github user and tracker id
response_hash = responses.inject({}) do |h,(tr_id, gh_uid, w_type)|
h[gh_uid] ||= {}
h[gh_uid][tr_id] ||= {}
h[gh_uid][tr_id][w_type] = true
h
end
# create all linked accounts
time_now_sql = GithubStargazer.connection.quote(Time.now)
response_hash.to_a.in_groups_of(1000,false) do |group|
# find which github remote ids we're dealing with
gh_uids = group.map(&:first)
# create any missing linked_accounts
rails_autoload = [LinkedAccount::Github, LinkedAccount::Github::Organization, LinkedAccount::Github::User]
existing_gh_uids = LinkedAccount::Github.where(uid: gh_uids).pluck(:uid)
missing_gh_uids = gh_uids - existing_gh_uids
if missing_gh_uids.length > 0
missing_gh_uids_sql = missing_gh_uids.map { |uid| "(#{time_now_sql}, #{time_now_sql}, 'LinkedAccount::Github::User', #{uid.to_i})" }
LinkedAccount::Github.connection.insert("INSERT INTO linked_accounts (created_at, updated_at, type, uid) VALUES #{missing_gh_uids_sql.join(',')}")
end
# create linked account hash
linked_account_hash = LinkedAccount::Github.where(uid: gh_uids).pluck(:id, :uid).inject({}) { |h,(id,uid)| h[uid]=id; h }
stargazer_inserts = []
group.each do |ghuid, tracker_map|
tracker_map.each do |tracker_id, hash|
stargazer_inserts << "(#{time_now_sql}, #{time_now_sql}, #{linked_account_hash[ghuid]}, #{tracker_id}, #{!!hash[:stargazer]}, #{!!hash[:subscriber]}, #{!!hash[:forker]})"
end
end
GithubStargazer.connection.insert("INSERT INTO github_stargazers (created_at, updated_at, linked_account_id, tracker_id, stargazer, subscriber, forker) VALUES #{stargazer_inserts.join(',')}")
end
end
protected
# this is an event machine that does 20 concurrent connections to get all of the stargazers, watchers, and forkers
def self.get_responses_from_github_api(options)
# queue up initial page loads, with page=nil
requests = []
tracker_map = Tracker.where(id: options[:tracker_ids]).pluck(:id, :remote_id).inject({}) { |h,(id,remote_id)| h[id] = remote_id; h }
options[:tracker_ids].each do |tracker_id|
[:stargazer, :subscriber, :forker].each do |watch_type|
requests.push(
tracker_id: tracker_id,
github_repository_uid: tracker_map[tracker_id],
watch_type: watch_type
)
end
end
# where the responses go
responses = []
concurrent_requests = 0
max_concurrent_requests = 20
no_requests_until = Time.now
EM.run do
repeater = Proc.new do
# puts "REPEATER #{concurrent_requests} < #{max_concurrent_requests} && #{requests.length} > 0 && #{no_requests_until} < #{Time.now}"
if concurrent_requests < max_concurrent_requests && requests.length > 0 && no_requests_until < Time.now
concurrent_requests += 1
request = requests.shift
url_path = case request[:watch_type]
when :stargazer then 'stargazers'
when :subscriber then 'subscribers'
when :forker then 'forks'
end
# generate request
params = { per_page: 25 }
params[:page] = request[:page] if request[:page]
if options[:oauth_token]
params[:oauth_token] = options[:oauth_token]
else
params[:client_id] = Api::Application.config.github_api[:client_id]
params[:client_secret] = Api::Application.config.github_api[:client_secret]
end
url = "https://api.github.com/repositories/#{request[:github_repository_uid]}/#{url_path}?#{params.to_param}"
# puts "REQUEST: #{url}"
http = EventMachine::HttpRequest.new(url).get
callback = proc { |http|
# puts "RESPONSE: #{url}"
concurrent_requests -= 1
if http.response_header.status == 200
# if the request was for the first page (page=nil), then queue up the rest of the pages
if http.response_header['LINK'] && !request[:page]
last_page = http.response_header['LINK'].scan(/page=(\d+)>; rel="last"/)[0][0].to_i
(2..last_page).each { |page| requests << request.merge(page: page) }
end
# parse response
JSON.parse(http.response).each do |row|
responses << [
request[:tracker_id],
request[:watch_type] == :forker ? row['owner']['id'] : row['id'],
request[:watch_type]
]
end
# queue the next one
repeater.call
elsif http.response_header.status == 404
# tracker deleted! queue remote_sync so it gets marked as deleted
Tracker.find(request[:tracker_id]).delay.remote_sync
elsif http.response.try(:include?, "abuse-rate-limits") && (request[:retries]||0) < 3
puts "DELAY 60 SECONDS"
no_requests_until = Time.now + 60.seconds
requests << request.merge(retries: (request[:retries]||0) + 1)
else
puts "ERROR: #{url}"
puts http.try(:errors)
puts http.response
pp http.response_header
EM.stop
end
}
http.callback &callback
http.errback &callback
# if we queued a request, maybe we can queue another
repeater.call
elsif concurrent_requests == 0 && requests.length == 0
EM.stop
end
end
EventMachine::PeriodicTimer.new(1) { repeater.call }
repeater.call
end
responses
end
end
| bountysource/core | app/models/github_stargazer.rb | Ruby | mit | 6,853 |
'use strict';
angular.module('articles').controller('ChangeHeaderImageController', ['$scope', '$timeout', '$stateParams', '$window', 'Authentication', 'FileUploader', 'Articles',
function ($scope, $timeout, $stateParams, $window, Authentication, FileUploader, Articles) {
$scope.user = Authentication.user;
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
$scope.imageURL = $scope.article.headerMedia || null;
// Create file uploader instance
$scope.uploader = new FileUploader({
url: 'api/articles/' + $stateParams.articleId + '/headerimage',
alias: 'newHeaderImage'
});
// Set file uploader image filter
$scope.uploader.filters.push({
name: 'imageFilter',
fn: function (item, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// Called after the user selected a new picture file
$scope.uploader.onAfterAddingFile = function (fileItem) {
if ($window.FileReader) {
var fileReader = new FileReader();
fileReader.readAsDataURL(fileItem._file);
fileReader.onload = function (fileReaderEvent) {
$timeout(function () {
$scope.imageURL = fileReaderEvent.target.result;
}, 0);
};
}
};
// Called after the article has been assigned a new header image
$scope.uploader.onSuccessItem = function (fileItem, response, status, headers) {
// Show success message
$scope.success = true;
// Populate user object
$scope.user = Authentication.user = response;
// Clear upload buttons
$scope.cancelUpload();
};
// Called after the user has failed to upload a new picture
$scope.uploader.onErrorItem = function (fileItem, response, status, headers) {
// Clear upload buttons
$scope.cancelUpload();
// Show error message
$scope.error = response.message;
};
// Change article header image
$scope.uploadHeaderImage = function () {
console.log($scope);
// Clear messages
$scope.success = $scope.error = null;
// Start upload
$scope.uploader.uploadAll();
};
// Cancel the upload process
$scope.cancelUpload = function () {
$scope.uploader.clearQueue();
//$scope.imageURL = $scope.article.profileImageURL;
};
}
]);
| davidsbelt/bacca-app | modules/articles/client/controllers/change-header-image.client.controller.js | JavaScript | mit | 2,451 |
/** @jsx h */
import h from '../../../helpers/h'
import { Mark } from '../../../..'
export default function(change) {
change.addMark(
Mark.create({
type: 'bold',
data: { thing: 'value' },
})
)
}
export const input = (
<value>
<document>
<paragraph>
<anchor />w<focus />ord
</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>
<anchor />
<b thing="value">w</b>
<focus />ord
</paragraph>
</document>
</value>
)
| ashutoshrishi/slate | packages/slate/test/changes/at-current-range/add-mark/with-mark-object.js | JavaScript | mit | 556 |
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* App\Entity$EditeurNatureSupport.
*
* @ORM\Table(name="editeurnaturesupport")
* @ORM\Entity(repositoryClass="App\Repository\EditeurNatureSupportRepository")
*/
class EditeurNatureSupport
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Editeur
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\Editeur",
* inversedBy="editeurNatureSupports"
* )
* @ORM\JoinColumn(nullable=false)
*/
private $editeur;
/**
* @var NatureSupport
*
* @ORM\ManyToOne(
* targetEntity="App\Entity\NatureSupport",
* inversedBy="editeurNatureSupports"
* )
* @ORM\JoinColumn(
* name="naturesupport_id",
* referencedColumnName="id",
* nullable=false
* )
*/
private $natureSupport;
/**
* @var Collection
*
* @ORM\ManyToMany(
* targetEntity="App\Entity\CategorieOeuvre",
* inversedBy="editeurNatureSupports"
* )
* @ORM\JoinTable(
* name="editeurnaturesupport_categorieoeuvre",
* joinColumns={
* @ORM\JoinColumn(
* name="editeurnaturesupport_id",
* referencedColumnName="id"
* )
* },
* inverseJoinColumns={
* @ORM\JoinColumn(
* name="categorieoeuvre_id",
* referencedColumnName="id"
* )
* }
* )
*/
private $categoriesOeuvres;
/**
* @var Collection
*
* @ORM\OneToMany(
* targetEntity="App\Entity\Support",
* mappedBy="editeurNatureSupport"
* )
*/
private $supports;
/**
* Constructeur.
*
* @param Editeur|null $editeur
* @param NatureSupport|null $natureSupport
*/
public function __construct(
Editeur $editeur = null,
NatureSupport $natureSupport = null
) {
$this->editeur = $editeur;
$this->natureSupport = $natureSupport;
$this->categoriesOeuvres = new ArrayCollection();
}
/**
* Get id.
*
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* Set editeur.
*
* @param Editeur|null $editeur
*/
public function setEditeur(Editeur $editeur = null): void
{
$this->editeur = $editeur;
}
/**
* Get editeur.
*
* @return Editeur
*/
public function getEditeur(): ?Editeur
{
return $this->editeur;
}
/**
* Set natureSupport.
*
* @param NatureSupport|null $natureSupport
*/
public function setNatureSupport(NatureSupport $natureSupport = null): void
{
$this->editeur = $natureSupport;
}
/**
* Get natureSupport.
*
* @return NatureSupport|null
*/
public function getNatureSupport(): ?NatureSupport
{
return $this->natureSupport;
}
/**
* Add categorieOeuvre.
*
* @param CategorieOeuvre $categorieOeuvre
*/
public function addCategorieOeuvre(CategorieOeuvre $categorieOeuvre): void
{
if (!$this->categoriesOeuvres->contains($categorieOeuvre)) {
$this->categoriesOeuvres[] = $categorieOeuvre;
$categorieOeuvre->addEditeurNatureSupport($this);
}
}
/**
* Remove categorieOeuvre.
*
* @param CategorieOeuvre $categorieOeuvre
*/
public function removeCategorieOeuvre(CategorieOeuvre $categorieOeuvre): void
{
if ($this->categoriesOeuvres->contains($categorieOeuvre)) {
$this->categoriesOeuvres->removeElement($categorieOeuvre);
$categorieOeuvre->removeEditeurNatureSupport($this);
}
}
/**
* Get categoriesOeuvres.
*
* @return Collection
*/
public function getCategoriesOeuvres(): Collection
{
return $this->categoriesOeuvres;
}
/**
* Add support.
*
* @param Support $support
*/
public function addSupport(Support $support): void
{
if (!$this->supports->contains($support)) {
$this->supports[] = $support;
}
$support->setEditeurNatureSupport($this);
}
/**
* Remove support.
*
* @param Support $support
*/
public function removeSupport(Support $support): void
{
if ($this->supports->contains($support)) {
$this->supports->removeElement($support);
}
$support->setEditeurNatureSupport(null);
}
/**
* Get supports.
*
* @return Collection
*/
public function getSupports(): Collection
{
return $this->supports;
}
}
| dmsr45/github_sf_media | src/Entity/EditeurNatureSupport.php | PHP | mit | 4,995 |
package main
import (
"net/http"
"sync"
"time"
"github.com/1lann/airlift/airlift"
humanize "github.com/dustin/go-humanize"
"github.com/gin-gonic/contrib/renders/multitemplate"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
)
func formatBasicTime(t time.Time) string {
return getDay(t) + " " + t.Format("January 2006 at 3:04 PM")
}
func init() {
registers = append(registers, func(r *gin.RouterGroup, t multitemplate.Render) {
t.AddFromFiles("notes", viewsPath+"/notes.tmpl",
viewsPath+"/components/base.tmpl")
r.GET("/notes", viewUserNotes)
t.AddFromFiles("view-note", viewsPath+"/view-note.tmpl",
viewsPath+"/components/base.tmpl")
r.GET("/notes/:id", viewNote)
r.POST("/notes/:id/star", func(c *gin.Context) {
starred := c.PostForm("starred") == "true"
username := c.MustGet("user").(airlift.User).Username
err := airlift.SetNoteStar(c.Param("id"), username, starred)
if err != nil {
panic(err)
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
})
}
func viewNote(c *gin.Context) {
id := c.Param("id")
user := c.MustGet("user").(airlift.User)
note, err := airlift.GetFullNote(id, user.Username)
if err != nil {
panic(err)
}
if note.Title == "" {
c.HTML(http.StatusNotFound, "not-found", nil)
return
}
files := []fileCard{
{
Name: "Notes",
Size: humanize.Bytes(note.Size),
URL: "/download/notes/" + note.ID,
},
}
session := sessions.Default(c)
uploadFlashes := session.Flashes("upload")
uploadSuccess := ""
if len(uploadFlashes) > 0 {
uploadSuccess = uploadFlashes[0].(string)
}
session.Save()
htmlOK(c, "view-note", gin.H{
"ActiveMenu": "notes",
"Note": note,
"Files": files,
"IsUploader": note.Uploader == user.Username,
"UploadTime": formatBasicTime(note.UploadTime),
"UpdatedTime": formatBasicTime(note.UpdatedTime),
"UploadSuccess": uploadSuccess,
})
}
func viewUserNotes(c *gin.Context) {
user := c.MustGet("user").(airlift.User)
wg := new(sync.WaitGroup)
wg.Add(2)
var starred []airlift.Note
go func() {
defer func() {
wg.Done()
}()
var err error
starred, err = airlift.GetStarredNotes(user.Username)
if err != nil {
panic(err)
}
}()
var uploaded []airlift.Note
go func() {
defer func() {
wg.Done()
}()
var err error
uploaded, err = airlift.GetUploadedNotes(user.Username)
if err != nil {
panic(err)
}
}()
deleted := false
session := sessions.Default(c)
uploadFlashes := session.Flashes("upload")
if len(uploadFlashes) > 0 && uploadFlashes[0] == "delete" {
deleted = true
}
session.Save()
wg.Wait()
htmlOK(c, "notes", gin.H{
"ActiveMenu": "notes",
"Starred": starred,
"Uploaded": uploaded,
"Deleted": deleted,
})
}
| 1lann/airlift | notes.go | GO | mit | 2,768 |
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Bake\Shell\Task;
use Cake\Console\Shell;
use Cake\Core\Configure;
use Cake\Database\Exception;
use Cake\Database\Schema\Table;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use Cake\Utility\Text;
use DateTimeInterface;
/**
* Task class for creating and updating fixtures files.
*
* @property \Bake\Shell\Task\BakeTemplateTask $BakeTemplate
* @property \Bake\Shell\Task\ModelTask $Model
*/
class FixtureTask extends BakeTask
{
/**
* Tasks to be loaded by this Task
*
* @var array
*/
public $tasks = [
'Bake.Model',
'Bake.BakeTemplate'
];
/**
* Get the file path.
*
* @return string
*/
public function getPath()
{
$dir = 'Fixture/';
$path = defined('TESTS') ? TESTS . $dir : ROOT . DS . 'tests' . DS . $dir;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . 'tests/' . $dir;
}
return str_replace('/', DS, $path);
}
/**
* Gets the option parser instance and configures it.
*
* @return \Cake\Console\ConsoleOptionParser
*/
public function getOptionParser()
{
$parser = parent::getOptionParser();
$parser = $parser->setDescription(
'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.'
)->addArgument('name', [
'help' => 'Name of the fixture to bake (without the `Fixture` suffix). ' .
'You can use Plugin.name to bake plugin fixtures.'
])->addOption('table', [
'help' => 'The table name if it does not follow conventions.',
])->addOption('count', [
'help' => 'When using generated data, the number of records to include in the fixture(s).',
'short' => 'n',
'default' => 1
])->addOption('schema', [
'help' => 'Create a fixture that imports schema, instead of dumping a schema snapshot into the fixture.',
'short' => 's',
'boolean' => true
])->addOption('records', [
'help' => 'Generate a fixture with records from the non-test database.' .
' Used with --count and --conditions to limit which records are added to the fixture.',
'short' => 'r',
'boolean' => true
])->addOption('conditions', [
'help' => 'The SQL snippet to use when importing records.',
'default' => '1=1',
])->addSubcommand('all', [
'help' => 'Bake all fixture files for tables in the chosen connection.'
]);
return $parser;
}
/**
* Execution method always used for tasks
* Handles dispatching to interactive, named, or all processes.
*
* @param string|null $name The name of the fixture to bake.
* @return null|bool
*/
public function main($name = null)
{
parent::main();
$name = $this->_getName($name);
if (empty($name)) {
$this->out('Choose a fixture to bake from the following:');
foreach ($this->Model->listUnskipped() as $table) {
$this->out('- ' . $this->_camelize($table));
}
return true;
}
$table = null;
if (isset($this->params['table'])) {
$table = $this->params['table'];
}
$model = $this->_camelize($name);
$this->bake($model, $table);
}
/**
* Bake All the Fixtures at once. Will only bake fixtures for models that exist.
*
* @return void
*/
public function all()
{
$tables = $this->Model->listUnskipped($this->connection, false);
foreach ($tables as $table) {
$this->main($table);
}
}
/**
* Assembles and writes a Fixture file
*
* @param string $model Name of model to bake.
* @param string|null $useTable Name of table to use.
* @return string Baked fixture content
* @throws \RuntimeException
*/
public function bake($model, $useTable = null)
{
$table = $schema = $records = $import = $modelImport = null;
if (!$useTable) {
$useTable = Inflector::tableize($model);
} elseif ($useTable !== Inflector::tableize($model)) {
$table = $useTable;
}
$importBits = [];
if (!empty($this->params['schema'])) {
$modelImport = true;
$importBits[] = "'table' => '{$useTable}'";
}
if (!empty($importBits) && $this->connection !== 'default') {
$importBits[] = "'connection' => '{$this->connection}'";
}
if (!empty($importBits)) {
$import = sprintf("[%s]", implode(', ', $importBits));
}
$connection = ConnectionManager::get($this->connection);
if (!method_exists($connection, 'schemaCollection')) {
throw new \RuntimeException(
'Cannot generate fixtures for connections that do not implement schemaCollection()'
);
}
$schemaCollection = $connection->schemaCollection();
try {
$data = $schemaCollection->describe($useTable);
} catch (Exception $e) {
$useTable = Inflector::underscore($model);
$table = $useTable;
$data = $schemaCollection->describe($useTable);
}
if ($modelImport === null) {
$schema = $this->_generateSchema($data);
}
if (empty($this->params['records'])) {
$recordCount = 1;
if (isset($this->params['count'])) {
$recordCount = $this->params['count'];
}
$records = $this->_makeRecordString($this->_generateRecords($data, $recordCount));
}
if (!empty($this->params['records'])) {
$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
}
return $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
}
/**
* Generate the fixture file, and write to disk
*
* @param string $model name of the model being generated
* @param array $otherVars Contents of the fixture file.
* @return string Content saved into fixture file.
*/
public function generateFixtureFile($model, array $otherVars)
{
$defaults = [
'name' => $model,
'table' => null,
'schema' => null,
'records' => null,
'import' => null,
'fields' => null,
'namespace' => Configure::read('App.namespace')
];
if ($this->plugin) {
$defaults['namespace'] = $this->_pluginNamespace($this->plugin);
}
$vars = $otherVars + $defaults;
$path = $this->getPath();
$filename = $vars['name'] . 'Fixture.php';
$this->BakeTemplate->set('model', $model);
$this->BakeTemplate->set($vars);
$content = $this->BakeTemplate->generate('tests/fixture');
$this->out("\n" . sprintf('Baking test fixture for %s...', $model), 1, Shell::QUIET);
$this->createFile($path . $filename, $content);
$emptyFile = $path . 'empty';
$this->_deleteEmptyFile($emptyFile);
return $content;
}
/**
* Generates a string representation of a schema.
*
* @param \Cake\Database\Schema\Table $table Table schema
* @return string fields definitions
*/
protected function _generateSchema(Table $table)
{
$cols = $indexes = $constraints = [];
foreach ($table->columns() as $field) {
$fieldData = $table->column($field);
$properties = implode(', ', $this->_values($fieldData));
$cols[] = " '$field' => [$properties],";
}
foreach ($table->indexes() as $index) {
$fieldData = $table->index($index);
$properties = implode(', ', $this->_values($fieldData));
$indexes[] = " '$index' => [$properties],";
}
foreach ($table->constraints() as $index) {
$fieldData = $table->constraint($index);
$properties = implode(', ', $this->_values($fieldData));
$constraints[] = " '$index' => [$properties],";
}
$options = $this->_values($table->options());
$content = implode("\n", $cols) . "\n";
if (!empty($indexes)) {
$content .= " '_indexes' => [\n" . implode("\n", $indexes) . "\n ],\n";
}
if (!empty($constraints)) {
$content .= " '_constraints' => [\n" . implode("\n", $constraints) . "\n ],\n";
}
if (!empty($options)) {
foreach ($options as &$option) {
$option = ' ' . $option;
}
$content .= " '_options' => [\n" . implode(",\n", $options) . "\n ],\n";
}
return "[\n$content ]";
}
/**
* Formats Schema columns from Model Object
*
* @param array $values options keys(type, null, default, key, length, extra)
* @return array Formatted values
*/
protected function _values($values)
{
$vals = [];
if (!is_array($values)) {
return $vals;
}
foreach ($values as $key => $val) {
if (is_array($val)) {
$vals[] = "'{$key}' => [" . implode(", ", $this->_values($val)) . "]";
} else {
$val = var_export($val, true);
if ($val === 'NULL') {
$val = 'null';
}
if (!is_numeric($key)) {
$vals[] = "'{$key}' => {$val}";
} else {
$vals[] = "{$val}";
}
}
}
return $vals;
}
/**
* Generate String representation of Records
*
* @param \Cake\Database\Schema\Table $table Table schema array
* @param int $recordCount The number of records to generate.
* @return array Array of records to use in the fixture.
*/
protected function _generateRecords(Table $table, $recordCount = 1)
{
$records = [];
for ($i = 0; $i < $recordCount; $i++) {
$record = [];
foreach ($table->columns() as $field) {
$fieldInfo = $table->column($field);
$insert = '';
switch ($fieldInfo['type']) {
case 'decimal':
$insert = $i + 1.5;
break;
case 'biginteger':
case 'integer':
case 'float':
case 'smallinteger':
case 'tinyinteger':
$insert = $i + 1;
break;
case 'string':
case 'binary':
$isPrimary = in_array($field, $table->primaryKey());
if ($isPrimary) {
$insert = Text::uuid();
} else {
$insert = "Lorem ipsum dolor sit amet";
if (!empty($fieldInfo['length'])) {
$insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
}
}
break;
case 'timestamp':
$insert = time();
break;
case 'datetime':
$insert = date('Y-m-d H:i:s');
break;
case 'date':
$insert = date('Y-m-d');
break;
case 'time':
$insert = date('H:i:s');
break;
case 'boolean':
$insert = 1;
break;
case 'text':
$insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
$insert .= " Convallis morbi fringilla gravida,";
$insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
$insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
$insert .= " vestibulum massa neque ut et, id hendrerit sit,";
$insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
$insert .= " duis vestibulum nunc mattis convallis.";
break;
case 'uuid':
$insert = Text::uuid();
break;
}
$record[$field] = $insert;
}
$records[] = $record;
}
return $records;
}
/**
* Convert a $records array into a string.
*
* @param array $records Array of records to be converted to string
* @return string A string value of the $records array.
*/
protected function _makeRecordString($records)
{
$out = "[\n";
foreach ($records as $record) {
$values = [];
foreach ($record as $field => $value) {
if ($value instanceof DateTimeInterface) {
$value = $value->format('Y-m-d H:i:s');
}
$val = var_export($value, true);
if ($val === 'NULL') {
$val = 'null';
}
$values[] = " '$field' => $val";
}
$out .= " [\n";
$out .= implode(",\n", $values);
$out .= "\n ],\n";
}
$out .= " ]";
return $out;
}
/**
* Interact with the user to get a custom SQL condition and use that to extract data
* to build a fixture.
*
* @param string $modelName name of the model to take records from.
* @param string|null $useTable Name of table to use.
* @return array Array of records.
*/
protected function _getRecordsFromTable($modelName, $useTable = null)
{
$recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
$conditions = (isset($this->params['conditions']) ? $this->params['conditions'] : '1=1');
if (TableRegistry::exists($modelName)) {
$model = TableRegistry::get($modelName);
} else {
$model = TableRegistry::get($modelName, [
'table' => $useTable,
'connection' => ConnectionManager::get($this->connection)
]);
}
$records = $model->find('all')
->where($conditions)
->limit($recordCount)
->enableHydration(false);
return $records;
}
}
| JayWalker512/CrueltyGame | cruelty/vendor/cakephp/bake/src/Shell/Task/FixtureTask.php | PHP | mit | 15,668 |
using System;
namespace _14.MagicLetter
{
class Program
{
static void Main(string[] args)
{
char letter1 = char.Parse(Console.ReadLine());
char letter2 = char.Parse(Console.ReadLine());
string letter3 = Console.ReadLine();
for (char i = letter1; i <= letter2; i++)
{
for (char p = letter1; p <= letter2; p++)
{
for (char k = letter1; k <= letter2; k++)
{
string result = $"{i}{p}{k}";
if (!result.Contains(letter3))
{
Console.Write(result + " ");
}
}
}
}
}
}
}
| spacex13/SoftUni-Homework | ConditionalStatementsAndLoops/14.MagicLetter/Program.cs | C# | mit | 806 |
<?php
namespace Metro;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\PsrHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
class Worker
{
/** @var ConsumableQueue */
private $metro;
/** @var JobExecutor */
private $jobExecutor;
/** @var string[] */
private $queues;
/** @var Logger */
private $logger;
/** @var int */
private $interval = 5000;
/** @var bool */
private $drainMode = false;
public function __construct(ConsumableQueue $metro, JobExecutor $jobExecutor, LoggerInterface $logger, ...$queueIds)
{
$this->metro = $metro;
$this->jobExecutor = $jobExecutor;
$this->setLogger($logger);
$this->queues = $queueIds;
}
public function setLogger(LoggerInterface $logger)
{
if ($logger instanceof \Monolog\Logger) {
$this->logger = $logger;
} else {
$this->logger = new Logger('metro', [new PsrHandler($logger)]);
}
}
public function identify()
{
return sprintf("%s@%s", getmypid(), gethostname());
}
/**
* @param int $timeInMilliseconds
* @return void
*/
public function setInterval($timeInMilliseconds)
{
$this->interval = $timeInMilliseconds;
}
public function quitAsap()
{
$this->drainMode = true;
}
public function work()
{
$identity = $this->identify();
$this->logger->notice(sprintf(
'%s waiting for work on queue(s) [%s]',
$identity,
join(', ', $this->queues)
));
for (;;) {
$job = $this->metro->pop($this->queues, $this);
if (null !== $job) {
$jobHandler = $this->metro->createTaskLogHander($job->getId());
$this->logger->pushHandler($jobHandler);
$this->logger->pushProcessor(function ($record) use ($job) {
$record['extra']['job_id'] = $job->getId();
return $record;
});
$this->workOn($job, $jobHandler);
$this->logger->popHandler();
$this->logger->popProcessor();
}
if ($this->interval <= 0) {
return;
}
if (null === $job) {
if ($this->drainMode) {
$this->logger->notice(sprintf('%s exiting because all queues are empty', $identity));
return;
}
usleep($this->interval * 1e3);
}
}
}
private function workOn(CommittedJob $job, HandlerInterface $jobHandler)
{
try {
$this->logger->notice("Starting work on {$job->getId()}");
$logProvider = new LogProvider($this->logger, $jobHandler);
$this->jobExecutor->execute($job, $logProvider);
$this->metro->succeed($job->getId());
$this->logger->notice("Finished work on {$job->getId()}");
} catch (\Exception $e) {
$this->logException($e, $job->getId());
$this->metro->fail($job->getId());
}
}
private function logException(\Exception $e, $jobId)
{
$trace = isset($e->traceString) ? $e->traceString : $e->getTraceAsString();
$this->logger->error("Job $jobId failed: " . $e->getMessage(), ['exception' => $e]);
foreach (explode(PHP_EOL, $trace) as $line) {
$this->logger->error($line);
}
}
}
| metro-q/metro | src/Worker.php | PHP | mit | 3,524 |
<?php
namespace EasiestWay\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
*/
class User extends BaseUser
{
/**
* @var integer
*/
protected $id;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
| easiestway/project | src/EasiestWay/MainBundle/Entity/User.php | PHP | mit | 358 |
package algorithms.sorting;
import java.util.Scanner;
/*
* Sample Challenge
* This is a simple challenge to get things started. Given a sorted array (ar)
* and a number (V), can you print the index location of V in the array?
*
* Input Format:
* There will be three lines of input:
*
* V - the value that has to be searched.
* n - the size of the array.
* ar - n numbers that make up the array.
*
* Output Format:
* Output the index of V in the array.
*
* Constraints:
* 1 <= n <= 1000
* -1000 <= V <= 1000, V is an element of ar
* It is guaranteed that V will occur in ar exactly once.
*
* Sample Input:
* 4
* 6
* 1 4 5 7 9 12
*
* Sample Output:
* 1
*/
public class FindIndexIntro {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int target = sc.nextInt();
int arraySize = sc.nextInt();
int targetIndex = -1;
int arrayIndex = 0;
while (arrayIndex < arraySize) {
if (target == sc.nextInt()) {
targetIndex = arrayIndex;
break;
}
arrayIndex++;
}
sc.close();
System.out.println(targetIndex);
}
} | RCoon/HackerRank | algorithms/sorting/FindIndexIntro.java | Java | mit | 1,297 |
require 'resque'
require 'resque/plugins/heroku_scaler/version'
require 'resque/plugins/heroku_scaler/config'
require 'resque/plugins/heroku_scaler/manager'
require 'resque/plugins/heroku_scaler/worker'
require 'resque/plugins/heroku_scaler/resque'
module Resque
module Plugins
module HerokuScaler
class << self
def run
startup
loop do
begin
scale
rescue Exception => e
log "Scale failed with #{e.class.name} #{e.message}"
end
wait_for_scale
end
end
def scale
required = scale_for(pending)
active = workers
return if required == active
if required > active
log "Scale workers from #{active} to #{required}"
scale_workers(required)
return
end
return if pending?
scale_down(active)
end
def wait_for_scale
sleep Resque::Plugins::HerokuScaler::Config.scale_interval
end
def scale_for(pending)
Resque::Plugins::HerokuScaler::Config.scale_for(pending)
end
def scale_workers(qty)
Resque::Plugins::HerokuScaler::Manager.workers = qty
end
def scale_down(active)
log "Scale #{active} workers down"
lock
timeout = Time.now + Resque::Plugins::HerokuScaler::Config.scale_timeout
until locked == active or Time.now >= timeout
sleep Resque::Plugins::HerokuScaler::Config.poll_interval
end
scale_workers(0)
timeout = Time.now + Resque::Plugins::HerokuScaler::Config.scale_timeout
until Time.now >= timeout
if offline?
log "#{active} workers scaled down successfully"
prune
break
end
sleep Resque::Plugins::HerokuScaler::Config.poll_interval
end
ensure
unlock
end
def workers
Resque::Plugins::HerokuScaler::Manager.workers
end
def offline?
workers.zero?
end
def pending?
pending > 0
end
def pending
Resque.info[:pending]
end
def lock
Resque.lock
end
def unlock
Resque.unlock
end
def locked
Resque.info[:locked]
end
def prune
Resque.prune
end
def configure
yield Resque::Plugins::HerokuScaler::Config
end
def startup
STDOUT.sync = true
trap('TERM') do
log "Shutting down scaler"
exit
end
log "Starting scaler"
unlock
end
def log(message)
puts "*** #{message}"
end
end
end
end
end | aarondunnington/resque-heroku-scaler | lib/resque/plugins/heroku_scaler.rb | Ruby | mit | 2,946 |
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace BlizzardAPI.Wow.DataResources
{
public class CharacterRaces
{
private List<CharacterRace> races = new List<CharacterRace>();
public List<CharacterRace> Races { get => races; set => races = value; }
public CharacterRaces(string region, string locale)
{
var racesData = ApiHelper.GetJsonFromUrl(
$"https://{region}.api.battle.net/wow/data/character/races?locale={locale}&apikey={ApiHandler.ApiKey}"
);
if (racesData == null)
return;
for (var i = 0; i < (racesData["races"] as JArray).Count; i++)
{
Races.Add(new CharacterRace
{
Id = racesData["races"][i]["id"],
Mask = racesData["races"][i]["mask"],
Side = racesData["races"][i]["side"],
Name = racesData["races"][i]["name"]
});
}
}
}
}
| EcadryM/BlizzardAPI | BlizzardAPI/BlizzardAPI.Wow/DataResources/CharacterRaces.cs | C# | mit | 1,046 |
/*
* The Life Simulation Challenge
* https://github.com/dankrusi/life-simulation-challenge
*
* Contributor(s):
* Dan Krusi <dan.krusi@nerves.ch> (original author)
*
* 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.
*/
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace LifeSimulation.Core.GUI
{
public class StartScreen : Form
{
#region Private Variables
private TableLayoutPanel _layout;
private CheckedListBox _checkedListRaces;
private Button _buttonSimulate;
private Label _labelInitialLifelets;
private TrackBar _trackbarInitialLifelets;
#endregion
#region Public Method
public StartScreen () : base()
{
// Init
// Window
//this.ClientSize = new Size(300, 500);
this.Text = "Life Simulation";
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.StartPosition = FormStartPosition.CenterScreen;
// Layout
_layout = new TableLayoutPanel();
_layout.Dock = DockStyle.Fill;
this.Controls.Add(_layout);
// Suspend layouting
_layout.SuspendLayout();
this.SuspendLayout();
// Races list
_checkedListRaces = new CheckedListBox();
_checkedListRaces.Dock = DockStyle.Fill;
_layout.Controls.Add(createLabel("Races to Simulate:"));
_layout.Controls.Add(_checkedListRaces);
// Initial lifelets
_labelInitialLifelets = createLabel("Initial Lifelets:");
_layout.Controls.Add(_labelInitialLifelets);
_trackbarInitialLifelets = new TrackBar();
_trackbarInitialLifelets.Dock = DockStyle.Fill;
_trackbarInitialLifelets.Minimum = 1;
_trackbarInitialLifelets.Maximum = 1000;
_trackbarInitialLifelets.TickStyle = TickStyle.None;
_trackbarInitialLifelets.Scroll += new System.EventHandler(trackbarInitialLifelets_Scroll);
_layout.Controls.Add(_trackbarInitialLifelets);
// Simulate button
_buttonSimulate = new Button();
_buttonSimulate.Dock = DockStyle.Fill;
_buttonSimulate.Text = "Simulate";
_buttonSimulate.Click += new System.EventHandler(buttonSimulate_Click);
_layout.Controls.Add(_buttonSimulate);
// Load races
ArrayList races = World.GetAvailableRaces();
foreach(Type type in races) _checkedListRaces.Items.Add(type,true);
_trackbarInitialLifelets.Value = (races.Count == 0 ? 1 : races.Count * Config.WorldInitialLifeletsPerRace);
// Special cases
if(races.Count == 0) {
_buttonSimulate.Enabled = false;
}
// Resume layouting
_layout.ResumeLayout(false);
_layout.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
// Send of some events
trackbarInitialLifelets_Scroll(null,null);
}
#endregion
#region UI Events
private void buttonSimulate_Click(object sender, EventArgs e) {
// Compile list of races
ArrayList races = new ArrayList();
foreach(Type type in _checkedListRaces.CheckedItems) races.Add(type);
// Create world
World world = new World(races,_trackbarInitialLifelets.Value,Config.WorldInitialSpawnMethod);
// Create and show viewport
Viewport viewport = new Viewport(world);
viewport.Show();
}
private void trackbarInitialLifelets_Scroll(object sender, EventArgs e) {
_labelInitialLifelets.Text = "Initial Lifelets: " + _trackbarInitialLifelets.Value;
}
#endregion
#region Private Methods
private Label createLabel(string text) {
Label lbl = new Label();
lbl.Text = text;
lbl.Dock = DockStyle.Fill;
return lbl;
}
#endregion
}
}
| dankrusi/life-simulation-challenge | Core/GUI/StartScreen.cs | C# | mit | 4,607 |
"""
Django settings for keyman project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$-2ijwgs8-3i*r#j@1ian5xrp+17)fz)%cdjjhwa#4x&%lk7v@'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'keys',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'keyman.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'keyman.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
| htlcnn/pyrevitscripts | HTL.tab/Test.panel/Test.pushbutton/keyman/keyman/keyman/settings.py | Python | mit | 3,109 |
<script src="flowplayer-6.0.5/flowplayer.min.js'"></script>
<script src="flowplayer-6.0.5/flowplayer.dashjs.min.js'"></script>
<script src="flowplayer-6.0.5/flowplayer.hlsjs.min.js'"></script>
<script src="flowplayer-6.0.5/flowplayer.quality-selector.min.js'"></script>
<link rel="flowplayer-6.0.5/skin/functional.css"/>
<link rel="flowplayer-6.0.5/flowplayer.quality-selector.css"/>
<div id="flowvid">
</div>
<script type="text/javascript">
window.onload = function () {
flowplayer("#flowvid", {
embed: false, // setup would need iframe embedding
// manual HLS level selection for Drive videos
hlsQualities: true,
// manual VOD quality selection when hlsjs is not supported
qualities: false, // if this is enabled and same as in hls it would select still mp4
splash:true, // splash vs logo
// logo will download the first part of an mp4 video and display a nice image
// problem with dash,hls: it downloads the complete video
// splash: will do nothing until play is pressed => provide our own image here
clip: {
loop: true,
sources: [
// first hls because it allows manual quality selection
{type:"application/x-mpegurl",src: "<?=$url?>master.m3u8" },
// then comes dash without manual quality selection but still good protocol
{type:"application/dash+xml", src: "<?=$url?>stream.mpd" },
// then mp4 because h264 is the standard and might be played nearly everywhere
{type:"video/mp4", src: "<?=$url?>video_02000.mp4"},
// then webm which has bigger videos and is afaik only required for older opera browsers
{type:"video/webm", src: "<?=$url?>video.webm"}
]
}
});
};
</script>
| balrok/web_video | video.php | PHP | mit | 1,711 |
package sx1272
const (
SX1272_REG_LR_FIFO byte = 0x00
// Common settings
SX1272_REG_LR_OPMODE = 0x01
SX1272_REG_LR_FRFMSB = 0x06
SX1272_REG_LR_FRFMID = 0x07
SX1272_REG_LR_FRFLSB = 0x08
// Tx settings
SX1272_REG_LR_PACONFIG = 0x09
SX1272_REG_LR_PARAMP = 0x0A
SX1272_REG_LR_OCP = 0x0B
// Rx settings
SX1272_REG_LR_LNA = 0x0C
// LoRa registers
SX1272_REG_LR_FIFOADDRPTR = 0x0D
SX1272_REG_LR_FIFOTXBASEADDR = 0x0E
SX1272_REG_LR_FIFORXBASEADDR = 0x0F
SX1272_REG_LR_FIFORXCURRENTADDR = 0x10
SX1272_REG_LR_IRQFLAGSMASK = 0x11
SX1272_REG_LR_IRQFLAGS = 0x12
SX1272_REG_LR_RXNBBYTES = 0x13
SX1272_REG_LR_RXHEADERCNTVALUEMSB = 0x14
SX1272_REG_LR_RXHEADERCNTVALUELSB = 0x15
SX1272_REG_LR_RXPACKETCNTVALUEMSB = 0x16
SX1272_REG_LR_RXPACKETCNTVALUELSB = 0x17
SX1272_REG_LR_MODEMSTAT = 0x18
SX1272_REG_LR_PKTSNRVALUE = 0x19
SX1272_REG_LR_PKTRSSIVALUE = 0x1A
SX1272_REG_LR_RSSIVALUE = 0x1B
SX1272_REG_LR_HOPCHANNEL = 0x1C
SX1272_REG_LR_MODEMCONFIG1 = 0x1D
SX1272_REG_LR_MODEMCONFIG2 = 0x1E
SX1272_REG_LR_SYMBTIMEOUTLSB = 0x1F
SX1272_REG_LR_PREAMBLEMSB = 0x20
SX1272_REG_LR_PREAMBLELSB = 0x21
SX1272_REG_LR_PAYLOADLENGTH = 0x22
SX1272_REG_LR_PAYLOADMAXLENGTH = 0x23
SX1272_REG_LR_HOPPERIOD = 0x24
SX1272_REG_LR_FIFORXBYTEADDR = 0x25
SX1272_REG_LR_FEIMSB = 0x28
SX1272_REG_LR_FEIMID = 0x29
SX1272_REG_LR_FEILSB = 0x2A
SX1272_REG_LR_RSSIWIDEBAND = 0x2C
SX1272_REG_LR_DETECTOPTIMIZE = 0x31
SX1272_REG_LR_INVERTIQ = 0x33
SX1272_REG_LR_DETECTIONTHRESHOLD = 0x37
SX1272_REG_LR_SYNCWORD = 0x39
SX1272_REG_LR_INVERTIQ2 = 0x3B
// end of documented register in datasheet
// I/O settings
SX1272_REG_LR_DIOMAPPING1 = 0x40
SX1272_REG_LR_DIOMAPPING2 = 0x41
// Version
SX1272_REG_LR_VERSION = 0x42
// Additional settings
SX1272_REG_LR_AGCREF = 0x43
SX1272_REG_LR_AGCTHRESH1 = 0x44
SX1272_REG_LR_AGCTHRESH2 = 0x45
SX1272_REG_LR_AGCTHRESH3 = 0x46
SX1272_REG_LR_PLLHOP = 0x4B
SX1272_REG_LR_TCXO = 0x58
SX1272_REG_LR_PADAC = 0x5A
SX1272_REG_LR_PLL = 0x5C
SX1272_REG_LR_PLLLOWPN = 0x5E
SX1272_REG_LR_FORMERTEMP = 0x6C
)
| NeuralSpaz/semtech1301 | sx1272/sx1272LoraRegisters.go | GO | mit | 2,318 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2.Bioinfo
{
public partial class ForceField
{
public class PwVdw : INonbonded, IHessBuilder4PwIntrAct
{
public virtual string[] FrcFldType { get { return new string[] { "Nonbonded", "LennardJones" }; } }
public virtual double? GetDefaultMinimizeStep() { return 0.0001; }
public virtual void EnvClear() { }
public virtual bool EnvAdd(string key, object value) { return false; }
// ! Wildcards used to minimize memory requirements
// NONBONDED NBXMOD 5 ATOM CDIEL FSHIFT VATOM VDISTANCE VFSWITCH -
// CUTNB 14.0 CTOFNB 12.0 CTONNB 10.0 EPS 1.0 E14FAC 1.0 WMIN 1.5
// !
// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
// !
// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
// !
// !atom ignored epsilon Rmin/2 ignored eps,1-4 Rmin/2,1-4
// !
// HT 0.0 -0.0460 0.2245 ! TIP3P
// HN1 0.0 -0.0460 0.2245
// CN7 0.0 -0.02 2.275 0.0 -0.01 1.90 !equivalent to protein CT1
// CN7B 0.0 -0.02 2.275 0.0 -0.01 1.90 !equivalent to protein CT1
// ...
/////////////////////////////////////////////////////////////
public virtual void Compute(Universe.Nonbonded14 nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
double radi = atom1.Rmin2_14; radi = (double.IsNaN(radi)==false) ? radi : atom1.Rmin2;
double radj = atom2.Rmin2_14; radj = (double.IsNaN(radj)==false) ? radj : atom2.Rmin2;
double epsi = atom1.eps_14; epsi = (double.IsNaN(epsi)==false) ? epsi : atom1.epsilon;
double epsj = atom2.eps_14; epsj = (double.IsNaN(epsj)==false) ? epsj : atom2.epsilon;
Compute(nonbonded, coords, ref energy, ref forces, ref hessian, radi, radj, epsi, epsj, pwfrc, pwspr);
}
public virtual void Compute(Universe.Nonbonded nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
double radi = atom1.Rmin2;
double radj = atom2.Rmin2;
double epsi = atom1.epsilon;
double epsj = atom2.epsilon;
Compute(nonbonded, coords, ref energy, ref forces, ref hessian, radi, radj, epsi, epsj, pwfrc, pwspr);
}
public virtual void Compute(Universe.AtomPack nonbonded, Vector[] coords, ref double energy, ref Vector[] forces, ref MatrixByArr[,] hessian
,double radi ,double radj ,double epsi ,double epsj, double[,] pwfrc=null, double[,] pwspr=null)
{
Universe.Atom atom1 = nonbonded.atoms[0];
Universe.Atom atom2 = nonbonded.atoms[1];
Vector pos0 = coords[0];
Vector pos1 = coords[1];
double rmin = (radi + radj);
double epsij = Math.Sqrt(epsi * epsj);
double lenergy, forceij, springij;
Compute(coords, out lenergy, out forceij, out springij, epsij, rmin);
double abs_forceij = Math.Abs(forceij);
if(pwfrc != null) pwfrc[0, 1] = pwfrc[1, 0] = forceij;
if(pwspr != null) pwspr[0, 1] = pwspr[1, 0] = springij;
///////////////////////////////////////////////////////////////////////////////
// energy
energy += lenergy;
///////////////////////////////////////////////////////////////////////////////
// force
if(forces != null)
{
Vector frc0, frc1;
GetForceVector(pos0, pos1, forceij, out frc0, out frc1);
forces[0] += frc0;
forces[1] += frc1;
}
///////////////////////////////////////////////////////////////////////////////
// hessian
if(hessian != null)
{
hessian[0, 1] += GetHessianBlock(coords[0], coords[1], springij, forceij);
hessian[1, 0] += GetHessianBlock(coords[1], coords[0], springij, forceij);
}
}
public static void Compute(Vector[] coords, out double energy, out double forceij, out double springij, double epsij, double rmin)
{
/// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
/// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
/// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
///
/// V(r) = epsij * r0^12 * rij^-12 - 2 * epsij * r0^6 * rij^-6
/// = epsij * (r0 / rij)^12 - 2 * epsij * (r0 / rij)^6
/// F(r) = -12 * epsij * r0^12 * rij^-13 - -6*2 * epsij * r0^6 * rij^-7
/// = -12 * epsij * (r0 / rij)^12 / rij - -6*2 * epsij * (r0 / rij)^6 / rij
/// K(r) = -13*-12 * epsij * r0^12 * rij^-14 - -7*-6*2 * epsij * r0^6 * rij^-8
/// = -13*-12 * epsij * (r0 / rij)^12 / rij^2 - -7*-6*2 * epsij * (r0 / rij)^6 / rij^2
double rij = (coords[1] - coords[0]).Dist;
double rij2 = rij*rij;
double rmin_rij = rmin / rij;
double rmin_rij_2 = rmin_rij * rmin_rij;
double rmin_rij_6 = rmin_rij_2 * rmin_rij_2 * rmin_rij_2;
double rmin_rij_12 = rmin_rij_6 * rmin_rij_6;
energy = epsij * rmin_rij_12 - 2 * epsij * rmin_rij_6;
forceij = (-12) * epsij * rmin_rij_12 / rij - (-6*2) * epsij * rmin_rij_6 / rij;
springij = (-13*-12) * epsij * rmin_rij_12 / rij2 - (-7*-6*2) * epsij * rmin_rij_6 / rij2;
HDebug.AssertIf(forceij>0, rmin<rij); // positive force => attractive
HDebug.AssertIf(forceij<0, rij<rmin); // negative force => repulsive
}
public void BuildHess4PwIntrAct(Universe.AtomPack info, Vector[] coords, out ValueTuple<int, int>[] pwidxs, out PwIntrActInfo[] pwhessinfos)
{
int idx1 = 0; // nonbonded.atoms[0].ID;
int idx2 = 1; // nonbonded.atoms[1].ID;
Universe.Atom atom1 = info.atoms[0];
Universe.Atom atom2 = info.atoms[1];
Vector diff = (coords[idx2] - coords[idx1]);
double dx = diff[0];
double dy = diff[1];
double dz = diff[2];
double radi = double.NaN;
double radj = double.NaN;
double epsi = double.NaN;
double epsj = double.NaN;
if(typeof(Universe.Nonbonded14).IsInstanceOfType(info))
{
radi = atom1.Rmin2_14; radi = (double.IsNaN(radi)==false) ? radi : atom1.Rmin2;
radj = atom2.Rmin2_14; radj = (double.IsNaN(radj)==false) ? radj : atom2.Rmin2;
epsi = atom1.eps_14; epsi = (double.IsNaN(epsi)==false) ? epsi : atom1.epsilon;
epsj = atom2.eps_14; epsj = (double.IsNaN(epsj)==false) ? epsj : atom2.epsilon;
}
if(typeof(Universe.Nonbonded).IsInstanceOfType(info))
{
radi = atom1.Rmin2;
radj = atom2.Rmin2;
epsi = atom1.epsilon;
epsj = atom2.epsilon;
}
HDebug.Assert(double.IsNaN(radi) == false, double.IsNaN(radj) == false, double.IsNaN(epsi) == false, double.IsNaN(epsj) == false);
// !V(Lennard-Jones) = Eps,i,j[(Rmin,i,j/ri,j)**12 - 2(Rmin,i,j/ri,j)**6]
// !epsilon: kcal/mole, Eps,i,j = sqrt(eps,i * eps,j)
// !Rmin/2: A, Rmin,i,j = Rmin/2,i + Rmin/2,j
//
// V(r) = epsij * r0^12 * rij^-12 - 2 * epsij * r0^6 * rij^-6
// F(r) = -12 * epsij * r0^12 * rij^-13 - -6*2 * epsij * r0^6 * rij^-7
// K(r) = -13*-12 * epsij * r0^12 * rij^-14 - -7*-6*2 * epsij * r0^6 * rij^-8
double r = (radi + radj);
double r6 = Math.Pow(r, 6);
double r12 = Math.Pow(r, 12);
double rij2 = (dx*dx + dy*dy + dz*dz);
double rij = Math.Sqrt(rij2);
double rij7 = Math.Pow(rij2, 3)*rij;
double rij8 = Math.Pow(rij2, 4);
double rij13 = Math.Pow(rij2, 6)*rij;
double rij14 = Math.Pow(rij2, 7);
double epsij = epsi*epsj;
double fij = ( -12) * epsij * r12 / rij13 - ( -6*2) * epsij * r6 / rij7;
double kij = (-13*-12) * epsij * r12 / rij14 - (-7*-6*2) * epsij * r6 / rij8;
pwidxs = new ValueTuple<int, int>[1];
pwidxs[0] = new ValueTuple<int, int>(0, 1);
pwhessinfos = new PwIntrActInfo[1];
pwhessinfos[0] = new PwIntrActInfo(kij, fij);
}
}
}
}
| htna/HCsbLib | HCsbLib/HCsbLib/HTLib2.Bioinfo/ForceField/ForceField.Pw/ForceField.PwVdw.cs | C# | mit | 10,124 |