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 |
|---|---|---|---|---|---|
<?php
/**
* Mirasvit
*
* This source file is subject to the Mirasvit Software License, which is available at http://mirasvit.com/license/.
* Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
* If you wish to customize this module for your needs
* Please refer to http://www.magentocommerce.com for more information.
*
* @category Mirasvit
* @package Sphinx Search Ultimate
* @version 2.3.1
* @revision 675
* @copyright Copyright (C) 2014 Mirasvit (http://mirasvit.com/)
*/
class Mirasvit_SearchIndex_Model_Index_External_Joomla_Zoo_Item extends Varien_Object
{
public function getContent()
{
$elements = json_decode($this->getElements(), true);
$content = array();
foreach ($elements as $element) {
foreach ($element as $value) {
if (isset($value['value'])) {
$content[] = $value['value'];
}
}
}
$content = implode(' ', $content);
return $content;
}
public function getUrl()
{
$url = $this->getIndex()->getProperty('url_template');
foreach ($this->getData() as $key => $value) {
$key = strtolower($key);
$url = str_replace('{'.$key.'}', $value, $url);
}
return $url;
}
public function getIndex()
{
return Mage::helper('searchindex/index')->getIndexModel('external_joomla_zoo');
}
} | mikrotikAhmet/mbe-cpdev | app/code/local/Mirasvit/SearchIndex/Model/Index/External/Joomla/Zoo/Item.php | PHP | mit | 1,474 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp.Controllers
{
public class DevelopersController : Controller
{
//
// GET: /Developer/
public ActionResult Index()
{
return View();
}
}
} | jdnichollsc/Javascript-Games | WebApp/Controllers/DevelopersController.cs | C# | mit | 325 |
package org.sdmlib.openbank.util;
import org.sdmlib.models.pattern.PatternObject;
import org.sdmlib.openbank.FeeValue;
import org.sdmlib.openbank.TransactionTypeEnum;
import org.sdmlib.models.pattern.AttributeConstraint;
import org.sdmlib.models.pattern.Pattern;
import java.math.BigInteger;
import org.sdmlib.openbank.util.BankPO;
import org.sdmlib.openbank.Bank;
import org.sdmlib.openbank.util.FeeValuePO;
public class FeeValuePO extends PatternObject<FeeValuePO, FeeValue>
{
public FeeValueSet allMatches()
{
this.setDoAllMatches(true);
FeeValueSet matches = new FeeValueSet();
while (this.getPattern().getHasMatch())
{
matches.add((FeeValue) this.getCurrentMatch());
this.getPattern().findMatch();
}
return matches;
}
public FeeValuePO(){
newInstance(null);
}
public FeeValuePO(FeeValue... hostGraphObject) {
if(hostGraphObject==null || hostGraphObject.length<1){
return ;
}
newInstance(null, hostGraphObject);
}
public FeeValuePO(String modifier)
{
this.setModifier(modifier);
}
public FeeValuePO createTransTypeCondition(TransactionTypeEnum value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_TRANSTYPE)
.withTgtValue(value)
.withSrc(this)
.withModifier(this.getPattern().getModifier())
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public FeeValuePO createTransTypeAssignment(TransactionTypeEnum value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_TRANSTYPE)
.withTgtValue(value)
.withSrc(this)
.withModifier(Pattern.CREATE)
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public TransactionTypeEnum getTransType()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) getCurrentMatch()).getTransType();
}
return null;
}
public FeeValuePO withTransType(TransactionTypeEnum value)
{
if (this.getPattern().getHasMatch())
{
((FeeValue) getCurrentMatch()).setTransType(value);
}
return this;
}
public FeeValuePO createPercentCondition(BigInteger value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_PERCENT)
.withTgtValue(value)
.withSrc(this)
.withModifier(this.getPattern().getModifier())
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public FeeValuePO createPercentAssignment(BigInteger value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_PERCENT)
.withTgtValue(value)
.withSrc(this)
.withModifier(Pattern.CREATE)
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public BigInteger getPercent()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) getCurrentMatch()).getPercent();
}
return null;
}
public FeeValuePO withPercent(BigInteger value)
{
if (this.getPattern().getHasMatch())
{
((FeeValue) getCurrentMatch()).setPercent(value);
}
return this;
}
public BankPO createBankPO()
{
BankPO result = new BankPO(new Bank[]{});
result.setModifier(this.getPattern().getModifier());
super.hasLink(FeeValue.PROPERTY_BANK, result);
return result;
}
public BankPO createBankPO(String modifier)
{
BankPO result = new BankPO(new Bank[]{});
result.setModifier(modifier);
super.hasLink(FeeValue.PROPERTY_BANK, result);
return result;
}
public FeeValuePO createBankLink(BankPO tgt)
{
return hasLinkConstraint(tgt, FeeValue.PROPERTY_BANK);
}
public FeeValuePO createBankLink(BankPO tgt, String modifier)
{
return hasLinkConstraint(tgt, FeeValue.PROPERTY_BANK, modifier);
}
public Bank getBank()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) this.getCurrentMatch()).getBank();
}
return null;
}
}
| SWE443-TeamRed/open-bank | open-bank/src/main/java/org/sdmlib/openbank/util/FeeValuePO.java | Java | mit | 4,269 |
var WALKING_SPEED_RATIO = 30; // how many times faster than walking speed are you?
var FIRST_PERSON = false;
var RESET_CAMERA_POSITION = function() {camera.position.set(-168, 25, -17);}
var PATH_ANIMATION_RUNNING = false;
function endPathAnimation() {
PATH_ANIMATION_RUNNING = false;
}
function nextCameraTween(path, index, sf, ef) {
var start = convertVec(coords[path[index]]);
var end = convertVec(coords[path[index+1]]);
if (index === 0) {start = (new THREE.Vector3()).lerpVectors(start, end, sf);}
if (index+1 === path.length - 1) {end = (new THREE.Vector3()).lerpVectors(start, end, 1-ef);}
var tween = new TWEEN.Tween(start).to(end, 500+start.distanceTo(end)*1400/WALKING_SPEED_RATIO);
tween.easing(TWEEN.Easing.Quadratic.InOut);
var dir = (new THREE.Vector3()).subVectors(end, start).normalize();
tween.onUpdate(function(){
controls.target = start;
});
if (index === path.length - 2) {
tween.onComplete(endPathAnimation);
return tween;
} else {
return tween.chain(nextCameraTween(path,index+1, sf, ef));
}
} | oliverodaa/cs184-final-proj | dwinelle/web/js/camera_helpers.js | JavaScript | mit | 1,100 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GeneralLevel : Level
{
public float completeLevelWaitTimeInSecs = 2;
private bool completeLevelTriggered;
private IEnumerator CompleteLevel()
{
yield return new WaitForSeconds(this.completeLevelWaitTimeInSecs);
if(SceneManager.GetActiveScene().buildIndex < SceneManager.sceneCount - 1)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
else
{
SceneManager.LoadScene("Credits");
}
}
public void CheckForCompletion()
{
StartCoroutine(GameManager.Instance.CheckIfWon());
}
public override void TriggerCompleteLevel()
{
if (!this.completeLevelTriggered)
{
this.completeLevelTriggered = true;
base.TriggerCompleteLevel();
StartCoroutine(this.CompleteLevel());
}
}
}
| p4dd9/ngj17_spirit | Assets/Scripts/GeneralLevel.cs | C# | mit | 1,012 |
<?php
/* AcmeDemoBundle:Secured:helloadmin.html.twig */
class __TwigTemplate_3423e47098ba90b7664f14d13a3832e1 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->blocks = array(
'title' => array($this, 'block_title'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "AcmeDemoBundle:Secured:layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 9
$context["code"] = $this->env->getExtension('demo')->getCode($this);
$this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = array())
{
echo twig_escape_filter($this->env, ("Hello " . $this->getContext($context, "name")), "html", null, true);
}
// line 5
public function block_content($context, array $blocks = array())
{
// line 6
echo " <h1>Hello ";
echo twig_escape_filter($this->env, $this->getContext($context, "name"), "html", null, true);
echo " secured for Admins only!</h1>
";
}
public function getTemplateName()
{
return "AcmeDemoBundle:Secured:helloadmin.html.twig";
}
public function isTraitable()
{
return false;
}
}
| pepesan/Ejemplo-Symfony2 | app/cache/dev/twig/34/23/e47098ba90b7664f14d13a3832e1.php | PHP | mit | 1,472 |
//! moment.js locale configuration
//! locale : Galician [gl]
//! author : Juan G. Hurtado : https://github.com/juanghurtado
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var gl = moment.defineLocale('gl', {
months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'),
monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'),
monthsParseExact: true,
weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),
weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D [de] MMMM [de] YYYY',
LLL : 'D [de] MMMM [de] YYYY H:mm',
LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
},
calendar : {
sameDay : function () {
return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
},
nextDay : function () {
return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
},
nextWeek : function () {
return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
},
lastDay : function () {
return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT';
},
lastWeek : function () {
return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
},
sameElse : 'L'
},
relativeTime : {
future : function (str) {
if (str.indexOf('un') === 0) {
return 'n' + str;
}
return 'en ' + str;
},
past : 'hai %s',
s : 'uns segundos',
m : 'un minuto',
mm : '%d minutos',
h : 'unha hora',
hh : '%d horas',
d : 'un día',
dd : '%d días',
M : 'un mes',
MM : '%d meses',
y : 'un ano',
yy : '%d anos'
},
ordinalParse : /\d{1,2}º/,
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return gl;
})); | OdimTech/Sisacon | Sisacon/Sisacon.UI/node_modules/fullcalendar/node_modules/moment/locale/gl.js | JavaScript | mit | 2,901 |
<?php
/* SensioDistributionBundle::Configurator/final.html.twig */
class __TwigTemplate_1d6d06e92ecd114d845ffc58222524b8 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("SensioDistributionBundle::Configurator/layout.html.twig");
$this->blocks = array(
'content_class' => array($this, 'block_content_class'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "SensioDistributionBundle::Configurator/layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content_class($context, array $blocks = array())
{
echo "config_done";
}
// line 4
public function block_content($context, array $blocks = array())
{
// line 5
echo " <div class=\"step\">
<h1>Well done!</h1>
";
// line 7
if ($this->getContext($context, "is_writable")) {
// line 8
echo " <h2>Your distribution is configured!</h2>
";
} else {
// line 10
echo " <h2 class=\"configure-error\">Your distribution is almost configured but...</h2>
";
}
// line 12
echo " <h3>
<span>
";
// line 14
if ($this->getContext($context, "is_writable")) {
// line 15
echo " Your parameters.yml file has been overwritten with these parameters (in <em>";
echo twig_escape_filter($this->env, $this->getContext($context, "yml_path"), "html", null, true);
echo "</em>):
";
} else {
// line 17
echo " Your parameters.yml file is not writeable! Here are the parameters you can copy and paste in <em>";
echo twig_escape_filter($this->env, $this->getContext($context, "yml_path"), "html", null, true);
echo "</em>:
";
}
// line 19
echo " </span>
</h3>
<textarea class=\"symfony-configuration\">";
// line 22
echo twig_escape_filter($this->env, $this->getContext($context, "parameters"), "html", null, true);
echo "</textarea>
";
// line 24
if ($this->getContext($context, "welcome_url")) {
// line 25
echo " <ul>
<li><a href=\"";
// line 26
echo twig_escape_filter($this->env, $this->getContext($context, "welcome_url"), "html", null, true);
echo "\">Go to the Welcome page</a></li>
</ul>
";
}
// line 29
echo " </div>
";
}
public function getTemplateName()
{
return "SensioDistributionBundle::Configurator/final.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 91 => 29, 85 => 26, 82 => 25, 80 => 24, 75 => 22, 70 => 19, 64 => 17, 58 => 15, 56 => 14, 52 => 12, 48 => 10, 44 => 8, 42 => 7, 38 => 5, 35 => 4, 29 => 3,);
}
}
| evgeny-s/symfony | app/cache/dev/twig/1d/6d/06e92ecd114d845ffc58222524b8.php | PHP | mit | 3,462 |
/*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Symbols chart
// ------------------------------
$(window).on("load", function(){
function generate(offset, amplitude) {
var res = [];
var start = 0, end = 10;
for (var i = 0; i <= 50; ++i) {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);
}
return res;
}
var data = [
{ data: generate(2, 1.8), points: { symbol: "circle" } },
{ data: generate(3, 1.5), points: { symbol: "square" } },
{ data: generate(4, 0.9), points: { symbol: "diamond" } },
{ data: generate(6, 1.4), points: { symbol: "triangle" } },
{ data: generate(7, 1.1), points: { symbol: "cross" } }
];
$.plot("#symbols", data, {
series: {
points: {
show: true,
radius: 3
}
},
grid: {
borderWidth: 1,
borderColor: "#e9e9e9",
color: '#999',
minBorderMargin: 20,
labelMargin: 10,
margin: {
top: 8,
bottom: 20,
left: 20
},
hoverable: true
},
colors: ['#00A5A8', '#626E82', '#FF7D4D','#FF4558', '#1B2942']
});
}); | areleogitdev/areleofinish | areleo/app-assets/js/scripts/charts/flot/line/symbols.js | JavaScript | mit | 1,770 |
#include <mimosa/options/options.hh>
#include "options.hh"
namespace hefur
{
const uint32_t & MAX_PEERS = *mo::addOption<uint32_t>(
"", "max-peers", "the maximum number of peers per torrent",
30000);
const uint32_t & MAX_TORRENT_SIZE = *mo::addOption<uint32_t>(
"", "max-torrent-size", "the maximum torrent size, in MiB",
10);
const uint32_t & MAX_TORRENT_NAME = *mo::addOption<uint32_t>(
"", "max-torrent-name", "the maximum torrent name length to truncate to",
64);
const uint32_t & MAX_SCAN_DEPTH = *mo::addOption<uint32_t>(
"", "max-scan-depth", "the maximum depth while scanning torrent-dir",
64);
const uint32_t & MAX_SCAN_INODES = *mo::addOption<uint32_t>(
"", "max-scan-inodes", "the maximum number of inode to scan while scanning torrent-dir",
128 * 1024);
const uint32_t & ANNOUNCE_INTERVAL = *mo::addOption<uint32_t>(
"", "announce-interval", "the duration in minutes between two announces",
15);
const uint32_t & SCRAPE_INTERVAL = *mo::addOption<uint32_t>(
"", "scrape-interval", "the duration in minutes between two scrapes",
15);
const uint32_t & HTTP_TIMEOUT = *mo::addOption<uint32_t>(
"", "http-timeout", "the number of milliseconds to wait until timeout", 2000);
const uint16_t & HTTP_PORT = *mo::addOption<uint16_t>(
"", "http-port", "the port to use, 0 to disable", 6969);
const uint16_t & HTTPS_PORT = *mo::addOption<uint16_t>(
"", "https-port", "the port to use, 0 to disable", 6970);
const uint16_t & UDP_PORT = *mo::addOption<uint16_t>(
"", "udp-port", "the port to use, 0 to disable", 6969);
const bool & IPV6 = *mo::addSwitch(
"", "ipv6", "bind on ipv6 instead of ipv4");
const bool & ALLOW_PROXY = *mo::addSwitch(
"", "allow-proxy", "allow the peer to specify its address (so usage of proxies)");
const bool & DISABLE_PEERS_PAGE = *mo::addSwitch(
"", "disable-peers-page", "disable the HTTP page /peers, which list torrent's peers");
const bool & DISABLE_STAT_PAGE = *mo::addSwitch(
"", "disable-stat-page", "disable the HTTP page /stat, which list served torrents");
const bool & DISABLE_FILE_PAGE = *mo::addSwitch(
"", "disable-file-page", "disable the HTTP page /file, which serve .torrent files");
const std::string & CERT = *mo::addOption<std::string>(
"", "http-cert", "the path to the certificate", "");
const std::string & KEY = *mo::addOption<std::string>(
"", "http-key", "the path to the key", "");
const std::string & TORRENT_DIR = *mo::addOption<std::string>(
"", "torrent-dir",
"the directory containing the allowed torrents,"
" if empty every torrents are allowed", "");
const uint32_t & SCAN_INTERVAL = *mo::addOption<uint32_t>(
"", "scan-interval", "the duration in seconds between two torrent-dir scans",
60);
const char * VERSION_MSG = mo::addMessage(
"", "version", "display the software's version",
"hefurd " HEFUR_VERSION "\n"
"Copyright (C) 2012 Alexandre Bique\n"
"License: MIT\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.");
const std::string & WWW_DIR = *mo::addOption<std::string>(
"", "www-dir",
"the directory containing the web data files (html, css, img)",
"/usr/share/hefur/www");
const std::string & CONTROL_SOCKET = *mo::addOption<std::string>(
"", "control-socket",
"the path to the control socket",
"/var/run/hefur/control");
}
| UIKit0/hefur | hefur/options.cc | C++ | mit | 3,505 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security;
namespace SQLDashboard.Controllers
{
public class AccountController : Controller
{
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);
HttpContext.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
public ActionResult SignOutCallback()
{
if (Request.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction("Index", "Home");
}
return View();
}
}
}
| MindFlavor/SQLDashboard | SQLDashboard/Controllers/AccountController.cs | C# | mit | 1,430 |
// T4 code generation is enabled for model 'C:\Users\maor gigi\documents\visual studio 2013\Projects\MVc_Assignment2\MVc_Assignment2\dataStore.edmx'.
// To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
// property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
// is open in the designer.
// If no context and entity classes have been generated, it may be because you created an empty model but
// have not yet chosen which version of Entity Framework to use. To generate a context class and entity
// classes for your model, open the model in the designer, right-click on the designer surface, and
// select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
// Item...'. | gigimaor/shoping-cart.net | dataStore.Designer.cs | C# | mit | 810 |
class User < ActiveRecord::Base
tango_user
simple_roles
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:token_authenticatable, :confirmable, :lockable,
:timeoutable
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :time_zone
validates :name,
:uniqueness => { :case_sensitive => false },
:length => { :minimum => 3, :maximum => 24 },
:allow_blank => false,
:format => { :with => /\A[a-z0-9]+(\s[a-z0-9]+)*\z/i }
before_save { self.email = email.downcase }
has_many :news, :dependent => :nullify
has_many :posts, :dependent => :nullify
has_many :topics, :dependent => :nullify
def self.guest
session[:guest_user] ||= Guest.new # create Guest model (usually not to be persisted!)
end
def roles_list(dummy=nil)
[:guest] + self.roles
end
def to_s
self.name
end
def to_param
"#{self.id}-#{self.name.parameterize}"
end
end
| Portalcake/gaming-base-core | app/models/user.rb | Ruby | mit | 1,076 |
# http://www.codewars.com/kata/54ff3102c1bad923760001f3
# --- iteration 1 ---
def getCount(str)
str.tr("^aeiou", "").size
end
| etdev/algorithms | 0_code_wars/vowel_count.rb | Ruby | mit | 129 |
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
namespace KspCraftOrganizer
{
public class SettingsService
{
private static readonly float PLUGIN_READ_TIME_THRESHOLD = 30;
private float lastPluginSettingsReadingTime;
private IKspAl ksp = IKspAlProvider.instance;
private FileLocationService fileLocationService = FileLocationService.instance;
private PluginSettings cachedPluginSettings;
public static readonly SettingsService instance = new SettingsService();
public ProfileSettingsDto readProfileSettings(string saveName){
return ksp.readProfileSettings(fileLocationService.getProfileSettingsFile(saveName), getPluginSettings().defaultAvailableTags);
}
public void writeProfileSettings(string saveName, ProfileSettingsDto dto)
{
ksp.writeProfileSettings(fileLocationService.getProfileSettingsFile(saveName), dto);
}
public void writeCraftSettingsForCraftFile(string craftFilePath, CraftSettingsDto dto) {
ksp.writeCraftSettings(fileLocationService.getCraftSettingsFileForCraftFile(craftFilePath), dto);
}
public CraftSettingsDto readCraftSettingsForCraftFile(string craftFilePath) {
return ksp.readCraftSettings(fileLocationService.getCraftSettingsFileForCraftFile(craftFilePath));
}
public CraftSettingsDto readCraftSettingsForCurrentCraft() {
return ksp.readCraftSettings(fileLocationService.getCraftSettingsFileForCraftFile(fileLocationService.getCraftSaveFilePathForCurrentShip()));
}
public void addAvailableTag(string saveName, string newTag) {
ProfileSettingsDto profileSettings = readProfileSettings(saveName);
SortedList<string, string> tags = new SortedList<string, string>();
foreach (string t in profileSettings.availableTags) {
if (!tags.ContainsKey(t)) {
tags.Add(t, t);
}
}
if (!tags.ContainsKey(newTag)) {
tags.Add(newTag, newTag);
profileSettings.availableTags = tags.Keys;
writeProfileSettings(saveName, profileSettings);
}
}
public PluginSettings getPluginSettings() {
if (cachedPluginSettings == null || (Time.realtimeSinceStartup - lastPluginSettingsReadingTime) > PLUGIN_READ_TIME_THRESHOLD) {
cachedPluginSettings = ksp.getPluginSettings(fileLocationService.getPluginSettingsPath());
lastPluginSettingsReadingTime = Time.realtimeSinceStartup;
}
return cachedPluginSettings;
}
}
}
| grzegrzk/ksp-craft-organizer | KspCraftOrganizerPlugin/services/SettingsService.cs | C# | mit | 2,374 |
/**
* Heldesks' code (Zendesk, etc..)
*/
App.helpdesk = {
init: function () {
// fetch template content from the extension
if (window.location.hostname.indexOf('zendesk.com') !== -1) {
App.helpdesk.zendesk.init();
}
},
zendesk: {
init: function () {
// inject the zendesk script into the dom
var script = document.createElement('script');
script.type = "text/javascript";
script.src = chrome.extension.getURL("pages/helpdesk/zendesk.js");
if (document.body) {
document.body.appendChild(script);
script.onload = function () {
document.body.removeChild(script);
};
}
// forward the message to the
window.addEventListener('message', function(event) {
if (event.data && event.data.request && event.data.request === 'suggestion-used') {
chrome.runtime.sendMessage({
'request': 'suggestion-used',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'template_id': event.data.template_id
}
});
}
});
var ticketUrl = "";
var ticketInterval = setInterval(function () {
if (window.location.pathname.indexOf('/agent/tickets/') !== -1) {
if (!ticketUrl || ticketUrl !== window.location.pathname) {
ticketUrl = window.location.pathname;
$('.macro-suggestions-container').remove();
var bodyInterval = setInterval(function () {
var subject = '';
var body = '';
$('.workspace').each(function (i, workspace) {
workspace = $(workspace);
if (workspace.css('display') !== 'none') {
var firstEvent = workspace.find('.event-container .event:first');
var isAgent = firstEvent.find('.user_photo').hasClass('agent');
// If it's an agent who has the last comment no point in suggesting anything
if (isAgent) {
return false;
}
subject = workspace.find('input[name=subject]').val();
body = firstEvent.find('.zd-comment').text();
}
});
if (!subject || !subject.length || !body.length) {
return;
}
clearInterval(bodyInterval);
chrome.runtime.sendMessage({
'request': 'suggestion',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'subject': subject,
'to': '',
'cc': '',
'bcc': '',
'from': '',
'body': body,
'helpdesk': 'zendesk'
}
}, function (macros) {
if (!_.size(macros)) {
return;
}
$('.macro-suggestions-container').remove();
var macroContainer = $("<div class='macro-suggestions-container'>");
for (var i in macros) {
var macro = macros[i];
var macroBtn = $("<a class='macro-suggestion'>");
var macroEl = $("<span class='macro-title'>");
/*
var scoreEl = $('<span class="macro-score"> </span>');
if (macro.score >= 0.9) {
scoreEl.addClass('macro-score-high');
}
if (macro.score >= 0.7 && macro.score < 0.9) {
scoreEl.addClass('macro-score-medium');
}
if (macro.score < 0.7) {
scoreEl.addClass('macro-score-low');
}
*/
macroBtn.attr('onclick', "gorgiasApplyMacroSuggestion(" + macro["external_id"] + ")");
macroBtn.attr('title', macro.body.replace(/\n/g, "<br />"));
macroBtn.attr('data-toggle', "tooltip");
macroBtn.attr('data-html', "true");
macroBtn.attr('data-placement', "bottom");
macroEl.html(macro.title);
macroBtn.append(macroEl);
//macroBtn.append(scoreEl);
macroContainer.append(macroBtn);
}
$('.comment_input .content .options').before(macroContainer);
});
}, 200);
}
} else {
ticketUrl = "";
}
}, 200);
}
}
};
| haveal/gorgias-chrome | src/content/js/helpdesk.js | JavaScript | mit | 6,435 |
/**
* @file tiledb_list.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* 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.
*
* @section DESCRIPTION
*
* It shows how to explore the contents of a TileDB directory.
*/
#include "tiledb.h"
#include <cstdio>
#include <cstdlib>
int main(int argc, char** argv) {
// Sanity check
if(argc != 2) {
fprintf(stderr, "Usage: ./tiledb_list parent_dir\n");
return -1;
}
// Initialize context with the default configuration parameters
TileDB_CTX* tiledb_ctx;
tiledb_ctx_init(&tiledb_ctx, NULL);
// Retrieve number of directories
int dir_num;
tiledb_ls_c(tiledb_ctx, argv[1], &dir_num);
// Exit if there are not TileDB objects in the input directory_
if(dir_num == 0)
return 0;
// Initialize variables
char** dirs = new char*[dir_num];
int* dir_types = new int[dir_num];
for(int i=0; i<dir_num; ++i)
dirs[i] = (char*) malloc(TILEDB_NAME_MAX_LEN);
// List TileDB objects
tiledb_ls(
tiledb_ctx, // Context
argv[1], // Parent directory
dirs, // Directories
dir_types, // Directory types
&dir_num); // Directory number
// Print TileDB objects
for(int i=0; i<dir_num; ++i) {
printf("%s ", dirs[i]);
if(dir_types[i] == TILEDB_ARRAY)
printf("ARRAY\n");
else if(dir_types[i] == TILEDB_METADATA)
printf("METADATA\n");
else if(dir_types[i] == TILEDB_GROUP)
printf("GROUP\n");
else if(dir_types[i] == TILEDB_WORKSPACE)
printf("WORKSPACE\n");
}
// Clean up
for(int i=0; i<dir_num; ++i)
free(dirs[i]);
free(dirs);
free(dir_types);
// Finalize context
tiledb_ctx_finalize(tiledb_ctx);
return 0;
}
| Intel-HLS/TileDB | examples/src/tiledb_ls.cc | C++ | mit | 2,958 |
/**
* Author: thegoldenmule
* Date: 3/17/13
*/
(function (global) {
"use strict";
var colorShaderVS = {
name: "color-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// calculate color
"vColor = uColor * aColor;" +
"}"
};
var colorShaderFS = {
name: "color-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"void main(void) {" +
"gl_FragColor = vColor;" +
"}"
};
var textureShaderVS = {
name: "texture-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = aColor * uColor;" +
"vUV = aUV;" +
"}"
};
var textureShaderFS = {
name: "texture-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"void main(void) {" +
"gl_FragColor = texture2D(uMainTextureSampler, vUV) * vColor;" +
"}"
};
var spriteSheetShaderVS = {
name: "ss-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec4 vVertexColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = uColor;" +
// note that in this shader, color.xy is the previous frame's uvs!
"vUV = aUV;" +
"vVertexColor = aColor;" +
"}"
};
var spriteSheetShaderFS = {
name: "ss-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec4 vVertexColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"uniform float uFutureBlendScalar;" +
"void main(void) {" +
"vec4 currentFrame = texture2D(uMainTextureSampler, vUV);" +
"vec4 futureFrame = texture2D(uMainTextureSampler, vec2(vVertexColor.xy));" +
"gl_FragColor = futureFrame * uFutureBlendScalar + currentFrame * (1.0 - uFutureBlendScalar);" +
"}"
};
var boundingBoxShaderVS = {
name: "bb-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 0.0, 1.0);" +
"vUV = aUV;" +
"}"
};
var boundingBoxShaderFS = {
name: "bb-shader-fs",
type: "x-shader/x-fragment",
body:
"varying vec2 vUV;" +
"void main(void) {" +
"gl_FragColor = vec4(1.0, 0.0, 0.0, 0.2);" +
"}"
};
var particleShaderVS = {
name: "particle-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = aColor * uColor;" +
"vUV = aUV;" +
"}"
};
var particleShaderFS = {
name: "particle-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"void main(void) {" +
"gl_FragColor = texture2D(uMainTextureSampler, vUV) * vColor;" +
"}"
};
global.__DEFAULT_SHADERS = [
colorShaderVS,
colorShaderFS,
textureShaderVS,
textureShaderFS,
spriteSheetShaderFS,
spriteSheetShaderVS,
boundingBoxShaderVS,
boundingBoxShaderFS,
particleShaderVS,
particleShaderFS
];
})(this); | thegoldenmule/boX | js/boX/DefaultShaders.js | JavaScript | mit | 6,653 |
// https://discuss.leetcode.com/topic/71438/c-dp-solution-with-comments
// https://discuss.leetcode.com/topic/76103/0-1-knapsack-detailed-explanation
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m+1][n+1];
for(String s : strs) {
int zeros = 0, ones = 0;
for(char c : s.toCharArray()) {
if(c - '0' == 0) zeros++;
else ones++;
}
// has to go from bigger to lower to avoid count the current string multiple times.
for(int i=m; i>=zeros; i--) {
for(int j=n; j>=ones; j--) {
dp[i][j] = Math.max(dp[i][j], 1+dp[i-zeros][j-ones]);
}
} // else not able to select the current string, no change to dp[i][j].
}
return dp[m][n];
}
}
| l33tnobody/l33t_sol | src/474OnesAndZeros.java | Java | mit | 867 |
module VirtualBox
module COM
module Interface
module Version_4_1_X
class ExecuteProcessStatus < AbstractEnum
map :undefined => 0,
:started => 1,
:terminated_normally => 2,
:terminated_signal => 3,
:terminated_abnormally => 4,
:timed_out_killed => 5,
:timed_out_abnormally => 6,
:down => 7,
:error => 8
end
end
end
end
end
| mitchellh/virtualbox | lib/virtualbox/com/interface/4.1.x/ExecuteProcessStatus.rb | Ruby | mit | 486 |
namespace StackFaceSystem.Data.Common.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public abstract class BaseModel<TKey> : IAuditInfo, IDeletableEntity
{
[Key]
public TKey Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
[Index]
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
}
} | EmilMitev/ASP.NET-MVC-Course-Project | Source/StackFaceSystem/Data/StackFaceSystem.Data.Common/Models/BaseModel{TKey}.cs | C# | mit | 522 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.queryProcessor.decomposer.query.visitors;
import com.foundationdb.sql.StandardException;
import com.foundationdb.sql.parser.FromSubquery;
import com.foundationdb.sql.parser.SelectNode;
import com.foundationdb.sql.parser.Visitable;
import madgik.exareme.master.queryProcessor.decomposer.query.SQLQuery;
/**
* @author heraldkllapi
*/
public class SelectVisitor extends AbstractVisitor {
public SelectVisitor(SQLQuery query) {
super(query);
}
@Override
public Visitable visit(Visitable node) throws StandardException {
if (node instanceof SelectNode) {
if (((SelectNode) node).isDistinct()) {
query.setOutputColumnsDistinct(true);
}
// Result columns
ResultColumnsVisitor projectVisitor = new ResultColumnsVisitor(query);
node.accept(projectVisitor);
// Input tables
FromListVisitor fromVisitor = new FromListVisitor(query);
node.accept(fromVisitor);
// Where conditions
WhereClauseVisitor whereVisitor = new WhereClauseVisitor(query);
whereVisitor.setVisitedJoin(true);
node.accept(whereVisitor);
// Group by
GroupByListVisitor groupByVisitor = new GroupByListVisitor(query);
node.accept(groupByVisitor);
return node;
}
return node;
}
@Override
public boolean skipChildren(Visitable node) {
return FromSubquery.class.isInstance(node);
}
}
| madgik/exareme | Exareme-Docker/src/exareme/exareme-master/src/main/java/madgik/exareme/master/queryProcessor/decomposer/query/visitors/SelectVisitor.java | Java | mit | 1,601 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
root.ng.common.locales['nl-sr'] = [
'nl-SR',
[['a.m.', 'p.m.'], u, u],
u,
[
['Z', 'M', 'D', 'W', 'D', 'V', 'Z'], ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'jan.', 'feb.', 'mrt.', 'apr.', 'mei', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.',
'dec.'
],
[
'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september',
'oktober', 'november', 'december'
]
],
u,
[['v.C.', 'n.C.'], ['v.Chr.', 'n.Chr.'], ['voor Christus', 'na Christus']],
1,
[6, 0],
['dd-MM-y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, '{1} \'om\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00;¤ -#,##0.00', '#E0'],
'$',
'Surinaamse dollar',
{
'AUD': ['AU$', '$'],
'CAD': ['C$', '$'],
'FJD': ['FJ$', '$'],
'JPY': ['JP¥', '¥'],
'SBD': ['SI$', '$'],
'SRD': ['$'],
'THB': ['฿'],
'TWD': ['NT$'],
'USD': ['US$', '$'],
'XPF': [],
'XXX': []
},
plural,
[
[['middernacht', '’s ochtends', '’s middags', '’s avonds', '’s nachts'], u, u],
[['middernacht', 'ochtend', 'middag', 'avond', 'nacht'], u, u],
['00:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '06:00']]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| mhevery/angular | packages/common/locales/global/nl-SR.js | JavaScript | mit | 2,475 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-22a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22
{
#ifndef OMITBAD
/* The global variable below is used to drive control flow in the sink function. Since it is in
a C++ namespace, it doesn't need a globally unique name. */
int badGlobal = 0;
void badSink(wchar_t * data);
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
badGlobal = 1; /* true */
badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The global variables below are used to drive control flow in the sink functions. Since they are in
a C++ namespace, they don't need globally unique names. */
int goodB2G1Global = 0;
int goodB2G2Global = 0;
int goodG2B1Global = 0;
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void goodB2G1Sink(wchar_t * data);
static void goodB2G1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
goodB2G1Global = 0; /* false */
goodB2G1Sink(data);
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void goodB2G2Sink(wchar_t * data);
static void goodB2G2()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
goodB2G2Global = 1; /* true */
goodB2G2Sink(data);
}
/* goodG2B1() - use goodsource and badsink */
void goodG2B1Sink(wchar_t * data);
static void goodG2B1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new */
data = new wchar_t;
goodG2B1Global = 1; /* true */
goodG2B1Sink(data);
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| maurer/tiamat | samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22a.cpp | C++ | mit | 3,767 |
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace SVX
{
public static class Utils
{
public static string ToUrlSafeBase64String(byte[] data)
{
return Convert.ToBase64String(data).Replace('+', '-').Replace('/', '_');
}
// The Contains method is failing to resolve: probably some BCT or CCI
// bug, which might be fixed in the new CCI. This isn't reached in the
// vProgram, so just get rid of the error for now.
// ~ t-mattmc@microsoft.com 2016-07-05
[BCTOmitImplementation]
public static byte[] FromUrlSafeBase64String(string data)
{
if (data.Contains('+') || data.Contains('/'))
throw new ArgumentException("Invalid url-safe base64 input");
return Convert.FromBase64String(data.Replace('-', '+').Replace('_', '/'));
}
public static string RandomIdString()
{
return ToUrlSafeBase64String(Guid.NewGuid().ToByteArray());
}
}
// We want to make this a struct, so we have to live with people being
// able to create default instances.
public struct Hasher
{
readonly int x;
public Hasher(int x)
{
this.x = x;
}
public Hasher With(int y)
{
unchecked
{
return new Hasher(31 * x + y);
}
}
// With(object o)? But the caller might want to use a custom EqualityComparer.
// I'd rather pay the boilerplate in the caller than try to deal with that here.
public static implicit operator int(Hasher h)
{
// If we cared about good distribution (e.g., different hashes
// for dictionaries that differ by a permutation of the values),
// we'd apply some function to h.x here.
return h.x;
}
public static readonly Hasher Start = new Hasher(17);
[BCTOmitImplementation]
static Hasher() { }
}
public static class SerializationUtils
{
// TODO(pmc): clean up duplicate code
// Minor duplicate code (only two funcions) from svAuth Utils, which I think is ok.
// Perhaps we can move some of svAuth Utils code to svX Utils code, then use the svX Utils code from svAuth
public static JObject ReflectObject(object o)
{
var writer = new JTokenWriter();
new JsonSerializer().Serialize(writer, o);
return (JObject)writer.Token;
}
public static T UnreflectObject<T>(JObject jo)
{
return new JsonSerializer().Deserialize<T>(new JTokenReader(jo));
}
// Compute SHA256 hash of a string
// https://msdn.microsoft.com/en-us/library/s02tk69a(v=vs.110).aspx
public static String Hash(String value)
{
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
}
}
| cs0317/SVAuth | SVX/Utils.cs | C# | mit | 3,415 |
package com.knr.recyclr;
import org.json.*;
public class UpcItem {
public String number;
public String itemName;
public String description;
public UpcItem(String json) {
try {
JSONObject jsonObj = new JSONObject(json);
this.number = jsonObj.getString("number");
this.itemName = jsonObj.getString("itemname");
this.description = jsonObj.getString("description");
} catch (JSONException e) {
this.number = "0";
this.itemName = "invalid item";
this.description = "invalid UPC code";
}
}
} | kj2wong/Recyclr | Recyclr/src/com/knr/recyclr/UpcItem.java | Java | mit | 521 |
package com.real.estate.parser;
import org.jsoup.nodes.Element;
import java.util.List;
/**
* Created by Snayki on 22.03.2016.
*/
public interface Parser<T> {
List<Element> parse();
T createFromElement(Element element);
}
| Snayki/real-estate | src/main/java/com/real/estate/parser/Parser.java | Java | mit | 236 |
/*****************************************************************************
The following code is derived, directly or indirectly, from the SystemC
source code Copyright (c) 1996-2010 by all Contributors.
All Rights reserved.
The contents of this file are subject to the restrictions and limitations
set forth in the SystemC Open Source License Version 2.4 (the "License");
You may not use this file except in compliance with such restrictions and
limitations. You may obtain instructions on how to receive a copy of the
License at http://www.systemc.org/. Software distributed by Contributors
under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License.
*****************************************************************************/
/*****************************************************************************
main.cpp -- This example shows the use of the sc_rvd classes to demonstrate
a communication channel that uses a ready-valid handshake.
Original Author: Andy Goodrich, Forte Design Systems, Inc.
*****************************************************************************/
// $Log: main.cpp,v $
// Revision 1.2 2011/08/15 16:43:24 acg
// Torsten Maehne: changes to remove unused argument warnings.
//
// Revision 1.1 2011/06/14 21:25:39 acg
// Andy Goodrich: moved examples from 2.2.1 potential release.
//
// Revision 1.1 2010/08/20 14:14:01 acg
// Andy Goodrich: new example using a ready-valid handshake for communication.
//
#include "systemc.h"
#include <iomanip>
#include "sc_rvd.h"
SC_MODULE(DUT)
{
SC_CTOR(DUT)
{
SC_CTHREAD(thread,m_clk.pos());
reset_signal_is(m_reset, false);
}
void thread()
{
sc_uint<8> data[10];
m_input.reset();
m_output.reset();
wait();
for (;;)
{
for ( int outer_i = 0; outer_i < 10; outer_i++ )
{
for ( int inner_i = 0; inner_i < outer_i; inner_i++ )
{
data[inner_i] = m_input.read();
cout << " " << std::setw(3) << data[inner_i]
<< " " << sc_time_stamp() << endl;
}
for ( int inner_i = 0; inner_i < outer_i; inner_i++ )
{
m_output = data[inner_i];
}
}
}
}
sc_in<bool> m_clk;
sc_rvd<sc_uint<8> >::in m_input;
sc_rvd<sc_uint<8> >::out m_output;
sc_in<bool> m_reset;
};
SC_MODULE(TB)
{
SC_CTOR(TB)
{
SC_CTHREAD(consumer,m_clk.pos());
reset_signal_is(m_reset, false);
SC_CTHREAD(producer,m_clk.pos());
reset_signal_is(m_reset, false);
}
void consumer()
{
sc_uint<8> data;
m_from_dut.reset();
wait();
for ( int i = 0; i < 40; i++ )
{
data = m_from_dut.read();
cout << " " << std::setw(3) << data << " "
<< sc_time_stamp() << endl;
}
sc_stop();
}
void producer()
{
sc_uint<8> data;
m_to_dut.reset();
wait();
for ( int i = 0;; i++ )
{
cout << " " << std::setw(3) << i << " "
<< sc_time_stamp() << endl;
data = i;
m_to_dut = data;
if ( i && (i % 6 == 0) ) wait(i);
}
}
sc_in<bool> m_clk;
sc_rvd<sc_uint<8> >::in m_from_dut;
sc_in<bool> m_reset;
sc_rvd<sc_uint<8> >::out m_to_dut;
};
int sc_main(int , char* [])
{
sc_clock clock;
DUT dut("dut");
sc_rvd<sc_uint<8> > dut_to_tb;
sc_signal<bool> reset;
TB tb("tb");
sc_rvd<sc_uint<8> > tb_to_dut;
dut.m_clk(clock);
dut.m_reset(reset);
dut.m_input(tb_to_dut);
dut.m_output(dut_to_tb);
tb.m_clk(clock);
tb.m_reset(reset);
tb.m_from_dut(dut_to_tb);
tb.m_to_dut(tb_to_dut);
cout << "producer dut consumer " << endl;
reset = false;
sc_start(1, SC_NS);
reset = true;
sc_start();
cout << "Program completed" << endl;
return 0;
}
| pombredanne/metamorphosys-desktop | metamorphosys/tonka/models/SystemC/systemc-2.3.0/examples/sysc/2.3/sc_rvd/main.cpp | C++ | mit | 4,256 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Media.Imaging;
using GitHub.Extensions;
using GitHub.Helpers;
using ReactiveUI;
namespace GitHub.Models
{
public class AutoCompleteSuggestion
{
readonly string prefix;
readonly string suffix;
readonly string[] descriptionWords;
public AutoCompleteSuggestion(string name, string description, string prefix)
: this(name, description, Observable.Return<BitmapSource>(null), prefix)
{
}
public AutoCompleteSuggestion(string name, string description, IObservable<BitmapSource> image, string prefix)
: this(name, description, image, prefix, null)
{
}
public AutoCompleteSuggestion(string name, IObservable<BitmapSource> image, string prefix, string suffix)
: this(name, null, image, prefix, suffix)
{
}
public AutoCompleteSuggestion(string name, string description, IObservable<BitmapSource> image, string prefix, string suffix)
{
Guard.ArgumentNotEmptyString(name, "name");
Guard.ArgumentNotEmptyString(prefix, "prefix"); // Suggestions have to have a triggering prefix.
Guard.ArgumentNotNull(image, "image");
Name = name;
Description = description;
if (image != null)
{
image = image.ObserveOn(RxApp.MainThreadScheduler);
}
Image = image;
this.prefix = prefix;
this.suffix = suffix;
// This is pretty naive, but since the Description is currently limited to a user's FullName,
// This is fine. When we add #issue completion, we may need to fancy this up a bit.
descriptionWords = (description ?? String.Empty)
.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// The name to display in the autocomplete list box. This should not have the "@" or ":" characters around it.
/// </summary>
public string Name { get; private set; }
public string Description { get; private set; }
public IObservable<BitmapSource> Image { get; private set; }
protected IReadOnlyCollection<string> DescriptionWords { get { return descriptionWords; } }
// What gets autocompleted.
public override string ToString()
{
return prefix + Name + suffix;
}
/// <summary>
/// Used to determine if the suggestion matches the text and if so, how it should be sorted. The larger the
/// rank, the higher it sorts.
/// </summary>
/// <remarks>
/// For mentions we sort suggestions in the following order:
///
/// 1. Login starts with text
/// 2. Component of Name starts with text (split name by spaces, then match each word)
///
/// Non matches return -1. The secondary sort is by Login ascending.
/// </remarks>
/// <param name="text">The suggestion text to match</param>
/// <returns>-1 for non-match and the sort order described in the remarks for matches</returns>
public virtual int GetSortRank(string text)
{
Guard.ArgumentNotNull(text, "text");
return Name.StartsWith(text, StringComparison.OrdinalIgnoreCase)
? 1
: descriptionWords.Any(word => word.StartsWith(text, StringComparison.OrdinalIgnoreCase))
? 0
: -1;
}
}
}
| github/VisualStudio | src/GitHub.Exports.Reactive/Models/AutoCompleteSuggestion.cs | C# | mit | 3,667 |
import NumeralFieldComponent from './Numeral'
const numeral = global.numeral
if (!numeral) {
throw new Error('Numeral is required in global variable')
}
export default class MoneyComponent extends NumeralFieldComponent {
unformatValue(label) {
return label === '' ? undefined : numeral._.stringToNumber(label)
}
formatValue(real) {
return numeral(real) ? numeral(real).format('$0,0.[000000000000000000000]') : ''
}
}
| orionsoft/parts | src/components/fields/numeral/Money.js | JavaScript | mit | 437 |
var gulp = require("gulp");
var util = require("gulp-util");
var config = require("../config")
gulp.task("watch", () => {
gulp.watch(`${config.src.ts}`, ["compile:ts"]).on("change", reportChange).on("error", swallowError);
gulp.watch(`${config.test.files}`, ["compile:test"]).on("change", reportChange).on("error", swallowError);
});
function reportChange(event) {
console.log(`File ${event.path} was ${event.type}, running tasks...`);
}
function swallowError(error) {
console.log(util.colors.red(`Error occurred while running watched task...`));
} | stephenlautier/ssv-angular-core | tools/build/tasks/dev.js | JavaScript | mit | 560 |
using System;
using System.Diagnostics;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace Noterium.Core.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example>
/// <code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example>
/// <code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that collection or enumerable value does not contain null elements
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class ItemNotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that collection or enumerable value can contain null elements
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class ItemCanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])" />-like form
/// </summary>
/// <example>
/// <code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Delegate)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute(string name)
{
Name = name;
}
[NotNull]
public string Name { get; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException" />
/// </summary>
/// <example>
/// <code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class InvokerParameterNameAttribute : Attribute
{
}
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item>
/// <c>NotifyChanged(string)</c>
/// </item>
/// <item>
/// <c>NotifyChanged(params string[])</c>
/// </item>
/// <item>
/// <c>NotifyChanged{T}(Expression{Func{T}})</c>
/// </item>
/// <item>
/// <c>NotifyChanged{T,U}(Expression{Func{T,U}})</c>
/// </item>
/// <item>
/// <c>SetProperty{T}(ref T, T, string)</c>
/// </item>
/// </list>
/// </remarks>
/// <example>
/// <code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item>
/// <c>NotifyChanged("Property")</c>
/// </item>
/// <item>
/// <c>NotifyChanged(() => Property)</c>
/// </item>
/// <item>
/// <c>NotifyChanged((VM x) => x.Property)</c>
/// </item>
/// <item>
/// <c>SetProperty(ref myField, value, "Property")</c>
/// </item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute()
{
}
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br />
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br />
/// <c>canbenull</c> annotation is only applicable for output parameters.<br />
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br />
/// </syntax>
/// <examples>
/// <list>
/// <item>
/// <code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code>
/// </item>
/// <item>
/// <code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code>
/// </item>
/// </list>
/// </examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false)
{
}
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; }
public bool ForceFullStates { get; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example>
/// <code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.All)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true)
{
}
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example>
/// <code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute
{
}
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull]
public Type BaseType { get; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
public UsedImplicitlyAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; }
public ImplicitUseTargetFlags TargetFlags { get; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
public MeansImplicitUseAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; }
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute" /> or <see cref="UsedImplicitlyAttribute" />
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute()
{
}
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
public string Comment { get; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class InstantHandleAttribute : Attribute
{
}
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example>
/// <code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class PureAttribute : Attribute
{
}
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute()
{
}
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
public string BasePath { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute()
{
}
public AspMvcActionAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute()
{
}
public AspMvcAreaAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute()
{
}
public AspMvcControllerAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcMasterAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcModelTypeAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcSupressViewErrorAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcDisplayTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcEditorTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcViewAttribute : PathReferenceAttribute
{
}
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example>
/// <code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMvcActionSelectorAttribute : Attribute
{
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute()
{
}
public HtmlElementAttributesAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull]
public string Name { get; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorSectionAttribute : Attribute
{
}
/// <summary>
/// Indicates how method invocation affects content of the collection
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; }
}
[Flags]
public enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute" /> attribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AssertionMethodAttribute : Attribute
{
}
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute" /> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted
/// </summary>
public enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value</summary>
IS_NOT_NULL = 3
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class TerminatesProgramAttribute : Attribute
{
}
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class LinqTunnelAttribute : Attribute
{
}
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class NoEnumerationAttribute : Attribute
{
}
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RegexPatternAttribute : Attribute
{
}
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be
/// treated as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c>
/// type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class XamlItemsControlAttribute : Attribute
{
}
/// <summary>
/// XAML attibute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute" /> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute(string tagName, Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
public string TagName { get; }
public Type ControlType { get; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspDataFieldAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspDataFieldsAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspMethodPropertyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
public string Attribute { get; }
}
[AttributeUsage(AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class AspTypePropertyAttribute : Attribute
{
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
public bool CreateConstructorReferences { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute(string type, string fieldName)
{
Type = type;
FieldName = fieldName;
}
public string Type { get; }
public string FieldName { get; }
}
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorHelperCommonAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Property)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorLayoutAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorWriteLiteralMethodAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorWriteMethodAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Parameter)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class RazorWriteMethodParameterAttribute : Attribute
{
}
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns.
/// </remarks>
[AttributeUsage(AttributeTargets.All)]
[Conditional("JETBRAINS_ANNOTATIONS")]
public sealed class NoReorder : Attribute
{
}
} | ekblom/noterium | src/Noterium.Core/Properties/Annotations.cs | C# | mit | 38,618 |
package com.microsoft.bingads.v12.customermanagement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Predicates" type="{https://bingads.microsoft.com/Customer/v12/Entities}ArrayOfPredicate" minOccurs="0"/>
* <element name="Ordering" type="{https://bingads.microsoft.com/Customer/v12/Entities}ArrayOfOrderBy" minOccurs="0"/>
* <element name="PageInfo" type="{https://bingads.microsoft.com/Customer/v12/Entities}Paging" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"predicates",
"ordering",
"pageInfo"
})
@XmlRootElement(name = "SearchClientLinksRequest")
public class SearchClientLinksRequest {
@XmlElement(name = "Predicates", nillable = true)
protected ArrayOfPredicate predicates;
@XmlElement(name = "Ordering", nillable = true)
protected ArrayOfOrderBy ordering;
@XmlElement(name = "PageInfo", nillable = true)
protected Paging pageInfo;
/**
* Gets the value of the predicates property.
*
* @return
* possible object is
* {@link ArrayOfPredicate }
*
*/
public ArrayOfPredicate getPredicates() {
return predicates;
}
/**
* Sets the value of the predicates property.
*
* @param value
* allowed object is
* {@link ArrayOfPredicate }
*
*/
public void setPredicates(ArrayOfPredicate value) {
this.predicates = value;
}
/**
* Gets the value of the ordering property.
*
* @return
* possible object is
* {@link ArrayOfOrderBy }
*
*/
public ArrayOfOrderBy getOrdering() {
return ordering;
}
/**
* Sets the value of the ordering property.
*
* @param value
* allowed object is
* {@link ArrayOfOrderBy }
*
*/
public void setOrdering(ArrayOfOrderBy value) {
this.ordering = value;
}
/**
* Gets the value of the pageInfo property.
*
* @return
* possible object is
* {@link Paging }
*
*/
public Paging getPageInfo() {
return pageInfo;
}
/**
* Sets the value of the pageInfo property.
*
* @param value
* allowed object is
* {@link Paging }
*
*/
public void setPageInfo(Paging value) {
this.pageInfo = value;
}
}
| bing-ads-sdk/BingAds-Java-SDK | proxies/com/microsoft/bingads/v12/customermanagement/SearchClientLinksRequest.java | Java | mit | 3,065 |
import { formatDistance, formatToLocaleString, defaultEnvironment, Environment } from './formatDate'
import { subDays } from 'date-fns'
import { ja, enUS } from 'date-fns/locale'
// memo(otofune): This requires that process.env.TZ equals to 'UTC'. (;;)
const jaEnvironment: Environment = { getLocale: () => ja }
const enUSEnvironment: Environment = { getLocale: () => enUS }
describe('format-date utility', () => {
describe('defaultEnvironment', () => {
let languageSpy: jest.SpyInstance
beforeAll(() => {
languageSpy = jest.spyOn(window.navigator, 'language', 'get')
})
afterEach(() => {
languageSpy.mockReset()
})
describe('with "ja-JP" locale', () => {
beforeEach(() => {
languageSpy.mockReturnValue('ja-JP')
})
it('navigaror.language must be ja-JP', () => {
expect(navigator.language).toBe('ja-JP')
})
it('getLocale must return ja locale', () => {
expect(defaultEnvironment.getLocale()).toBe(ja)
})
})
describe('with "ja" locale', () => {
beforeEach(() => {
languageSpy.mockReturnValue('ja')
})
it('navigaror.language must be ja', () => {
expect(navigator.language).toBe('ja')
})
it('getLocale must return ja locale', () => {
expect(defaultEnvironment.getLocale()).toBe(ja)
})
})
describe('with "en" locale', () => {
beforeEach(() => {
languageSpy.mockReturnValue('en')
})
it('navigaror.language must be en', () => {
expect(navigator.language).toBe('en')
})
it('getLocale must return enUS locale', () => {
expect(defaultEnvironment.getLocale()).toBe(enUS)
})
})
describe('with "de-DE" locale (unsupported)', () => {
beforeEach(() => {
languageSpy.mockReturnValue('de-DE')
})
it('navigaror.language must be de-DE', () => {
expect(navigator.language).toBe('de-DE')
})
it('getLocale must return enUS locale', () => {
expect(defaultEnvironment.getLocale()).toBe(enUS)
})
})
})
describe('formatToLocaleString', () => {
it('with ja environment', () => {
expect(formatToLocaleString('2019-09-29T03:01:21.200Z', jaEnvironment)).toBe('2019/09/29 3:01:21')
})
it('with en environment', () => {
expect(formatToLocaleString('2019-09-29T03:01:21.200Z', enUSEnvironment)).toBe('Sep 29, 2019, 3:01:21 AM')
})
})
describe('formatDistance', () => {
it('must include suffix (ago)', () => {
const d = subDays(Date.now(), 3)
expect(formatDistance(d, Date.now(), enUSEnvironment)).toBe('3 days ago')
})
it('must include suffix (前)', () => {
const d = subDays(Date.now(), 3)
expect(formatDistance(d, Date.now(), jaEnvironment)).toBe('3日前')
})
})
})
| crowi/crowi | client/util/formatDate.test.ts | TypeScript | mit | 2,827 |
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserify = require('gulp-browserify'),
concat = require('gulp-concat'),
gulpif = require('gulp-if'),
uglify = require('gulp-uglify'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
sequence = require('run-sequence'),
less = require('gulp-less'),
zip = require('gulp-zip'),
rev = require('gulp-rev-append'),
gutil = require('gulp-util');
var production = gutil.env.type === "production";
var game_name = gutil.env.name || 'fp'
var paths = {
source: {
canvas_js: './app/js/' + game_name + '/canvas.js',
web_js: './app/js/' + game_name + '/web.js',
canvas_css: './app/less/' + game_name + '/canvas.less',
web_css: './app/less/' + game_name + '/web.less',
baseJsDir: './app/js/**',
js: './app/js/**/*.js',
css: './app/less/**/*.less',
libs: [
'./bower_components/phaser/build/phaser.js'
]
},
dest: {
base: './public/' + game_name + '/',
html: './public/' + game_name + '/index.html',
js: './public/' + game_name + '/js',
css: './public/' + game_name + '/css'
}
};
gulp.task('rev', function() {
gulp.src(paths.dest.html)
.pipe(rev())
.pipe(gulp.dest(paths.dest.base));
});
gulp.task('copy_libs', function () {
gulp.src(paths.source.libs)
.pipe(uglify({outSourceMaps: false}))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('canvas_js', function() {
gulp.src(paths.source.canvas_js)
.pipe(plumber())
.pipe(browserify())
.pipe(concat('canvas.js'))
.pipe(gulpif(production, uglify()))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('web_js', function() {
gulp.src(paths.source.web_js)
.pipe(plumber())
.pipe(browserify())
.pipe(concat('web.js'))
.pipe(gulpif(production, uglify()))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('canvas_css', function() {
gulp.src(paths.source.canvas_css)
.pipe(plumber())
.pipe(less({ compress: true }))
.pipe(gulp.dest(paths.dest.css));
});
gulp.task('web_css', function() {
gulp.src(paths.source.web_css)
.pipe(plumber())
.pipe(less({ compress: true }))
.pipe(gulp.dest(paths.dest.css));
});
gulp.task('lint', function() {
gulp.src(paths.source.js)
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('watch', function() {
gulp.watch(paths.source.baseJsDir, function() {
sequence('canvas_js', 'web_js', 'lint')
});
gulp.watch(paths.source.css, function() {
sequence('canvas_css', 'web_css')
})
});
gulp.task('zip', function () {
return gulp.src([
'public/' + game_name + '/**/*'
])
.pipe(zip(game_name +'_dist.zip'))
.pipe(gulp.dest('./dist'))
});
gulp.task('build', [
'canvas_js',
'web_js',
'canvas_css',
'web_css',
'rev'
]);
| Daniel1984/60fps | gulpfile.js | JavaScript | mit | 2,819 |
<?php
namespace Chronos\ChronoAdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class RoadStateType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
;
}
public function getName()
{
return 'chronos_chronoadminbundle_roadstatetype';
}
}
| Guimove/Chronos | src/Chronos/ChronoAdminBundle/Form/RoadStateType.php | PHP | mit | 411 |
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
var path = require('path');
// Basic Gulp task syntax
gulp.task('hello', function() {
console.log('Hello Martin!');
});
// Development Tasks
// -----------------
// Start browserSync server
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app'
}
})
});
gulp.task('sass', function() {
return gulp.src('app/css/*.+(scss|sass)') // Gets all files ending with .scss in app/scss and children dirs
.pipe(sass()) // Passes it through a gulp-sass
.pipe(gulp.dest('app/css')) // Outputs it in the css folder
.pipe(browserSync.reload({ // Reloading with Browser Sync
stream: true
}));
});
// Watchers
gulp.task('watch', function() {
gulp.watch('app/css/*.+(scss|sass)', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
});
// Optimization Tasks
// ------------------
// Optimizing CSS and JavaScript
gulp.task('useref', function() {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('app/js/*.js', uglify()))
.pipe(gulpIf('app/css/*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
// Optimizing Images
gulp.task('images', function() {
return gulp.src('app/img/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true,
})))
.pipe(gulp.dest('dist/images'))
});
// Copying fonts
gulp.task('fonts', function() {
return gulp.src('app/fonts/**/*').pipe(gulp.dest('dist/fonts'))
});
// Cleaning
gulp.task('clean', function() {
return del.sync('dist').then(function(cb) {return cache.clearAll(cb);});
});
gulp.task('clean:dist', function() {
return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});
// Build Sequences
// ---------------
gulp.task('default', function(callback) {
runSequence(['sass', 'browserSync'], 'watch', callback)
});
gulp.task('build', function(callback) {
runSequence('clean:dist', 'sass', ['useref', 'images', 'fonts'], callback)
});
| martinrajdl/faunafilm | gulpfile.js | JavaScript | mit | 2,512 |
(function () {
var Demo = {
init: function () {
this.syntaxHighlight();
this.sticky();
},
syntaxHighlight: function () {
hljs.initHighlighting();
},
sticky: function () {
var $sticky = $('[data-sticky]');
$sticky.sticky({
topSpacing: 10
});
}
};
Demo.init();
})();
| SwiftCMS/Pluit | documentation/doc.js | JavaScript | mit | 417 |
if defined?(::Rails::Railtie)
class EnumColumnRailtie < Rails::Railtie
# initializer 'enum_column.initialize', :after => 'active_record.initialize_database' do |app|
ActiveSupport.on_load :active_record do
require 'enum/mysql_adapter'
require 'enum/enum_adapter'
require 'enum/schema_statements'
require 'enum/schema_definitions'
require 'enum/quoting'
require 'enum/validations'
end
ActiveSupport.on_load :action_view do
require 'enum/active_record_helper'
end
# end
end
end | quarkstudio/enum_column | lib/enum_column.rb | Ruby | mit | 568 |
import 'reflect-metadata';
import { SchemaObject, XParameterObject } from '@ts-stack/openapi-spec';
import { Parameters } from './parameters';
import { Column } from '../decorators/column';
describe('Parameters', () => {
describe('without data model', () => {
it('required path with someName', () => {
const params = new Parameters().required('path', 'someName').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'someName', required: true }];
expect(params).toEqual(expectParams);
});
it('optional cookie with otherName', () => {
const params = new Parameters().optional('cookie', 'otherName').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'otherName', required: false }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', 'postId').optional('cookie', 'someName').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'postId', required: true },
{ in: 'cookie', name: 'someName', required: false },
];
expect(params).toEqual(expectParams);
});
});
describe('with data model', () => {
class Model1 {
prop1: number;
prop2?: string;
}
it('required path with prop1', () => {
const params = new Parameters().required('path', Model1, 'prop1').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'prop1', required: true }];
expect(params).toEqual(expectParams);
});
it('optional cookie with prop2', () => {
const params = new Parameters().optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'prop2', required: false }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', Model1, 'prop1').optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'prop1', required: true },
{ in: 'cookie', name: 'prop2', required: false },
];
expect(params).toEqual(expectParams);
});
});
describe('with data model and metadata of the model', () => {
const column1: SchemaObject = { type: 'number', minimum: 0, maximum: 100 };
const column2: SchemaObject = { type: 'string', minLength: 1, maxLength: 5 };
class Model1 {
@Column(column1)
prop1: number;
@Column(column2)
prop2?: string;
}
it('required path with prop1', () => {
const params = new Parameters().required('path', Model1, 'prop1').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'prop1', required: true, schema: column1 }];
expect(params).toEqual(expectParams);
});
it('optional cookie with prop2', () => {
const params = new Parameters().optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'prop2', required: false, schema: column2 }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', Model1, 'prop1').optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'prop1', required: true, schema: column1 },
{ in: 'cookie', name: 'prop2', required: false, schema: column2 },
];
expect(params).toEqual(expectParams);
});
});
describe('bindTo() and recursive()', () => {
it('case 1', () => {
const params = new Parameters()
.required('path', 'postId')
.optional('query', 'page')
.bindTo('lastParamInPath')
.bindTo('httpMethod', 'GET')
.getParams();
expect(params).toEqual([
{ in: 'path', name: 'postId', required: true },
{
in: 'query',
name: 'page',
required: false,
'x-bound-to-path-param': false,
'x-bound-to-http-method': 'GET',
},
]);
});
});
});
| restify-ts/core | packages/openapi/src/utils/parameters.spec.ts | TypeScript | mit | 4,225 |
var Tile = function (type, x, y) {
this.type = type;
this.tint = 0;
this.hover = false;
this.isAllowed = undefined;
this.isAllowedForBeat = undefined;
this.x = x;
this.y = y;
this.graphic = new fabric.Rect({
left: Tile.size * x,
top: Tile.size * y,
fill: type === Tile.TileType.NONPLAYABLE ? Tile.ColorNonplayable : Tile.ColorPlayable,
width: Tile.size,
height: Tile.size,
selectable: false,
obj: this
});
canvas.add(this.graphic);
};
Tile.size = undefined;
Tile.ColorPlayable = "#717070";
Tile.ColorNonplayable = "#d9d9d9";
Tile.ColorAllowed = "#38b321";
Tile.ColorMovingToNow = "#b8c153";
Tile.ColorAllowedForBeat = "#cf3a3a";
Tile.TileType = {
PLAYABLE: 0,
NONPLAYABLE: 1
};
Tile.prototype.setMan = function(man) {
this.man = man;
};
Tile.prototype.clearMan = function() {
this.man = undefined; //TODO null? +RETHINK
};
Tile.prototype.setAsAllowed = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowed, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowed = true;
};
Tile.prototype.setAsAllowedForBeat = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowedForBeat, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowedForBeat = true;
};
Tile.prototype.clearHighlights = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorPlayable, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowed = false;
this.isAllowedForBeat = false;
};
Tile.prototype.setAsMovingToNow = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorMovingToNow, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
};
Tile.prototype.isAllowedForMove = function() {
return this.isAllowed || this.isAllowedForBeat;
};
Tile.prototype.onMouseOver = function() {
if (this.isAllowedForMove()) {
var graphic = this.graphic;
fabric.util.animateColor(graphic.fill, //TODO: colorAllowed/this.fill +REFACTOR
Color(graphic.fill).lightenByRatio(0.2).toString(), hoverAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
}
};
Tile.prototype.onMouseOut = function() {
if (this.isAllowedForMove()) {
var graphic = this.graphic;
fabric.util.animateColor(graphic.fill, Color(graphic.fill).darkenByRatio(0.1666).toString(),
hoverAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
}
};
Tile.prototype.onMouseDown = function() {
if (this.isAllowedForMove()) {
//move men to selected (this) tile
board.sendMove(board.selectedMan.tile, this);
board.moveSelectedManTo(this);
} else {
//or unselect man, if clicked on empty tile
board.unselect();
}
};
| misko321/draughts | public/js/tile.js | JavaScript | mit | 3,185 |
/*
* Books.cpp
* Author: suyashd95
*/
#include "Books.h"
#include <iostream>
#include <cstring>
using namespace std;
Books::Books() {
stock = new int[size];
price = new float[size];
author = new const char*[size];
publisher = new const char*[size];
title = new const char*[size];
populateData();
}
void Books::populateData() {
for(int i = 0; i < size; i++) {
switch(i) {
case 0:
stock[i] = 10;
price[i] = 500.00;
author[i] = "JK Rowling";
publisher[i] = "Bloomsbury";
title[i] = "Harry Potter";
break;
case 1:
stock[i] = 0;
price[i] = 200.00;
author[i] = "Jeffrey Archer";
publisher[i] = "Penguin";
title[i] = "A Quiver Full Of Arrows";
break;
case 2:
stock[i] = 3;
price[i] = 1000.00;
author[i] = "JKR Tolkien";
publisher[i] = "Penguin";
title[i] = "The Lord Of The Rings";
break;
case 3:
stock[i] = 0;
price[i] = 80.00;
author[i] = "Danielle Steele";
publisher[i] = "Penguin";
title[i] = "A Perfect Stranger";
break;
case 4:
stock[i] = 7;
price[i] = 300.00;
author[i] = "Jane Austen";
publisher[i] = "Bloomsbury";
title[i] = "Pride & Prejudice";
break;
}
}
}
void Books::bookPurchase() {
string author, title;
cout << "Enter the author of the book: " << flush;
getline(cin, author, '\n');
cout << "Enter the title of the book: " << flush;
getline(cin, title, '\n');
char found = 'n';
for(int i = 0; i < size; i++) {
int condition1 = strcmp(this->author[i], author.c_str());
int condition2 = strcmp(this->title[i], title.c_str());
if(condition1 == 0 && condition2 == 0) {
found = 'y';
cout << endl;
cout << "Search Successful..." << endl;
cout << "Details of the Book:\n" << endl;
cout << " Author: " << this->author[i] << endl;
cout << " Title: " << this->title[i] << endl;
cout << "Publisher: " << this->publisher[i] << endl;
cout << " Price: " << this->price[i] << endl;
unsigned int requiredCopies;
cout << "Please enter the number of copies required for purchase: " << flush;
cin >> requiredCopies;
cout << endl;
if(requiredCopies <= this->stock[i])
cout << "Total Cost: " << this->price[i] * requiredCopies << endl;
else
cout << "Required copies not in stock." << endl;
break;
}
}
if(found == 'n')
cout << "\nSearch Unsuccessful...\nBook is not available." << endl;
}
Books::~Books() {
delete [] stock;
delete [] price;
delete [] author;
delete [] publisher;
delete [] title;
}
| SuyashD95/cplusplus-prog-exercises | Programming Exercises/Chapter 6 - Constructors and Destructors/Question 3/src/Books.cpp | C++ | mit | 2,512 |
using Castle.Core.Logging;
using Bivi.Infrastructure.Constant;
using Bivi.Infrastructure.Services.Depots;
using Bivi.Infrastructure.Services.Encryption;
using Bivi.BackOffice.Web.Controllers.ActionResults;
using Bivi.BackOffice.Web.Controllers.Filters;
using Bivi.BackOffice.Web.Controllers.Helpers;
using Bivi.BackOffice.Web.Controllers.Modularity;
using Bivi.BackOffice.Web.ViewModels.ModelBuilders.Administration.LienExterne;
using Bivi.BackOffice.Web.ViewModels.ModelBuilders.Common;
using Bivi.BackOffice.Web.ViewModels.Pages.Administration.LienExterne.Details.InforsGenerales;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Bivi.Infrastructure.Extensions;
using System.Transactions;
using Bivi.Infrastructure.Attributes.Modularity;
using Bivi.Domaine;
using Bivi.BackOffice.Web.ViewModels.Pages.Administration.LienExterne.Details;
using Bivi.Domaine.Criterias;
using Bivi.Infrastructure.Services.Caching;
using Bivi.Infrastructure.Services.Exports;
using Bivi.BackOffice.Web.ViewModels.Pages.Common;
namespace Bivi.BackOffice.Web.Controllers.Administration
{
public class LienExterneController : ModularController
{
private readonly ILienExterneModelBuilder _lienExterneModelBuilder;
public LienExterneController(
ILogger logger,
ICryptography encryption,
IDepotFactory depotFactory,
ILienExterneModelBuilder lienExterneModelBuilder,
ICommonModelBuilder commonModelBuilder,
ICaching cachingService,
IExcelExport exportService)
: base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
{
_lienExterneModelBuilder = lienExterneModelBuilder;
Page = PageEnum.LienExterne;
}
public ActionResult Index()
{
return ProcessPage();
}
[HttpGet]
public ActionResult Recherche()
{
BuildActionContext(VueEnum.LienExterneSearch);
var vm = _commonModelBuilder.BuildPartialViewModel(Context, null);
return View(vm);
}
[HttpPost]
public ActionResult Recherche(SearchLienExterneCriterias criterias)
{
var res = _depotFactory.LienExterneDepot.Search(criterias.Description);
var model = new RechercheResultViewModel
{
Results = res
};
if (criterias.ExportExcel)
{
model.ExportUrl = CreateExportFile(res, "ExportRechercheDemande.xls", FileDownloadTypes.ExportRecherche);
}
return new JsonHttpStatusResult((int)HttpStatusCode.OK, model);
}
public ActionResult Details(long id, long? vueID)
{
var vm = _commonModelBuilder.BuildDetailsViewModel(Context, (long)ActionModeAffichageEnum.Consultation, (long)GroupeVueEnum.LienExterneDetails, id, vueID);
foreach (var item in vm.GroupeVue.Vues)
{
item.Url = RoutesHelper.GetUrl(item.CodeRoute, new { id = id, utilisateurID = Context.User.ID, vueID = item.ID, type = Constants.GetStringValue(GroupeVueTraductibleEnum.LienExterne) });
}
return View("~/Views/Common/Details.cshtml", vm);
}
public ActionResult InformationsGenerales(long id)
{
BuildActionContext(VueEnum.LienExterneInformationsGenerales);
var vm = _lienExterneModelBuilder.BuildInfosGeneralesViewModel(Context, id);
return View(vm);
}
public ActionResult Create()
{
var vm = _commonModelBuilder.BuildDetailsViewModel(Context, (long)ActionModeAffichageEnum.Creation, (long)GroupeVueEnum.LienExterneDetails, 0, null);
foreach (var item in vm.GroupeVue.Vues)
{
item.Url = RoutesHelper.GetUrl(item.CodeRoute, new { id = 0 });
}
return View("~/Views/Common/Details.cshtml", vm);
}
[HttpPost]
[ValidateModelState]
public ActionResult SaveInformationsGenerales(InfosGeneralesViewModel model)
{
BuildActionContext(VueEnum.LienExterneInformationsGenerales, model.LienExterne.ID, model.LienExterne.ID > 0 ? (long)TypeActionEnum.Save : (long)TypeActionEnum.Add, model.TimeStamp);
var lienExterne = AutoMapper.Mapper.Map<LienExterneViewModel, LienExterne>(model.LienExterne);
var lien = Save(() => _depotFactory.LienExterneDepot.SaveLienExterneInfosGenerales(lienExterne));
return new JsonHttpStatusResult((int)HttpStatusCode.OK, new { id = lien.ID });
}
}
}
| apo-j/Projects_Working | Bivi/src/Bivi.BackOffice/Bivi.BackOffice.Web.Controllers/Controllers/Administration/LienExterneController.cs | C# | mit | 4,921 |
/*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.preapproval.search;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import br.com.uol.pagseguro.api.PagSeguro;
import br.com.uol.pagseguro.api.common.domain.PreApprovalStatus;
import br.com.uol.pagseguro.api.utils.XMLUnmarshallListener;
/**
* Implementation of {@code PreApprovalSummary} and {@code XMLUnmarshallListener}
*
* @author PagSeguro Internet Ltda.
*/
public class PreApprovalSummaryXML implements PreApprovalSummary, XMLUnmarshallListener {
private PagSeguro pagSeguro;
private String name;
private String code;
private Date date;
private String tracker;
private String statusId;
private String reference;
private Date lastEvent;
private String charge;
PreApprovalSummaryXML() {
}
@Override
public void onUnmarshal(PagSeguro pagseguro, String rawData) {
this.pagSeguro = pagseguro;
}
@Override
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
@Override
public String getCode() {
return code;
}
@XmlElement
public void setCode(String code) {
this.code = code;
}
@Override
public Date getDate() {
return date;
}
@XmlElement
public void setDate(Date date) {
this.date = date;
}
@Override
public String getTracker() {
return tracker;
}
@XmlElement
public void setTracker(String tracker) {
this.tracker = tracker;
}
@Override
public PreApprovalStatus getStatus() {
return new PreApprovalStatus(getStatusId());
}
public String getStatusId() {
return statusId;
}
@XmlElement(name = "status")
public void setStatusId(String statusId) {
this.statusId = statusId;
}
@Override
public String getReference() {
return reference;
}
@XmlElement
public void setReference(String reference) {
this.reference = reference;
}
@Override
public Date getLastEvent() {
return lastEvent;
}
@XmlElement(name = "lastEventDate")
public void setLastEvent(Date lastEvent) {
this.lastEvent = lastEvent;
}
@Override
public String getCharge() {
return charge;
}
@XmlElement
public void setCharge(String charge) {
this.charge = charge;
}
@Override
public PreApprovalDetail getDetail() {
return pagSeguro.preApprovals().search().byCode(getCode());
}
@Override
public String toString() {
return "PreApprovalSummaryXML{" +
"pagSeguro=" + pagSeguro +
", name='" + name + '\'' +
", code='" + code + '\'' +
", date=" + date +
", tracker='" + tracker + '\'' +
", statusId='" + statusId + '\'' +
", reference='" + reference + '\'' +
", lastEvent=" + lastEvent +
", charge='" + charge + '\'' +
'}';
}
}
| girinoboy/lojacasamento | pagseguro-api/src/main/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalSummaryXML.java | Java | mit | 3,550 |
/**
* Michael' (The non-Asian one's) librarys.<br>
* Thank you for the help!
* @author Michael [???]
*
*/
package com.shadow53.libs; | Vectis99/sshs-2016-willamette | src/com/shadow53/libs/package-info.java | Java | mit | 137 |
using System;
using Amazon.DynamoDBv2.DataModel;
using AspNetCore.Identity.DynamoDB.Converters;
namespace AspNetCore.Identity.DynamoDB.Models
{
public abstract class DynamoUserContactRecord : IEquatable<DynamoUserEmail>
{
protected DynamoUserContactRecord() {}
protected DynamoUserContactRecord(string value) : this()
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Value = value;
}
public string Value { get; set; }
[DynamoDBProperty(typeof(DateTimeOffsetConverter))]
public DateTimeOffset ConfirmedOn { get; set; }
public bool Equals(DynamoUserEmail other)
{
return other != null && other.Value.Equals(Value);
}
public bool IsConfirmed()
{
return ConfirmedOn != default(DateTimeOffset);
}
public void SetConfirmed()
{
SetConfirmed(DateTimeOffset.Now);
}
public void SetConfirmed(DateTimeOffset confirmationTime)
{
if (ConfirmedOn == default(DateTimeOffset))
{
ConfirmedOn = confirmationTime;
}
}
public void SetUnconfirmed()
{
ConfirmedOn = default(DateTimeOffset);
}
}
} | miltador/AspNetCore.Identity.DynamoDB | src/AspNetCore.Identity.DynamoDB/Models/DynamoUserContactRecord.cs | C# | mit | 1,099 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_execlp_82_bad.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sinks: execlp
* BadSink : execute command with wexeclp
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__wchar_t_connect_socket_execlp_82.h"
#ifdef _WIN32
#include <process.h>
#define EXECLP _wexeclp
#else /* NOT _WIN32 */
#define EXECLP execlp
#endif
namespace CWE78_OS_Command_Injection__wchar_t_connect_socket_execlp_82
{
void CWE78_OS_Command_Injection__wchar_t_connect_socket_execlp_82_bad::action(wchar_t * data)
{
/* wexeclp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
}
#endif /* OMITBAD */
| maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s05/CWE78_OS_Command_Injection__wchar_t_connect_socket_execlp_82_bad.cpp | C++ | mit | 1,346 |
define( 'type.Integer', {
// class configuration
alias : 'int integer',
extend : __lib__.type.Number,
// public properties
precision : 0,
// public methods
valid : function( v ) {
return this.parent( v, true ) && Math.floor( v ) === v;
},
// internal methods
init : function() {
var max = this.max, min = this.min;
this.precision = 0;
this.parent( arguments );
// since we want our Types to be instantiated with as much correctness as possible,
// we don't want to cast our max/min as Integers
if ( max !== Number.POSITIVE_INFINITY )
this.max = max;
if ( min !== Number.NEGATIVE_INFINITY )
this.min = min;
},
value : function( v ) {
return Math.round( this.parent( arguments ) );
}
} );
| agreco/expurg8 | src/type/Integer.js | JavaScript | mit | 765 |
package ua.com.fielden.platform.entity_centre.review;
import java.util.Date;
import ua.com.fielden.platform.domaintree.testing.EntityWithStringKeyType;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.CompositeKeyMember;
import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.annotation.KeyTitle;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.Observable;
/**
* Entity for "domain tree representation" testing.
*
* @author TG Team
*
*/
@KeyTitle(value = "Key title", desc = "Key desc")
@KeyType(DynamicEntityKey.class)
public class EvenSlaverDomainEntity extends AbstractEntity<DynamicEntityKey> {
private static final long serialVersionUID = 1L;
protected EvenSlaverDomainEntity() {
}
////////// Range types //////////
@IsProperty
@CompositeKeyMember(1)
private Integer integerProp = null;
@IsProperty
@CompositeKeyMember(2)
private Double doubleProp = 0.0;
@IsProperty
private Date dateProp;
////////// A property of entity type //////////
@IsProperty
private EntityWithStringKeyType simpleEntityProp;
public Integer getIntegerProp() {
return integerProp;
}
@Observable
public void setIntegerProp(final Integer integerProp) {
this.integerProp = integerProp;
}
public Double getDoubleProp() {
return doubleProp;
}
@Observable
public void setDoubleProp(final Double doubleProp) {
this.doubleProp = doubleProp;
}
public Date getDateProp() {
return dateProp;
}
@Observable
public void setDateProp(final Date dateProp) {
this.dateProp = dateProp;
}
public EntityWithStringKeyType getSimpleEntityProp() {
return simpleEntityProp;
}
@Observable
public void setSimpleEntityProp(final EntityWithStringKeyType simpleEntityProp) {
this.simpleEntityProp = simpleEntityProp;
}
}
| fieldenms/tg | platform-pojo-bl/src/test/java/ua/com/fielden/platform/entity_centre/review/EvenSlaverDomainEntity.java | Java | mit | 2,107 |
#!/usr/bin/env python
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.5'
import cmd
import functools
import os
import sys
from polar import Device
from polar.pb import device_pb2 as pb_device
__INTRO = """
_| _| _|
_| _|_| _|_| _|_|_| _|_|_| _|_| _| _|_|
_| _| _| _| _| _| _| _| _| _| _| _| _|_|_|_|
_| _| _| _| _| _| _| _| _| _| _| _| _|
_| _|_| _|_| _|_|_| _| _| _|_| _| _|_|_|
_|
_|
ver. {}
"""
def check_if_device_is_connected(f):
"""
Decorator. Checks if device is connected before invoking function.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
if args[0].device is not None:
return f(*args, **kwargs)
else:
print '[!] Device disconnected.'
print
return wrapper
class LoopholeCli(cmd.Cmd):
""" Loophole command line interface class. """
__PROMPT = 'loophole({})>'
def __init__(self):
"""Constructor.
"""
cmd.Cmd.__init__(self)
self.prompt = LoopholeCli.__PROMPT.format('no device')
self.device = None
# end-of-method __init__
def do_exit(self, _):
"""Quit.
Usage: exit
"""
if self.device is not None:
self.device.close()
sys.exit(0)
# end-of-method do_exit
def do_EOF(self, _):
"""Quit. handles EOF"""
self.do_exit(_)
# end-of-method do_EOF
def do_list(self, _):
"""List available Polar devices.
Usage: list
"""
devs = Device.list()
if len(devs) > 0:
for i, dev in enumerate(devs):
try:
info = Device.get_info(dev)
except ValueError as err:
print "Device no: %i" % i
print "Device info:"
print dev
print "-"*79
if 'langid' in err.message:
raise ValueError(
(
"Can't get device info. Origin Error: %s\n"
"Maybe this is a permission issue.\n"
"Please read section 'permission' in README ;)"
) % err
)
raise # raise origin error
print '{} - {} ({})'.format(i, info['product_name'], info['serial_number'])
else:
print '[!] No Polar devices found!'
print
# end-of-method do_list
def do_connect(self, dev_no):
"""Connect Polar device. Run 'list' to see available devices.
Usage: connect <device_no>
"""
try:
dev_no = int(dev_no)
except ValueError:
print '[!] You need to specify the device number. Run \'list\' to see available devices.'
print
return
try:
devs = Device.list()
dev = devs[dev_no]
serial = Device.get_info(dev)['serial_number']
self.prompt = LoopholeCli.__PROMPT.format(serial)
self.device = Device(dev)
self.device.open()
print '[+] Device connected.'
print
except IndexError:
print '[!] Device not found or failed to open it. Run \'list\' to see available devices.'
print
# end-of-method do_connect
@check_if_device_is_connected
def do_disconnect(self, _):
"""Disconnect Polar device.
"""
self.device.close()
self.device = None
self.prompt = LoopholeCli.__PROMPT.format('no device')
print '[+] Device disconnected.'
print
# end-of-method do_disconnect
@check_if_device_is_connected
def do_get(self, line):
"""Read file from device and store in under local_path.
Usage: get <device_path> <local_path>
"""
try:
src, dest = line.strip().split()
data = self.device.read_file(src)
with open(dest, 'wb') as outfile:
outfile.write(bytearray(data))
print '[+] File \'{}\' saved to \'{}\''.format(src, dest)
print
except ValueError:
print '[!] Invalid command usage.'
print '[!] Usage: get <source> <destination>'
print
# end-of-method do_get
@check_if_device_is_connected
def do_delete(self, line):
"""Delete file from device.
Usage: delete <device_path>
"""
path = line.strip()
_ = self.device.delete(path)
# end-of-method do_delete
@check_if_device_is_connected
def do_dump(self, path):
"""Dump device memory. Path is local folder to store dump.
Usage: dump <local_path>
"""
print '[+] Reading files tree...'
dev_map = self.device.walk(self.device.SEP)
for directory in dev_map.keys():
fixed_directory = directory.replace(self.device.SEP, os.sep)
full_path = os.path.abspath(os.path.join(path, fixed_directory[1:]))
if not os.path.exists(full_path):
os.makedirs(full_path)
d = dev_map[directory]
files = [e for e in d.entries if not e.name.endswith('/')]
for file in files:
with open(os.path.join(full_path, file.name), 'wb') as fh:
print '[+] Dumping {}{}'.format(directory, file.name)
data = self.device.read_file('{}{}'.format(directory, file.name))
fh.write(bytearray(data))
print '[+] Device memory dumped.'
print
# end-of-method do_dump
@check_if_device_is_connected
def do_info(self, _):
"""Print connected device info.
Usage: info
"""
info = Device.get_info(self.device.usb_device)
print '{:>20s} - {}'.format('Manufacturer', info['manufacturer'])
print '{:>20s} - {}'.format('Product name', info['product_name'])
print '{:>20s} - {}'.format('Vendor ID', info['vendor_id'])
print '{:>20s} - {}'.format('Product ID', info['product_id'])
print '{:>20s} - {}'.format('Serial number', info['serial_number'])
try:
data = self.device.read_file('/DEVICE.BPB')
resp = ''.join(chr(c) for c in data)
d = pb_device.PbDeviceInfo()
d.ParseFromString(resp)
bootloader_version = '{}.{}.{}'.format(d.bootloader_version.major, d.bootloader_version.minor, d.bootloader_version.patch)
print '{:>20s} - {}'.format('Bootloader version', bootloader_version)
platform_version = '{}.{}.{}'.format(d.platform_version.major, d.platform_version.minor, d.platform_version.patch)
print '{:>20s} - {}'.format('Platform version', platform_version)
device_version = '{}.{}.{}'.format(d.device_version.major, d.device_version.minor, d.device_version.patch)
print '{:>20s} - {}'.format('Device version', device_version)
print '{:>20s} - {}'.format('SVN revision', d.svn_rev)
print '{:>20s} - {}'.format('Hardware code', d.hardware_code)
print '{:>20s} - {}'.format('Color', d.product_color)
print '{:>20s} - {}'.format('Product design', d.product_design)
except:
print '[!] Failed to get extended info.'
print ' '
# end-of-method do_info
@check_if_device_is_connected
def do_fuzz(self, _):
import polar
num = _.strip()
if len(num) > 0:
num = int(num)
resp = self.device.send_raw([0x01, num] + [0x00] * 62)
print 'req: {} '.format(num),
if resp:
print 'err code: {}'.format(polar.PFTP_ERROR[resp[0]])
return
for i in xrange(256):
#raw_input('Sending [{}]...<press enter>'.format(i))
if (i & 0x03) == 2:
continue
if i in [3, 251, 252]:
continue
resp = self.device.send_raw([0x01, i] + [0x00] * 62)
print 'resp: {} '.format(i),
if resp:
print 'err code: {}'.format(polar.PFTP_ERROR[resp[0]])
else:
print
# end-of-method do_fuzz
@check_if_device_is_connected
def do_put_file(self, line):
path, filename = line.split()
self.device.put_file(path.strip(), filename.strip())
# end-of-method do_put_file
@check_if_device_is_connected
def do_walk(self, path):
"""Walk file system. Default device_path is device root folder.
Usage: walk [device_path]
"""
if not path.endswith('/'):
path += '/'
fs = self.device.walk(path)
keyz = fs.keys()
keyz.sort()
for k in keyz:
print k
d = fs[k]
files = [e for e in d.entries if not e.name.endswith('/')]
files.sort()
for f in files:
print '{}{} ({} bytes)'.format(k, f.name, f.size)
print
# end-of-method do_walk
pass
# end-of-class Loophole
def main():
cli = LoopholeCli()
cli.cmdloop(__INTRO.format(__version__))
# end-of-function main
##
# Entry point
if __name__ == '__main__':
main()
| rsc-dev/loophole | loophole/__main__.py | Python | mit | 9,572 |
using EnhancedChannelManager.Entities.Enterprises;
using EnhancedChannelManager.Library;
namespace EnhancedChannelManager.Entities.Accounts
{
public class Customer : Account, IOwnedEntity<Enterprise>
{
public Enterprise Owner { get; set; }
}
}
| onashackem/EnhancedChannelManager | src/EnhancedChannelManager/Entities/Accounts/Customer.cs | C# | mit | 268 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- disable iPhone inital scale -->
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
<?php
// Spit out meta tags
foreach($data->getMeta() as $name => $content)
echo '<meta name="'.$name.'" content="'.$content.'" >';
?>
<?php
// Determine page title
$title = $data->getTitle();
if( $data->getPageTitle() )
$title = $data->getPageTitle()." - ".$title;
?>
<title><?php echo $title ?></title>
<?php
// Spit out CSS
foreach($data->getCss() as $css)
echo "<link rel='stylesheet' href='".$css['file']."' type='text/css' />\n";
?>
<?php
// Detect mobile device
function isMobile() {
return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
if(isMobile()): ?>
<link href="/contexts/default/css/media-queries.css" rel="stylesheet" type="text/css">
<?php endif ?>
<!--[if lt IE 9]>
<script src="/erdiko/libraries/javascript/html5.js"></script>
<script src="/erdiko/libraries/javascript/css3-mediaqueries.js"></script>
<![endif]-->
</head>
<body>
<div id="pagewrap">
<?php echo $data->getHeader(); ?>
<div class="content-main">
<?php echo $this->getLayout(); ?>
</div>
<?php echo $data->getFooter(); ?>
</div>
<?php
// Spit out JS below the footer
foreach($this->getJs() as $js)
{
if($js['active'])
echo "<script src='".$js['file']."'></script>\n";
}
?>
<script type="text/javascript">/* <![CDATA[ */
$(document).ready(function() {
});
/* ]]> */</script>
</body>
</html>
| ArroyoLabs/meetups | d3demo_php/public/themes/erdiko/templates/default.php | PHP | mit | 1,660 |
<!doctype html>
<html class="no-js" lang="">
<head>
<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
<meta name="description" content="">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>
<div class="content">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>
<div class="main">
<div class="location">
<p class="breadcrumbs">Essays > Little Hope for Hemp</p>
<p class="expandcollapse">
<a href="">Expand All</a> | <a href="">Collapse All</a>
</p>
</div>
<!-- begin essay -->
<h1>Little Hope for Hemp</h1>
<p> Meanwhile, the US government does little to prevent the thousands of deaths, injuries, and illnesses caused annually by tobacco and alcoholtwo of the most addictive, dangerous, popular (and profitable)drugs in the world</p>
<!-- end essay -->
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>
</body>
</html> | javanigus/zabuun | essay/2165-little-hope-for-hemp.php | PHP | mit | 1,174 |
<?php use_helper('I18N', 'Date', 'JavascriptBase') ?>
<?php include_partial('sfJqueryTreeDoctrineManager/assets') ?>
<div id="sf_admin_container">
<h1><?php echo sfInflector::humanize(sfInflector::underscore($model)); ?> Nested Set Manager</h1>
<?php include_partial('sfJqueryTreeDoctrineManager/flashes') ?>
<?php if ($hasManyRoots && !$sf_request->hasParameter('root') ):?>
<?php include_partial('sfJqueryTreeDoctrineManager/manager_roots', array('model' => $model, 'field' => $field, 'root' => $root, 'roots' => $roots)) ?>
<?php else: ?>
<?php include_partial('sfJqueryTreeDoctrineManager/manager_tree', array('model' => $model, 'field' => $field, 'root' => $root, 'records' => $records, 'hasManyRoots' => $hasManyRoots)) ?>
<?php endif;?>
</div>
| Symfony-Plugins/sfJqueryTreeDoctrineManagerPlugin | modules/sfJqueryTreeDoctrineManager/templates/_manager.php | PHP | mit | 775 |
/**
* KeyParser.ts
*
* Simple parsing logic to take vim key bindings / chords,
* and return a normalized object.
*/
export interface IKey {
character: string
shift: boolean
alt: boolean
control: boolean
meta: boolean
}
export interface IKeyChord {
chord: IKey[]
}
export const parseKeysFromVimString = (keys: string): IKeyChord => {
const chord: IKey[] = []
let idx = 0
while (idx < keys.length) {
if (keys[idx] !== "<") {
chord.push(parseKey(keys[idx]))
} else {
const endIndex = getNextCharacter(keys, idx + 1)
// Malformed if there isn't a corresponding '>'
if (endIndex === -1) {
return { chord }
}
const keyContents = keys.substring(idx + 1, endIndex)
chord.push(parseKey(keyContents))
idx = endIndex + 1
}
idx++
}
return {
chord,
}
}
const getNextCharacter = (str: string, startIndex: number): number => {
let i = startIndex
while (i < str.length) {
if (str[i] === ">") {
return i
}
i++
}
return -1
}
export const parseKey = (key: string): IKey => {
if (key.indexOf("-") === -1) {
return {
character: key,
shift: false,
alt: false,
control: false,
meta: false,
}
}
const hasControl = key.indexOf("c-") >= 0 || key.indexOf("C-") >= 0
const hasShift = key.indexOf("s-") >= 0 || key.indexOf("S-") >= 0
const hasAlt = key.indexOf("a-") >= 0 || key.indexOf("A-") >= 0
const hasMeta = key.indexOf("m-") >= 0 || key.indexOf("M-") >= 0
const lastIndexoFHyphen = key.lastIndexOf("-")
const finalKey = key.substring(lastIndexoFHyphen + 1, key.length)
return {
character: finalKey,
shift: hasShift,
alt: hasAlt,
control: hasControl,
meta: hasMeta,
}
}
// Parse a chord string (e.g. <c-s-p>) into textual descriptions of the relevant keys
// <c-s-p> -> ["control", "shift", "p"]
export const parseChordParts = (keys: string): string[] => {
const parsedKeys = parseKeysFromVimString(keys)
if (!parsedKeys || !parsedKeys.chord || parsedKeys.chord.length === 0) {
return null
}
const firstChord = parsedKeys.chord[0]
const chordParts: string[] = []
if (firstChord.meta) {
chordParts.push("meta")
}
if (firstChord.control) {
chordParts.push("control")
}
if (firstChord.alt) {
chordParts.push("alt")
}
if (firstChord.shift) {
chordParts.push("shift")
}
chordParts.push(firstChord.character)
return chordParts
}
| extr0py/oni | browser/src/Input/KeyParser.ts | TypeScript | mit | 2,737 |
import * as React from 'react';
import { connect } from 'react-redux';
import * as Actions from './Actions';
import { ITrackHistoryState } from './ITypes';
let Dropzone = require('react-dropzone');
interface IProps extends ITrackHistoryState {
dispatch: Function;
};
function selectState(state: ITrackHistoryState) {
return state;
};
class Component extends React.Component<IProps, any> {
private static styles = {
button: {
backgroundColor: '#518D21',
borderRadius: '3px',
border: '1px solid rgba(255, 255, 255, 0.2)',
fontSize: '20px',
width: '26px',
height: '22px',
lineHeight: '20px',
fontWeight: 'bold',
padding: '0px 1px',
boxSizing: 'content-box',
color: 'white',
textAlign: 'center',
cursor: 'pointer'
},
disabled: {
backgroundColor: 'rgb(102, 102, 102)',
cursor: 'default'
},
input: {
margin: '4px 0px',
outline: 'none',
border: 'none',
overflow: 'hidden',
width: '100%',
height: '16px',
},
blueBg: {
backgroundColor: 'rgb(33, 122, 141)',
},
clipboard: {
backgroundColor: 'transparent',
// color: 'rgb(33, 122, 141)',
color: '#6FB3D2',
borderColor: '#6FB3D2',
borderStyle: 'dashed',
},
container: {
width: '100%',
position: 'fixed',
bottom: 0,
boxShadow: '0px 0px 4px rgba(0, 0, 0, 0.3)',
backgroundColor: '#2A2F3A',
// maxWidth: '1000px',
color: 'white',
padding: '12px 12px 8px',
left: 0,
boxSizing: 'border-box',
zIndex: 1000
},
links: {
padding: '0px 6px'
},
actions: {
fontSize: 'smaller',
float: 'right',
marginTop: '6px'
},
};
private playback: { setTimeoutReference: number, isPlaying: boolean } = {
setTimeoutReference: null,
isPlaying: false,
};
private timeFromStart = (pos1: number) => {
return Math.floor((this.props.stateHistory.timestamps[pos1] - this.props.stateHistory.timestamps[0 + 1]) / 1000);
};
private currentTime = () => this.timeFromStart(this.props.stateHistory.current);
private totalTime = () => this.timeFromStart(this.props.stateHistory.timestamps.length - 1);
private playUntilEnd = () => {
if (this.props.stateHistory.current >= this.props.stateHistory.timestamps.length - 1) {
return this.stopPlackback();
} else {
const nextActionInMiliseconds =
this.props.stateHistory.timestamps[this.props.stateHistory.current + 1]
- this.props.stateHistory.timestamps[this.props.stateHistory.current];
// Dispatch action after gap and call self
setTimeout(() => {
this.props.dispatch(Actions.selectHistory(this.props.stateHistory.current + 1));
this.playUntilEnd();
}, nextActionInMiliseconds);
}
};
private stopPlackback = () => {
clearTimeout(this.playback.setTimeoutReference);
this.playback.isPlaying = false;
this.forceUpdate(); // refresh immediately to show new play button status, needed becuase we are cheating and not modifying props
};
private startPlayback = () => {
this.playback.isPlaying = true;
this.playUntilEnd();
this.forceUpdate();
};
private selectHistory = (e) => {
this.props.dispatch(Actions.selectHistory(parseInt(e.target.value, 10)));
};
private changeHistory = (step: number) => {
let selected = this.props.stateHistory.current + step;
// Upper & lower bound
if (selected > this.props.stateHistory.history.length - 1) {
selected = this.props.stateHistory.history.length - 1;
} else if (selected < 1) {
selected = 1;
}
this.props.dispatch(Actions.selectHistory(selected));
};
/**
* Read uploaded json file and dispatch action
*/
private uploadHistory = (files: File[]) => {
const blob = files[0].slice(0);
const reader = new FileReader();
reader.onloadend = () => {
const json = JSON.parse(reader.result);
this.props.dispatch(Actions.uploadHistory(json));
};
reader.readAsText(blob);
};
private downloadHistory(e: any) {
e.target.href = `data:text/json;charset=utf-8, ${encodeURIComponent(JSON.stringify(this.props.stateHistory)) }`;
}
public render() {
return (
<div style={ Component.styles.container }>
<div>
<div style={{ float: 'right' }}>
<span style={ this.playback.isPlaying ? { marginRight: '10px', display: 'inline-block'} : {}}>
{ this.playback.isPlaying && `${this.currentTime()}s|${this.totalTime()}s` }
</span>
{ this.props.stateHistory.current } / { this.props.stateHistory.history.length - 1 }
<button onClick={ this.changeHistory.bind(this, -1)} title='Previous state' style={
this.playback.isPlaying || this.props.stateHistory.current <= 1 ?
Object.assign({}, Component.styles.button, Component.styles.disabled) : Component.styles.button
}>{'<'}</button>
<button onClick={ this.changeHistory.bind(this, 1) } title='Next state' style={
this.playback.isPlaying || this.props.stateHistory.current >= this.props.stateHistory.history.length - 1 ?
Object.assign({}, Component.styles.button, Component.styles.disabled) : Component.styles.button
}>{'>'}</button>
<button onClick={ this.playback.isPlaying ? this.stopPlackback : this.startPlayback } title='Realtime Playblack' style={
this.props.stateHistory.current >= this.props.stateHistory.history.length - 1 ?
Object.assign({}, Component.styles.button, Component.styles.disabled) : Component.styles.button
}>{ this.playback.isPlaying ? '■' : '▸'}</button>
<a
href='#'
onClick={ this.downloadHistory.bind(this) }
download='state.json'
title='Download state'
style={ Object.assign({}, Component.styles.button, Component.styles.blueBg, Component.styles.links) }
>⇓</a>
<Dropzone
multiple={false}
title='Upload state'
onDrop={ this.uploadHistory }
style={ Object.assign({ float: 'right' }, Component.styles.button, Component.styles.clipboard) }>⇧</Dropzone>
</div>
<div style={{ width: 'auto', overflow: 'hidden', paddingRight: '19px' }}>
<input
type='range'
step={1}
min={1}
style={ Component.styles.input }
max={this.props.stateHistory.history.length - 1}
value={ `${this.props.stateHistory.current}` }
onChange={ this.selectHistory.bind(this) }
/>
</div>
<div style={ Component.styles.actions }>
{ this.props.stateHistory.actions[this.props.stateHistory.current] }
</div>
</div>
</div>
);
}
}
export default connect(selectState)(Component);
| inakianduaga/redux-state-history | src/Component.tsx | TypeScript | mit | 7,208 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Task03EnglishNameOfLastDigit
{
static void Main(string[] args)
{
long number = long.Parse(Console.ReadLine());
string numberInLetters = FindTheLastDigitInLetters(number);
Console.WriteLine(numberInLetters);
}
private static string FindTheLastDigitInLetters(long number)
{
long lastDigit = long.Parse(number.ToString().Last().ToString());
switch (lastDigit)
{
case 0:
{
return "zero";
break;
}
case 1:
{
return "one";
break;
}
case 2:
{
return "two";
break;
}
case 3:
{
return "three";
break;
}
case 4:
{
return "four";
break;
}
case 5:
{
return "five";
break;
}
case 6:
{
return "six";
break;
}
case 7:
{
return "seven";
break;
}
case 8:
{
return "eight";
break;
}
case 9:
{
return "nine";
break;
}
default:
return string.Empty;
break;
}
}
}
| samuilll/BeginnerExams | PrgrammingFundametnalsFast/04_MethodsAndDebbuging/Task03EnglishNameOfLastDigit/Task03EnglishNameOfLastDigit.cs | C# | mit | 1,860 |
import json
import sublime
import sublime_plugin
from .edit import Edit
class PawnBuildPathCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel(
"Working directory that contains pawncc.exe",
"C:\\Pawno\\",
self.onPawnPathDone,
None,
None
)
def onPawnPathDone(self, path):
view = self.view.window().new_file()
path = path.replace("\\", "/")
obj = {
"cmd": [
"pawncc.exe",
"$file",
"-o$file_path/$file_base_name",
"-;+",
"-(+",
"-d3"
],
"file_regex": r"(.*?)\(([0-9]*)[- 0-9]*\)",
"selector": "source.pwn",
"working_dir": path
}
with Edit(view) as edit:
edit.insert(0, json.dumps(obj, indent=4))
view.set_name("Pawn.sublime-build")
view.run_command("save")
| Southclaw/pawn-sublime-language | PawnBuildPath.py | Python | mit | 1,010 |
var postData = querystring.stringify({
'value' : '55',
'room_id' : '1'
});
var options = {
hostname: 'localhost',
port: 80,
path: '/temperatures',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
| MirkoC/SmartHouseRaspberryPiServer | post_to_rails.js | JavaScript | mit | 701 |
<?php
use Assert\Assertion;
use expect\FailedMessage;
use expect\matcher\ToMatch;
describe(ToMatch::class, function () {
describe('#match', function () {
beforeEach(function () {
$this->matcher = new ToMatch('/foo/');
});
context('when match', function () {
it('return true', function () {
$result = $this->matcher->match('foo');
Assertion::true($result);
});
});
context('when unmatch', function () {
it('return false', function () {
$result = $this->matcher->match('bar');
Assertion::false($result);
});
});
});
describe('#reportFailed', function () {
beforeEach(function () {
$this->matcher = new ToMatch('/foo/');
$this->message = new FailedMessage();
});
it('report failed message', function () {
$this->matcher->match('bar');
$this->matcher->reportFailed($this->message);
$message = $this->loadFixture('text:toMatch:failedMessage');
Assertion::same((string) $this->message, $message);
});
});
describe('#reportNegativeFailed', function () {
beforeEach(function () {
$this->matcher = new ToMatch('/foo/');
$this->message = new FailedMessage();
});
it('report failed message', function () {
$this->matcher->match('foo');
$this->matcher->reportNegativeFailed($this->message);
$message = $this->loadFixture('text:toMatch:negativeFailedMessage');
Assertion::same((string) $this->message, $message);
});
});
});
| expectation-php/expect | spec/matcher/ToMatch.spec.php | PHP | mit | 1,724 |
class node:
def __init__(self):
self.outputs=[]
def set(self):
for out in self.outputs:
out.set()
def clear(self):
for out in self.outputs:
out.clear()
class switch:
def __init__(self):
self.outputs=[]
self.state=False
self.input=False
def set(self):
self.input=True
if(self.state):
for out in self.outputs:
out.set()
def clear(self):
self.input=False
for out in self.outputs:
out.clear()
def open(self):
self.state=False
for out in self.outputs:
out.clear()
def close(self):
self.input=True
if(self.input):
for out in self.outputs:
out.set()
class light:
def __init__(self):
self.outputs=[]
def set(self):
print('light set')
for out in self.outputs:
out.set()
def clear(self):
print('light cleared')
for out in self.outputs:
out.clear()
if __name__ == '__main__':
a=node()
s=switch()
b=node()
l=light()
a.outputs.append(s)
s.outputs.append(b)
b.outputs.append(l)
a.set()
s.close()
print('switch close')
s.open() | mikadam/LadderiLogical | tests/node.py | Python | mit | 1,030 |
namespace MyServer.Web.Data
{
using Microsoft.AspNetCore.Identity;
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
} | atanas-georgiev/MyServer | src/Web/MyServer.Web/Data/ApplicationUser.cs | C# | mit | 229 |
package com.nepfix.sim.elements;
import com.nepfix.sim.core.Processor;
import java.util.Map;
public class UnitProcessor implements Processor {
private String id;
@Override public void init(String id, Map<String, String> args) {
this.id = id;
}
@Override public String process(String input) {
return input;
}
@Override public String getId() {
return id;
}
}
| pabloogc/Nepfix | sim/src/main/java/com/nepfix/sim/elements/UnitProcessor.java | Java | mit | 416 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TwitchIntegrator
{
internal class CitizenManagerMod : CitizenManager
{
public string GetCitizenName(uint citizenID)
{
return TwitchNames.GetName((int) citizenID);
}
}
}
| kiwiploetze/TwitchIntegrator | CitizenManagerMod.cs | C# | mit | 329 |
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* 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 techreborn.blocks.storage.item;
import net.minecraft.block.BlockState;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.ToolItem;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.api.blockentity.IMachineGuiHandler;
import reborncore.common.blocks.BlockMachineBase;
import reborncore.common.util.RebornInventory;
import reborncore.common.util.WorldUtils;
import techreborn.blockentity.storage.item.StorageUnitBaseBlockEntity;
import techreborn.blockentity.GuiType;
import techreborn.init.TRContent;
public class StorageUnitBlock extends BlockMachineBase {
public final TRContent.StorageUnit unitType;
public StorageUnitBlock(TRContent.StorageUnit unitType) {
super((Settings.of(unitType.name.equals("crude") ? Material.WOOD : Material.METAL).strength(2.0F, 2.0F)));
this.unitType = unitType;
}
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return new StorageUnitBaseBlockEntity(pos, state, unitType);
}
@Override
public ActionResult onUse(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockHitResult hitResult) {
if (unitType == TRContent.StorageUnit.CREATIVE || worldIn.isClient) {
return super.onUse(state, worldIn, pos, playerIn, hand, hitResult);
}
final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) worldIn.getBlockEntity(pos);
ItemStack stackInHand = playerIn.getStackInHand(Hand.MAIN_HAND);
Item itemInHand = stackInHand.getItem();
if (storageEntity != null && itemInHand != Items.AIR && (storageEntity.isSameType(stackInHand) && !storageEntity.isFull() ||
(!storageEntity.isLocked() && storageEntity.isEmpty() && (!(itemInHand instanceof ToolItem))))) {
// Add item which is the same type (in users inventory) into storage
for (int i = 0; i < playerIn.getInventory().size() && !storageEntity.isFull(); i++) {
ItemStack curStack = playerIn.getInventory().getStack(i);
if (curStack.getItem() == itemInHand) {
playerIn.getInventory().setStack(i, storageEntity.processInput(curStack));
}
}
return ActionResult.SUCCESS;
}
return super.onUse(state, worldIn, pos, playerIn, hand, hitResult);
}
@Override
public void onBlockBreakStart(BlockState state, World world, BlockPos pos, PlayerEntity player) {
super.onBlockBreakStart(state, world, pos, player);
if (world.isClient) return;
final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) world.getBlockEntity(pos);
ItemStack stackInHand = player.getStackInHand(Hand.MAIN_HAND);
if (storageEntity != null && (stackInHand.isEmpty() || storageEntity.isSameType(stackInHand)) && !storageEntity.isEmpty()) {
RebornInventory<StorageUnitBaseBlockEntity> inventory = storageEntity.getInventory();
ItemStack out = inventory.getStack(StorageUnitBaseBlockEntity.OUTPUT_SLOT);
// Drop stack if sneaking
if (player.isSneaking()) {
WorldUtils.dropItem(new ItemStack(out.getItem()), world, player.getBlockPos());
out.decrement(1);
} else {
WorldUtils.dropItem(out, world, player.getBlockPos());
out.setCount(0);
}
inventory.setHashChanged();
}
}
@Override
public IMachineGuiHandler getGui() {
return GuiType.STORAGE_UNIT;
}
}
| TechReborn/TechReborn | src/main/java/techreborn/blocks/storage/item/StorageUnitBlock.java | Java | mit | 4,798 |
<?php
namespace App\Command\Import;
use App\Command\BaseCommand;
use App\Entity\Framework\LsDoc;
class MarkImportLogsAsReadCommand extends BaseCommand
{
/**
* @var LsDoc
*/
private $doc;
public function __construct(LsDoc $doc)
{
$this->doc = $doc;
}
public function getDoc(): LsDoc
{
return $this->doc;
}
}
| opensalt/opensalt | core/src/Command/Import/MarkImportLogsAsReadCommand.php | PHP | mit | 371 |
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\BaseHttpException;
use Symfony\Component\HttpKernel\NotFoundHttpException;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\DoctrineServiceProvider;
use Silex\Extension\UrlGeneratorExtension;
use Silex\Extension\TwigExtension;
use Silex\Extension\SymfonyBridgesExtension;
$app = new Silex\Application();
// Debug Mode = TRUE (dev)
$app['debug'] = true;
$app->register(new FormServiceProvider());
$app->register(new TwigServiceProvider(),[
'twig.path' => __DIR__.'/../view',
]);
// Controllers Code
$blogPosts = array(
1 => array(
'date' => '2014-05-06',
'author' => '@j05145',
'title' => 'Using Silex',
'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat, a, quae quis quod soluta porro dolores? Illum, beatae quaerat ut quam consequuntur debitis distinctio sit voluptate eum non maxime accusantium.',
),
);
$app->get('/blog', function() use ($blogPosts) {
$output = '';
foreach ($blogPosts as $post) {
$output .= $post['title'];
$output .= '<br />';
}
return $output;
});
/**
* Dynamic Routes for Blogs Posts
* Passing {id} value as an argument to the closure
* abort() Method is used if requested post doesn't exist
*/
$app->get('/blog/show/{id}', function (Silex\Application $app, $id) use ($blogPosts) {
if (!isset($blogPosts[$id])) {
$app->abort(404, "El post $id no existe.");
}
$post = $blogPosts[$id];
return "<h1>{$post['title']}</h1>".
"<p>{$post['body']}</p>";
});
/**
* User login
*/
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_mysql',
'dbhost' => 'localhost',
'dbname' => 'mydbname',
'user' => 'root',
'password' => '',
),
));
/*$app->register(new Silex\Provider\SessionServiceProvider());*/
$app->get('/', function(Silex\Application $app){
$twigvars = array();
$twigvars['title'] = "Silex App";
$twigvars['content'] = "Lorem ipsum ";
return $app['twig']->render('index.html.twig', $twigvars);
});
$app->get('/hello', function() {
return 'Hello!';
});
$app->run(); | Josiastech/silexApp | web/index.php | PHP | mit | 2,418 |
<?php
namespace Nature;
class UserToken {
private $timePassed = 1418464671;
private $codeMaps = "~!@#$%^&*()_+=-{}[]|\;,.<>?/abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private $key;
private $uid;
private $expire=604800;
function __construct($key=null){
if(!is_null($key)) {
$this->setKey($key);
}
}
function __toString(){
$uid = $this->num2code($this->uid);
$expire = $this->num2code($this->expire - $this->timePassed);
//更短:过去之时不再有
return $uid.':'.$this->encrypt($uid.':'.$expire);
}
function setExpire($time){
$this->expire = $time;
return $this;
}
function setKey($key){
$this->key = $key;
return $this;
}
function setUid($uid) {
$this->uid = $uid;
return $this;
}
function verify($token){
list($rawuid, $token) = explode(":", $token, 2);
$uid = $this->code2num($rawuid);
$data = $this->decrypt($token);
if(!$data || !strpos($data, ':')) {
return false;
}
list($encryptUid, $expire) = explode(":", $data, 2);
if($encryptUid !== $rawuid) {
return false;
}
$expire = $this->code2num($expire);
if(!is_numeric($expire) || ($expire + $this->timePassed) < time()){
return false;
}
return $uid;
}
function parseUid($token){
list($rawuid, $token) = explode(":", $token, 2);
return $this->code2num($rawuid);
}
function num2code($number) {
static $cache = [];
if(!isset($cache[$number])) {
$out = "";
$len = strlen($this->codeMaps);
while ($number >= $len) {
$key = $number % $len;
$number = intval(floor($number / $len) - 1);
$out = $this->codeMaps{$key}.$out;
}
$cache[$number] = $this->codeMaps{$number}.$out;
}
return $cache[$number];
}
function code2num($code) {
static $cache = [];
if(!isset($cache[$code])) {
$len = strlen($this->codeMaps);
$codelen = strlen($code);
$num = 0;
$i = $codelen;
for($j=0; $j<$codelen; $j++){
$i--;
$char = $code{$j};
$pos = strpos($this->codeMaps, $char);
$num += (pow($len, $i) * ($pos + 1));
}
$num--;
$cache[$code] = intval($num);
}
return $cache[$code];
}
function encrypt($data) {
$encrypt = openssl_encrypt($data, 'bf-ecb', $this->key, OPENSSL_RAW_DATA);
return base64_encode($encrypt);
}
function decrypt($str) {
$str = base64_decode($str);
$str = openssl_decrypt($str, 'bf-ecb', $this->key, OPENSSL_RAW_DATA);
return $str;
}
} | shiny/Nature | App/Nature/UserToken.class.php | PHP | mit | 2,810 |
// Copyright © 2017 Viro Media. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.viromedia.bridge.component.node;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ThemedReactContext;
/**
* SceneManager for building a {@link VRTScene}
* corresponding to the ViroScene.js control.
*/
public class VRTSceneManagerImpl extends VRTSceneManager<VRTScene> {
public VRTSceneManagerImpl(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "VRTScene";
}
@Override
protected VRTScene createViewInstance(ThemedReactContext reactContext) {
return new VRTScene(reactContext);
}
}
| viromedia/viro | android/viro_bridge/src/main/java/com/viromedia/bridge/component/node/VRTSceneManagerImpl.java | Java | mit | 1,801 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace HTLib2.Bioinfo
{
public partial class Pdb
{
[Serializable]
public class Model : Element, IComparable<Model>, IBinarySerializable
{
/// http://www.wwpdb.org/documentation/format23/sect9.html#MODEL
///
/// MODEL
///
/// The MODEL record specifies the model serial number when multiple
/// structures are presented in a single coordinate entry, as is
/// often the case with structures determined by NMR.
///
/// Record Format
///
/// COLUMNS DATA TYPE FIELD DEFINITION
/// -------------------------------------------------------------
/// 1 - 6 Record name "MODEL "
/// 11 - 14 Integer serial Model serial number.
///
/// Example
/// 1 2 3 4 5 6 7 8
/// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
/// MODEL 1
/// ATOM 1 N ALA 1 11.104 6.134 -6.504 1.00 0.00 N
/// ATOM 2 CA ALA 1 11.639 6.071 -5.147 1.00 0.00 C
/// ...
/// ...
/// ATOM 293 1HG GLU 18 -14.861 -4.847 0.361 1.00 0.00 H
/// ATOM 294 2HG GLU 18 -13.518 -3.769 0.084 1.00 0.00 H
/// TER 295 GLU 18
/// ENDMDL
/// MODEL 2
/// ATOM 296 N ALA 1 10.883 6.779 -6.464 1.00 0.00 N
/// ATOM 297 CA ALA 1 11.451 6.531 -5.142 1.00 0.00 C
/// ...
/// ...
/// ATOM 588 1HG GLU 18 -13.363 -4.163 -2.372 1.00 0.00 H
/// ATOM 589 2HG GLU 18 -12.634 -3.023 -3.475 1.00 0.00 H
/// TER 590 GLU 18
/// ENDMDL
public static string RecordName { get { return "MODEL "; } }
Model(string line)
: base(line)
{
}
public static Model FromString(string line)
{
HDebug.Assert(IsModel(line));
return new Model(line);
}
public static Model FromModelSerial(int serial)
{
// 0 1 2 3 4 5 6 7 8
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
char[] line = "MODEL ".ToArray();
string strserial = string.Format("{0,4}", serial);
for(int i=0; i<4; i++) line[i+idxs_serial[0]] = strserial[i];
return new Model(new string(line));
}
public static bool IsModel(string line) { return (line.Substring(0, 6) == "MODEL "); }
public int serial { get { return Integer(idxs_serial ).Value; } } static readonly int[] idxs_serial = new int[]{11,14}; // 11 - 14 Integer serial Model serial number.
// IComparable<Model>
int IComparable<Model>.CompareTo(Model other)
{
return serial.CompareTo(other.serial);
}
//public override string ToString()
//{
// string str = string.Format("{0:D} {1}, {2:d} {3}", serial, name.Trim(), resSeq, resName.Trim());
// str += string.Format(", pos({0:G4},{1:G4},{2:G4})", x, y, z);
// str += string.Format(", alt({0}), chain({1})", altLoc, chainID);
// return str;
//}
////////////////////////////////////////////////////////////////////////////////////
// IBinarySerializable
public new void BinarySerialize(HBinaryWriter writer)
{
}
public Model(HBinaryReader reader) : base(reader)
{
}
// IBinarySerializable
////////////////////////////////////////////////////////////////////////////////////
// Serializable
public Model(SerializationInfo info, StreamingContext ctxt) : base(info, ctxt) {}
public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
| htna/HCsbLib | HCsbLib/HCsbLib/HTLib2.Bioinfo/Pdb/Pdb.Element/CoordinateSection/Pdb.Model.cs | C# | mit | 5,446 |
class CreateDiners < ActiveRecord::Migration
def change
create_table :diners do |t|
t.integer :signup_id
t.string :diner_name
t.timestamps null: false
end
end
end
| heath3conk/katz-golf-tournament | db/migrate/20160522202905_create_diners.rb | Ruby | mit | 194 |
package za.co.cporm.model.loader.support;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.CursorLoader;
import za.co.cporm.model.generate.TableDetails;
import za.co.cporm.model.query.Select;
import za.co.cporm.model.util.CPOrmCursor;
import za.co.cporm.model.util.ContentResolverValues;
/**
* Created by hennie.brink on 2015-03-31.
*/
public class CPOrmLoader<Model> extends CursorLoader {
private TableDetails tableDetails;
private int cacheSize = 0;
/**
* Creates a new cursor loader using the select statement provided. The default implementation
* will enable the cache of the cursor to improve view performance. To manually specify the
* cursor cache size, use the overloaded constructor.
* @param context The context that will be used to create the cursor.
* @param select The select statement that will be used to retrieve the data.
*/
public CPOrmLoader(Context context, Select<Model> select) {
super(context);
ContentResolverValues resolverValues = select.asContentResolverValue(context);
setUri(resolverValues.getItemUri());
setProjection(resolverValues.getProjection());
setSelection(resolverValues.getWhere());
setSelectionArgs(resolverValues.getWhereArgs());
setSortOrder(resolverValues.getSortOrder());
tableDetails = resolverValues.getTableDetails();
}
/**
* Creates a new cursor loader using the select statement provided. You
* can specify the cache size to use, or use -1 to disable cursor caching.
* @param context The context that will be used to create the cursor.
* @param select The select statement that will be used to retrieve the data.
* @param cacheSize The cache size for the cursor, or -1 to disable caching
*/
public CPOrmLoader(Context context, Select<Model> select, int cacheSize) {
this(context, select);
enableCursorCache(cacheSize);
}
public void enableCursorCache(int size) {
cacheSize = size;
}
@Override
public CPOrmCursor<Model> loadInBackground() {
Cursor asyncCursor = super.loadInBackground();
if(asyncCursor == null)
return null;
CPOrmCursor<Model> cursor = new CPOrmCursor<>(tableDetails, asyncCursor);
if(cacheSize == 0){
cursor.enableCache();
} else if(cacheSize > 0) {
cursor.enableCache(cacheSize);
}
//Prefetch at least some items in preparation for the list
int count = cursor.getCount();
for (int i = 0; i < count && cursor.isCacheEnabled() && i < 100; i++) {
cursor.moveToPosition(i);
Model inflate = cursor.inflate();
}
return cursor;
}
}
| Wackymax/CPOrm | CPOrm/src/main/java/za/co/cporm/model/loader/support/CPOrmLoader.java | Java | mit | 2,810 |
import React from 'react';
import PostImage from '../components/story/PostImage';
import TwoPostImages from '../components/story/TwoPostImages';
import StoryPage from '../components/story/StoryPage';
import StoryTextBlock from '../components/story/StoryTextBlock';
import StoryImages from '../components/story/StoryImages';
import StoryIntro from '../components/story/StoryIntro';
const imgDirPath = "/images/stories/2016-11-20-irina-and-lucian-maternity-photo-session/";
const imgDirPath1 = "stories/2016-11-20-irina-and-lucian-maternity-photo-session";
class IrinaAndLucianMaternityPhotoSessionStory extends React.Component {
constructor() {
super();
}
render() {
return (
<StoryPage logoDirPath={imgDirPath1}
logoPrefix="teaser"
logoNumber="08-2048"
title="Irina & Lucian Maternity Photos"
author="Dan"
location="Charlottenburg Palace, Berlin"
tags="maternity, baby, pregnancy">
<StoryIntro>
Our friends, Lucian and Irina are having a baby. This is such a wonderful moment!
We decided to go together at the Charlottenburg Palace to do a maternity photo session.
We were really lucky we got a wonderful sunny weekend, the last sunny one this autumn,
before all of the leaves have already fallen.
</StoryIntro>
<StoryTextBlock title="The Charlottenburg Palace">
The impressive palace is a great place to take photos and this time is
covered with scaffolding, which somehow gives a symbolic hint to our photo shoot:
"work in progress!" We start our photo session here,
taking advantage of the bright sun. I'm using a polarizer filter here,
to make the colors pop!
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="01" />
<TwoPostImages dirPath={imgDirPath}
number1="02"
number2="03" />
<TwoPostImages dirPath={imgDirPath}
number1="05"
number2="06" />
<PostImage dirPath={imgDirPath} number="07" />
<PostImage dirPath={imgDirPath} number="10" />
<PostImage dirPath={imgDirPath} number="27" />
</StoryImages>
<StoryTextBlock title="The Forest">
The sun coming through the colorful leaves of the autumn gave the perfect light for the next photos.
Using a long lens allowed me to isolate my subjects and bring that great shallow depth of field!
I'll let you observe the authentic joy on Lucian and Irina's faces, brought by this great moment in their lives,
having a baby.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="16" />
<TwoPostImages dirPath={imgDirPath}
number1="13"
number2="15" />
<PostImage dirPath={imgDirPath} number="19" />
<TwoPostImages dirPath={imgDirPath}
number1="20"
number2="21" />
<PostImage dirPath={imgDirPath} number="22" />
<TwoPostImages dirPath={imgDirPath}
number1="23"
number2="24" />
<PostImage dirPath={imgDirPath} number="35" />
</StoryImages>
<StoryTextBlock title="The Lake">
Moving away from "the forest", we chose the nearby lake is our third location.
<br/>
In the next photo, the contrast between the blue lake and Irina's orange
pullover is just amazing.
<br/>
You might already know that the bridge in the Charlottenburg Garden is
one of our <a href="/streets-of-berlin/charlottenburg-bridge-in-autumn.html">favorite
places</a>. Like always, it gave me a really nice opportunity to play
with reflections.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="28" />
<PostImage dirPath={imgDirPath} number="30" />
<PostImage dirPath={imgDirPath} number="31" />
<PostImage dirPath={imgDirPath} number="37" />
<PostImage dirPath={imgDirPath} number="39" />
<PostImage dirPath={imgDirPath} number="42" />
</StoryImages>
<StoryTextBlock title="The Autumn">
The colors of the autumn are just amazing! My favorite photo from this
series is the next one. I call it "The Tree of Life", as there are four
colors spreading from each of the corners, one for each of the seasons.
We have spring and summer to the left, and autumn and winter to the right.
And of course, pregnant Irina in the middle getting support from her dear
husband, Lucian.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="44" />
<PostImage dirPath={imgDirPath} number="46" />
<PostImage dirPath={imgDirPath} number="48" />
<PostImage dirPath={imgDirPath} number="51" />
<TwoPostImages dirPath={imgDirPath}
number1="52"
number2="53" />
<PostImage dirPath={imgDirPath} number="54" />
<TwoPostImages dirPath={imgDirPath}
number1="55"
number2="56" />
<PostImage dirPath={imgDirPath} number="59" />
<TwoPostImages dirPath={imgDirPath}
number1="60"
number2="61" />
<TwoPostImages dirPath={imgDirPath}
number1="62"
number2="63" />
<PostImage dirPath={imgDirPath} number="64" />
</StoryImages>
</StoryPage>);
}
}
export default IrinaAndLucianMaternityPhotoSessionStory;
| danpersa/remindmetolive-react | src/stories/2016-11-20-irina-and-lucian-maternity-photo-session.js | JavaScript | mit | 6,016 |
/// <reference types="node" />
declare module 'sqlite3' {
// Type definitions for sqlite3 3.1
// Project: http://github.com/mapbox/node-sqlite3
// Definitions by: Nick Malaguti <https://github.com/nmalaguti>
// Sumant Manne <https://github.com/dpyro>
// Behind The Math <https://github.com/BehindTheMath>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import events = require('events')
export const OPEN_READONLY: number
export const OPEN_READWRITE: number
export const OPEN_CREATE: number
export const OPEN_SHAREDCACHE: number
export const OPEN_PRIVATECACHE: number
export const OPEN_URI: number
export const cached: {
Database(
filename: string,
callback?: (this: Database, err: Error | null) => void
): Database
Database(
filename: string,
mode?: number,
callback?: (this: Database, err: Error | null) => void
): Database
}
export interface RunResult extends Statement {
lastID: number
changes: number
}
export class Statement {
bind (callback?: (err: Error | null) => void): this
bind (...params: any[]): this
reset (callback?: (err: null) => void): this
finalize (callback?: (err: Error) => void): Database
run (callback?: (err: Error | null) => void): this
run (
params: any,
callback?: (this: RunResult, err: Error | null) => void
): this
run (...params: any[]): this
get (callback?: (err: Error | null, row?: any) => void): this
get (
params: any,
callback?: (this: RunResult, err: Error | null, row?: any) => void
): this
get (...params: any[]): this
all (callback?: (err: Error | null, rows: any[]) => void): this
all (
params: any,
callback?: (this: RunResult, err: Error | null, rows: any[]) => void
): this
all (...params: any[]): this
each (
callback?: (err: Error | null, row: any) => void,
complete?: (err: Error | null, count: number) => void
): this
each (
params: any,
callback?: (this: RunResult, err: Error | null, row: any) => void,
complete?: (err: Error | null, count: number) => void
): this
each (...params: any[]): this
}
export class Database extends events.EventEmitter {
constructor (filename: string, callback?: (err: Error | null) => void)
constructor (
filename: string,
mode?: number,
callback?: (err: Error | null) => void
)
close (callback?: (err: Error | null) => void): void
run (
sql: string,
callback?: (this: RunResult, err: Error | null) => void
): this
run (
sql: string,
params: any,
callback?: (this: RunResult, err: Error | null) => void
): this
run (sql: string, ...params: any[]): this
get (
sql: string,
callback?: (this: Statement, err: Error | null, row: any) => void
): this
get (
sql: string,
params: any,
callback?: (this: Statement, err: Error | null, row: any) => void
): this
get (sql: string, ...params: any[]): this
all (
sql: string,
callback?: (this: Statement, err: Error | null, rows: any[]) => void
): this
all (
sql: string,
params: any,
callback?: (this: Statement, err: Error | null, rows: any[]) => void
): this
all (sql: string, ...params: any[]): this
each (
sql: string,
callback?: (this: Statement, err: Error | null, row: any) => void,
complete?: (err: Error | null, count: number) => void
): this
each (
sql: string,
params: any,
callback?: (this: Statement, err: Error | null, row: any) => void,
complete?: (err: Error | null, count: number) => void
): this
each (sql: string, ...params: any[]): this
exec (
sql: string,
callback?: (this: Statement, err: Error | null) => void
): this
prepare (
sql: string,
callback?: (this: Statement, err: Error | null) => void
): Statement
prepare (
sql: string,
params: any,
callback?: (this: Statement, err: Error | null) => void
): Statement
prepare (sql: string, ...params: any[]): Statement
serialize (callback?: () => void): void
parallelize (callback?: () => void): void
on (event: 'trace', listener: (sql: string) => void): this
on (event: 'profile', listener: (sql: string, time: number) => void): this
on (event: 'error', listener: (err: Error) => void): this
on (event: 'open' | 'close', listener: () => void): this
on (event: string, listener: (...args: any[]) => void): this
configure (option: 'busyTimeout', value: number): void
interrupt (): void
loadExtension (path: string, callback?: (err: Error | null) => void): void
}
export function verbose (): sqlite3
export interface sqlite3 {
OPEN_READONLY: number
OPEN_READWRITE: number
OPEN_CREATE: number
OPEN_SHAREDCACHE: number
OPEN_PRIVATECACHE: number
OPEN_URI: number
cached: typeof cached
RunResult: RunResult
Statement: typeof Statement
Database: typeof Database
verbose(): this
}
}
| kriasoft/node-sqlite | src/vendor-typings/sqlite3/index.d.ts | TypeScript | mit | 5,194 |
<?php
declare(strict_types = 1);
namespace Rx\Testing;
use Rx\TestCase;
class RecordedTest extends TestCase
{
public function testRecordedWillUseStrictCompareIfNoEqualsMethod()
{
$recorded1 = new Recorded(1, 5);
$recorded2 = new Recorded(1, "5");
$recorded3 = new Recorded(1, 5);
$this->assertFalse($recorded1->equals($recorded2));
$this->assertTrue($recorded1->equals($recorded3));
}
public function testRecordedToString()
{
$recorded = new Recorded(1, 5);
$this->assertEquals("5@1", $recorded->__toString());
}
}
| ReactiveX/RxPHP | test/Rx/Testing/RecordedTest.php | PHP | mit | 602 |
/*The MIT License (MIT)
Copyright (c) 2014 PMU Staff
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.Generic;
using System.Text;
using Client.Logic.Maps;
namespace Client.Logic.Editors.RDungeons
{
public class EditableRDungeonTrap
{
public Tile SpecialTile { get; set; }
public int AppearanceRate { get; set; }
public EditableRDungeonTrap()
{
SpecialTile = new Tile();
}
}
}
| Sprinkoringo/PMU-Client | Client/Editors/RDungeons/EditableRDungeonTrap.cs | C# | mit | 1,465 |
module Locomotive
module LiquidExtras
module Filters
module Math
def round(input, digits = 0)
input.to_f.round(digits)
end
end
::Liquid::Template.register_filter(Math)
end
end
end
| warp/liquid_extras | lib/locomotive/liquid_extras/filters/math.rb | Ruby | mit | 239 |
/*
* The MIT License
*
* Copyright 2015 Ryan Gilera.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.daytron.twaattin.presenter;
import com.github.daytron.twaattin.ui.LoginScreen;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.Position;
import com.vaadin.ui.Button;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import java.security.Principal;
/**
*
* @author Ryan Gilera
*/
public class LogoutBehaviour implements Button.ClickListener {
private final static long serialVersionUID = 1L;
@Override
public void buttonClick(Button.ClickEvent event) {
VaadinSession.getCurrent().setAttribute(Principal.class, null);
UI.getCurrent().setContent(new LoginScreen());
Notification logoutNotification = new Notification(
"You've been logout", Notification.Type.TRAY_NOTIFICATION);
logoutNotification.setPosition(Position.TOP_CENTER);
logoutNotification.show(Page.getCurrent());
}
}
| Daytron/Twaattin | src/main/java/com/github/daytron/twaattin/presenter/LogoutBehaviour.java | Java | mit | 2,099 |
package org.railwaystations.api.resources;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils;
import org.railwaystations.api.PhotoImporter;
import org.railwaystations.api.StationsRepository;
import org.railwaystations.api.model.Station;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Path("/")
public class SlackCommandResource {
private static final Pattern PATTERN_SEARCH = Pattern.compile("\\s*search\\s*(.*)");
private static final Pattern PATTERN_SHOW = Pattern.compile("\\s*show\\s\\s*([a-z]{1,3})\\s\\s*(\\w*)");
private static final Pattern PATTERN_SHOW_LEGACY = Pattern.compile("\\s*show\\s\\s*(\\d*)");
private final StationsRepository repository;
private final String verificationToken;
private final PhotoImporter photoImporter;
public SlackCommandResource(final StationsRepository repository, final String verificationToken, final PhotoImporter photoImporter) {
this.repository = repository;
this.verificationToken = verificationToken;
this.photoImporter = photoImporter;
}
@POST
@Path("slack")
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public SlackResponse command(@FormParam("token") final String token,
@FormParam("text") final String text,
@FormParam("response_url") final String responseUrl) {
if (!StringUtils.equals(verificationToken, token)) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
if (StringUtils.equals("import", text)) {
photoImporter.importPhotosAsync();
return new SlackResponse(ResponseType.in_channel, "Importing photos");
}
final Matcher matcherSearch = PATTERN_SEARCH.matcher(text);
if (matcherSearch.matches()) {
final Map<Station.Key, String> stations = repository.findByName(matcherSearch.group(1));
if (!stations.isEmpty()){
return new SlackResponse(ResponseType.in_channel, toMessage(stations));
}
return new SlackResponse(ResponseType.in_channel, "No stations found");
}
final Matcher matcherShow = PATTERN_SHOW.matcher(text);
if (matcherShow.matches()) {
return showStation(matcherShow.group(1).toLowerCase(Locale.ENGLISH), matcherShow.group(2));
}
final Matcher matcherShowLegacy = PATTERN_SHOW_LEGACY.matcher(text);
if (matcherShowLegacy.matches()) {
return showStation(null, matcherShowLegacy.group(1));
}
return new SlackResponse(ResponseType.ephimeral, String.format("I understand:%n- '/rsapi search <station-name>'%n- '/rsapi show <country-code> <station-id>%n- '/rsapi import'%n"));
}
private SlackResponse showStation(final String country, final String id) {
final Station.Key key = new Station.Key(country, id);
final Station station = repository.findByKey(key);
if (station == null) {
return new SlackResponse(ResponseType.in_channel, "Station with " + key + " not found");
} else {
return new SlackResponse(ResponseType.in_channel, toMessage(station));
}
}
private String toMessage(final Map<Station.Key, String> stations) {
final StringBuilder sb = new StringBuilder(String.format("Found:%n"));
stations.keySet().forEach(station -> sb.append(String.format("- %s: %s%n", stations.get(station), station)));
return sb.toString();
}
private String toMessage(final Station station) {
return String.format("Station: %s - %s%nCountry: %s%nLocation: %f,%f%nPhotographer: %s%nLicense: %s%nPhoto: %s%n", station.getKey().getId(), station.getTitle(), station.getKey().getCountry(), station.getCoordinates().getLat(), station.getCoordinates().getLon(), station.getPhotographer(), station.getLicense(), station.getPhotoUrl());
}
public enum ResponseType {
ephimeral,
in_channel
}
/**
* <div>
* {
* “response_type”: “ephemeral”,
* “text”: “How to use /please”,
* “attachments”:[
* {
* “text”:”To be fed, use `/please feed` to request food. We hear the elf needs food badly.\nTo tease, use `/please tease` — we always knew you liked noogies.\nYou’ve already learned how to getStationsByCountry help with `/please help`.”
* }
* ]
* }
* </div>
*/
private static class SlackResponse {
@JsonProperty("response_type")
private final ResponseType responseType;
@JsonProperty("text")
private final String text;
private SlackResponse(final ResponseType responseType, final String text) {
this.responseType = responseType;
this.text = text;
}
public String getText() {
return text;
}
public ResponseType getResponseType() {
return responseType;
}
}
}
| pstorch/bahnhoefe.gpx | src/main/java/org/railwaystations/api/resources/SlackCommandResource.java | Java | mit | 5,251 |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { DBModule } from '@ngrx/db';
import {
StoreRouterConnectingModule,
RouterStateSerializer,
} from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { CoreModule } from './core/core.module';
import { AuthModule } from './auth/auth.module';
import { routes } from './routes';
import { reducers, metaReducers } from './reducers';
import { schema } from './db';
import { CustomRouterStateSerializer } from './shared/utils';
import { AppComponent } from './core/containers/app';
import { environment } from '../environments/environment';
@NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpModule,
RouterModule.forRoot(routes, { useHash: true }),
/**
* StoreModule.forRoot is imported once in the root module, accepting a reducer
* function or object map of reducer functions. If passed an object of
* reducers, combineReducers will be run creating your application
* meta-reducer. This returns all providers for an @ngrx/store
* based application.
*/
StoreModule.forRoot(reducers, { metaReducers }),
/**
* @ngrx/router-store keeps router state up-to-date in the store.
*/
StoreRouterConnectingModule,
/**
* Store devtools instrument the store retaining past versions of state
* and recalculating new states. This enables powerful time-travel
* debugging.
*
* To use the debugger, install the Redux Devtools extension for either
* Chrome or Firefox
*
* See: https://github.com/zalmoxisus/redux-devtools-extension
*/
!environment.production ? StoreDevtoolsModule.instrument() : [],
/**
* EffectsModule.forRoot() is imported once in the root module and
* sets up the effects class to be initialized immediately when the
* application starts.
*
* See: https://github.com/ngrx/platform/blob/master/docs/effects/api.md#forroot
*/
EffectsModule.forRoot([]),
/**
* `provideDB` sets up @ngrx/db with the provided schema and makes the Database
* service available.
*/
DBModule.provideDB(schema),
CoreModule.forRoot(),
AuthModule.forRoot(),
],
providers: [
/**
* The `RouterStateSnapshot` provided by the `Router` is a large complex structure.
* A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided
* by `@ngrx/router-store` to include only the desired pieces of the snapshot.
*/
{ provide: RouterStateSerializer, useClass: CustomRouterStateSerializer },
],
bootstrap: [AppComponent],
})
export class AppModule {}
| jupiter101/platform | example-app/app/app.module.ts | TypeScript | mit | 3,067 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2010-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package co.mewf.minirs.rs;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the annotated method responds to HTTP GET requests.
*
* @author Paul Sandoz
* @author Marc Hadley
* @see HttpMethod
* @since 1.0
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(HttpMethod.GET)
@Documented
public @interface GET {
}
| mewf/minirs-core | src/main/java/co/mewf/minirs/rs/GET.java | Java | mit | 2,502 |
<?php
namespace anli\user\models;
use anli\user\models\TenantUser;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
/**
* TenantUserSearch represents the model behind the search form about `app\models\TenantUser`.
*/
class TenantUserSearch extends TenantUser
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'tenant_id', 'user_id', 'create_user_id', 'update_user_id'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = TenantUser::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'tenant_id' => $this->tenant_id,
'user_id' => $this->user_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'create_user_id' => $this->create_user_id,
'update_user_id' => $this->update_user_id,
]);
return $dataProvider;
}
}
| anli/yii2-user | models/TenantUserSearch.php | PHP | mit | 1,696 |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j.exceptions;
/**
* Global exception throws when a critical error occurs (this exception is
* set as Runtime in order not to force the user to manage the exception in a
* try/catch).
*
* @author Julien Chable
* @version 1.0
*/
@SuppressWarnings("serial")
public class OpenXML4JRuntimeException extends RuntimeException {
public OpenXML4JRuntimeException(String msg) {
super(msg);
}
}
| tobyclemson/msci-project | vendor/poi-3.6/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java | Java | mit | 1,364 |
search_result['3225']=["topic_00000000000007B9.html","ApplicantDetailRequestDto.Notes Property",""]; | asiboro/asiboro.github.io | vsdoc/search--/s_3225.js | JavaScript | mit | 100 |
<?php
/**
* Debug Addon
* @author sven[ät]koalashome[punkt]de Sven Eichler
* @package redaxo4
*/
$REX['ADDON']['install']['ko_debug'] = 0;
| olien/RexBase15 | redaxo/include/addons/ko_debug/uninstall.inc.php | PHP | mit | 147 |
<script language="javascript">
$(document).ready(function(){
$(function() {
$("#pagination a").each(function() {
var g = window.location.href.slice(window.location.href.indexOf('?'));
var href = $(this).attr('href');
$(this).attr('href', href+g);
});
});
});
function chkallClick(o) {
var form = document.form;
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == "checkbox" && form.elements[i].name != "chkall") {
form.elements[i].checked = document.form.chkall.checked;
}
}
}
function checkdelete()
{
var alert = window.confirm("Do you want to delete ?");
if (alert == true)
return true;
else
return false;
}
</script>
<?php if (!empty($msg)):?>
<div class="alert alert-<?php echo $msg['type'];?>" role="alert"><?php echo $msg['text'];
?></div>
<?php endif;?>
<div class="control-group">
<form method="post" action="<?php echo base_url().'order-cancel'?>" name="form">
<span>Name Search</span>
<div class="control-group">
<div class="btn-group">
<input value="<?php echo !empty($keyword)?$keyword:'';?>" type="text" class="form-control" name="keyword" placeholder="Search">
<span class="input-group-btn">
<input type="submit" name="search-button" class="btn btn-default" onClick="return search();" value="Search">
<input type="submit" name="clear-button" class="btn btn-default" onClick="return document.form.submit();" value="Clear">
</span>
</div>
</div>
</form>
</div>
<?php if (count($orders) == 0):?>
<div class="alert alert-info alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Notice!</strong> Empty Product
</div>
<?php else :?>
<table class="table table-striped">
<thead>
<tr>
<th width="2%"></th>
<th width="10%"><a href="?order=order_id&dir=<?php echo $order_dir;?>">Order ID</a></th>
<th width="10%"><a href="?order=order_date&dir=<?php echo $order_dir;?>">Date</a></th>
<th width="10%"><a href="?order=count_items&dir=<?php echo $order_dir;?>">Total items</a></th>
<th width="10%"><a href="?order=total_value&dir=<?php echo $order_dir;?>">Total value</a></th>
<th width="10%"><a href="?order=payment&dir=<?php echo $order_dir;?>">Payment</a></th>
<th width="5%"><a href="?order=cancelled_by&dir=<?php echo $order_dir;?>">Cancelled by</a></th>
<th width="10%"><a href="?order=cancel_reason&dir=<?php echo $order_dir;?>">Reason</a></th>
<th width="5%"><a href="?order=cancelled_date&dir=<?php echo $order_dir;?>">Cancelled date</a></th>
<th width="10%"><a href="?order=cancel_note&dir=<?php echo $order_dir;?>">Notes</a></th>
</tr>
</thead>
<tbody id="accordion" role="tablist" aria-multiselectable="true">
<?php $i = 1;?>
<?php foreach ($orders as $key => $order):?>
<tr>
<td>
<a class="no-borders btn btn-default collapsed" data-parent="#accordion" role="button" data-toggle="collapse" href="#collapse<?php echo $order['order_id']?>" aria-expanded="true" aria-controls="collapse<?php echo $order['order_id']?>">
<i class="fa fa-chevron-right" ></i>
</a>
</td>
<td><a href="<?php echo base_url().'order-detail/'.$order['order_id'];?>"><?php echo $order['order_id'];
?></a></td>
<td><?php echo $order['order_date']?></td>
<td><?php echo $order['count_items'];?></td>
<td><?php echo $order['total_value'];?></td>
<td><?php echo $order['payment'];?></td>
<td><?php echo $order['cancelled_by'];?></td>
<td><?php echo $order['order_cancel_reason_name'];?></td>
<td><?php echo $order['cancelled_date'];?></td>
<td><?php echo $order['cancel_note'];?></td>
</tr>
<tr>
<td colspan="10">
<table class="table collapse" id="collapse<?php echo $order['order_id'];?>">
<thead>
<tr>
<th width="10%">Customer</th>
<th width="20%">Address</th>
<th width="20%">Product name</th>
<th width="5%">Quantity</th>
<th width="5%">Price</th>
<th width="20%">Stock</th>
</tr>
</thead>
<tbody>
<?php foreach ($order['items'] as $key => $item):?>
<tr>
<td>
<div><a href="<?php echo base_url().'customer-detail/'.$order['order_cus_id']?>"><?=$order['cus_name']?></a></div>
<div><?=$order['cus_phone']?></div>
</td>
<td><?php echo $order['cus_address'];?></td>
<td>
<div><a href="<?php echo base_url().'product-detail/'.$item['order_item_prod_id'];?>"><?php echo $item['prod_name']?></a></div>
<div>
<?php if (!empty($item['variant_value'][0])):?>
<?php echo $item['variant_value'][0];?>
<?php endif;?>
<?php if (!empty($item['variant_value'][1])):?>
<?php echo ' - '.$item['variant_value'][1];?>
<?php endif;?>
</div>
</td>
<td><?php echo $item['order_item_quantity'];?></td>
<td><?php echo $item['order_item_price']*$item['order_item_quantity'];?></td>
<td>
<?php foreach ($item['stock'] as $k => $ware):?>
<?php echo $k.': '.$ware;?>
<?php endforeach;?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</td>
</tr>
<?php $i++;?>
<div class="modal fade" id="orderModal<?php echo $order['order_id'];?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
<?php endforeach;?>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<ul class="pagination" id="pagination">
<?php echo $this->pagination->create_links();?>
</ul>
</td>
</tr>
</tfoot>
</table>
<?php endif;?>
| vuonghuynhthanhtu/administrator.lacasa.com | application/views/pages/order_cancel.php | PHP | mit | 7,186 |
require 'spec_helper'
describe Booker::BusinessClient do
let(:base_url) { 'https://apicurrent-app.booker.ninja/webservice4/json/BusinessService.svc' }
let(:temp_access_token) { 'token' }
let(:temp_access_token_expires_at) { Time.now + 1.minute }
let(:client_id) { 'client_id' }
let(:client_secret) { 'client_secret' }
let(:booker_account_name) { 'booker_account_name' }
let(:booker_username) { 'booker_username' }
let(:booker_password) { 'booker_password' }
let(:client) do
Booker::BusinessClient.new(
temp_access_token: temp_access_token,
temp_access_token_expires_at: temp_access_token_expires_at,
client_id: client_id,
client_secret: client_secret,
booker_account_name: booker_account_name,
booker_username: booker_username,
booker_password: booker_password
)
end
describe 'constants' do
it 'sets constants to right vals' do
expect(described_class::ACCESS_TOKEN_HTTP_METHOD).to eq :post
expect(described_class::ACCESS_TOKEN_ENDPOINT).to eq '/accountlogin'
end
end
describe 'modules' do
it 'has right modules included' do
expect(described_class.ancestors).to include Booker::BusinessREST
end
end
describe '#initialize' do
it 'builds a client with the valid options given' do
expect(client.temp_access_token).to eq 'token'
expect(client.temp_access_token_expires_at).to be_a(Time)
end
it 'uses the default base url when none is provided' do
expect(client.base_url).to eq 'https://apicurrent-app.booker.ninja/webservice4/json/BusinessService.svc'
end
context "ENV['BOOKER_BUSINESS_SERVICE_URL'] is set" do
before do
expect(ENV).to receive(:[]).with('BOOKER_CLIENT_ID')
expect(ENV).to receive(:[]).with('BOOKER_CLIENT_SECRET')
expect(ENV).to receive(:[]).with('BOOKER_BUSINESS_SERVICE_URL').and_return 'http://from_env'
end
it 'sets the default value from env' do
expect(subject.base_url).to eq 'http://from_env'
end
end
end
describe '#env_base_url_key' do
it('returns env_base_url_key') { expect(subject.env_base_url_key).to eq 'BOOKER_BUSINESS_SERVICE_URL' }
end
describe '#default_base_url' do
it('returns default_base_url') do
expect(subject.default_base_url).to eq base_url
end
end
describe '#access_token_options' do
it('returns access_token_options') do
expect(client.access_token_options).to eq(
client_id: client_id,
client_secret: client_secret,
'AccountName' => booker_account_name,
'UserName' => booker_username,
'Password' => booker_password
)
end
end
describe 'super #get_access_token' do
let(:temp_access_token) { nil }
let(:temp_access_token_expires_at) { nil }
let(:http_options) do
{
client_id: client_id,
client_secret: client_secret,
'AccountName' => booker_account_name,
'UserName' => booker_username,
'Password' => booker_password
}
end
let(:now) { Time.parse('2015-01-09') }
let(:expires_in) { 100 }
let(:expires_at) { now + expires_in }
let(:access_token) { 'access_token' }
let(:response) do
{
'expires_in' => expires_in.to_s,
'access_token' => access_token
}
end
before { allow(Time).to receive(:now).with(no_args).and_return(now) }
context 'response present' do
before do
expect(client).to receive(:post).with('/accountlogin', http_options, nil).and_return(true)
expect(true).to receive(:parsed_response).with(no_args).and_return(response)
expect(client).to receive(:update_token_store).with(no_args)
end
it 'sets token info and returns a temp access token' do
token = client.get_access_token
expect(token).to eq access_token
expect(token).to eq client.temp_access_token
expect(client.temp_access_token_expires_at).to be_a Time
expect(client.temp_access_token_expires_at).to eq expires_at
end
end
context 'response not present' do
let(:response) { {} }
before do
expect(client).to receive(:post).with('/accountlogin', http_options, nil).and_raise(Booker::Error)
expect(client).to_not receive(:update_token_store)
end
it 'raises Booker::InvalidApiCredentials, does not set token info' do
expect { client.get_access_token }.to raise_error Booker::InvalidApiCredentials
expect(client.temp_access_token_expires_at).to eq nil
expect(client.temp_access_token).to eq nil
end
end
end
end
| AbeCole/booker_ruby | spec/lib/booker/business_client_spec.rb | Ruby | mit | 4,902 |
import * as Jungle from '../../../jungle'
const {Construct, Composite, Domain, Cell, j, J} = Jungle;
import * as Debug from '../../../util/debug'
describe("A Cell", function () {
Debug.Crumb.defaultOptions.log = console;
Debug.Crumb.defaultOptions.debug = true;
let cell;
beforeEach(function(){
cell = J.recover(j('cell', {
head:{
retain:true,
},
mouth:j('inward'),
stomach:j('cell',{
swallow :j('resolve',{
outer(food){
this.earth.contents = food
}
}),
contents:'empty'
}),
oesophagus:j('media:direct', {
law:':mouth->stomach:swallow'
}),
}))
})
it('should deposit to the stomach, via oesophagus', function(){
let crumb = new Debug.Crumb("Beginning Feed");
cell.shell.contacts.mouth.put("Nachos", crumb);
expect(cell.exposed.stomach.contents).toBe("Nachos");
})
it('should properly dispose', function(){
cell.dispose();
expect(cell.shell.scan(':mouth')[":mouth"]).toBe(undefined)
})
});
| Space-Ed/junglejs | ts_src/test/specs/tertiary/cellSpec.ts | TypeScript | mit | 1,305 |
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop is used to identify usages of http methods
# like `get`, `post`, `put`, `path` without the usage of keyword arguments
# in your tests and change them to use keyword arguments.
#
# @example
# # bad
# get :new, { user_id: 1}
#
# # good
# get :new, params: { user_id: 1 }
class HttpPositionalArguments < Cop
MSG = 'Use keyword arguments instead of ' \
'positional arguments for http call: `%s`.'.freeze
KEYWORD_ARGS = [
:headers, :env, :params, :body, :flash, :as,
:xhr, :session, :method, :format
].freeze
HTTP_METHODS = [:get, :post, :put, :patch, :delete, :head].freeze
def on_send(node)
receiver, http_method, http_path, data = *node
# if the first word on the line is not an http method, then skip
return unless HTTP_METHODS.include?(http_method)
# if the data is nil then we don't need to add keyword arguments
# because there is no data to put in params or headers, so skip
return if data.nil?
return unless needs_conversion?(data)
# ensures this is the first method on the line
# there is an edge case here where sometimes the http method is
# wrapped into another method, but its just safer to skip those
# cases and process manually
return unless receiver.nil?
# a http_method without a path?, must be something else
return if http_path.nil?
add_offense(node, node.loc.selector, format(MSG, node.method_name))
end
# @return [Boolean] true if the line needs to be converted
def needs_conversion?(data)
# if the line has already been converted to use keyword args
# then skip
# ie. get :new, params: { user_id: 1 } (looking for keyword arg)
value = data.descendants.find do |d|
KEYWORD_ARGS.include?(d.children.first) if d.type == :sym
end
value.nil?
end
def convert_hash_data(data, type)
# empty hash or no hash return empty string
return '' if data.nil? || data.children.count < 1
hash_data = if data.hash_type?
format('{ %s }', data.children.map(&:source).join(', '))
else
# user supplies an object,
# no need to surround with braces
data.source
end
format(', %s: %s', type, hash_data)
end
# given a pre Rails 5 method: get :new, user_id: @user.id, {}
#
# @return lambda of auto correct procedure
# the result should look like:
# get :new, params: { user_id: @user.id }, headers: {}
# the http_method is the method use to call the controller
# the controller node can be a symbol, method, object or string
# that represents the path/action on the Rails controller
# the data is the http parameters and environment sent in
# the Rails 5 http call
def autocorrect(node)
_receiver, http_method, http_path, *data = *node
controller_action = http_path.source
params = convert_hash_data(data.first, 'params')
headers = convert_hash_data(data.last, 'headers') if data.count > 1
# the range of the text to replace, which is the whole line
code_to_replace = node.loc.expression
# what to replace with
new_code = format('%s %s%s%s', http_method, controller_action,
params, headers)
->(corrector) { corrector.replace(code_to_replace, new_code) }
end
end
end
end
end
| melch/rubocop | lib/rubocop/cop/rails/http_positional_arguments.rb | Ruby | mit | 3,883 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Portal = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* Created by meyve on 10.10.17*/
var Portal = exports.Portal = function (_React$Component) {
_inherits(Portal, _React$Component);
function Portal(props) {
_classCallCheck(this, Portal);
var _this = _possibleConstructorReturn(this, (Portal.__proto__ || Object.getPrototypeOf(Portal)).call(this, props));
_this.wrapper = function () {
return _react2.default.createElement(
'div',
{ className: 'react_portal-wrapper',
ref: function ref(wrapper) {
return _this.wrapperElement = wrapper;
} },
_this.props.children
);
};
_this.portalContainer = null;
_this.state = {
isOpened: Boolean(props.isOpened)
};
_this.openPortal = _this.openPortal.bind(_this);
_this.closePortal = _this.closePortal.bind(_this);
_this.handleEscKeyPress = _this.handleEscKeyPress.bind(_this);
_this.handleOutsideClick = _this.handleOutsideClick.bind(_this);
_this.getDefaultDomNode = _this.getDefaultDomNode.bind(_this);
_this.createPortal = _this.createPortal.bind(_this);
return _this;
}
_createClass(Portal, [{
key: 'componentDidMount',
value: function componentDidMount() {
if (this.props.closeOnEsc) {
document.addEventListener('keydown', this.handleEscKeyPress);
}
if (this.props.closeOnOutsideClick) {
document.addEventListener('mouseup', this.handleOutsideClick);
document.addEventListener('touchstart', this.handleOutsideClick);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.props.hasOwnProperty('isOpened')) {
if (this.props.isOpened !== nextProps.isOpened) {
return nextProps.isOpened ? this.openPortal() : this.closePortal();
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.props.closeOnEsc) {
document.removeEventListener('keydown', this.handleEscKeyPress);
}
if (this.props.closeOnOutsideClick) {
document.removeEventListener('mouseup', this.handleOutsideClick);
document.removeEventListener('touchstart', this.handleOutsideClick);
}
}
}, {
key: 'getDefaultDomNode',
value: function getDefaultDomNode() {
var reactContainerId = 'react_portal-container';
this.portalContainer = document.getElementById(reactContainerId);
if (!this.portalContainer) {
this.portalContainer = document.createElement('div');
this.portalContainer.id = reactContainerId;
document.body.appendChild(this.portalContainer);
}
return document.getElementById(reactContainerId);
}
}, {
key: 'openPortal',
value: function openPortal() {
if (this.props.beforeOpen) this.props.beforeOpen();
return this.setState({ isOpened: true }, this.props.onOpen);
}
}, {
key: 'closePortal',
value: function closePortal() {
if (this.props.beforeClose) this.props.beforeClose();
return this.setState({ isOpened: false }, this.props.onClose);
}
}, {
key: 'handleOutsideClick',
value: function handleOutsideClick(event) {
if (!this.state.isOpened) return;
if (!this.wrapperElement || this.wrapperElement.contains(event.target)) {
return;
}
this.closePortal();
}
}, {
key: 'handleEscKeyPress',
value: function handleEscKeyPress(event) {
if (event.keyCode === 27 && this.state.isOpened) {
this.closePortal();
}
}
}, {
key: 'createPortal',
value: function createPortal() {
return _reactDom2.default.createPortal(this.wrapper(), this.portalContainer);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (!this.props.node && !this.portalContainer) this.getDefaultDomNode();
return _react2.default.createElement(
'div',
{ className: 'react_portal-root', ref: function ref(root) {
return _this2.root = root;
} },
this.props.openPortalByClickOnElement && _react2.default.cloneElement(this.props.openPortalByClickOnElement, { onClick: this.openPortal }),
this.state.isOpened && this.createPortal()
);
}
}]);
return Portal;
}(_react2.default.Component);
Portal.propTypes = {
isOpened: _propTypes2.default.bool,
closeOnEsc: _propTypes2.default.bool,
closeOnOutsideClick: _propTypes2.default.bool,
openPortalByClickOnElement: _propTypes2.default.any,
onOpen: _propTypes2.default.func,
beforeOpen: _propTypes2.default.func,
onClose: _propTypes2.default.func,
beforeClose: _propTypes2.default.func
}; | meyve/react-portalizer | build/index.js | JavaScript | mit | 7,276 |
package construtores;
public class ConstrutorTesteDrive {
public static void main(String[] args) {
// Construtor c1 = new Construtor();
// System.out.println("--c1\n" + c1.getNomeERg() + "\n\n");
Construtor c2 = new Construtor("Odair");
System.out.println("--c2\n" + c2.getNomeERg() + "\n\n");
Construtor c3 = new Construtor("Odair", "123456");
System.out.println("--c3\n" + c3.getNomeERg() + "\n\n");
}
}
| wesleyegberto/study-ocjp | src/construtores/ConstrutorTesteDrive.java | Java | mit | 449 |
package com.veaer.glass.viewpager;
import android.support.v4.view.ViewPager;
import com.veaer.glass.trigger.Trigger;
/**
* Created by Veaer on 15/11/18.
*/
public class PagerTrigger extends Trigger implements ViewPager.OnPageChangeListener {
private ColorProvider colorProvider;
private int startPosition, endPosition, maxLimit;
public static Trigger addTrigger(ViewPager viewPager, ColorProvider colorProvider) {
PagerTrigger viewPagerTrigger = new PagerTrigger(colorProvider);
viewPager.addOnPageChangeListener(viewPagerTrigger);
viewPagerTrigger.onPageSelected(0);
return viewPagerTrigger;
}
PagerTrigger(ColorProvider colorProvider) {
this.colorProvider = colorProvider;
maxLimit = colorProvider.getCount() - 1;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (isScrollingRight(position)) {
startPosition = position;
endPosition = Math.min(maxLimit, position + 1);
} else {
startPosition = Math.min(maxLimit, position + 1);
endPosition = position;
}
initColorGenerator();
setColor(ColorGenerator.getColor(position, positionOffset));
}
@Override
public void onPageScrollStateChanged(int state) {
//do nothing
}
@Override
public void onPageSelected(int position) {
endPosition = position;
startPosition = position;
initColorGenerator();
}
private boolean isScrollingRight(int position) {
return position == startPosition;
}
private void initColorGenerator() {
ColorGenerator.init(startPosition, endPosition, colorProvider);
}
}
| Veaer/Glass | glass/src/main/java/com/veaer/glass/viewpager/PagerTrigger.java | Java | mit | 1,762 |
#include "catch.hpp"
#include "SearchExpression.hpp"
using namespace quip;
TEST_CASE("Search expressions can be constructed from an empty expression.", "[SearchExpressionTests]") {
SearchExpression expression("");
REQUIRE_FALSE(expression.valid());
}
TEST_CASE("Search expressions can be constructed from a simple expression.", "[SearchExpressionTests]") {
SearchExpression expression("foo");
REQUIRE(expression.valid());
REQUIRE(expression.expression() == "foo");
}
TEST_CASE("Search expressions can be constructed from an expression with a trailing class.", "[SearchExpressionTests]") {
SearchExpression expression("[a-z");
REQUIRE_FALSE(expression.valid());
}
TEST_CASE("Search expressions can be constructed from an expression with a trailing slash.", "[SearchExpressionTests]") {
SearchExpression expression("\\");
REQUIRE_FALSE(expression.valid());
}
| jpetrie/quip | Projects/Core.Tests/SearchExpressionTests.cpp | C++ | mit | 894 |
/* global HTMLImageElement */
/* global HTMLCanvasElement */
/* global SVGElement */
import getOptionsFromElement from "./getOptionsFromElement.js";
import renderers from "../renderers";
import {InvalidElementException} from "../exceptions/exceptions.js";
// Takes an element and returns an object with information about how
// it should be rendered
// This could also return an array with these objects
// {
// element: The element that the renderer should draw on
// renderer: The name of the renderer
// afterRender (optional): If something has to done after the renderer
// completed, calls afterRender (function)
// options (optional): Options that can be defined in the element
// }
function getRenderProperties(element){
// If the element is a string, query select call again
if(typeof element === "string"){
return querySelectedRenderProperties(element);
}
// If element is array. Recursivly call with every object in the array
else if(Array.isArray(element)){
var returnArray = [];
for(let i = 0; i < element.length; i++){
returnArray.push(getRenderProperties(element[i]));
}
return returnArray;
}
// If element, render on canvas and set the uri as src
else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLImageElement){
return newCanvasRenderProperties(element);
}
// If SVG
else if(
(element && element.nodeName && element.nodeName.toLowerCase() === 'svg') ||
(typeof SVGElement !== 'undefined' && element instanceof SVGElement)
){
return {
element: element,
options: getOptionsFromElement(element),
renderer: renderers.SVGRenderer
};
}
// If canvas (in browser)
else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLCanvasElement){
return {
element: element,
options: getOptionsFromElement(element),
renderer: renderers.CanvasRenderer
};
}
// If canvas (in node)
else if(element && element.getContext){
return {
element: element,
renderer: renderers.CanvasRenderer
};
}
else if(element && typeof element === 'object' && !element.nodeName) {
return {
element: element,
renderer: renderers.ObjectRenderer
};
}
else{
throw new InvalidElementException();
}
}
function querySelectedRenderProperties(string){
var selector = document.querySelectorAll(string);
if(selector.length === 0){
return undefined;
}
else{
let returnArray = [];
for(let i = 0; i < selector.length; i++){
returnArray.push(getRenderProperties(selector[i]));
}
return returnArray;
}
}
function newCanvasRenderProperties(imgElement){
var canvas = document.createElement('canvas');
return {
element: canvas,
options: getOptionsFromElement(imgElement),
renderer: renderers.CanvasRenderer,
afterRender: function(){
imgElement.setAttribute("src", canvas.toDataURL());
}
};
}
export default getRenderProperties;
| lindell/JsBarcode | src/help/getRenderProperties.js | JavaScript | mit | 2,868 |
using System;
class MalkoKote
{
static void Main()
{
int size = int.Parse(Console.ReadLine());
char character = char.Parse(Console.ReadLine());
//int height = size;
int width = size / 2 + 4;
int catBodyWidth = width / 2 + 1;
// part 1
Console.WriteLine("{0}{1}{2}{1}{3}",
new string(' ', 1), new string(character, 1), new string(' ', catBodyWidth - 4), new string(' ', catBodyWidth));
// part 2
for (int i = 0; i < size / 4 - 1; i++)
{
Console.WriteLine("{0}{1}{2}",
new string(' ', 1), new string(character, catBodyWidth - 2), new string(' ', catBodyWidth));
}
// part 3
for (int i = 0; i < size / 4 - 1; i++)
{
Console.WriteLine("{0}{1}{2}",
new string(' ', 2), new string(character, catBodyWidth - 4), new string(' ', catBodyWidth + 1));
}
// part 4 - like part 2
for (int i = 0; i < size / 4 - 1; i++)
{
Console.WriteLine("{0}{1}{2}",
new string(' ', 1), new string(character, catBodyWidth - 2), new string(' ', catBodyWidth));
}
// part 5
Console.WriteLine("{0}{1}{2}{3}",
new string(' ', 1), new string(character, catBodyWidth - 2),
new string(' ', 3), new string(character, catBodyWidth - 3));
// part 6
for (int i = 0; i < size / 4 + 1; i++) //size / 4 - 1 + 2
{
Console.WriteLine("{0}{1}{2}{3}",
new string(character, catBodyWidth), new string(' ', 2),
new string(character, 1), new string(' ', width / 2 - 3));
}
// part 7
Console.WriteLine("{0}{1}{2}{3}",
new string(character, catBodyWidth), new string(' ', 1), new string(character, 2), new string(' ', width / 2 - 3));
// part 8
Console.WriteLine("{0}{1}{2}",
new string(' ', 1), new string(character, catBodyWidth + 1),
new string(' ', width - catBodyWidth - 2)); // width - 1 - (catBodyWidth + 1)
}
} | petyakostova/Telerik-Academy | C#/C# 1 Contests/4/Malko-Kote/04. Malko-Kote/MalkoKote.cs | C# | mit | 2,124 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Order */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Orders', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="col-xs-12">
<div class="row">
<div class="col-md-2">
<div class="row">
<?php echo $this->render('@vendor/kirillantv/yii2-swap/views/management/_menu'); ?>
</div>
</div>
<div class="col-md-10">
<div class="order-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'item_id',
'catcher_id',
'status',
],
]) ?>
</div>
</div>
</div>
</div>
| kirillantv/yii2-swap | views/management/orders/view.php | PHP | mit | 1,263 |
/*
* MIT License
*
* Copyright (c) 2020 Choko (choko@curioswitch.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import './organization';
import './storage';
| curioswitch/curiostack | cluster/pulumi/root/bootstrap/index.ts | TypeScript | mit | 1,198 |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.marketing.campaign.drawcamp.trigger
/// </summary>
public class AlipayMarketingCampaignDrawcampTriggerRequest : IAopRequest<AlipayMarketingCampaignDrawcampTriggerResponse>
{
/// <summary>
/// 营销抽奖活动触发
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.marketing.campaign.drawcamp.trigger";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| erikzhouxin/CSharpSolution | OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/AlipayMarketingCampaignDrawcampTriggerRequest.cs | C# | mit | 2,422 |
package main
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
const (
usageText = `SCANEO
Generate Go code to convert database rows into arbitrary structs.
USAGE
scaneo [options] paths...
OPTIONS
-o, -output
Set the name of the generated file. Default is scans.go.
-p, -package
Set the package name for the generated file. Default is current
directory name.
-u, -unexport
Generate unexported functions. Default is export all.
-w, -whitelist
Only include structs specified in case-sensitive, comma-delimited
string.
-v, -version
Print version and exit.
-h, -help
Print help and exit.
EXAMPLES
tables.go is a file that contains one or more struct declarations.
Generate scan functions based on structs in tables.go.
scaneo tables.go
Generate scan functions and name the output file funcs.go
scaneo -o funcs.go tables.go
Generate scans.go with unexported functions.
scaneo -u tables.go
Generate scans.go with only struct Post and struct user.
scaneo -w "Post,user" tables.go
NOTES
Struct field names don't have to match database column names at all.
However, the order of the types must match.
Integrate this with go generate by adding this line to the top of your
tables.go file.
//go:generate scaneo $GOFILE
`
)
type fieldToken struct {
Name string
Type string
}
type structToken struct {
Name string
Fields []fieldToken
}
func main() {
log.SetFlags(0)
outFilename := flag.String("o", "scans.go", "")
packName := flag.String("p", "current directory", "")
unexport := flag.Bool("u", false, "")
whitelist := flag.String("w", "", "")
version := flag.Bool("v", false, "")
help := flag.Bool("h", false, "")
flag.StringVar(outFilename, "output", "scans.go", "")
flag.StringVar(packName, "package", "current directory", "")
flag.BoolVar(unexport, "unexport", false, "")
flag.StringVar(whitelist, "whitelist", "", "")
flag.BoolVar(version, "version", false, "")
flag.BoolVar(help, "help", false, "")
flag.Usage = func() { log.Println(usageText) } // call on flag error
flag.Parse()
if *help {
// not an error, send to stdout
// that way people can: scaneo -h | less
fmt.Println(usageText)
return
}
if *version {
fmt.Println("scaneo version 1.2.0")
return
}
if *packName == "current directory" {
wd, err := os.Getwd()
if err != nil {
log.Fatal("couldn't get working directory:", err)
}
*packName = filepath.Base(wd)
}
files, err := findFiles(flag.Args())
if err != nil {
log.Println("couldn't find files:", err)
log.Fatal(usageText)
}
structToks := make([]structToken, 0, 8)
for _, file := range files {
toks, err := parseCode(file, *whitelist)
if err != nil {
log.Println(`"syntax error" - parser probably`)
log.Fatal(err)
}
structToks = append(structToks, toks...)
}
if err := genFile(*outFilename, *packName, *unexport, structToks); err != nil {
log.Fatal("couldn't generate file:", err)
}
}
func findFiles(paths []string) ([]string, error) {
if len(paths) < 1 {
return nil, errors.New("no starting paths")
}
// using map to prevent duplicate file path entries
// in case the user accidently passes the same file path more than once
// probably because of autocomplete
files := make(map[string]struct{})
for _, path := range paths {
info, err := os.Stat(path)
if err != nil {
return nil, err
}
if !info.IsDir() {
// add file path to files
files[path] = struct{}{}
continue
}
filepath.Walk(path, func(fp string, fi os.FileInfo, _ error) error {
if fi.IsDir() {
// will still enter directory
return nil
} else if fi.Name()[0] == '.' {
return nil
}
// add file path to files
files[fp] = struct{}{}
return nil
})
}
deduped := make([]string, 0, len(files))
for f := range files {
deduped = append(deduped, f)
}
return deduped, nil
}
func parseCode(source string, commaList string) ([]structToken, error) {
wlist := make(map[string]struct{})
if commaList != "" {
wSplits := strings.Split(commaList, ",")
for _, s := range wSplits {
wlist[s] = struct{}{}
}
}
structToks := make([]structToken, 0, 8)
fset := token.NewFileSet()
astf, err := parser.ParseFile(fset, source, nil, 0)
if err != nil {
return nil, err
}
var filter bool
if len(wlist) > 0 {
filter = true
}
//ast.Print(fset, astf)
for _, decl := range astf.Decls {
genDecl, isGeneralDeclaration := decl.(*ast.GenDecl)
if !isGeneralDeclaration {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, isTypeDeclaration := spec.(*ast.TypeSpec)
if !isTypeDeclaration {
continue
}
structType, isStructTypeDeclaration := typeSpec.Type.(*ast.StructType)
if !isStructTypeDeclaration {
continue
}
// found a struct in the source code!
var structTok structToken
// filter logic
if structName := typeSpec.Name.Name; !filter {
// no filter, collect everything
structTok.Name = structName
} else if _, exists := wlist[structName]; filter && !exists {
// if structName not in whitelist, continue
continue
} else if filter && exists {
// structName exists in whitelist
structTok.Name = structName
}
structTok.Fields = make([]fieldToken, 0, len(structType.Fields.List))
// iterate through struct fields (1 line at a time)
for _, fieldLine := range structType.Fields.List {
fieldToks := make([]fieldToken, len(fieldLine.Names))
// get field name (or names because multiple vars can be declared in 1 line)
for i, fieldName := range fieldLine.Names {
fieldToks[i].Name = parseIdent(fieldName)
}
var fieldType string
// get field type
switch typeToken := fieldLine.Type.(type) {
case *ast.Ident:
// simple types, e.g. bool, int
fieldType = parseIdent(typeToken)
case *ast.SelectorExpr:
// struct fields, e.g. time.Time, sql.NullString
fieldType = parseSelector(typeToken)
case *ast.ArrayType:
// arrays
fieldType = parseArray(typeToken)
case *ast.StarExpr:
// pointers
fieldType = parseStar(typeToken)
}
if fieldType == "" {
continue
}
// apply type to all variables declared in this line
for i := range fieldToks {
fieldToks[i].Type = fieldType
}
structTok.Fields = append(structTok.Fields, fieldToks...)
}
structToks = append(structToks, structTok)
}
}
return structToks, nil
}
func parseIdent(fieldType *ast.Ident) string {
// return like byte, string, int
return fieldType.Name
}
func parseSelector(fieldType *ast.SelectorExpr) string {
// return like time.Time, sql.NullString
ident, isIdent := fieldType.X.(*ast.Ident)
if !isIdent {
return ""
}
return fmt.Sprintf("%s.%s", parseIdent(ident), fieldType.Sel.Name)
}
func parseArray(fieldType *ast.ArrayType) string {
// return like []byte, []time.Time, []*byte, []*sql.NullString
var arrayType string
switch typeToken := fieldType.Elt.(type) {
case *ast.Ident:
arrayType = parseIdent(typeToken)
case *ast.SelectorExpr:
arrayType = parseSelector(typeToken)
case *ast.StarExpr:
arrayType = parseStar(typeToken)
}
if arrayType == "" {
return ""
}
return fmt.Sprintf("[]%s", arrayType)
}
func parseStar(fieldType *ast.StarExpr) string {
// return like *bool, *time.Time, *[]byte, and other array stuff
var starType string
switch typeToken := fieldType.X.(type) {
case *ast.Ident:
starType = parseIdent(typeToken)
case *ast.SelectorExpr:
starType = parseSelector(typeToken)
case *ast.ArrayType:
starType = parseArray(typeToken)
}
if starType == "" {
return ""
}
return fmt.Sprintf("*%s", starType)
}
func genFile(outFile, pkg string, unexport bool, toks []structToken) error {
if len(toks) < 1 {
return errors.New("no structs found")
}
fout, err := os.Create(outFile)
if err != nil {
return err
}
defer fout.Close()
data := struct {
PackageName string
Tokens []structToken
Visibility string
}{
PackageName: pkg,
Visibility: "S",
Tokens: toks,
}
if unexport {
// func name will be scanFoo instead of ScanFoo
data.Visibility = "s"
}
fnMap := template.FuncMap{"title": strings.Title}
scansTmpl, err := template.New("scans").Funcs(fnMap).Parse(scansText)
if err != nil {
return err
}
if err := scansTmpl.Execute(fout, data); err != nil {
return err
}
return nil
}
| variadico/scaneo | scaneo.go | GO | mit | 8,566 |
#include <core/stdafx.h>
#include <core/smartview/NickNameCache.h>
namespace smartview
{
void SRowStruct::parse()
{
cValues = blockT<DWORD>::parse(parser);
if (*cValues)
{
if (*cValues < _MaxEntriesSmall)
{
lpProps = std::make_shared<PropertiesStruct>(*cValues, true, false);
lpProps->block::parse(parser, false);
}
}
}
void SRowStruct::parseBlocks()
{
addChild(cValues, L"cValues = 0x%1!08X! = %1!d!", cValues->getData());
addChild(lpProps);
}
void NickNameCache::parse()
{
m_Metadata1 = blockBytes::parse(parser, 4);
m_ulMajorVersion = blockT<DWORD>::parse(parser);
m_ulMinorVersion = blockT<DWORD>::parse(parser);
m_cRowCount = blockT<DWORD>::parse(parser);
if (*m_cRowCount)
{
if (*m_cRowCount < _MaxEntriesEnormous)
{
m_lpRows.reserve(*m_cRowCount);
for (DWORD i = 0; i < *m_cRowCount; i++)
{
m_lpRows.emplace_back(block::parse<SRowStruct>(parser, false));
}
}
}
m_cbEI = blockT<DWORD>::parse(parser);
m_lpbEI = blockBytes::parse(parser, *m_cbEI, _MaxBytes);
m_Metadata2 = blockBytes::parse(parser, 8);
}
void NickNameCache::parseBlocks()
{
setText(L"Nickname Cache");
addLabeledChild(L"Metadata1", m_Metadata1);
addChild(m_ulMajorVersion, L"Major Version = %1!d!", m_ulMajorVersion->getData());
addChild(m_ulMinorVersion, L"Minor Version = %1!d!", m_ulMinorVersion->getData());
addChild(m_cRowCount, L"Row Count = %1!d!", m_cRowCount->getData());
if (!m_lpRows.empty())
{
auto i = DWORD{};
for (const auto& row : m_lpRows)
{
addChild(row, L"Row %1!d!", i);
i++;
}
}
addLabeledChild(L"Extra Info", m_lpbEI);
addLabeledChild(L"Metadata 2", m_Metadata2);
}
} // namespace smartview | stephenegriffin/mfcmapi | core/smartview/NickNameCache.cpp | C++ | mit | 1,725 |