text
stringlengths 2
1.04M
| meta
dict |
---|---|
<?php
/**
* Tax rate collection
*/
namespace Magento\Tax\Model\Resource\Calculation\Rate;
class Collection extends \Magento\Framework\Model\Resource\Db\Collection\AbstractCollection
{
/**
* Value of fetched from DB of rules per cycle
*/
const TAX_RULES_CHUNK_SIZE = 1000;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @param \Magento\Core\Model\EntityFactory $entityFactory
* @param \Magento\Framework\Logger $logger
* @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
* @param \Magento\Framework\Event\ManagerInterface $eventManager
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param mixed $connection
* @param \Magento\Framework\Model\Resource\Db\AbstractDb $resource
*/
public function __construct(
\Magento\Core\Model\EntityFactory $entityFactory,
\Magento\Framework\Logger $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Store\Model\StoreManagerInterface $storeManager,
$connection = null,
\Magento\Framework\Model\Resource\Db\AbstractDb $resource = null
) {
$this->_storeManager = $storeManager;
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
}
/**
* Resource initialization
*
* @return void
*/
protected function _construct()
{
$this->_init('Magento\Tax\Model\Calculation\Rate', 'Magento\Tax\Model\Resource\Calculation\Rate');
}
/**
* Join country table to result
*
* @return $this
*/
public function joinCountryTable()
{
$this->_select->join(
['country_table' => $this->getTable('directory_country')],
'main_table.tax_country_id = country_table.country_id',
['country_name' => 'iso2_code']
);
return $this;
}
/**
* Join Region Table
*
* @return $this
*/
public function joinRegionTable()
{
$this->_select->joinLeft(
['region_table' => $this->getTable('directory_country_region')],
'main_table.tax_region_id = region_table.region_id',
['region_name' => 'code']
);
return $this;
}
/**
* Join rate title for specified store
*
* @param \Magento\Store\Model\Store|string|int $store
* @return $this
*/
public function joinTitle($store = null)
{
$storeId = (int)$this->_storeManager->getStore($store)->getId();
$this->_select->joinLeft(
['title_table' => $this->getTable('tax_calculation_rate_title')],
$this->getConnection()->quoteInto(
'main_table.tax_calculation_rate_id = title_table.tax_calculation_rate_id AND title_table.store_id = ?',
$storeId
),
['title' => 'value']
);
return $this;
}
/**
* Joins store titles for rates
*
* @return $this
*/
public function joinStoreTitles()
{
$storeCollection = $this->_storeManager->getStores(true);
foreach ($storeCollection as $store) {
$tableAlias = sprintf('title_table_%s', $store->getId());
$joinCondition = implode(
' AND ',
[
"main_table.tax_calculation_rate_id = {$tableAlias}.tax_calculation_rate_id",
$this->getConnection()->quoteInto($tableAlias . '.store_id = ?', $store->getId())
]
);
$this->_select->joinLeft(
[$tableAlias => $this->getTable('tax_calculation_rate_title')],
$joinCondition,
[$tableAlias => 'value']
);
}
return $this;
}
/**
* Add rate filter
*
* @param int $rateId
* @return $this
*/
public function addRateFilter($rateId)
{
if (is_int($rateId) && $rateId > 0) {
return $this->addFieldToFilter('main_table.tax_rate_id', $rateId);
}
return $this;
}
/**
* Retrieve option array
*
* @return array
*/
public function toOptionArray()
{
return $this->_toOptionArray('tax_calculation_rate_id', 'code');
}
/**
* Retrieve option hash
*
* @return array
*/
public function toOptionHash()
{
return $this->_toOptionHash('tax_calculation_rate_id', 'code');
}
/**
* Convert items array to hash for select options
* using fetchItem method
*
* @see fetchItem()
*
* @return array
*/
public function toOptionHashOptimized()
{
$result = [];
while ($item = $this->fetchItem()) {
$result[$item->getData('tax_calculation_rate_id')] = $item->getData('code');
}
return $result;
}
/**
* Get rates array without memory leak
*
* @return array
*/
public function getOptionRates()
{
$size = self::TAX_RULES_CHUNK_SIZE;
$page = 1;
$rates = [];
do {
$offset = $size * ($page - 1);
$this->getSelect()->reset();
$this->getSelect()
->from(
['rates' => $this->getMainTable()],
['tax_calculation_rate_id', 'code']
)
->limit($size, $offset);
$rates = array_merge($rates, $this->toOptionArray());
$this->clear();
$page++;
} while ($this->getSize() > $offset);
return $rates;
}
}
| {
"content_hash": "9c0839ea9e27de58bc7d582ca060340f",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 120,
"avg_line_length": 27.704761904761906,
"alnum_prop": 0.5440013750429701,
"repo_name": "webadvancedservicescom/magento",
"id": "e9f427e3b0e6fda6c8251f06f5ef5c98ebf848b6",
"size": "5908",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/Magento/Tax/Model/Resource/Calculation/Rate/Collection.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "16380"
},
{
"name": "CSS",
"bytes": "2592299"
},
{
"name": "HTML",
"bytes": "9192193"
},
{
"name": "JavaScript",
"bytes": "2874762"
},
{
"name": "PHP",
"bytes": "41399372"
},
{
"name": "Shell",
"bytes": "3084"
},
{
"name": "VCL",
"bytes": "3547"
},
{
"name": "XSLT",
"bytes": "19817"
}
],
"symlink_target": ""
} |
- [DOTFILES / ARCHIVOS DE CONFIGURACION](#dotfiles--archivos-de-configuracion)
- [INSTALLATION / INSTALACION](#installation--instalacion)
## DOTFILES / ARCHIVOS DE CONFIGURACION
- These are the dotfiles that I use on my computers.
- Estos son los archivos de configuración que utilizo en mis equipos.
## INSTALLATION / INSTALACION
- To complete the installation the Ansible package is required.
- Para la instalación es necesario el paquete Ansible.
1. ` git clone` https://github.com/velizluisma/dotfiles.git
2. ` cd dotfiles/`
3. ` ansible-playbook install.yml`
| {
"content_hash": "25c3e32536f0932338db5e6374374c72",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 78,
"avg_line_length": 33.529411764705884,
"alnum_prop": 0.7649122807017544,
"repo_name": "velizluisma/dotfiles",
"id": "33e2cc3367f648d232a62bee324b4447e2b6c326",
"size": "616",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1886"
},
{
"name": "Shell",
"bytes": "1564"
},
{
"name": "Vim script",
"bytes": "4570"
}
],
"symlink_target": ""
} |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Live;
namespace Microsoft.Live.Web.UnitTests
{
[TestClass]
public class LiveUtilityUnitTests
{
[TestMethod]
public void LiveUtility_ValidateNotNullParameter_Normal()
{
LiveUtility.ValidateNotNullParameter("4303432830243", "client_id");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void LiveUtility_ValidateNotNullParameter_Invalid()
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(null, "client_id");
}
[TestMethod]
public void LiveUtility_ValidateNotNullOrEmptyString_Normal()
{
LiveUtility.ValidateNotNullOrWhiteSpaceString("4303432830243", "client_id");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void LiveUtility_ValidateNotNullOrEmptyString_NullParameter()
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(null, "client_id");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void LiveUtility_ValidateNotNullOrEmptyString_EmptyParameter()
{
LiveUtility.ValidateNotNullOrWhiteSpaceString("", "client_id");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void LiveUtility_ValidateNotNullOrEmptyString_WhiteSpaceParameter()
{
LiveUtility.ValidateNotNullOrWhiteSpaceString(" \t ", "client_id");
}
[TestMethod]
public void LiveUtility_ValidateUrl_http()
{
LiveUtility.ValidateUrl("http://www.foo.com", "redirectUrl");
}
[TestMethod]
public void LiveUtility_ValidateUrl_https()
{
LiveUtility.ValidateUrl("https://www.foo.com", "redirectUrl");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void LiveUtility_ValidateUrl_Null()
{
LiveUtility.ValidateUrl(null, "redirectUrl");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void LiveUtility_ValidateUrl_WhiteSpace()
{
LiveUtility.ValidateUrl(" ", "redirectUrl");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void LiveUtility_ValidateUrl_InvalidScheme()
{
LiveUtility.ValidateUrl("ftp://foo.com/callback", "redirectUrl");
}
}
}
| {
"content_hash": "84f9f5682a4a797fc71b1d95847b59d4",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 88,
"avg_line_length": 31.174418604651162,
"alnum_prop": 0.6370757180156658,
"repo_name": "arashkeivan/LiveSDK-for-Windows",
"id": "1fc1fdc0f5b0edec04cf14f2a7a0ad0526291237",
"size": "3980",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/Web/UnitTests/LiveUtilityUnitTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "731"
},
{
"name": "C#",
"bytes": "1467537"
},
{
"name": "CSS",
"bytes": "28940"
},
{
"name": "HTML",
"bytes": "39297"
},
{
"name": "JavaScript",
"bytes": "107725"
},
{
"name": "PHP",
"bytes": "6133"
}
],
"symlink_target": ""
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createResponseStatusError = createResponseStatusError;
exports.extractFilenameFromHeader = extractFilenameFromHeader;
exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
exports.validateResponseStatus = validateResponseStatus;
var _util = require("../shared/util.js");
var _content_disposition = require("./content_disposition.js");
var _display_utils = require("./display_utils.js");
function validateRangeRequestCapabilities({
getResponseHeader,
isHttp,
rangeChunkSize,
disableRange
}) {
(0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
const returnValues = {
allowRangeRequests: false,
suggestedLength: undefined
};
const length = parseInt(getResponseHeader("Content-Length"), 10);
if (!Number.isInteger(length)) {
return returnValues;
}
returnValues.suggestedLength = length;
if (length <= 2 * rangeChunkSize) {
return returnValues;
}
if (disableRange || !isHttp) {
return returnValues;
}
if (getResponseHeader("Accept-Ranges") !== "bytes") {
return returnValues;
}
const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
if (contentEncoding !== "identity") {
return returnValues;
}
returnValues.allowRangeRequests = true;
return returnValues;
}
function extractFilenameFromHeader(getResponseHeader) {
const contentDisposition = getResponseHeader("Content-Disposition");
if (contentDisposition) {
let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
if (filename.includes("%")) {
try {
filename = decodeURIComponent(filename);
} catch (ex) {}
}
if ((0, _display_utils.isPdfFile)(filename)) {
return filename;
}
}
return null;
}
function createResponseStatusError(status, url) {
if (status === 404 || status === 0 && url.startsWith("file:")) {
return new _util.MissingPDFException('Missing PDF "' + url + '".');
}
return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
}
function validateResponseStatus(status) {
return status === 200 || status === 206;
} | {
"content_hash": "faeacc7f509d098aaf43e6fa8cf3d250",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 128,
"avg_line_length": 25.921348314606742,
"alnum_prop": 0.7095795405288253,
"repo_name": "sitewaerts/cordova-plugin-document-viewer",
"id": "af771272d9562fdbb4f2378df4202dee2279f180",
"size": "3101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/common/js/pdfjs-dist/lib/display/network_utils.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "565"
},
{
"name": "CSS",
"bytes": "552050"
},
{
"name": "HTML",
"bytes": "11270"
},
{
"name": "Java",
"bytes": "31036"
},
{
"name": "JavaScript",
"bytes": "12314564"
},
{
"name": "Objective-C",
"bytes": "371064"
},
{
"name": "Shell",
"bytes": "215"
}
],
"symlink_target": ""
} |
<?php
namespace Kunstmaan\AdminBundle\Helper\Security\Acl;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\QuoteStrategy;
use Doctrine\ORM\Query;
use Doctrine\ORM\Query\Parameter;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\QueryBuilder;
use InvalidArgumentException;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\MaskBuilder;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Role\RoleInterface;
/**
* AclHelper is a helper class to help setting the permissions when querying using ORM.
*
* @see https://gist.github.com/1363377
*/
class AclHelper
{
/**
* @var EntityManager
*/
private $em;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var QuoteStrategy
*/
private $quoteStrategy;
/**
* @var RoleHierarchyInterface
*/
private $roleHierarchy;
/**
* Constructor.
*
* @param EntityManager $em The entity manager
* @param TokenStorageInterface $tokenStorage The security token storage
* @param RoleHierarchyInterface $rh The role hierarchies
*/
public function __construct(EntityManager $em, TokenStorageInterface $tokenStorage, RoleHierarchyInterface $rh)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
$this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
$this->roleHierarchy = $rh;
}
/**
* Apply the ACL constraints to the specified query builder, using the permission definition.
*
* @param QueryBuilder $queryBuilder The query builder
* @param PermissionDefinition $permissionDef The permission definition
*
* @return Query
*/
public function apply(QueryBuilder $queryBuilder, PermissionDefinition $permissionDef)
{
$whereQueryParts = $queryBuilder->getDQLPart('where');
if (empty($whereQueryParts)) {
$queryBuilder->where('1 = 1'); // this will help in cases where no where query is specified
}
$query = $this->cloneQuery($queryBuilder->getQuery());
$builder = new MaskBuilder();
foreach ($permissionDef->getPermissions() as $permission) {
$mask = constant(get_class($builder).'::MASK_'.strtoupper($permission));
$builder->add($mask);
}
$query->setHint('acl.mask', $builder->get());
$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Kunstmaan\AdminBundle\Helper\Security\Acl\AclWalker');
$rootEntity = $permissionDef->getEntity();
$rootAlias = $permissionDef->getAlias();
// If either alias or entity was not specified - use default from QueryBuilder
if (empty($rootEntity) || empty($rootAlias)) {
$rootEntities = $queryBuilder->getRootEntities();
$rootAliases = $queryBuilder->getRootAliases();
$rootEntity = $rootEntities[0];
$rootAlias = $rootAliases[0];
}
$query->setHint('acl.root.entity', $rootEntity);
$query->setHint('acl.extra.query', $this->getPermittedAclIdsSQLForUser($query));
$classMeta = $this->em->getClassMetadata($rootEntity);
$entityRootTableName = $this->quoteStrategy->getTableName(
$classMeta,
$this->em->getConnection()->getDatabasePlatform()
);
$query->setHint('acl.entityRootTableName', $entityRootTableName);
$query->setHint('acl.entityRootTableDqlAlias', $rootAlias);
return $query;
}
/**
* Returns valid IDs for a specific entity with ACL restrictions for current user applied.
*
* @param PermissionDefinition $permissionDef
*
* @throws InvalidArgumentException
*
* @return array
*/
public function getAllowedEntityIds(PermissionDefinition $permissionDef)
{
$rootEntity = $permissionDef->getEntity();
if (empty($rootEntity)) {
throw new InvalidArgumentException('You have to provide an entity class name!');
}
$builder = new MaskBuilder();
foreach ($permissionDef->getPermissions() as $permission) {
$mask = constant(get_class($builder).'::MASK_'.strtoupper($permission));
$builder->add($mask);
}
$query = new Query($this->em);
$query->setHint('acl.mask', $builder->get());
$query->setHint('acl.root.entity', $rootEntity);
$sql = $this->getPermittedAclIdsSQLForUser($query);
$rsm = new ResultSetMapping();
$rsm->addScalarResult('id', 'id');
$nativeQuery = $this->em->createNativeQuery($sql, $rsm);
$transform = function ($item) {
return $item['id'];
};
$result = array_map($transform, $nativeQuery->getScalarResult());
return $result;
}
/**
* @return null|TokenStorageInterface
*/
public function getTokenStorage()
{
return $this->tokenStorage;
}
/**
* Clone specified query with parameters.
*
* @param Query $query
*
* @return Query
*/
protected function cloneQuery(Query $query)
{
$aclAppliedQuery = clone $query;
$params = $query->getParameters();
// @var $param Parameter
foreach ($params as $param) {
$aclAppliedQuery->setParameter($param->getName(), $param->getValue(), $param->getType());
}
return $aclAppliedQuery;
}
/**
* This query works well with small offset, but if want to use it with large offsets please refer to the link on how to implement
* http://www.scribd.com/doc/14683263/Efficient-Pagination-Using-MySQL
* This will only check permissions on the first entity added in the from clause, it will not check permissions
* By default the number of rows returned are 10 starting from 0.
*
* @param Query $query
*
* @return string
*/
private function getPermittedAclIdsSQLForUser(Query $query)
{
$aclConnection = $this->em->getConnection();
$databasePrefix = is_file($aclConnection->getDatabase()) ? '' : $aclConnection->getDatabase().'.';
$mask = $query->getHint('acl.mask');
$rootEntity = '"'.str_replace('\\', '\\\\', $query->getHint('acl.root.entity')).'"';
// @var $token TokenInterface
$token = $this->tokenStorage->getToken();
$userRoles = [];
$user = null;
if (null !== $token) {
$user = $token->getUser();
$userRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
}
// Security context does not provide anonymous role automatically.
$uR = ['"IS_AUTHENTICATED_ANONYMOUSLY"'];
// @var $role RoleInterface
foreach ($userRoles as $role) {
// The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
if ('ROLE_USER' !== $role->getRole()) {
$uR[] = '"'.$role->getRole().'"';
}
}
$uR = array_unique($uR);
$inString = implode(' OR s.identifier = ', $uR);
if (is_object($user)) {
$inString .= ' OR s.identifier = "'.str_replace(
'\\',
'\\\\',
get_class($user)
).'-'.$user->getUserName().'"';
}
$selectQuery = <<<SELECTQUERY
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
LEFT JOIN {$databasePrefix}acl_entries e ON (
e.class_id = o.class_id AND (e.object_identity_id = o.id
OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
)
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
s.id = e.security_identity_id
)
WHERE c.class_type = {$rootEntity}
AND (s.identifier = {$inString})
AND e.mask & {$mask} > 0
SELECTQUERY;
return $selectQuery;
}
}
| {
"content_hash": "894c77cd4b07128fa0a34f2312410144",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 133,
"avg_line_length": 34.865546218487395,
"alnum_prop": 0.6202699445649554,
"repo_name": "hgabka/KunstmaanBundlesCMS",
"id": "1c527be22179f3c2e8174ed39de8587082037b9e",
"size": "8298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Kunstmaan/AdminBundle/Helper/Security/Acl/AclHelper.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "46244"
},
{
"name": "CSS",
"bytes": "468600"
},
{
"name": "Gherkin",
"bytes": "22178"
},
{
"name": "HTML",
"bytes": "934141"
},
{
"name": "Hack",
"bytes": "20"
},
{
"name": "JavaScript",
"bytes": "4087160"
},
{
"name": "PHP",
"bytes": "2946789"
},
{
"name": "Ruby",
"bytes": "2363"
},
{
"name": "Shell",
"bytes": "235"
}
],
"symlink_target": ""
} |
package ru.stqa.rep.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.rep.addressbook.model.GroupData;
import ru.stqa.rep.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
public class GroupDeletionTests extends TestBase {
@BeforeMethod
public void ensurePrecondition() {
if (app.db().groups().size() == 0) {
app.goTo().groupPage();
app.group().create(new GroupData().withName("Друзья").withHeader("Друзья").withFooter("Домашняя группа"));
}
}
@Test
public void testGroupDeletion() {
Groups before = app.db().groups();
GroupData deletedGroup = before.iterator().next();
app.goTo().groupPage();
app.group().delete(deletedGroup);
Groups after = app.db().groups();
assertEquals(after.size(), before.size() - 1);
System.out.println("БЫЛО: "+ before.size()+ " СТАЛО: " +after.size());
assertThat(after, equalTo(before.without(deletedGroup)));
System.out.println("СТАРАЯ ПРОВЕРКА ДО: "+ after+ " СТАЛО: " +before.without(deletedGroup));
verifyGroupListInUI(); //новая проверка
}
}
| {
"content_hash": "3f68f7a4f720bec1cff61e064a182e21",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 112,
"avg_line_length": 30.390243902439025,
"alnum_prop": 0.7070626003210273,
"repo_name": "zevgenia/java_rep",
"id": "442c3dfde92fb1df783ffecc7e3202763ae41105",
"size": "1315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addressbook/src/test/java/ru/stqa/rep/addressbook/tests/GroupDeletionTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2107"
},
{
"name": "CSS",
"bytes": "15120"
},
{
"name": "HTML",
"bytes": "155834"
},
{
"name": "Java",
"bytes": "64975"
},
{
"name": "JavaScript",
"bytes": "21008"
},
{
"name": "Shell",
"bytes": "5221"
}
],
"symlink_target": ""
} |
package main
import (
"context"
compute "cloud.google.com/go/compute/apiv1"
computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)
func main() {
ctx := context.Background()
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in:
// https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
c, err := compute.NewFirewallPoliciesRESTClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &computepb.PatchRuleFirewallPolicyRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/compute/v1#PatchRuleFirewallPolicyRequest.
}
op, err := c.PatchRule(ctx, req)
if err != nil {
// TODO: Handle error.
}
err = op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
}
// [END compute_v1_generated_FirewallPolicies_PatchRule_sync]
| {
"content_hash": "9de206ab7bb443055736d05dc1d95841",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 114,
"avg_line_length": 28.333333333333332,
"alnum_prop": 0.7221719457013575,
"repo_name": "googleapis/google-cloud-go",
"id": "3ca1fa55b4cf89fadb888256779b033b46c261f0",
"size": "1845",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "internal/generated/snippets/compute/apiv1/FirewallPoliciesClient/PatchRule/main.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "10349"
},
{
"name": "C",
"bytes": "74"
},
{
"name": "Dockerfile",
"bytes": "1841"
},
{
"name": "Go",
"bytes": "7626642"
},
{
"name": "M4",
"bytes": "43723"
},
{
"name": "Makefile",
"bytes": "1455"
},
{
"name": "Python",
"bytes": "718"
},
{
"name": "Shell",
"bytes": "27309"
}
],
"symlink_target": ""
} |
{-# OPTIONS_GHC -Wall #-}
module BoneDewd.MapParse (getElevation) where
import Control.Applicative ((<$>))
import qualified Data.ByteString.Lazy as L
import Data.Binary
import Data.Binary.Get
import Data.Int
import Data.Word
import System.FilePath ((</>))
import System.IO (IOMode(..), SeekMode(..), hSeek, withBinaryFile)
getElevation :: (Word16,Word16) -> IO Int8
getElevation (x,y) = do
withBinaryFile ("mul" </> "map0.mul") ReadMode $ \f -> do
hSeek f AbsoluteSeek (fromIntegral seekLoc)
runGet (get :: Get Int8) <$> L.hGet f 1
where blocklen = 196 :: Int
xblock = (fromIntegral x) `div` 8 :: Int
yblock = (fromIntegral y) `div` 8 :: Int
blocknum = (xblock * 512) + yblock :: Int
cellLen = 3 :: Int
xcell = (fromIntegral x) `mod` 8 :: Int
ycell = (fromIntegral y) `mod` 8 :: Int
cellnum = xcell + (ycell * 8) :: Int
seekLoc = (blocklen * blocknum) + 4 + (cellLen * cellnum) + 2 :: Int
| {
"content_hash": "e6bb425dd055f661423e8d0ed88f357f",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 78,
"avg_line_length": 39.44,
"alnum_prop": 0.6125760649087221,
"repo_name": "dreamcodez/bonedewd",
"id": "1a2216ed2954368fb965ae0a66844ae1d8701872",
"size": "986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BoneDewd/MapParse.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5803"
},
{
"name": "Haskell",
"bytes": "55568"
},
{
"name": "Shell",
"bytes": "185"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Mon Nov 26 17:22:20 MSK 2012 -->
<TITLE>
Uses of Class org.apache.poi.hwpf.model.Xst (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-11-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hwpf.model.Xst (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hwpf/model/Xst.html" title="class in org.apache.poi.hwpf.model"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hwpf/model/\class-useXst.html" target="_top"><B>FRAMES</B></A>
<A HREF="Xst.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hwpf.model.Xst</B></H2>
</CENTER>
No usage of org.apache.poi.hwpf.model.Xst
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hwpf/model/Xst.html" title="class in org.apache.poi.hwpf.model"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hwpf/model/\class-useXst.html" target="_top"><B>FRAMES</B></A>
<A HREF="Xst.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| {
"content_hash": "4339af33326036a2de4893243fcbb85a",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 214,
"avg_line_length": 42.04081632653061,
"alnum_prop": 0.5878640776699029,
"repo_name": "brenthand/Panda",
"id": "a0b3ad44523bf35678a393d5cf87f1ebc7e59932",
"size": "6180",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "poi-3.9/docs/apidocs/org/apache/poi/hwpf/model/class-use/Xst.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16091"
},
{
"name": "Java",
"bytes": "17953"
}
],
"symlink_target": ""
} |
using System;
namespace Platform.VirtualFileSystem
{
/// <summary>
/// Interface for objects that can resolve VFS nodes.
/// </summary>
public interface INodeResolver
{
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the file.
/// </exception>
IFile ResolveFile(string name);
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the directory.
/// </exception>
IDirectory ResolveDirectory(string name);
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="scope"></param>
/// <returns></returns>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the directory.
/// </exception>
IFile ResolveFile(string name, AddressScope scope);
/// <summary>
/// Resolves a directory within the file system.
/// </summary>
/// <param name="name">
/// </param>
/// <param name="scope">
/// </param>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the directory.
/// </exception>
IDirectory ResolveDirectory(string name, AddressScope scope);
/// <summary>
/// Gets the node with the specified name.
/// </summary>
/// <remarks>
/// <p>If the node doesn't exist, an exception is thrown (see exceptions documentation).</p>
/// <p>Relative paths can only be resolved on directories.</p>
/// <p>This method should behave the same as a call to <c>Resolve(string, NodeType.Any)</c></p>
/// </remarks>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the node.
/// </exception>
INode Resolve(string name);
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="scope"></param>
/// <returns></returns>
/// <remarks>
/// <seealso cref="Resolve(string, NodeType)"/>
/// <seealso cref="Resolve(string, NodeType, AddressScope)"/>
/// </remarks>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the node.
/// </exception>
INode Resolve(string name, AddressScope scope);
/// <summary>
/// Resolves a node within the file system.
/// </summary>
/// <remarks>
/// <p>If the node doesn't exist, a new node of the type <c>nodeType</c> is constructed and returned.</p>
/// <p>Note: You will have to call <c>INode.Create</c> on the returned object to actually
/// create the file/directory.</p>
/// <p>Relative paths can only be resolved on directories.</p>
/// <p>If the <c>nodeType</c> is <see cref="NodeType.Any"/> then the method should
/// behave the same as the method <see cref="Resolve(string)"/></p>
/// </remarks>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the node.
/// </exception>
INode Resolve(string name, NodeType nodeType);
/// <summary>
/// Resolves a node within the file system.
/// </summary>
/// <param name="name">The name of the node to look for.</param>
/// <param name="nodeType">The <see cref="NodeType"/> of node to look for.</param>
/// <param name="scope">The <see cref="AddressScope"/> of the node.</param>
/// <returns></returns>
/// <exception cref="VirtualFileSystemException">
/// An error occured while trying to resolve the node.
/// </exception>
INode Resolve(string name, NodeType nodeType, AddressScope scope);
}
}
| {
"content_hash": "7b56cbf511370b132a119105959f52f7",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 107,
"avg_line_length": 33.75229357798165,
"alnum_prop": 0.646099483555314,
"repo_name": "furesoft/Platform.VirtualFileSystem",
"id": "d5aa3e8fe634d264849ab8be8d9601c33631caf3",
"size": "3679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Platform.VirtualFileSystem/IResolver.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "919698"
},
{
"name": "Smalltalk",
"bytes": "1522"
}
],
"symlink_target": ""
} |
package org.lagonette.app.app.widget.adapter.decorator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.ViewGroup;
import org.lagonette.app.R;
import org.lagonette.app.app.widget.viewholder.EmptyViewHolder;
import org.zxcv.chainadapter.decorator.VoidDecorator;
public class EmptyViewDecorator
extends VoidDecorator<EmptyViewHolder> {
public EmptyViewDecorator() {
super(R.id.view_type_empty_view);
}
@NonNull
@Override
public EmptyViewHolder createViewHolder(@NonNull ViewGroup parent, int viewType) {
return new EmptyViewHolder(parent);
}
@Override
protected void onBindViewHolder(@Nullable Void aVoid, @NonNull EmptyViewHolder viewHolder) {
}
}
| {
"content_hash": "af9c4373a22413720514aef51a10b0c2",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 93,
"avg_line_length": 25.137931034482758,
"alnum_prop": 0.803840877914952,
"repo_name": "La-Gonette/lagonette-android",
"id": "f519abb7401a2c18af072a97a99a10679761ddd8",
"size": "729",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/org/lagonette/app/app/widget/adapter/decorator/EmptyViewDecorator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "324201"
}
],
"symlink_target": ""
} |
package org.springframework.boot.autoconfigure.web.servlet.error;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
/**
* Abstract base class for error {@link Controller} implementations.
*
* @author Dave Syer
* @author Phillip Webb
* @since 1.3.0
* @see ErrorAttributes
*/
public abstract class AbstractErrorController implements ErrorController {
private final ErrorAttributes errorAttributes;
private final List<ErrorViewResolver> errorViewResolvers;
public AbstractErrorController(ErrorAttributes errorAttributes) {
this(errorAttributes, null);
}
public AbstractErrorController(ErrorAttributes errorAttributes,
List<ErrorViewResolver> errorViewResolvers) {
Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
this.errorAttributes = errorAttributes;
this.errorViewResolvers = sortErrorViewResolvers(errorViewResolvers);
}
private List<ErrorViewResolver> sortErrorViewResolvers(
List<ErrorViewResolver> resolvers) {
List<ErrorViewResolver> sorted = new ArrayList<>();
if (resolvers != null) {
sorted.addAll(resolvers);
AnnotationAwareOrderComparator.sortIfNecessary(sorted);
}
return sorted;
}
protected Map<String, Object> getErrorAttributes(HttpServletRequest request,
boolean includeStackTrace) {
WebRequest webRequest = new ServletWebRequest(request);
return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
}
protected boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equalsIgnoreCase(parameter);
}
protected HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
try {
return HttpStatus.valueOf(statusCode);
}
catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
/**
* Resolve any specific error views. By default this method delegates to
* {@link ErrorViewResolver ErrorViewResolvers}.
* @param request the request
* @param response the response
* @param status the HTTP status
* @param model the suggested model
* @return a specific {@link ModelAndView} or {@code null} if the default should be
* used
* @since 1.4.0
*/
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
}
| {
"content_hash": "7cb9f250df5d4597a56a07a25152aab7",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 84,
"avg_line_length": 31.785046728971963,
"alnum_prop": 0.7803587180241106,
"repo_name": "donhuvy/spring-boot",
"id": "b396be45282f66145c3b554c232dc4ea62cfe75e",
"size": "4021",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/AbstractErrorController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1948"
},
{
"name": "CSS",
"bytes": "115"
},
{
"name": "Dockerfile",
"bytes": "1770"
},
{
"name": "FreeMarker",
"bytes": "3599"
},
{
"name": "Groovy",
"bytes": "59146"
},
{
"name": "HTML",
"bytes": "70214"
},
{
"name": "Java",
"bytes": "14728751"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Kotlin",
"bytes": "36215"
},
{
"name": "Ruby",
"bytes": "884"
},
{
"name": "Shell",
"bytes": "37223"
},
{
"name": "Smarty",
"bytes": "2885"
},
{
"name": "XSLT",
"bytes": "3545"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Enum. syst. pl. 32. 1760 (Select. stirp. amer. hist. 256, t. 173, fig. 54. 1763)
#### Original name
null
### Remarks
null | {
"content_hash": "7b05d24dad265f14e3e0e5736a4ef7b0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 80,
"avg_line_length": 16.076923076923077,
"alnum_prop": 0.6650717703349283,
"repo_name": "mdoering/backbone",
"id": "ea8668c1df1a5fb28c805cd3eba218c80d295d26",
"size": "255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Jatropha/Jatropha integerrima/ Syn. Jatropha hastata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class FacebookConnection < Collector::Connection
worker FacebookWorker
handle_cast :friends_added do |data|
info [@manager.id, 'Friends added'].inspect
end
handle_cast :message_added do |data|
info [@manager.id, 'Message added'].inspect
end
end
| {
"content_hash": "0ae2ac34f28f78a8e93aa2ad084a332d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 48,
"avg_line_length": 24.09090909090909,
"alnum_prop": 0.720754716981132,
"repo_name": "arsemyonov/collector",
"id": "6c49f7aa9e40d888f992a5c6fb7c8e81367841b3",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/connections/facebook_connection.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9276"
}
],
"symlink_target": ""
} |
@interface FUProgressComboBox : HMImageComboBox {
NSImage *progressImage;
CGFloat progress;
BOOL showingPopUp;
BOOL firstKeyDownHasHappened;
}
- (void)showDefaultIcon;
- (void)showPopUpWithItemCount:(NSInteger)count;
- (void)hidePopUp;
@property (nonatomic) CGFloat progress;
@property (nonatomic, retain) NSImage *progressImage;
@end | {
"content_hash": "266c8dd50946433c942289998cc1572b",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 53,
"avg_line_length": 25.142857142857142,
"alnum_prop": 0.7670454545454546,
"repo_name": "mital/fluidium",
"id": "30b0565a735d6583473ba4c912b744c45406977f",
"size": "981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fluidium/src/FUProgressComboBox.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "950262"
},
{
"name": "Objective-C",
"bytes": "3280123"
}
],
"symlink_target": ""
} |
package com.sksamuel.scrimage.filter
import com.sksamuel.scrimage.ImmutableImage
import org.scalatest.{BeforeAndAfter, FunSuite, OneInstancePerTest}
class OpacityFilterTest extends FunSuite with BeforeAndAfter with OneInstancePerTest {
val original = ImmutableImage.fromStream(getClass.getResourceAsStream("/bird_small.png"))
test("opacity filter output matches expected") {
val expected = ImmutableImage.fromStream(getClass.getResourceAsStream("/com/sksamuel/scrimage/filters/bird_small_opacity.png"))
val actual = original.filter(new OpacityFilter(0.5f))
assert(actual === expected)
}
}
| {
"content_hash": "8043e451300b2ccd9263bb7f9199240a",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 131,
"avg_line_length": 40.733333333333334,
"alnum_prop": 0.7970540098199672,
"repo_name": "sksamuel/scrimage",
"id": "3e01d3c5ad91c74b0084c8fa55b0314f9a9d7327",
"size": "611",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scrimage-filters/src/test/scala/com/sksamuel/scrimage/filter/OpacityFilterTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "433213"
},
{
"name": "Kotlin",
"bytes": "122355"
},
{
"name": "Scala",
"bytes": "60675"
}
],
"symlink_target": ""
} |
package org.sakaiproject.gradebookng.business.helpers;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.gradebookng.business.model.GbGradeInfo;
import org.sakaiproject.gradebookng.business.model.GbStudentGradeInfo;
import org.sakaiproject.gradebookng.business.model.ImportColumn;
import org.sakaiproject.gradebookng.business.model.ImportedGrade;
import org.sakaiproject.gradebookng.business.model.ImportedGradeItem;
import org.sakaiproject.gradebookng.business.model.ImportedGradeWrapper;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItem;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItemDetail;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItemStatus;
import org.sakaiproject.gradebookng.tool.model.AssignmentStudentGradeInfo;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;
/**
* Helper to handling parsing and processing of an imported gradebook file
*/
@Slf4j
public class ImportGradesHelper extends BaseImportHelper {
private static final String IMPORT_USER_ID = "Student ID";
private static final String IMPORT_USER_NAME = "Student Name";
protected static final String ASSIGNMENT_HEADER_PATTERN = "{0} [{1}]";
protected static final String ASSIGNMENT_HEADER_COMMENT_PATTERN = "*/ {0} Comments */";
protected static final String HEADER_STANDARD_PATTERN = "{0}";
/**
* Parse a CSV into a list of ImportedGrade objects. Returns list if ok, or null if error
*
* @param is InputStream of the data to parse
* @return
*/
public static ImportedGradeWrapper parseCsv(final InputStream is, final Map<String, String> userMap) {
// manually parse method so we can support arbitrary columns
final CSVReader reader = new CSVReader(new InputStreamReader(is));
String[] nextLine;
int lineCount = 0;
final List<ImportedGrade> list = new ArrayList<ImportedGrade>();
Map<Integer, ImportColumn> mapping = null;
try {
while ((nextLine = reader.readNext()) != null) {
if (lineCount == 0) {
// header row, capture it
mapping = mapHeaderRow(nextLine);
} else {
// map the fields into the object
list.add(mapLine(nextLine, mapping, userMap));
}
lineCount++;
}
} catch (final Exception e) {
log.error("Error reading imported file: " + e.getClass() + " : " + e.getMessage());
return null;
} finally {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
final ImportedGradeWrapper importedGradeWrapper = new ImportedGradeWrapper();
importedGradeWrapper.setColumns(mapping.values());
importedGradeWrapper.setImportedGrades(list);
return importedGradeWrapper;
}
/**
* Parse an XLS into a list of ImportedGrade objects Note that only the first sheet of the Excel file is supported.
*
* @param is InputStream of the data to parse
* @return
*/
public static ImportedGradeWrapper parseXls(final InputStream is, final Map<String, String> userMap) {
int lineCount = 0;
final List<ImportedGrade> list = new ArrayList<ImportedGrade>();
Map<Integer, ImportColumn> mapping = null;
try {
final Workbook wb = WorkbookFactory.create(is);
final Sheet sheet = wb.getSheetAt(0);
for (final Row row : sheet) {
final String[] r = convertRow(row);
if (lineCount == 0) {
// header row, capture it
mapping = mapHeaderRow(r);
} else {
// map the fields into the object
list.add(mapLine(r, mapping, userMap));
}
lineCount++;
}
} catch (final Exception e) {
log.error("Error reading imported file: " + e.getClass() + " : " + e.getMessage());
return null;
}
final ImportedGradeWrapper importedGradeWrapper = new ImportedGradeWrapper();
importedGradeWrapper.setColumns(mapping.values());
importedGradeWrapper.setImportedGrades(list);
return importedGradeWrapper;
}
/**
* Takes a row of data and maps it into the appropriate ImportedGrade properties We have a fixed list of properties, anything else goes
* into ResourceProperties
*
* @param line
* @param mapping
* @return
*/
private static ImportedGrade mapLine(final String[] line, final Map<Integer, ImportColumn> mapping, final Map<String, String> userMap) {
final ImportedGrade grade = new ImportedGrade();
final ResourceProperties p = new BaseResourcePropertiesEdit();
for (final Map.Entry<Integer, ImportColumn> entry : mapping.entrySet()) {
final int i = entry.getKey();
// trim in case some whitespace crept in
final ImportColumn importColumn = entry.getValue();
// String col = trim(entry.getValue());
// In case there aren't enough data fields in the line to match up with the number of columns needed
String lineVal = null;
if (i < line.length) {
lineVal = trim(line[i]);
}
// now check each of the main properties in turn to determine which one to set, otherwise set into props
if (StringUtils.equals(importColumn.getColumnTitle(), IMPORT_USER_ID)) {
grade.setStudentEid(lineVal);
grade.setStudentUuid(userMap.get(lineVal));
} else if (StringUtils.equals(importColumn.getColumnTitle(), IMPORT_USER_NAME)) {
grade.setStudentName(lineVal);
} else if (ImportColumn.TYPE_ITEM_WITH_POINTS == importColumn.getType()) {
final String assignmentName = importColumn.getColumnTitle();
ImportedGradeItem importedGradeItem = grade.getGradeItemMap().get(assignmentName);
if (importedGradeItem == null) {
importedGradeItem = new ImportedGradeItem();
grade.getGradeItemMap().put(assignmentName, importedGradeItem);
importedGradeItem.setGradeItemName(assignmentName);
}
importedGradeItem.setGradeItemScore(lineVal);
} else if (ImportColumn.TYPE_ITEM_WITH_COMMENTS == importColumn.getType()) {
final String assignmentName = importColumn.getColumnTitle();
ImportedGradeItem importedGradeItem = grade.getGradeItemMap().get(assignmentName);
if (importedGradeItem == null) {
importedGradeItem = new ImportedGradeItem();
grade.getGradeItemMap().put(assignmentName, importedGradeItem);
importedGradeItem.setGradeItemName(assignmentName);
}
importedGradeItem.setGradeItemComment(lineVal);
} else {
// only add if not blank
if (StringUtils.isNotBlank(lineVal)) {
p.addProperty(importColumn.getColumnTitle(), lineVal);
}
}
}
grade.setProperties(p);
return grade;
}
public static List<ProcessedGradeItem> processImportedGrades(final ImportedGradeWrapper importedGradeWrapper,
final List<Assignment> assignments, final List<GbStudentGradeInfo> currentGrades) {
final List<ProcessedGradeItem> processedGradeItems = new ArrayList<ProcessedGradeItem>();
final Map<String, Assignment> assignmentNameMap = new HashMap<String, Assignment>();
final Map<String, ProcessedGradeItem> assignmentProcessedGradeItemMap = new HashMap<String, ProcessedGradeItem>();
final Map<Long, AssignmentStudentGradeInfo> transformedGradeMap = transformCurrentGrades(currentGrades);
// Map the assignment name back to the Id
for (final Assignment assignment : assignments) {
assignmentNameMap.put(assignment.getName(), assignment);
}
for (final ImportColumn column : importedGradeWrapper.getColumns()) {
boolean needsAdded = false;
final String assignmentName = StringUtils.trim(column.getColumnTitle()); //trim whitespace so we can match properly
ProcessedGradeItem processedGradeItem = assignmentProcessedGradeItemMap.get(assignmentName);
if (processedGradeItem == null) {
processedGradeItem = new ProcessedGradeItem();
needsAdded = true;
}
final Assignment assignment = assignmentNameMap.get(assignmentName);
final ProcessedGradeItemStatus status = determineStatus(column, assignment, importedGradeWrapper, transformedGradeMap);
if (column.getType() == ImportColumn.TYPE_ITEM_WITH_POINTS) {
processedGradeItem.setItemTitle(assignmentName);
processedGradeItem.setItemPointValue(column.getPoints());
processedGradeItem.setStatus(status);
} else if (column.getType() == ImportColumn.TYPE_ITEM_WITH_COMMENTS) {
processedGradeItem.setCommentLabel(assignmentName + " Comments");
processedGradeItem.setCommentStatus(status);
} else {
// Just get out
log.warn("Bad column type - " + column.getType() + ". Skipping.");
continue;
}
if (assignment != null) {
processedGradeItem.setItemId(assignment.getId());
}
final List<ProcessedGradeItemDetail> processedGradeItemDetails = new ArrayList<>();
for (final ImportedGrade importedGrade : importedGradeWrapper.getImportedGrades()) {
final ImportedGradeItem importedGradeItem = importedGrade.getGradeItemMap().get(assignmentName);
if (importedGradeItem != null) {
final ProcessedGradeItemDetail processedGradeItemDetail = new ProcessedGradeItemDetail();
processedGradeItemDetail.setStudentEid(importedGrade.getStudentEid());
processedGradeItemDetail.setStudentUuid(importedGrade.getStudentUuid());
processedGradeItemDetail.setGrade(importedGradeItem.getGradeItemScore());
processedGradeItemDetail.setComment(importedGradeItem.getGradeItemComment());
processedGradeItemDetails.add(processedGradeItemDetail);
}
}
processedGradeItem.setProcessedGradeItemDetails(processedGradeItemDetails);
if (needsAdded) {
processedGradeItems.add(processedGradeItem);
assignmentProcessedGradeItemMap.put(assignmentName, processedGradeItem);
}
}
return processedGradeItems;
}
private static ProcessedGradeItemStatus determineStatus(final ImportColumn column, final Assignment assignment,
final ImportedGradeWrapper importedGradeWrapper,
final Map<Long, AssignmentStudentGradeInfo> transformedGradeMap) {
ProcessedGradeItemStatus status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UNKNOWN);
if (assignment == null) {
status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_NEW);
} else if (assignment.getExternalId() != null) {
status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_EXTERNAL, assignment.getExternalAppName());
} else {
for (final ImportedGrade importedGrade : importedGradeWrapper.getImportedGrades()) {
final AssignmentStudentGradeInfo assignmentStudentGradeInfo = transformedGradeMap.get(assignment.getId());
final ImportedGradeItem importedGradeItem = importedGrade.getGradeItemMap().get(column.getColumnTitle());
String actualScore = null;
String actualComment = null;
if (assignmentStudentGradeInfo != null) {
final GbGradeInfo actualGradeInfo = assignmentStudentGradeInfo.getStudentGrades().get(importedGrade.getStudentEid());
if (actualGradeInfo != null) {
actualScore = actualGradeInfo.getGrade();
actualComment = actualGradeInfo.getGradeComment();
}
}
String importedScore = null;
String importedComment = null;
if (importedGradeItem != null) {
importedScore = importedGradeItem.getGradeItemScore();
importedComment = importedGradeItem.getGradeItemComment();
}
if (column.getType() == ImportColumn.TYPE_ITEM_WITH_POINTS) {
final String trimmedImportedScore = StringUtils.removeEnd(importedScore, ".0");
final String trimmedActualScore = StringUtils.removeEnd(actualScore, ".0");
if (trimmedImportedScore != null && !trimmedImportedScore.equals(trimmedActualScore)) {
status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UPDATE);
break;
}
} else if (column.getType() == ImportColumn.TYPE_ITEM_WITH_COMMENTS) {
if (importedComment != null && !importedComment.equals(actualComment)) {
status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UPDATE);
break;
}
}
}
// If we get here, must not have been any changes
if (status.getStatusCode() == ProcessedGradeItemStatus.STATUS_UNKNOWN) {
status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_NA);
}
// TODO - What about if a user was added to the import file?
// That probably means that actualGradeInfo from up above is null...but what do I do?
}
return status;
}
private static Map<Long, AssignmentStudentGradeInfo> transformCurrentGrades(final List<GbStudentGradeInfo> currentGrades) {
final Map<Long, AssignmentStudentGradeInfo> assignmentMap = new HashMap<Long, AssignmentStudentGradeInfo>();
for (final GbStudentGradeInfo studentGradeInfo : currentGrades) {
for (final Map.Entry<Long, GbGradeInfo> entry : studentGradeInfo.getGrades().entrySet()) {
final Long assignmentId = entry.getKey();
AssignmentStudentGradeInfo assignmentStudentGradeInfo = assignmentMap.get(assignmentId);
if (assignmentStudentGradeInfo == null) {
assignmentStudentGradeInfo = new AssignmentStudentGradeInfo();
assignmentStudentGradeInfo.setAssignmemtId(assignmentId);
assignmentMap.put(assignmentId, assignmentStudentGradeInfo);
}
assignmentStudentGradeInfo.addGrade(studentGradeInfo.getStudentEid(), entry.getValue());
}
}
return assignmentMap;
}
}
| {
"content_hash": "1c75b8649adfae6fbf5ec25c1aeb041d",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 137,
"avg_line_length": 40.251479289940825,
"alnum_prop": 0.7540610069827269,
"repo_name": "joserabal/sakai",
"id": "0ce65c2b70ca071574f6bd78750e4ff63a23094e",
"size": "13605",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradebookng/tool/src/java/org/sakaiproject/gradebookng/business/helpers/ImportGradesHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "5172"
},
{
"name": "CSS",
"bytes": "2119816"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "5568167"
},
{
"name": "Java",
"bytes": "47583983"
},
{
"name": "JavaScript",
"bytes": "9803719"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "962699"
},
{
"name": "PLSQL",
"bytes": "2325413"
},
{
"name": "Perl",
"bytes": "61738"
},
{
"name": "Python",
"bytes": "44698"
},
{
"name": "Ruby",
"bytes": "1276"
},
{
"name": "Shell",
"bytes": "19259"
},
{
"name": "SourcePawn",
"bytes": "2247"
},
{
"name": "XSLT",
"bytes": "280557"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sat May 16 22:22:32 CEST 2015 -->
<title>org.apache.cassandra.db.columniterator</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../org/apache/cassandra/db/columniterator/package-summary.html" target="classFrame">org.apache.cassandra.db.columniterator</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="IColumnIteratorFactory.html" title="interface in org.apache.cassandra.db.columniterator" target="classFrame"><i>IColumnIteratorFactory</i></a></li>
<li><a href="OnDiskAtomIterator.html" title="interface in org.apache.cassandra.db.columniterator" target="classFrame"><i>OnDiskAtomIterator</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="IdentityQueryFilter.html" title="class in org.apache.cassandra.db.columniterator" target="classFrame">IdentityQueryFilter</a></li>
<li><a href="LazyColumnIterator.html" title="class in org.apache.cassandra.db.columniterator" target="classFrame">LazyColumnIterator</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "6a806fb5a507edc7fd22d5b1c44f85a6",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 168,
"avg_line_length": 55.04,
"alnum_prop": 0.7194767441860465,
"repo_name": "sayanh/ViewMaintenanceCassandra",
"id": "4a48af90f6d0d428cb29dcc7c7473d223e3695f3",
"size": "1376",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "doc/org/apache/cassandra/db/columniterator/package-frame.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "801"
},
{
"name": "Batchfile",
"bytes": "21834"
},
{
"name": "GAP",
"bytes": "62279"
},
{
"name": "Java",
"bytes": "10347352"
},
{
"name": "PowerShell",
"bytes": "39438"
},
{
"name": "Python",
"bytes": "314996"
},
{
"name": "Shell",
"bytes": "50026"
},
{
"name": "Thrift",
"bytes": "40282"
}
],
"symlink_target": ""
} |
@import AVFoundation;
#import <MBProgressHUD/MBProgressHUD.h>
#import <AFNetworking/UIImageView+AFNetworking.h>
#import <AFNetworking/AFNetworking.h>
#import <FontAwesomeKit/FAKIonIcons.h>
#import "TaxaSearchViewController.h"
#import "ImageStore.h"
#import "TaxonPhoto.h"
#import "TaxonDetailViewController.h"
#import "FAKINaturalist.h"
#import "ExploreTaxon.h"
#import "ExploreTaxonRealm.h"
#import "ExploreTaxonRealm.h"
#import "ObsDetailTaxonCell.h"
#import "TaxaAPI.h"
#import "ObservationAPI.h"
#import "NSURL+INaturalist.h"
#import "TaxonSuggestionCell.h"
#import "UIColor+INaturalist.h"
#import "ExploreTaxonScore.h"
#import "ObservationPhoto.h"
#import "ObserverCount.h"
#import "IdentifierCount.h"
#import "ExploreUser.h"
#import "UIImage+INaturalist.h"
@interface TaxaSearchViewController () <UISearchResultsUpdating, UISearchControllerDelegate, UITableViewDelegate, UITableViewDataSource>
@property UISearchController *searchController;
@property RLMResults <ExploreTaxonRealm *> *searchResults;
@property RLMNotificationToken *searchResultsToken;
@property NSArray <ExploreTaxonScore *> *scores;
@property NSArray <NSString *> *creditNames;
@property ExploreTaxonRealm *commonAncestor;
@property BOOL showingSuggestions;
@property BOOL showingNearbySuggestionsOnly;
@property IBOutlet UIImageView *headerImageView;
@property IBOutlet UITableView *tableView;
@property IBOutlet NSLayoutConstraint *headerHeightConstraint;
@property IBOutlet UIView *loadingView;
@property IBOutlet UILabel *statusLabel;
@property IBOutlet UIActivityIndicatorView *loadingSpinner;
@property IBOutlet UIView *suggestionHeaderView;
@property UIBarButtonItem *nearbySwitchButton;
@property UIToolbar *doneToolbar;
@end
@implementation TaxaSearchViewController
#pragma mark - UISearchControllerDelegate
- (void)willPresentSearchController:(UISearchController *)searchController {
self.headerHeightConstraint.constant = 0.0f;
[self.view setNeedsLayout];
self.showingSuggestions = NO;
[self.tableView reloadData];
}
- (void)didPresentSearchController:(UISearchController *)searchController {
[searchController.searchBar becomeFirstResponder];
}
- (void)willDismissSearchController:(UISearchController *)searchController {
// if the we aren't showing suggestions for any reason, if the user
// dismisses the search controller then we should just totally bail
// on taxa search
if (![[NSUserDefaults standardUserDefaults] boolForKey:kINatSuggestionsPrefKey]) {
// no suggestions without permission
[self.delegate taxaSearchViewControllerCancelled];
} else if (self.imageToClassify || (self.observationToClassify && self.observationToClassify.sortedObservationPhotos.count > 0)) {
// switch back to suggestions mode
self.headerHeightConstraint.constant = 132.0f;
[self.view setNeedsLayout];
self.showingSuggestions = YES;
[self.tableView reloadData];
if (self.scores.count == 0 && !self.commonAncestor) {
self.tableView.backgroundView.hidden = NO;
}
} else {
// no suggestions without a photo
[self.delegate taxaSearchViewControllerCancelled];
}
}
#pragma mark - Taxa Search Stuff
- (TaxaAPI *)api {
static TaxaAPI *_api = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_api = [[TaxaAPI alloc] init];
});
return _api;
}
- (ObservationAPI *)obsApi {
static ObservationAPI *_api = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_api = [[ObservationAPI alloc] init];
});
return _api;
}
// https://stackoverflow.com/a/31245380/3796488
- (BOOL)shouldQueryAPI {
// ex. "櫻花" means "cherry blossom" in Chinese.
NSInteger minCharsTaxaSearch = 3;
BOOL isHan = ([self.searchController.searchBar.text rangeOfString:@"\\p{Han}" options:NSRegularExpressionSearch].location != NSNotFound);
if (isHan) {
minCharsTaxaSearch = 1;
}
BOOL hasEnoughChars = (self.searchController.searchBar.text.length >= minCharsTaxaSearch);
return hasEnoughChars;
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
if (self.showingSuggestions) {
return;
}
self.tableView.backgroundView.hidden = TRUE;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
// don't bother querying api until the user has entered a reasonable amount of text
if (![self shouldQueryAPI]) {
self.searchResults = nil;
[self.tableView reloadData];
return;
}
// update the local results
[self searchLocal:searchController.searchBar.text];
// query node, put into realm, update UI
[self.api taxaMatching:searchController.searchBar.text handler:^(NSArray *results, NSInteger count, NSError *error) {
// put the results into realm
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
for (ExploreTaxon *taxon in results) {
ExploreTaxonRealm *etr = [[ExploreTaxonRealm alloc] initWithMantleModel:taxon];
[realm addOrUpdateObject:etr];
}
[realm commitWriteTransaction];
// update the UI
dispatch_async(dispatch_get_main_queue(), ^{
[self searchLocal:searchController.searchBar.text];
});
}];
}
- (void)searchLocal:(NSString *)term {
term = [term stringByFoldingWithOptions:NSDiacriticInsensitiveSearch
locale:[NSLocale currentLocale]];
// query realm
RLMResults *results = [ExploreTaxonRealm objectsWhere:@"searchableCommonName contains[c] %@ OR searchableScientificName contains[c] %@ OR searchableLastMatchedTerm contains[c] %@", term, term, term];
// filter out inactive taxa
results = [results objectsWhere:@"isActive = TRUE"];
NSArray *sorts = @[
[RLMSortDescriptor sortDescriptorWithKeyPath:@"rankLevel"
ascending:NO],
[RLMSortDescriptor sortDescriptorWithKeyPath:@"observationCount"
ascending:NO]
];
self.searchResults = [results sortedResultsUsingDescriptors:sorts];
// invalidate & re-create the update token for the new search results
if (self.searchResultsToken) {
[self.searchResultsToken invalidate];
}
__weak typeof(self)weakSelf = self;
self.searchResultsToken = [self.searchResults addNotificationBlock:^(RLMResults * _Nullable results, RLMCollectionChange * _Nullable change, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.tableView reloadData];
});
}];
[self.tableView reloadData];
}
- (IBAction)clickedCancel:(UIControl *)control {
[self.delegate taxaSearchViewControllerCancelled];
}
#pragma mark - UIViewController lifecycle
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
self.coordinate = kCLLocationCoordinate2DInvalid;
// default to only showing nearby suggestions
self.showingNearbySuggestionsOnly = YES;
}
return self;
}
- (void)dealloc {
[self.searchResultsToken invalidate];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.doneToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(kbDoneTapped)];
self.doneToolbar.items = @[flex, doneBtn];
UISwitch *switcher = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
self.nearbySwitchButton = [[UIBarButtonItem alloc] initWithCustomView:switcher];
self.nearbySwitchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:nil];
self.navigationItem.rightBarButtonItem = self.nearbySwitchButton;
// setup the search controller
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.obscuresBackgroundDuringPresentation = false;
self.searchController.searchBar.placeholder = NSLocalizedString(@"Look up a species by name",
@"placeholder text for taxon search bar");
self.searchController.searchBar.inputAccessoryView = self.doneToolbar;
self.searchController.delegate = self;
self.definesPresentationContext = YES;
// user prefs determine autocorrection/spellcheck behavior of the species guess field
if ([[NSUserDefaults standardUserDefaults] boolForKey:kINatAutocompleteNamesPrefKey]) {
[self.searchController.searchBar setAutocorrectionType:UITextAutocorrectionTypeYes];
[self.searchController.searchBar setSpellCheckingType:UITextSpellCheckingTypeDefault];
} else {
[self.searchController.searchBar setAutocorrectionType:UITextAutocorrectionTypeNo];
[self.searchController.searchBar setSpellCheckingType:UITextSpellCheckingTypeNo];
}
// setup the table view
self.tableView.tableHeaderView = self.searchController.searchBar;
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.tableView registerNib:[UINib nibWithNibName:@"TaxonCell" bundle:nil]
forCellReuseIdentifier:@"TaxonCell"];
// don't show the extra lines when no tv rows
self.tableView.tableFooterView = [UIView new];
// design tweaks for suggestions header
self.suggestionHeaderView.layer.borderWidth = 0.5f;
self.suggestionHeaderView.layer.borderColor = [UIColor lightGrayColor].CGColor;
self.headerImageView.layer.cornerRadius = 1.0f;
self.headerImageView.layer.borderWidth = 1.0f;
self.headerImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
// we're shrinking a decently sized image down to a small square,
// so provide a minification filter that's easier on the eyes and
// produces fewer resizing artifacts
self.headerImageView.layer.minificationFilter = kCAFilterTrilinear;
self.headerImageView.layer.minificationFilterBias = 0.1;
// this is the callback for our suggestions api call
INatAPISuggestionsCompletionHandler done = ^(NSArray *suggestions, ExploreTaxon *parent, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
self.tableView.backgroundView = self.loadingView;
self.loadingSpinner.hidden = YES;
self.statusLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Cannot load suggestions: %@",
@"error when loading suggestions. %@ is the error message"),
error.localizedDescription];
} else {
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
if (parent) {
ExploreTaxonRealm *etr = [[ExploreTaxonRealm alloc] initWithMantleModel:parent];
[realm addOrUpdateObject:etr];
self.commonAncestor = etr;
}
for (ExploreTaxonScore *ets in suggestions) {
ExploreTaxonRealm *etr = [[ExploreTaxonRealm alloc] initWithMantleModel:ets.exploreTaxon];
[realm addOrUpdateObject:etr];
}
[realm commitWriteTransaction];
self.scores = suggestions;
// remove the loading view
self.tableView.backgroundView = nil;
[self.tableView reloadData];
NSMutableArray *taxaIds = [NSMutableArray array];
if (self.commonAncestor) {
[taxaIds addObject:@(self.commonAncestor.taxonId)];
}
for (ExploreTaxonScore *ets in self.scores) {
[taxaIds addObject:@(ets.exploreTaxon.taxonId)];
}
if (arc4random_uniform(2) == 1) {
// load observers
[[self obsApi] topObserversForTaxaIds:taxaIds handler:^(NSArray *results, NSInteger count, NSError *error) {
NSMutableArray <NSString *> *credits = [NSMutableArray array];
for (ObserverCount *oc in results) {
if (oc.observer.name && oc.observer.name.length > 0) {
[credits addObject:oc.observer.name];
} else {
[credits addObject:oc.observer.login];
}
}
self.creditNames = [NSArray arrayWithArray:credits];
[self.tableView reloadData];
}];
} else {
[[self obsApi] topIdentifiersForTaxaIds:taxaIds handler:^(NSArray *results, NSInteger count, NSError *error) {
NSMutableArray <NSString *> *credits = [NSMutableArray array];
for (IdentifierCount *ic in results) {
if (ic.identifier.name && ic.identifier.name.length > 0) {
[credits addObject:ic.identifier.name];
} else {
[credits addObject:ic.identifier.login];
}
}
self.creditNames = [NSArray arrayWithArray:credits];
[self.tableView reloadData];
}];
}
}
});
};
if (self.hidesDoneButton) {
self.navigationItem.rightBarButtonItem = nil;
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:kINatSuggestionsPrefKey]) {
// no suggestions without permission
[self showNoSuggestions];
} else if (self.imageToClassify) {
[self loadAndShowImageSuggestionsWithCompletion:done];
} else if (self.observationToClassify && self.observationToClassify.sortedObservationPhotos.count > 0) {
[self loadAndShowObservationSuggestionsWithCompletion:done];
} else {
// no suggestions without a photo
[self showNoSuggestions];
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// start the taxon search ui right away if we're not loading
// suggestions
if (!self.showingSuggestions) {
// have to enqueue this, otherwise it's too early to have
// the searchBar -becomeFirstResponder, even in -viewDidAppear:
dispatch_async(dispatch_get_main_queue(), ^{
// start the search UI right away
[self.searchController setActive:YES];
});
}
}
- (void)loadAndShowImageSuggestionsWithCompletion:(INatAPISuggestionsCompletionHandler)done {
self.showingSuggestions = YES;
self.headerImageView.image = [self imageToClassify];
self.tableView.backgroundView = self.loadingView;
[[self api] suggestionsForImage:self.imageToClassify
location:self.coordinate
date:self.observedOn
handler:done];
}
- (void)loadAndShowObservationSuggestionsWithCompletion:(INatAPISuggestionsCompletionHandler)done {
self.showingSuggestions = YES;
id <INatPhoto> op = [[self.observationToClassify sortedObservationPhotos] firstObject];
[self.headerImageView setImageWithURL:[op squarePhotoUrl]];
self.tableView.backgroundView = self.loadingView;
[[self api] suggestionsForObservationId:self.observationToClassify.inatRecordId
handler:done];
}
- (void)showNoSuggestions {
self.showingSuggestions = NO;
self.headerHeightConstraint.constant = 0.0f;
// if the query field is pre-populated with a placeholder,
// then search for it automatically.
if (self.query && self.query.length > 0) {
self.searchController.searchBar.text = self.query;
}
}
- (void)changeSuggestionsFilter {
self.showingNearbySuggestionsOnly = !self.showingNearbySuggestionsOnly;
[self.tableView reloadData];
}
#pragma mark - UIButton targets
- (void)kbDoneTapped {
[self.searchController.searchBar endEditing:YES];
}
#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self showingSuggestions]) {
// switcher cell is the last TV section
if ((self.commonAncestor && indexPath.section == 2) || (!self.commonAncestor && indexPath.section == 1)) {
SwitcherCell *cell = [tableView dequeueReusableCellWithIdentifier:@"switcher"
forIndexPath:indexPath];
cell.switchLabel.text = NSLocalizedString(@"Show nearby suggestions only", nil);
cell.switchLabel.numberOfLines = 0;
cell.switcher.on = self.showingNearbySuggestionsOnly;
[cell.switcher addTarget:self
action:@selector(changeSuggestionsFilter)
forControlEvents:UIControlEventValueChanged];
return cell;
}
TaxonSuggestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"suggestion"
forIndexPath:indexPath];
ExploreTaxonScore *ts = nil;
id <TaxonVisualization> taxon = nil;
if (indexPath.section == 0 && self.commonAncestor) {
taxon = self.commonAncestor;
} else {
if (self.showingNearbySuggestionsOnly) {
ts = [[self nearbyScores] objectAtIndex:indexPath.item];
} else {
ts = [self.scores objectAtIndex:indexPath.item];
}
taxon = [ts exploreTaxon];
}
if (ts) {
NSString *reason = @"";
if (ts.visionScore > 0 && ts.frequencyScore > 0) {
reason = NSLocalizedString(@"Visually Similar / Seen Nearby", @"basis for a species suggestion");
} else if (ts.visionScore > 0) {
reason = NSLocalizedString(@"Visually Similar", @"basis for a species suggestion");
} else if (ts.frequencyScore > 0) {
reason = NSLocalizedString(@"Seen Nearby", @"basis for a suggestion");
}
cell.comment.text = reason;
} else {
cell.comment.text = nil;
}
UIImage *iconicTaxonImage = [[ImageStore sharedImageStore] iconicTaxonImageForName:taxon.iconicTaxonName];
if (taxon.photoUrl) {
[cell.image setImageWithURL:taxon.photoUrl
placeholderImage:iconicTaxonImage];
} else {
[cell.image setImage:iconicTaxonImage];
}
cell.primaryName.text = taxon.displayFirstName;
if (taxon.displayFirstNameIsItalicized) {
cell.primaryName.font = [UIFont italicSystemFontOfSize:cell.primaryName.font.pointSize];
}
cell.secondaryName.text = taxon.displaySecondName;
if (taxon.displaySecondNameIsItalicized) {
cell.secondaryName.font = [UIFont italicSystemFontOfSize:cell.secondaryName.font.pointSize];
} else {
cell.secondaryName.font = [UIFont systemFontOfSize:cell.secondaryName.font.pointSize];
}
return cell;
}
if (self.allowsFreeTextSelection && indexPath.section == 1) {
return [self cellForUnknownTaxonInTableView:tableView];
} else {
ExploreTaxonRealm *etr = [self.searchResults objectAtIndex:indexPath.item];
return [self cellForTaxon:etr inTableView:tableView];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
if ([self showingSuggestions]) {
if ((self.commonAncestor && indexPath.section == 2) || (!self.commonAncestor && indexPath.section == 1)) {
// no accessory for switcher cell but let's be safe
return;
} else if (indexPath.section == 0 && self.commonAncestor) {
[self showTaxonId:self.commonAncestor.taxonId];
} else {
ExploreTaxonScore *ets = nil;
if (self.showingNearbySuggestionsOnly) {
ets = [[self nearbyScores] objectAtIndex:indexPath.item];
} else {
ets = [self.scores objectAtIndex:indexPath.item];
}
ExploreTaxon *taxon = ets.exploreTaxon;
[self showTaxonId:taxon.taxonId];
}
} else {
if (self.searchResults.count > 0 && indexPath.section == 0) {
ExploreTaxonRealm *taxon = [self.searchResults objectAtIndex:indexPath.item];
[self showTaxonId:taxon.taxonId];
} else {
// do nothing
}
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self showingSuggestions]) {
if ((self.commonAncestor && indexPath.section == 2) || (!self.commonAncestor && indexPath.section == 1)) {
// be safe for switcher cell
return;
} else if (indexPath.section == 0 && self.commonAncestor) {
[self.delegate taxaSearchViewControllerChoseTaxon:self.commonAncestor
chosenViaVision:YES];
} else {
ExploreTaxonScore *ets = nil;
if (self.showingNearbySuggestionsOnly) {
ets = [[self nearbyScores] objectAtIndex:indexPath.item];
} else {
ets = [self.scores objectAtIndex:indexPath.item];
}
ExploreTaxon *taxon = ets.exploreTaxon;
[self.delegate taxaSearchViewControllerChoseTaxon:taxon
chosenViaVision:YES];
}
} else {
if (indexPath.section == 1) {
[self.delegate taxaSearchViewControllerChoseSpeciesGuess:self.searchController.searchBar.text];
} else if (self.searchResults.count > 0) {
ExploreTaxonRealm *etr = [self.searchResults objectAtIndex:indexPath.item];
[self.delegate taxaSearchViewControllerChoseTaxon:etr
chosenViaVision:NO];
} else {
// shouldn't happen, do nothing
}
}
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self showingSuggestions]) {
if ((self.commonAncestor && indexPath.section == 2) || (!self.commonAncestor && indexPath.section == 1)) {
// nearby switch, 80 pts for second row
return 80;
} else {
return 80;
}
} else {
return 60;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if ([self showingSuggestions]) {
if (self.scores && self.scores.count > 0) {
return self.commonAncestor ? 3 : 2;
} else {
return 1;
}
} else if ([self shouldQueryAPI]) {
return self.allowsFreeTextSelection ? 2 : 1;
} else if (self.scores.count > 0) {
if (self.commonAncestor) {
return 2;
} else {
return 1;
}
} else {
return 1;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([self showingSuggestions]) {
if ((self.commonAncestor && section == 2) || (!self.commonAncestor && section == 1)) {
return NSLocalizedString(@"Nearby Suggestions Filter", nil);
} else {
if (self.commonAncestor) {
if (section == 0) {
NSString *base = NSLocalizedString(@"We're pretty sure this is in the %1$@ %2$@.",
@"comment for common ancestor suggestion. %1$@ is the rank name (order, family), whereas %2$@ is the actual rank (Animalia, Insecta)");
return [NSString stringWithFormat:base,
self.commonAncestor.rankName, self.commonAncestor.scientificName];
} else {
return NSLocalizedString(@"Here are our top suggestions:", nil);
}
} else if (self.scores.count > 0) {
return NSLocalizedString(@"We're not confident enough to make a recommendation, but here are our top suggestions.", nil);
} else {
return NSLocalizedString(@"We're not confident enough to make a recommendation.", nil);
}
}
} else {
if (self.allowsFreeTextSelection) {
if ([self shouldQueryAPI] && section == 0) {
if (self.searchResults.count > 0) {
return @"iNaturalist";
} else {
return NSLocalizedString(@"No iNaturalist Results", nil);
}
} else if ([self shouldQueryAPI] && section == 1) {
return NSLocalizedString(@"Placeholder", nil);
}
}
}
return nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([self showingSuggestions]) {
if ((self.commonAncestor && section == 2) || (!self.commonAncestor && section == 1)) {
// don't show the switcher until we've had a chance to load the suggestions
if (self.scores && self.scores.count > 0) {
return 1;
} else {
return 0;
}
} else {
if (self.commonAncestor) {
if (section == 0) {
return 1;
} else {
if (self.showingNearbySuggestionsOnly) {
return [[self nearbyScores] count];
} else {
return self.scores.count;
}
}
} else {
if (self.showingNearbySuggestionsOnly) {
return [[self nearbyScores] count];
} else {
return self.scores.count;
}
}
}
} else {
if (self.allowsFreeTextSelection) {
if ([self shouldQueryAPI]) {
if (section == 0) {
return self.searchResults.count;
} else {
return 1;
}
} else {
return 0;
}
} else {
if ([self shouldQueryAPI]) {
return self.searchResults.count;
} else {
return 0;
}
}
}
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
if ([self showingSuggestions] && self.scores.count > 0) {
if ((self.commonAncestor && section == 1) || section == 0) {
if (self.creditNames && self.creditNames.count == 3) {
NSString *base = NSLocalizedString(@"Suggestions based on observations and identifications provided by the iNaturalist community, including %@, %@, %@, and many others.", nil);
return [NSString stringWithFormat:base, self.creditNames[0], self.creditNames[1], self.creditNames[2]];
} else {
return NSLocalizedString(@"Suggestions based on observations and identifications provided by the iNaturalist community.", nil);
}
}
}
return nil;
}
#pragma mark - TaxonDetailViewControllerDelegate
- (void)taxonDetailViewControllerClickedActionForTaxonId:(NSInteger)taxonId {
ExploreTaxonRealm *etr = [ExploreTaxonRealm objectForPrimaryKey:@(taxonId)];
[self.delegate taxaSearchViewControllerChoseTaxon:etr
chosenViaVision:[self showingSuggestions]];
}
#pragma mark - TableView helpers
- (void)showTaxonId:(NSInteger)taxonId {
ExploreTaxonRealm *etr = [ExploreTaxonRealm objectForPrimaryKey:@(taxonId)];
if (etr) {
TaxonDetailViewController *tdvc = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil] instantiateViewControllerWithIdentifier:@"TaxonDetailViewController"];
tdvc.taxonId = taxonId;
tdvc.delegate = self;
tdvc.showsActionButton = YES;
if (CLLocationCoordinate2DIsValid(self.coordinate)) {
tdvc.observationCoordinate = self.coordinate;
} else if (self.observationToClassify && CLLocationCoordinate2DIsValid(self.observationToClassify.visibleLocation)) {
tdvc.observationCoordinate = self.observationToClassify.visibleLocation;
}
[self.navigationController pushViewController:tdvc animated:YES];
}
}
- (UITableViewCell *)cellForUnknownTaxonInTableView:(UITableView *)tableView {
ObsDetailTaxonCell *cell = (ObsDetailTaxonCell *)[tableView dequeueReusableCellWithIdentifier:@"TaxonCell"];
FAKIcon *unknown = [FAKINaturalist speciesUnknownIconWithSize:44.0f];
[unknown addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor]];
[cell.taxonImageView cancelImageDownloadTask];
[cell.taxonImageView setImage:[unknown imageWithSize:CGSizeMake(44, 44)]];
cell.taxonImageView.layer.borderWidth = 0.0f;
cell.taxonNameLabel.text = self.searchController.searchBar.text;
cell.taxonNameLabel.textColor = [UIColor blackColor];
cell.taxonNameLabel.font = [UIFont systemFontOfSize:cell.taxonNameLabel.font.pointSize];
cell.taxonSecondaryNameLabel.text = @"";
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
- (UITableViewCell *)cellForTaxon:(ExploreTaxonRealm *)etr inTableView:(UITableView *)tableView {
if (!etr) {
return [self cellForUnknownTaxonInTableView:tableView];
}
ObsDetailTaxonCell *cell = (ObsDetailTaxonCell *)[tableView dequeueReusableCellWithIdentifier:@"TaxonCell"];
UIImage *iconicTaxonImage = [[ImageStore sharedImageStore] iconicTaxonImageForName:etr.iconicTaxonName];
if (etr.photoUrl) {
[cell.taxonImageView setImageWithURL:etr.photoUrl
placeholderImage:iconicTaxonImage];
} else {
[cell.taxonImageView setImage:iconicTaxonImage];
}
cell.taxonImageView.layer.borderWidth = 1.0f;
cell.taxonNameLabel.text = etr.displayFirstName;
if (etr.displayFirstNameIsItalicized) {
cell.taxonNameLabel.font = [UIFont italicSystemFontOfSize:cell.taxonNameLabel.font.pointSize];
}
cell.taxonSecondaryNameLabel.text = etr.displaySecondName;
if (etr.displaySecondNameIsItalicized) {
cell.taxonSecondaryNameLabel.font = [UIFont italicSystemFontOfSize:cell.taxonSecondaryNameLabel.font.pointSize];
}
cell.accessoryType = UITableViewCellAccessoryDetailButton;
return cell;
}
- (NSArray *)nearbyScores {
static NSPredicate *nearbyPredicate = nil;
if (!nearbyPredicate) {
nearbyPredicate = [NSPredicate predicateWithBlock:^BOOL(ExploreTaxonScore *score, NSDictionary *bindings) {
return score.frequencyScore > 0;
}];
}
return [self.scores filteredArrayUsingPredicate:nearbyPredicate];
}
@end
@implementation SwitcherCell
@end
| {
"content_hash": "168aec1c0c85924f626f5fe422fc3955",
"timestamp": "",
"source": "github",
"line_count": 795,
"max_line_length": 203,
"avg_line_length": 40.88176100628931,
"alnum_prop": 0.6204116796406265,
"repo_name": "inaturalist/INaturalistIOS",
"id": "616ef38a7d5b4e6f03c186b608326a057f634b6a",
"size": "32660",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "INaturalistIOS/Controllers/Taxa/TaxaSearchViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2496"
},
{
"name": "Objective-C",
"bytes": "1718672"
},
{
"name": "Python",
"bytes": "4110"
},
{
"name": "Ruby",
"bytes": "2513"
},
{
"name": "Swift",
"bytes": "86487"
},
{
"name": "XSLT",
"bytes": "17377"
}
],
"symlink_target": ""
} |
_This is because the issue is void in Magento 2 as modules can be added via composer and you can get around this issue in Magento 1 with a couple of simple scripts - I assume all your modules are already in seperate repositories!_
1) sync.sh where you add your Magento's install dependant modules via rsync
```bash
#!/bin/bash
# Repeat for all modules
rsync -vaz /path/to/module/root /path/to/magento/root
```
2) clean.sh because rsync doesn't handle the deletes (sync, delete a file in the module, sync, file file will not be deleted in Magento). This should be run periodically.
```bash
#!/bin/bash
# Remove all the code
rm -rf /path/to/magento/root
rsync -vaz /path/to/clean/magento /path/to/magento/root
chmod -R 777 app/etc media var includes
./sync.sh
```
<!--
# originator
This will hopefully be a package to help manage Magento modules across projects
# Logic behind the design.
Before 'originator' we used to rsync our modules into the code pool, the main issue is if you delete a file in the
module, it stays in the destination. The --delete flag doesn't work because it tries to delete every file inside
Magento that's not in the original module destination.
## Originator solution
### Single code copy
Chances are if you're a developer you want to checkout your modules into a single location and use them across multiple
Magento projects. We suggest an absolute or relative path that will be consistent across environments.
### Use GIT
When originator iterates over your projects originator.json file it will check if the module exists, if it doesn't
you'll be prompted about it and the program will exist.
If the module does exist, you can configure originator to pull the code from the branch.
### Rsync --delete correction
Fixing the --delete correction requires a cache of all files within the module from start to finish. To make it
environment agnostic this will be stores in a simple file, rather than a database. This will be done
in the modules '.originator_file_cache' which will simple list relative paths from the module root to all files.
If they no longer exists in the module but exist in the destination, then they are removed from the destination.
### Module configuration
Modules themselves don't need any configuration, it is the application that needs configuration. The originator.yml specifies
the relative paths to the required modules. When 'originator run' is executed it will merge the modules from those paths
into the magento_root (default public). During this execution the '.originator_file_cache' file will be updated with any new
files / directories. Originator will also update the modules '.originator_projects' file which contains absolute paths
to the current projects which use this module. This allows developers to call 'originator -module-update' from the module directory which
will tell the application which modules need a re-merge (Adds name to '.originator_module_status') or call
'originator -module-force-merge' to force a re-merge on all projects which use that module.
## Terminology
1. Application|Magento - this is the Magento application
2. Module - is a Magento module to be merged into the application, this is generally stored externally to the
application and merged in
## Committing
### Application
* Commit the 'originator.yml' file.
* Commit any new source files after originator has run into the magento_root directory as you would.
* Don't commit the '.originator_module_status' file.
### Modules
* Commit the '.originator_file_cache' file as this is the primary module history file and if deleted can then be reinstated
from VC.
* Don't commit the '.originator_projects', this is a platform specific project location file.
-->
| {
"content_hash": "3ecf3f8ee8e68d3eb4413a21ef1075fd",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 230,
"avg_line_length": 44.38095238095238,
"alnum_prop": 0.778969957081545,
"repo_name": "philelson/Originator",
"id": "21f689fbf8760e9d4485f36ba12ccc1dc91291ed",
"size": "3768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "25947"
}
],
"symlink_target": ""
} |
import html from 'choo/html';
import styles from './styles.css';
import buttonAnimation from '../buttonAnimation.css';
export default ({machineparts, modal: {content: {id, content, value}}}, emit) => {
const {title, children, color} = content;
return html`
<div class=${styles.wrapper}>
<div class=${styles.overlay} onclick=${close}></div>
<div class=${styles.modal} style="background-color: ${color}">
<h2 class="${styles.title}">${title}</h2>
${children(id, value, emit)}
<button class=${styles.button + ' ' + buttonAnimation.hoverEffect} onclick=${close}>Opslaan</button>
</div>
</div>
`;
function close({target}) {
if (machineparts[id].value !== undefined) {
return emit('hideModal', id);
}
target.classList.add(styles.deny);
setTimeout(() => target.classList.remove(styles.deny), 1000);
}
};
| {
"content_hash": "b62544c5c1d0083228ec82dc586cd9ad",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 108,
"avg_line_length": 30.517241379310345,
"alnum_prop": 0.6248587570621469,
"repo_name": "rijkvanzanten/obachine",
"id": "061ac2162279269391a24c162f7f41b1547b8825",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/modal/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20281"
},
{
"name": "HTML",
"bytes": "220"
},
{
"name": "JavaScript",
"bytes": "44857"
}
],
"symlink_target": ""
} |
.include <bsd.own.mk>
.if ${MKDOC} != "no"
BINDIR= ${PFIX_EXAMPLEDIR}
DIST= ${NETBSDSRCDIR}/external/ibm-public/postfix/dist/README_FILES
.PATH: ${DIST}
.include "../readme.mk"
FILES= AAAREADME RELEASE_NOTES ${PFIX_README_FILES}
.endif
.include <bsd.prog.mk>
| {
"content_hash": "06df9f65739745efab43df5e104d7d14",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 67,
"avg_line_length": 18.857142857142858,
"alnum_prop": 0.696969696969697,
"repo_name": "execunix/vinos",
"id": "fc1e1ae532c979b7a0044c257be24d2b6482f9ee",
"size": "323",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "external/ibm-public/postfix/share/README_FILES/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\Route */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="route-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'number')->textInput(['maxlength' => true]) ?>
<?=
$form->field($model, 'start_id_station')->widget(\kartik\select2\Select2::classname(), [
'data' => $stations,
'options' => ['placeholder' => ''],
'pluginOptions' => [
'allowClear' => true
],
])
?>
<?=
$form->field($model, 'end_id_station')->widget(\kartik\select2\Select2::classname(), [
'data' => $stations,
'options' => ['placeholder' => ''],
'pluginOptions' => [
'allowClear' => true
],
])
?>
<?= $form->field($model, 'interval')->textInput() ?>
<?= $form->field($model, 'duration')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| {
"content_hash": "173c170d242ada064772c655dd9eeed7",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 154,
"avg_line_length": 25.340425531914892,
"alnum_prop": 0.5272879932829555,
"repo_name": "pers1307/Bus-depot",
"id": "2e535eeef51506a6256f4a7b79cdf7192b70e5ff",
"size": "1207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/views/route/_form.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "758"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "629569"
},
{
"name": "HTML",
"bytes": "1698308"
},
{
"name": "JavaScript",
"bytes": "2867118"
},
{
"name": "PHP",
"bytes": "295623"
},
{
"name": "Shell",
"bytes": "3257"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=type.N143.html">
</head>
<body>
<p>Redirecting to <a href="type.N143.html">type.N143.html</a>...</p>
<script>location.replace("type.N143.html" + location.search + location.hash);</script>
</body>
</html> | {
"content_hash": "1d63d882327fd5772a6203cdd9b8c6ae",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 90,
"avg_line_length": 29.7,
"alnum_prop": 0.6531986531986532,
"repo_name": "nitro-devs/nitro-game-engine",
"id": "dbe259a034564354437174ce06bbe61126daa749",
"size": "297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/typenum/consts/N143.t.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CMake",
"bytes": "1032"
},
{
"name": "Rust",
"bytes": "59380"
}
],
"symlink_target": ""
} |
package de.atomfrede.mate.application.rest.common;
public class LoginFailedException extends Exception {
}
| {
"content_hash": "102188718198fd9b4869d14fbc5a5ea8",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 21.8,
"alnum_prop": 0.8256880733944955,
"repo_name": "atomfrede/freezing-octo-bear",
"id": "0084150bcaefd8d8faf5050b23dc7391930775b3",
"size": "109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mate.application/src/main/java/de/atomfrede/mate/application/rest/common/LoginFailedException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2027"
},
{
"name": "HTML",
"bytes": "17537"
},
{
"name": "Java",
"bytes": "145689"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Example.ScrumPoker.Plugin.Properties {
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if ((resourceMan == null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Example.ScrumPoker.Plugin.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| {
"content_hash": "aeb3517b4a9e465e40cf0dd2e6ac2668",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 191,
"avg_line_length": 44.75806451612903,
"alnum_prop": 0.6126126126126126,
"repo_name": "SAEnergy/Superstructure",
"id": "98b8246703f7be72180cc4122bcb8aae34fd9b1c",
"size": "2777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Src/Client/Plugins/Example.ScrumPoker.Plugin/Properties/Resources.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "51198"
},
{
"name": "XSLT",
"bytes": "3323"
}
],
"symlink_target": ""
} |
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace InteropServices
{
//Constructors Tests
//ComConversionLossAttribute()
TEST(mscorlib_System_Runtime_InteropServices_ComConversionLossAttribute_Fixture,DefaultConstructor)
{
mscorlib::System::Runtime::InteropServices::ComConversionLossAttribute *value = new mscorlib::System::Runtime::InteropServices::ComConversionLossAttribute();
EXPECT_NE(NULL, value->GetNativeObject());
}
//Public Methods Tests
//Public Properties Tests
// Property TypeId
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Runtime_InteropServices_ComConversionLossAttribute_Fixture,get_TypeId_Test)
{
}
}
}
}
}
| {
"content_hash": "c8a58a7cc46c18692956a5e72e3f4d94",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 162,
"avg_line_length": 21.076923076923077,
"alnum_prop": 0.6763990267639902,
"repo_name": "brunolauze/MonoNative",
"id": "1417853f38b4615f45cc5a6fc4aaef1baf246d24",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_ComConversionLossAttribute_Fixture.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "137243"
},
{
"name": "C#",
"bytes": "104880"
},
{
"name": "C++",
"bytes": "18404064"
},
{
"name": "CSS",
"bytes": "1754"
},
{
"name": "HTML",
"bytes": "16925"
},
{
"name": "Shell",
"bytes": "132"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4a0158701a4640afb1f300a870cb8c1c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "af827c93d83258cf7ab3b6a92d6a56a1068fe793",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rhamnaceae/Rhamnus/Rhamnus jacobi-salvadorii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package proxy
import (
"errors"
)
var (
ErrorInvalidAuthentication = errors.New("Invalid authentication.")
ErrorInvalidProtocolVersion = errors.New("Invalid protocol version.")
ErrorAlreadyListening = errors.New("Already listening on another port.")
)
| {
"content_hash": "c737478a0f6ed86e1996e40e319a15b7",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 79,
"avg_line_length": 24.09090909090909,
"alnum_prop": 0.7547169811320755,
"repo_name": "evolsnow/v2ray-core",
"id": "f956419bd74533f7cd7a706ef819d14361c2a44f",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "proxy/errors.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "543483"
},
{
"name": "Shell",
"bytes": "10327"
}
],
"symlink_target": ""
} |
from fooster.web import web, form
import mock
import pytest
test_body = b'test'
test_chunks = b'a' * (web.max_line_size + 1)
test_encoded = b'test=t%C3%ABst&foo=bar&wow&such=dog'
test_binary = 'thisisatëst'.encode(web.default_encoding)
test_boundary = 'boundåry'
test_mime_empty = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="empty"; filename="empty"\r\n\r\n').encode(web.http_encoding)
test_mime_basic = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_bad = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\nContent-Length: ' + str(len(test_body) + 1) + '\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_chunks = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\n\r\n').encode(web.http_encoding) + test_chunks
test_mime_too_long = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\n\r\n').encode(web.http_encoding) + b'a' * (form.max_memory_size + web.max_line_size + 1)
test_mime_length = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\nContent-Length: ' + str(len(test_body)) + '\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_no_disposition = ('--' + test_boundary + '\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_bad_disposition = ('--' + test_boundary + '\r\nContent-Disposition: bad-data; name="body"\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_bad_length = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="body"\r\nContent-Length: "bad"\r\n\r\n').encode(web.http_encoding) + test_body
test_mime_filename = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary"; filename="binary"\r\nContent-Type: application/octet-stream\r\nContent-Length: ' + str(len(test_binary)) + '\r\n\r\n').encode(web.http_encoding) + test_binary
test_mime_filename_bad = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary_attached"; filename="binary"\r\nContent-Type: application/octet-stream\r\nContent-Length: ' + str(len(test_binary) + 1) + '\r\n\r\n').encode(web.http_encoding) + test_binary
test_mime_filename_bad_type = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary"; filename="binary"\r\nContent-Type: ;\r\nContent-Length: ' + str(len(test_binary)) + '\r\n\r\n').encode(web.http_encoding) + test_binary
test_mime_filename_no_length = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary"; filename="binary"\r\nContent-Type: application/octet-stream\r\n\r\n').encode(web.http_encoding) + test_binary
test_mime_filename_too_long = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary"; filename="binary"\r\nContent-Type: application/octet-stream\r\n\r\n').encode(web.http_encoding) + b'a' * (form.max_file_size + web.max_line_size + 1)
test_mime_utf8 = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary_utf8"\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n').encode(web.http_encoding) + test_binary
test_mime_extra = ('--' + test_boundary + '\r\nContent-Disposition: form-data; name="binary_utf8"\r\nContent-Type: text/plain; charset=utf-8\r\nMIME-Version: 1.0\r\nHeader: Value\r\n\r\n').encode(web.http_encoding) + test_binary
test_separator = '\r\n'.encode(web.http_encoding)
test_end = ('--' + test_boundary + '--\r\n').encode(web.http_encoding)
class EchoHandler(form.FormHandler):
def do_get(self):
return 204, ''
def do_post(self):
return 200, self.request.body
def test_form_get():
request = mock.MockHTTPRequest(None, ('', 0), None, method='GET', handler=EchoHandler)
response = request.handler.respond()
assert response[0] == 204
assert response[1] == ''
def test_form_post():
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_body, method='POST', handler=EchoHandler)
response = request.handler.respond()
assert request.body == test_body
assert response[0] == 200
assert response[1] == test_body
def test_form_urlencoded():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'application/x-www-form-urlencoded')
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_encoded, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['test'] == 'tëst'
assert request.body['foo'] == 'bar'
assert request.body['wow'] == ''
assert request.body['such'] == 'dog'
def test_form_urlencoded_bad():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'application/x-www-form-urlencoded')
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_encoded + 'å'.encode(web.default_encoding), headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['test'] == 'tëst'
assert request.body['foo'] == 'bar'
assert request.body['wow'] == ''
assert request.body['such'] == 'dogå'
def test_form_multipart_basic():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['body'] == test_body.decode()
def test_form_multipart_bad():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_bad + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_chunks():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_chunks + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['body'] == test_chunks.decode()
def test_form_multipart_basic_too_long():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_too_long + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 413
def test_form_multipart_basic_length():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_length + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['body'] == test_body.decode()
def test_form_multipart_expect():
request_headers = web.HTTPHeaders()
request_headers.set('Expect', '100-continue')
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['body'] == test_body.decode()
def test_form_multipart_bad_mime():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Length', str(len(test_mime_basic + test_separator + test_end) + 1))
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_bad_mime_length():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Length', '"bad"')
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_too_long():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Length', str(form.max_multipart_fragments * form.max_file_size + 1))
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 413
def test_form_multipart_bad_boundary():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=a' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_too_many():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=(test_mime_basic + test_separator) * (form.max_multipart_fragments + 1) + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 413
def test_form_multipart_no_disposition():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_no_disposition + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_bad_disposition():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_bad_disposition + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_bad_length():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_bad_length + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_bad_read():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_empty, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 500
def test_form_multipart_filename():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_filename + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['binary']['filename'] == 'binary'
assert request.body['binary']['type'] == 'application/octet-stream'
assert request.body['binary']['length'] == len(test_binary)
assert request.body['binary']['file'].read() == test_binary
def test_form_multipart_filename_no_length():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_filename_no_length + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['binary']['filename'] == 'binary'
assert request.body['binary']['type'] == 'application/octet-stream'
assert request.body['binary']['length'] == len(test_binary)
assert request.body['binary']['file'].read() == test_binary
def test_form_multipart_filename_too_long():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_filename_too_long + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 413
def test_form_multipart_filename_bad():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_filename_bad + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
with pytest.raises(web.HTTPError) as error:
request.handler.respond()
assert error.value.code == 400
def test_form_multipart_filename_bad_type():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_filename_bad_type + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['binary']['filename'] == 'binary'
assert request.body['binary']['type'] == 'text/plain'
assert request.body['binary']['length'] == len(test_binary)
assert request.body['binary']['file'].read() == test_binary
def test_form_multipart_utf8():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_utf8 + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['binary_utf8'] == test_binary.decode()
def test_form_multipart_extra():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_extra + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['binary_utf8'] == test_binary.decode()
def test_form_multipart_multi():
request_headers = web.HTTPHeaders()
request_headers.set('Content-Type', 'multipart/form-data; boundary=' + test_boundary)
request = mock.MockHTTPRequest(None, ('', 0), None, body=test_mime_basic + test_separator + test_mime_filename + test_separator + test_mime_utf8 + test_separator + test_end, headers=request_headers, method='POST', handler=EchoHandler)
request.handler.respond()
assert request.body['body'] == test_body.decode()
assert request.body['binary']['filename'] == 'binary'
assert request.body['binary']['type'] == 'application/octet-stream'
assert request.body['binary']['length'] == len(test_binary)
assert request.body['binary']['file'].read() == test_binary
assert request.body['binary_utf8'] == test_binary.decode()
| {
"content_hash": "244dc649436b573b895e1a545a463a19",
"timestamp": "",
"source": "github",
"line_count": 379,
"max_line_length": 272,
"avg_line_length": 44.010554089709764,
"alnum_prop": 0.6952637889688249,
"repo_name": "fkmclane/web.py",
"id": "be3284c5b323aa9c5ec458efe579c61e1f97974c",
"size": "16686",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/test_form.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "153611"
}
],
"symlink_target": ""
} |
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface HaxeWildcard extends HaxePsiCompositeElement {
@NotNull
HaxeReferenceExpression getReferenceExpression();
}
| {
"content_hash": "60f599507013cb62177407237d0cc142",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 63,
"avg_line_length": 22.4,
"alnum_prop": 0.8005952380952381,
"repo_name": "JetBrains/intellij-haxe",
"id": "b07527ba1482b1df6843dc6cd6410b88679ecfdb",
"size": "1000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen/com/intellij/plugins/haxe/lang/psi/HaxeWildcard.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2332"
},
{
"name": "Haxe",
"bytes": "73646"
},
{
"name": "JFlex",
"bytes": "16860"
},
{
"name": "Java",
"bytes": "2958738"
},
{
"name": "Makefile",
"bytes": "547"
},
{
"name": "Shell",
"bytes": "3228"
}
],
"symlink_target": ""
} |
#include "physics/CCPhysicsShape.h"
#if CC_USE_PHYSICS
#include <climits>
#include "chipmunk.h"
#include "physics/CCPhysicsBody.h"
#include "physics/CCPhysicsWorld.h"
#include "chipmunk/CCPhysicsBodyInfo_chipmunk.h"
#include "chipmunk/CCPhysicsShapeInfo_chipmunk.h"
#include "chipmunk/CCPhysicsHelper_chipmunk.h"
NS_CC_BEGIN
extern const float PHYSICS_INFINITY;
PhysicsShape::PhysicsShape()
: _body(nullptr)
, _info(nullptr)
, _type(Type::UNKNOWN)
, _area(0)
, _mass(0)
, _moment(0)
, _tag(0)
, _categoryBitmask(UINT_MAX)
, _collisionBitmask(UINT_MAX)
, _contactTestBitmask(0)
, _group(0)
{
}
PhysicsShape::~PhysicsShape()
{
CC_SAFE_DELETE(_info);
}
bool PhysicsShape::init(Type type)
{
_info = new PhysicsShapeInfo(this);
if (_info == nullptr) return false;
_type = type;
return true;
}
void PhysicsShape::setMass(float mass)
{
if (mass < 0)
{
return;
}
if (_body)
{
_body->addMass(-_mass);
_body->addMass(mass);
};
_mass = mass;
}
void PhysicsShape::setMoment(float moment)
{
if (moment < 0)
{
return;
}
if (_body)
{
_body->addMoment(-_moment);
_body->addMoment(moment);
};
_moment = moment;
}
void PhysicsShape::setMaterial(const PhysicsMaterial& material)
{
setDensity(material.density);
setRestitution(material.restitution);
setFriction(material.friction);
}
PhysicsBodyInfo* PhysicsShape::bodyInfo() const
{
if (_body != nullptr)
{
return _body->_info;
}else
{
return nullptr;
}
}
PhysicsShapeCircle::PhysicsShapeCircle()
{
}
PhysicsShapeCircle::~PhysicsShapeCircle()
{
}
PhysicsShapeBox::PhysicsShapeBox()
{
}
PhysicsShapeBox::~PhysicsShapeBox()
{
}
PhysicsShapePolygon::PhysicsShapePolygon()
{
}
PhysicsShapePolygon::~PhysicsShapePolygon()
{
}
PhysicsShapeEdgeBox::PhysicsShapeEdgeBox()
{
}
PhysicsShapeEdgeBox::~PhysicsShapeEdgeBox()
{
}
PhysicsShapeEdgeChain::PhysicsShapeEdgeChain()
{
}
PhysicsShapeEdgeChain::~PhysicsShapeEdgeChain()
{
}
PhysicsShapeEdgePolygon::PhysicsShapeEdgePolygon()
{
}
PhysicsShapeEdgePolygon::~PhysicsShapeEdgePolygon()
{
}
PhysicsShapeEdgeSegment::PhysicsShapeEdgeSegment()
{
}
PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment()
{
}
void PhysicsShape::setDensity(float density)
{
if (density < 0)
{
return;
}
_material.density = density;
if (_material.density == PHYSICS_INFINITY)
{
setMass(PHYSICS_INFINITY);
}else if (_area > 0)
{
setMass(PhysicsHelper::float2cpfloat(_material.density * _area));
}
}
void PhysicsShape::setRestitution(float restitution)
{
_material.restitution = restitution;
for (cpShape* shape : _info->getShapes())
{
cpShapeSetElasticity(shape, PhysicsHelper::float2cpfloat(restitution));
}
}
void PhysicsShape::setFriction(float friction)
{
_material.friction = friction;
for (cpShape* shape : _info->getShapes())
{
cpShapeSetFriction(shape, PhysicsHelper::float2cpfloat(friction));
}
}
void PhysicsShape::recenterPoints(Vector2* points, int count, const Vector2& center)
{
cpVect* cpvs = new cpVect[count];
cpRecenterPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count));
PhysicsHelper::cpvs2points(cpvs, points, count);
delete[] cpvs;
if (center != Vector2::ZERO)
{
for (int i = 0; i < count; ++i)
{
points[i] += center;
}
}
}
Vector2 PhysicsShape::getPolyonCenter(const Vector2* points, int count)
{
cpVect* cpvs = new cpVect[count];
cpVect center = cpCentroidForPoly(count, PhysicsHelper::points2cpvs(points, cpvs, count));
delete[] cpvs;
return PhysicsHelper::cpv2point(center);
}
void PhysicsShape::setBody(PhysicsBody *body)
{
// already added
if (body != nullptr && _body == body)
{
return;
}
if (_body != nullptr)
{
_body->removeShape(this);
}
if (body == nullptr)
{
_info->setBody(nullptr);
_body = nullptr;
}else
{
_info->setBody(body->_info->getBody());
_body = body;
}
}
// PhysicsShapeCircle
PhysicsShapeCircle* PhysicsShapeCircle::create(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset/* = Vector2(0, 0)*/)
{
PhysicsShapeCircle* shape = new PhysicsShapeCircle();
if (shape && shape->init(radius, material, offset))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset /*= Vector2(0, 0)*/)
{
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::CIRCLE));
cpShape* shape = cpCircleShapeNew(_info->getSharedBody(), radius, PhysicsHelper::point2cpv(offset));
CC_BREAK_IF(shape == nullptr);
_info->add(shape);
_area = calculateArea();
_mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
_moment = calculateDefaultMoment();
setMaterial(material);
return true;
} while (false);
return false;
}
float PhysicsShapeCircle::calculateArea(float radius)
{
return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, radius));
}
float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Vector2& offset)
{
return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass),
0,
PhysicsHelper::float2cpfloat(radius),
PhysicsHelper::point2cpv(offset)));
}
float PhysicsShapeCircle::calculateArea()
{
return PhysicsHelper::cpfloat2float(cpAreaForCircle(0, cpCircleShapeGetRadius(_info->getShapes().front())));
}
float PhysicsShapeCircle::calculateDefaultMoment()
{
cpShape* shape = _info->getShapes().front();
return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass),
0,
cpCircleShapeGetRadius(shape),
cpCircleShapeGetOffset(shape)));
}
float PhysicsShapeCircle::getRadius() const
{
return PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(_info->getShapes().front()));
}
Vector2 PhysicsShapeCircle::getOffset()
{
return PhysicsHelper::cpv2point(cpCircleShapeGetOffset(_info->getShapes().front()));
}
// PhysicsShapeEdgeSegment
PhysicsShapeEdgeSegment* PhysicsShapeEdgeSegment::create(const Vector2& a, const Vector2& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
PhysicsShapeEdgeSegment* shape = new PhysicsShapeEdgeSegment();
if (shape && shape->init(a, b, material, border))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeEdgeSegment::init(const Vector2& a, const Vector2& b, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::EDGESEGMENT));
cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(),
PhysicsHelper::point2cpv(a),
PhysicsHelper::point2cpv(b),
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr);
_info->add(shape);
_mass = PHYSICS_INFINITY;
_moment = PHYSICS_INFINITY;
_center = a.getMidpoint(b);
setMaterial(material);
return true;
} while (false);
return false;
}
Vector2 PhysicsShapeEdgeSegment::getPointA() const
{
return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->ta);
}
Vector2 PhysicsShapeEdgeSegment::getPointB() const
{
return PhysicsHelper::cpv2point(((cpSegmentShape*)(_info->getShapes().front()))->tb);
}
Vector2 PhysicsShapeEdgeSegment::getCenter()
{
return _center;
}
// PhysicsShapeBox
PhysicsShapeBox* PhysicsShapeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset/* = Vector2(0, 0)*/)
{
PhysicsShapeBox* shape = new PhysicsShapeBox();
if (shape && shape->init(size, material, offset))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset /*= Vector2(0, 0)*/)
{
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::BOX));
cpVect wh = PhysicsHelper::size2cpv(size);
cpVect vec[4] =
{
{-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f}
};
cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), 4, vec, PhysicsHelper::point2cpv(offset));
CC_BREAK_IF(shape == nullptr);
_info->add(shape);
_offset = offset;
_area = calculateArea();
_mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
_moment = calculateDefaultMoment();
setMaterial(material);
return true;
} while (false);
return false;
}
float PhysicsShapeBox::calculateArea(const Size& size)
{
cpVect wh = PhysicsHelper::size2cpv(size);
cpVect vec[4] =
{
{-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f}
};
return PhysicsHelper::cpfloat2float(cpAreaForPoly(4, vec));
}
float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Vector2& offset)
{
cpVect wh = PhysicsHelper::size2cpv(size);
cpVect vec[4] =
{
{-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f}
};
return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForPoly(PhysicsHelper::float2cpfloat(mass),
4,
vec,
PhysicsHelper::point2cpv(offset)));
}
float PhysicsShapeBox::calculateArea()
{
cpShape* shape = _info->getShapes().front();
return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts));
}
float PhysicsShapeBox::calculateDefaultMoment()
{
cpShape* shape = _info->getShapes().front();
return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero));
}
void PhysicsShapeBox::getPoints(Vector2* points) const
{
cpShape* shape = _info->getShapes().front();
PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, points, ((cpPolyShape*)shape)->numVerts);
}
Size PhysicsShapeBox::getSize() const
{
cpShape* shape = _info->getShapes().front();
return PhysicsHelper::cpv2size(cpv(cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)),
cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1))));
}
// PhysicsShapePolygon
PhysicsShapePolygon* PhysicsShapePolygon::create(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset/* = Vector2(0, 0)*/)
{
PhysicsShapePolygon* shape = new PhysicsShapePolygon();
if (shape && shape->init(points, count, material, offset))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapePolygon::init(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, const Vector2& offset/* = Vector2(0, 0)*/)
{
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::POLYGEN));
cpVect* vecs = new cpVect[count];
PhysicsHelper::points2cpvs(points, vecs, count);
cpShape* shape = cpPolyShapeNew(_info->getSharedBody(), count, vecs, PhysicsHelper::point2cpv(offset));
CC_SAFE_DELETE_ARRAY(vecs);
CC_BREAK_IF(shape == nullptr);
_info->add(shape);
_area = calculateArea();
_mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area;
_moment = calculateDefaultMoment();
_center = PhysicsHelper::cpv2point(cpCentroidForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts));
setMaterial(material);
return true;
} while (false);
return false;
}
float PhysicsShapePolygon::calculateArea(const Vector2* points, int count)
{
cpVect* vecs = new cpVect[count];
PhysicsHelper::points2cpvs(points, vecs, count);
float area = PhysicsHelper::cpfloat2float(cpAreaForPoly(count, vecs));
CC_SAFE_DELETE_ARRAY(vecs);
return area;
}
float PhysicsShapePolygon::calculateMoment(float mass, const Vector2* points, int count, const Vector2& offset)
{
cpVect* vecs = new cpVect[count];
PhysicsHelper::points2cpvs(points, vecs, count);
float moment = mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForPoly(mass, count, vecs, PhysicsHelper::point2cpv(offset)));
CC_SAFE_DELETE_ARRAY(vecs);
return moment;
}
float PhysicsShapePolygon::calculateArea()
{
cpShape* shape = _info->getShapes().front();
return PhysicsHelper::cpfloat2float(cpAreaForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts));
}
float PhysicsShapePolygon::calculateDefaultMoment()
{
cpShape* shape = _info->getShapes().front();
return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY
: PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero));
}
Vector2 PhysicsShapePolygon::getPoint(int i) const
{
return PhysicsHelper::cpv2point(cpPolyShapeGetVert(_info->getShapes().front(), i));
}
void PhysicsShapePolygon::getPoints(Vector2* outPoints) const
{
cpShape* shape = _info->getShapes().front();
PhysicsHelper::cpvs2points(((cpPolyShape*)shape)->verts, outPoints, ((cpPolyShape*)shape)->numVerts);
}
int PhysicsShapePolygon::getPointsCount() const
{
return ((cpPolyShape*)_info->getShapes().front())->numVerts;
}
Vector2 PhysicsShapePolygon::getCenter()
{
return _center;
}
// PhysicsShapeEdgeBox
PhysicsShapeEdgeBox* PhysicsShapeEdgeBox::create(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Vector2& offset/* = Vector2(0, 0)*/)
{
PhysicsShapeEdgeBox* shape = new PhysicsShapeEdgeBox();
if (shape && shape->init(size, material, border, offset))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/, const Vector2& offset/*= Vector2(0, 0)*/)
{
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::EDGEBOX));
cpVect vec[4] = {};
vec[0] = PhysicsHelper::point2cpv(Vector2(-size.width/2+offset.x, -size.height/2+offset.y));
vec[1] = PhysicsHelper::point2cpv(Vector2(+size.width/2+offset.x, -size.height/2+offset.y));
vec[2] = PhysicsHelper::point2cpv(Vector2(+size.width/2+offset.x, +size.height/2+offset.y));
vec[3] = PhysicsHelper::point2cpv(Vector2(-size.width/2+offset.x, +size.height/2+offset.y));
int i = 0;
for (; i < 4; ++i)
{
cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%4],
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr);
_info->add(shape);
}
CC_BREAK_IF(i < 4);
_offset = offset;
_mass = PHYSICS_INFINITY;
_moment = PHYSICS_INFINITY;
setMaterial(material);
return true;
} while (false);
return false;
}
void PhysicsShapeEdgeBox::getPoints(cocos2d::Vector2 *outPoints) const
{
int i = 0;
for(auto shape : _info->getShapes())
{
outPoints[i++] = PhysicsHelper::cpv2point(((cpSegmentShape*)shape)->a);
}
}
// PhysicsShapeEdgeBox
PhysicsShapeEdgePolygon* PhysicsShapeEdgePolygon::create(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
PhysicsShapeEdgePolygon* shape = new PhysicsShapeEdgePolygon();
if (shape && shape->init(points, count, material, border))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeEdgePolygon::init(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
cpVect* vec = nullptr;
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::EDGEPOLYGEN));
vec = new cpVect[count];
PhysicsHelper::points2cpvs(points, vec, count);
_center = PhysicsHelper::cpv2point(cpCentroidForPoly(count, vec));
int i = 0;
for (; i < count; ++i)
{
cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[(i+1)%count],
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr);
cpShapeSetElasticity(shape, 1.0f);
cpShapeSetFriction(shape, 1.0f);
_info->add(shape);
}
CC_SAFE_DELETE_ARRAY(vec);
CC_BREAK_IF(i < count);
_mass = PHYSICS_INFINITY;
_moment = PHYSICS_INFINITY;
setMaterial(material);
return true;
} while (false);
CC_SAFE_DELETE_ARRAY(vec);
return false;
}
Vector2 PhysicsShapeEdgePolygon::getCenter()
{
return _center;
}
void PhysicsShapeEdgePolygon::getPoints(cocos2d::Vector2 *outPoints) const
{
int i = 0;
for(auto shape : _info->getShapes())
{
outPoints[i++] = PhysicsHelper::cpv2point(((cpSegmentShape*)shape)->a);
}
}
int PhysicsShapeEdgePolygon::getPointsCount() const
{
return static_cast<int>(_info->getShapes().size() + 1);
}
// PhysicsShapeEdgeChain
PhysicsShapeEdgeChain* PhysicsShapeEdgeChain::create(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
PhysicsShapeEdgeChain* shape = new PhysicsShapeEdgeChain();
if (shape && shape->init(points, count, material, border))
{
shape->autorelease();
return shape;
}
CC_SAFE_DELETE(shape);
return nullptr;
}
bool PhysicsShapeEdgeChain::init(const Vector2* points, int count, const PhysicsMaterial& material/* = MaterialDefault*/, float border/* = 1*/)
{
cpVect* vec = nullptr;
do
{
CC_BREAK_IF(!PhysicsShape::init(Type::EDGECHAIN));
vec = new cpVect[count];
PhysicsHelper::points2cpvs(points, vec, count);
_center = PhysicsHelper::cpv2point(cpCentroidForPoly(count, vec));
int i = 0;
for (; i < count - 1; ++i)
{
cpShape* shape = cpSegmentShapeNew(_info->getSharedBody(), vec[i], vec[i+1],
PhysicsHelper::float2cpfloat(border));
CC_BREAK_IF(shape == nullptr);
cpShapeSetElasticity(shape, 1.0f);
cpShapeSetFriction(shape, 1.0f);
_info->add(shape);
}
CC_SAFE_DELETE_ARRAY(vec);
CC_BREAK_IF(i < count - 1);
_mass = PHYSICS_INFINITY;
_moment = PHYSICS_INFINITY;
setMaterial(material);
return true;
} while (false);
CC_SAFE_DELETE_ARRAY(vec);
return false;
}
Vector2 PhysicsShapeEdgeChain::getCenter()
{
return _center;
}
void PhysicsShapeEdgeChain::getPoints(Vector2* outPoints) const
{
int i = 0;
for(auto shape : _info->getShapes())
{
outPoints[i++] = PhysicsHelper::cpv2point(((cpSegmentShape*)shape)->a);
}
outPoints[i++] = PhysicsHelper::cpv2point(((cpSegmentShape*)_info->getShapes().back())->a);
}
int PhysicsShapeEdgeChain::getPointsCount() const
{
return static_cast<int>(_info->getShapes().size() + 1);
}
void PhysicsShape::setGroup(int group)
{
if (group < 0)
{
for (auto shape : _info->getShapes())
{
cpShapeSetGroup(shape, (cpGroup)group);
}
}
_group = group;
}
bool PhysicsShape::containsPoint(const Vector2& point) const
{
for (auto shape : _info->getShapes())
{
if (cpShapePointQuery(shape, PhysicsHelper::point2cpv(point)))
{
return true;
}
}
return false;
}
NS_CC_END
#endif // CC_USE_PHYSICS
| {
"content_hash": "f3fd9a2cfb0afee549f6f59a87457e7a",
"timestamp": "",
"source": "github",
"line_count": 814,
"max_line_length": 186,
"avg_line_length": 26.62039312039312,
"alnum_prop": 0.6161797960219668,
"repo_name": "MandukaGames/tutorial-puzzle",
"id": "60171cbec0891f981875d6a6d8670676ce9177db",
"size": "22941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cocos2d/cocos/physics/CCPhysicsShape.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "16972847"
},
{
"name": "C#",
"bytes": "43441"
},
{
"name": "C++",
"bytes": "7584267"
},
{
"name": "Java",
"bytes": "437138"
},
{
"name": "Objective-C",
"bytes": "853981"
},
{
"name": "Objective-C++",
"bytes": "236177"
},
{
"name": "Perl",
"bytes": "2767"
},
{
"name": "PowerShell",
"bytes": "18747"
},
{
"name": "Python",
"bytes": "33299"
},
{
"name": "Shell",
"bytes": "26834"
}
],
"symlink_target": ""
} |
package pointer_test
import (
"fmt"
"sort"
"github.com/chenjianlong/go.tools/go/callgraph"
"github.com/chenjianlong/go.tools/go/loader"
"github.com/chenjianlong/go.tools/go/pointer"
"github.com/chenjianlong/go.tools/go/ssa"
)
// This program demonstrates how to use the pointer analysis to
// obtain a conservative call-graph of a Go program.
// It also shows how to compute the points-to set of a variable,
// in this case, (C).f's ch parameter.
//
func Example() {
const myprog = `
package main
import "fmt"
type I interface {
f(map[string]int)
}
type C struct{}
func (C) f(m map[string]int) {
fmt.Println("C.f()")
}
func main() {
var i I = C{}
x := map[string]int{"one":1}
i.f(x) // dynamic method call
}
`
// Construct a loader.
conf := loader.Config{SourceImports: true}
// Parse the input file.
file, err := conf.ParseFile("myprog.go", myprog)
if err != nil {
fmt.Print(err) // parse error
return
}
// Create single-file main package and import its dependencies.
conf.CreateFromFiles("main", file)
iprog, err := conf.Load()
if err != nil {
fmt.Print(err) // type error in some package
return
}
// Create SSA-form program representation.
prog := ssa.Create(iprog, 0)
mainPkg := prog.Package(iprog.Created[0].Pkg)
// Build SSA code for bodies of all functions in the whole program.
prog.BuildAll()
// Configure the pointer analysis to build a call-graph.
config := &pointer.Config{
Mains: []*ssa.Package{mainPkg},
BuildCallGraph: true,
}
// Query points-to set of (C).f's parameter m, a map.
C := mainPkg.Type("C").Type()
Cfm := prog.LookupMethod(C, mainPkg.Object, "f").Params[1]
config.AddQuery(Cfm)
// Run the pointer analysis.
result, err := pointer.Analyze(config)
if err != nil {
panic(err) // internal error in pointer analysis
}
// Find edges originating from the main package.
// By converting to strings, we de-duplicate nodes
// representing the same function due to context sensitivity.
var edges []string
callgraph.GraphVisitEdges(result.CallGraph, func(edge *callgraph.Edge) error {
caller := edge.Caller.Func
if caller.Pkg == mainPkg {
edges = append(edges, fmt.Sprint(caller, " --> ", edge.Callee.Func))
}
return nil
})
// Print the edges in sorted order.
sort.Strings(edges)
for _, edge := range edges {
fmt.Println(edge)
}
fmt.Println()
// Print the labels of (C).f(m)'s points-to set.
fmt.Println("m may point to:")
var labels []string
for _, l := range result.Queries[Cfm].PointsTo().Labels() {
label := fmt.Sprintf(" %s: %s", prog.Fset.Position(l.Pos()), l)
labels = append(labels, label)
}
sort.Strings(labels)
for _, label := range labels {
fmt.Println(label)
}
// Output:
// (main.C).f --> fmt.Println
// main.init --> fmt.init
// main.main --> (main.C).f
//
// m may point to:
// myprog.go:18:21: makemap
}
| {
"content_hash": "2b6c7d369a66b82ed1c7a1ed8bae9e60",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 79,
"avg_line_length": 23.68595041322314,
"alnum_prop": 0.6688764829030007,
"repo_name": "chenjianlong/go.tools",
"id": "9d2b983d30b4cad2f11c28551f10f3f4939934f0",
"size": "3026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "go/pointer/example_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "39567"
},
{
"name": "CSS",
"bytes": "30345"
},
{
"name": "Emacs Lisp",
"bytes": "8434"
},
{
"name": "Go",
"bytes": "3883241"
},
{
"name": "JavaScript",
"bytes": "51682"
},
{
"name": "Shell",
"bytes": "5787"
},
{
"name": "VimL",
"bytes": "3376"
}
],
"symlink_target": ""
} |
package com.piticlistudio.playednext.company.model.entity.datasource;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test cases
* Created by jorge.garcia on 13/02/2017.
*/
public class IGDBCompanyTest {
private IGDBCompany data = IGDBCompany.create(50, "company_name", "company_url", "company_slug", 1000, 2000);
@Test
public void create() throws Exception {
assertNotNull(data);
assertEquals(50, data.id());
assertEquals("company_name", data.name());
assertEquals("company_url", data.url());
assertEquals("company_slug", data.slug());
assertEquals(1000, data.created_at());
assertEquals(2000, data.updated_at());
}
@Test
public void getId() throws Exception {
assertEquals(50, data.getId());
}
@Test
public void getName() throws Exception {
assertEquals("company_name", data.getName());
}
} | {
"content_hash": "84ab551986ceaac45193d634df1a548b",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 113,
"avg_line_length": 26.542857142857144,
"alnum_prop": 0.6447793326157158,
"repo_name": "Yorxxx/playednext",
"id": "652c011d82f2e7daedf314551e4efe0e90debd3b",
"size": "929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/test/java/com/piticlistudio/playednext/company/model/entity/datasource/IGDBCompanyTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "798466"
}
],
"symlink_target": ""
} |
Configuration SPF
{
Import-DscResource -Module xSQLServer
Import-DscResource -Module xSCVMM
Import-DscResource -Module xSCSPF
# Set role and instance variables
$Roles = $AllNodes.Roles | Sort-Object -Unique
foreach($Role in $Roles)
{
$Servers = @($AllNodes.Where{$_.Roles | Where-Object {$_ -eq $Role}}.NodeName)
Set-Variable -Name ($Role.Replace(" ","").Replace(".","") + "s") -Value $Servers
if($Servers.Count -eq 1)
{
Set-Variable -Name ($Role.Replace(" ","").Replace(".","")) -Value $Servers[0]
if(
$Role.Contains("Database") -or
$Role.Contains("Datawarehouse") -or
$Role.Contains("Reporting") -or
$Role.Contains("Analysis") -or
$Role.Contains("Integration")
)
{
$Instance = $AllNodes.Where{$_.NodeName -eq $Servers[0]}.SQLServers.Where{$_.Roles | Where-Object {$_ -eq $Role}}.InstanceName
Set-Variable -Name ($Role.Replace(" ","").Replace(".","").Replace("Server","Instance")) -Value $Instance
}
}
}
Node $AllNodes.NodeName
{
# Set LCM to reboot if needed
LocalConfigurationManager
{
DebugMode = $true
RebootNodeIfNeeded = $true
}
# Install .NET Framework 3.5 on SQL nodes
if(
($SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer -eq $Node.NodeName) -or
($SQLServer2012ManagementTools | Where-Object {$_ -eq $Node.NodeName})
)
{
WindowsFeature "NET-Framework-Core"
{
Ensure = "Present"
Name = "NET-Framework-Core"
Source = $Node.SourcePath + "\WindowsServer.TP\sources\sxs"
}
}
# Install IIS on Web Service servers
if(
($SystemCenterTechnicalPreviewServiceProviderFoundationServers | Where-Object {$_ -eq $Node.NodeName})
)
{
WindowsFeature "Web-WebServer"
{
Ensure = "Present"
Name = "Web-WebServer"
}
WindowsFeature "Web-Basic-Auth"
{
Ensure = "Present"
Name = "Web-Basic-Auth"
}
WindowsFeature "Web-Windows-Auth"
{
Ensure = "Present"
Name = "Web-Windows-Auth"
}
WindowsFeature "Web-Asp-Net45"
{
Ensure = "Present"
Name = "Web-Asp-Net45"
}
WindowsFeature "NET-WCF-HTTP-Activation45"
{
Ensure = "Present"
Name = "NET-WCF-HTTP-Activation45"
}
WindowsFeature "ManagementOData"
{
Ensure = "Present"
Name = "ManagementOData"
}
WindowsFeature "Web-Request-Monitor"
{
Ensure = "Present"
Name = "Web-Request-Monitor"
}
WindowsFeature "Web-Http-Tracing"
{
Ensure = "Present"
Name = "Web-Http-Tracing"
}
WindowsFeature "Web-Scripting-Tools"
{
Ensure = "Present"
Name = "Web-Scripting-Tools"
}
}
# Install SQL Instances
if(
($SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer -eq $Node.NodeName)
)
{
foreach($SQLServer in $Node.SQLServers)
{
$SQLInstanceName = $SQLServer.InstanceName
$Features = ""
if(
(
($SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer -eq $Node.NodeName) -and
($SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseInstance -eq $SQLInstanceName)
)
)
{
$Features += "SQLENGINE"
}
$Features = $Features.Trim(",")
if($Features -ne "")
{
xSqlServerSetup ($Node.NodeName + $SQLInstanceName)
{
DependsOn = "[WindowsFeature]NET-Framework-Core"
SourcePath = $Node.SourcePath
SourceFolder = "SQLServer2014.en"
SetupCredential = $Node.InstallerServiceAccount
InstanceName = $SQLInstanceName
Features = $Features
SQLSysAdminAccounts = $Node.AdminAccount
}
xSqlServerFirewall ($Node.NodeName + $SQLInstanceName)
{
DependsOn = ("[xSqlServerSetup]" + $Node.NodeName + $SQLInstanceName)
SourcePath = $Node.SourcePath
SourceFolder = "SQLServer2014.en"
InstanceName = $SQLInstanceName
Features = $Features
}
}
}
}
# Install SQL Management Tools
if($SQLServer2012ManagementTools | Where-Object {$_ -eq $Node.NodeName})
{
xSqlServerSetup "SQLMT"
{
DependsOn = "[WindowsFeature]NET-Framework-Core"
SourcePath = $Node.SourcePath
SourceFolder = "SQLServer2014.en"
SetupCredential = $Node.InstallerServiceAccount
InstanceName = "NULL"
Features = "SSMS,ADV_SSMS"
}
}
# Install SPF prerequisites
if($SystemCenterTechnicalPreviewServiceProviderFoundationServers | Where-Object {$_ -eq $Node.NodeName})
{
if($Node.ASPNETMVC4)
{
$ASPNETMVC4 = (Join-Path -Path $Node.ASPNETMVC4 -ChildPath "AspNetMVC4Setup.exe")
}
else
{
$ASPNETMVC4 = "\Prerequisites\ASPNETMVC4\AspNetMVC4Setup.exe"
}
Package "ASPNETMVC4"
{
Ensure = "Present"
Name = "Microsoft ASP.NET MVC 4 Runtime"
ProductId = ""
Path = (Join-Path -Path $Node.SourcePath -ChildPath $ASPNETMVC4)
Arguments = "/q"
Credential = $Node.InstallerServiceAccount
}
if($Node.WCFDataServices50)
{
$WCFDataServices50 = (Join-Path -Path $Node.WCFDataServices50 -ChildPath "WCFDataServices.exe")
}
else
{
$WCFDataServices50 = "\Prerequisites\WCF50\WCFDataServices.exe"
}
Package "WCFDataServices50"
{
Ensure = "Present"
Name = "WCF Data Services 5.0 (for OData v3) Primary Components"
ProductId = ""
Path = (Join-Path -Path $Node.SourcePath -ChildPath $WCFDataServices50)
Arguments = "/q"
Credential = $Node.InstallerServiceAccount
}
xSCVMMConsoleSetup "VMMC"
{
Ensure = "Present"
SourcePath = $Node.SourcePath
SourceFolder = "\SystemCenter.TP\VirtualMachineManager"
SetupCredential = $Node.InstallerServiceAccount
}
}
# Create DependsOn for SPF Server
$DependsOn = @(
"[Package]ASPNETMVC4",
"[Package]WCFDataServices50",
"[xSCVMMConsoleSetup]VMMC"
)
# Install first Server
if ($SystemCenterTechnicalPreviewServiceProviderFoundationServers[0] -eq $Node.NodeName)
{
# Wait for SQL Server
if ($SystemCenterTechnicalPreviewServiceProviderFoundationServers[0] -eq $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer)
{
$DependsOn += @(("[xSqlServerFirewall]" + $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer + $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseInstance))
}
else
{
WaitForAll "SPFDB"
{
NodeName = $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer
ResourceName = ("[xSqlServerFirewall]" + $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer + $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseInstance)
Credential = $Node.InstallerServiceAccount
RetryCount = 720
RetryIntervalSec = 5
}
$DependsOn += @("[WaitForAll]SPFDB")
}
# Install first Web Service Server
xSCSPFServerSetup "SPF"
{
DependsOn = $DependsOn
Ensure = "Present"
SourcePath = $Node.SourcePath
SourceFolder = "\SystemCenter.TP\Orchestrator"
SetupCredential = $Node.InstallerServiceAccount
DatabaseServer = $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer
SCVMM = $Node.SPFServiceAccount
SCAdmin = $Node.SPFServiceAccount
SCProvider = $Node.SPFServiceAccount
SCUsage = $Node.SPFServiceAccount
VMMSecurityGroupUsers = $Node.AdminAccount
AdminSecurityGroupUsers = $Node.AdminAccount
ProviderSecurityGroupUsers = $Node.AdminAccount
UsageSecurityGroupUsers = $Node.AdminAccount
}
}
# Wait for first server
if(
($SystemCenterTechnicalPreviewServiceProviderFoundationServers | Where-Object {$_ -eq $Node.NodeName}) -and
(!($SystemCenterTechnicalPreviewServiceProviderFoundationServers[0] -eq $Node.NodeName))
)
{
WaitForAll "SPF"
{
NodeName = $SystemCenterTechnicalPreviewServiceProviderFoundationServers[0]
ResourceName = "[xSCSPFServerSetup]SPF"
RetryIntervalSec = 5
RetryCount = 720
Credential = $Node.InstallerServiceAccount
}
$DependsOn += @("[WaitForAll]SPF")
}
# Install additional servers
if(
($SystemCenterTechnicalPreviewServiceProviderFoundationServers | Where-Object {$_ -eq $Node.NodeName}) -and
(!($SystemCenterTechnicalPreviewServiceProviderFoundationServers[0] -eq $Node.NodeName))
)
{
xSCSPFServerSetup "SPF"
{
DependsOn = $DependsOn
Ensure = "Present"
SourcePath = $Node.SourcePath
SourceFolder = "\SystemCenter.TP\Orchestrator"
SetupCredential = $Node.InstallerServiceAccount
DatabaseServer = $SystemCenterTechnicalPreviewServiceProviderFoundationDatabaseServer
SCVMM = $Node.SPFServiceAccount
SCAdmin = $Node.SPFServiceAccount
SCProvider = $Node.SPFServiceAccount
SCUsage = $Node.SPFServiceAccount
VMMSecurityGroupUsers = $Node.AdminAccount
AdminSecurityGroupUsers = $Node.AdminAccount
ProviderSecurityGroupUsers = $Node.AdminAccount
UsageSecurityGroupUsers = $Node.AdminAccount
}
}
}
}
$SecurePassword = ConvertTo-SecureString -String "Pass@word1" -AsPlainText -Force
$InstallerServiceAccount = New-Object System.Management.Automation.PSCredential ("CONTOSO\!Installer", $SecurePassword)
$LocalSystemAccount = New-Object System.Management.Automation.PSCredential ("SYSTEM", $SecurePassword)
$SPFServiceAccount = New-Object System.Management.Automation.PSCredential ("CONTOSO\!spf", $SecurePassword)
$ConfigurationData = @{
AllNodes = @(
@{
NodeName = "*"
PSDscAllowPlainTextPassword = $true
SourcePath = "\\RD01\Installer"
InstallerServiceAccount = $InstallerServiceAccount
LocalSystemAccount = $LocalSystemAccount
SPFServiceAccount = $SPFServiceAccount
AdminAccount = "CONTOSO\Administrator"
}
@{
NodeName = "SPF01.contoso.com"
Roles = @(
"System Center Technical Preview Service Provider Foundation Database Server",
"System Center Technical Preview Service Provider Foundation Server",
"SQL Server 2012 Management Tools"
)
SQLServers = @(
@{
Roles = @("System Center Technical Preview Service Provider Foundation Database Server")
InstanceName = "MSSQLSERVER"
}
)
}
)
}
foreach($Node in $ConfigurationData.AllNodes)
{
if($Node.NodeName -ne "*")
{
Start-Process -FilePath "robocopy.exe" -ArgumentList ("`"C:\Program Files\WindowsPowerShell\Modules`" `"\\" + $Node.NodeName + "\c$\Program Files\WindowsPowerShell\Modules`" /e /purge /xf") -NoNewWindow -Wait
}
}
SPF -ConfigurationData $ConfigurationData
Set-DscLocalConfigurationManager -Path .\SPF -Verbose
Start-DscConfiguration -Path .\SPF -Verbose -Wait -Force
| {
"content_hash": "3f32d30c599b712b5297c38f67ebb703",
"timestamp": "",
"source": "github",
"line_count": 358,
"max_line_length": 216,
"avg_line_length": 37.93296089385475,
"alnum_prop": 0.5407952871870397,
"repo_name": "phongdly/puppetlabs-dsc",
"id": "0fdd4f4018b513fcf9ddd2283056965ba434b93a",
"size": "13602",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/puppet_x/dsc_resources/xSCSPF/Examples/SCSPF-SingleServer-TP.ps1",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "902"
},
{
"name": "HTML",
"bytes": "144434"
},
{
"name": "PowerShell",
"bytes": "3820614"
},
{
"name": "Puppet",
"bytes": "446"
},
{
"name": "Ruby",
"bytes": "3782042"
},
{
"name": "Shell",
"bytes": "2778"
}
],
"symlink_target": ""
} |
module SoundGen
require 'wavefile'
SAMPLE_RATE = 44100 # Hz per second
FREQUENCY = 700.0 # Hz
CHUNK_DURATION = 120.0 # ms per dot
WAVE_FUNC = Math::PI * 2
class << self
def main(sequence)
sequence = morse_to_digits(sequence)
samples = generate_samples(sequence)
save(samples)
end
private
def generate_samples(sequence)
position_in_period = 0.0
position_in_period_delta = FREQUENCY / SAMPLE_RATE
num_samples = (SAMPLE_RATE * calculate_duration(sequence)).to_i
samples = [].fill(0.0, 0, num_samples)
num_samples.times do |i|
# interpolate position of current sample to position in sequence
sequence_index = (sequence.length.to_f * i / num_samples).round
samples[i] = Math::sin(position_in_period * WAVE_FUNC) * (sequence[sequence_index]).to_i
position_in_period += position_in_period_delta
if (position_in_period >= 1.0)
position_in_period -= 1.0
end
end
samples
end
def save(samples = [])
bs_format = WaveFile::Format.new(:mono, :float, SAMPLE_RATE)
buffer = WaveFile::Buffer.new(samples, bs_format)
f_name = "morse-sound-#{Time.now.to_i}.wav"
ws_format = WaveFile::Format.new(:mono, :pcm_16, SAMPLE_RATE)
WaveFile::Writer.new(f_name, ws_format) { |writer| writer.write(buffer) }
end
def morse_to_digits(sequence)
sequence.gsub!('-', '11110')
sequence.gsub!('.', '10')
sequence.gsub!(' ', '00000')
sequence
end
def calculate_duration(sequence)
(sequence.length * CHUNK_DURATION / 1000)
end
end
end
| {
"content_hash": "822ecf19556b01d42e4a192bbff55c90",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 96,
"avg_line_length": 23.65714285714286,
"alnum_prop": 0.6141304347826086,
"repo_name": "lochnessathome/morse",
"id": "d48dcd723187b01801f1ade3cf9e95c6974a774b",
"size": "1656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sound_gen.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3953"
}
],
"symlink_target": ""
} |
"""Coordinator for metrics of various targets in evaluation."""
import collections
import os
from typing import List, Mapping, Optional, Tuple, Type
from absl import logging
import dataclasses
from ehr_prediction_modeling.eval import metrics_data
import numpy as np
import tensorflow.compat.v1 as tf
@dataclasses.dataclass(frozen=True)
class MetricsTarget(object):
"""Describes a target metrics will be computed for."""
target_name: str
split_name: str
mask_name: Optional[str] = None
def to_string(self) -> str:
"""Returns a string description of this target."""
return (f"Target: {self.target_name}, Split: {self.split_name}, Mask: "
f"{self.mask_name}")
class MetricsCoordinator(object):
"""Base class for accumulating data used to calculate metrics."""
def __init__(self):
"""Initializes metrics coordinator."""
self._data_dict = {}
def add_data(self,
metrics_data_type: Type[metrics_data.MetricsTypes],
data: Tuple[float],
target_name: str,
split_name: str,
mask_name: Optional[str] = None):
"""Extends object's lists of data.
Args:
metrics_data_type: The subclass of MetricsData that will be used to store
this data.
data: A batch of data to add. Tuple should contain data listed in the
order required by the relevant MetricsData add_data method. For example,
For RegressionMetricsData, data should be (predictions, targets,
weights).
target_name: Name of the target the data descibes.
split_name: Name of the split the data is from.
mask_name: Name of the mask used with the data given.
Raises:
ValueError if the data given is found invalid by the MetricsData class.
"""
metrics_target = MetricsTarget(target_name, split_name, mask_name)
if metrics_target not in self._data_dict:
self._data_dict[metrics_target] = metrics_data_type()
self._data_dict[metrics_target].add_data(*data)
def _clear_data(self):
"""Clears any data in _data_dict."""
self._data_dict = {}
def log_metrics(self, current_step: int, clear_data: bool = False) -> None:
"""Logs all metrics, then may clear stored metrics data.
Args:
current_step: Current step we are evaluating.
clear_data: If true, all stored data will be cleared.
"""
for metrics_target, data in self._data_dict.items():
data.log_metrics(metrics_target.to_string(), current_step)
if clear_data:
# Clear any data after it is logged.
self._clear_data()
def add_batch_to_binary_metrics_data(metrics_coordinator, target_names,
predictions, binary_targets,
eval_mask_dict, split_name):
"""Adds binary tasks predictions to BinaryMetricsData objects.
Args:
metrics_coordinator: MetricsCoordinator, used to accumulate metrics for each
target.
target_names: list of str, the names of the targets in the task.
predictions: array of predictions in time-major shape wnct [num_unroll,
batch_size, channels, num_targets].
binary_targets: array of binary targets in time-major shape wnct [
num_unroll, batch_size, channels, num_targets].
eval_mask_dict: dict of string mask name to array, the loss masks to be used
in evaluation, in time-major shape wnct [num_unroll, batch_size, channels,
num_targets].
split_name: str, name of the data split this batch is from.
"""
num_targets = len(target_names)
# Split predictions by target into a list of length num_targets.
predictions_per_target = np.split(
predictions, indices_or_sections=num_targets, axis=3)
for mask_name, mask in eval_mask_dict.items():
positive_filter_and_mask = (mask * binary_targets).astype(bool)
negative_filter_and_mask = (
mask * (np.ones_like(binary_targets) - binary_targets)).astype(bool)
positive_masks_per_target = np.split(
positive_filter_and_mask, indices_or_sections=num_targets, axis=3)
negative_masks_per_target = np.split(
negative_filter_and_mask, indices_or_sections=num_targets, axis=3)
for idx, target_name in enumerate(target_names):
positives = predictions_per_target[idx][positive_masks_per_target[idx]]
positive_weights = np.ones_like(positives)
negatives = predictions_per_target[idx][negative_masks_per_target[idx]]
negative_weights = np.ones_like(negatives)
metrics_coordinator.add_data(
metrics_data.BinaryMetricsData,
(positives, negatives, positive_weights, negative_weights),
target_name,
split_name,
mask_name=mask_name)
def add_batch_to_regression_metrics_data(metrics_coordinator, target_names,
predictions, targets, eval_mask_dict,
split_name):
"""Adds regression tasks predictions to RegressionMetricsData objects.
Args:
metrics_coordinator: MetricsCoordinator, used to accumulate metrics for each
target.
target_names: list of str, the names of the targets in the task.
predictions: array of predictions in time-major shape wnct [num_unroll,
batch_size, channels, num_targets].
targets: array of float targets in time-major shape wnct [ num_unroll,
batch_size, channels, num_targets].
eval_mask_dict: dict of string mask name to array, the loss masks to be used
in evaluation, in time-major shape wnct [num_unroll, batch_size, channels,
num_targets].
split_name: str, name of the data split this batch is from.
"""
num_targets = len(target_names)
predictions_per_target = np.split(
predictions, indices_or_sections=num_targets, axis=3)
target_list = np.split(
targets, indices_or_sections=num_targets, axis=3)
for mask_name, mask in eval_mask_dict.items():
masks_per_target = np.split(
mask, indices_or_sections=num_targets, axis=3)
for idx, target_name in enumerate(target_names):
predictions = predictions_per_target[idx][masks_per_target[idx].astype(
bool)]
targets = target_list[idx][masks_per_target[idx].astype(bool)]
weights = np.ones_like(predictions)
metrics_coordinator.add_data(
metrics_data.RegressionMetricsData, (predictions, targets, weights),
target_name,
split_name,
mask_name=mask_name)
| {
"content_hash": "c62ff2af93fb7c4523a81e896d3f9b44",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 80,
"avg_line_length": 39.70552147239264,
"alnum_prop": 0.6699629171817059,
"repo_name": "google/ehr-predictions",
"id": "992aca5f808ab0d5db7f4b7a08610648ec6a3648",
"size": "7094",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "ehr_prediction_modeling/eval/metrics_coordinator.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "7231"
},
{
"name": "Python",
"bytes": "357547"
}
],
"symlink_target": ""
} |
import React, {Component} from 'react';
import './layer.less';
import img_src from '../../images/temp/logo1.png';
class Layer extends Component {
render() {
return (
<div className="layer">
<div > this is the layer content </div>
<a> this is a link </a>
<div className="image-css"> image </div>
<br/>
<img src={img_src} />
</div>
);
}
}
export default Layer; | {
"content_hash": "c21f4ca3bb9f909022139144b8926553",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 50,
"avg_line_length": 19.65,
"alnum_prop": 0.6005089058524173,
"repo_name": "mozhengFly/test",
"id": "77c146263d3471396dbd5a3eb168b9b54cc207e9",
"size": "427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "my-react-webpack/src/components/layer/layer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16342"
},
{
"name": "HTML",
"bytes": "2893"
},
{
"name": "Java",
"bytes": "25370"
},
{
"name": "JavaScript",
"bytes": "61272"
}
],
"symlink_target": ""
} |
from . import *
from .core import ReadyForObject, ReadyForConnection
from cached_property import cached_property
from .errors import UserNoIDException
class User(ReadyForObject):
def __init__(self, user_id=None, user_url=None, backed_at=None, name=None):
if user_id is None and user_url is None:
raise ValueError('no one of argument which must be supplied')
elif user_id is not None:
self.__id = user_id
self.user_url = None
elif user_url is not None:
self.user_url = user_url
self.__id = None
# This property activate when this user is gotten from comment page of project.
self.backed_at = backed_at
self.setted_name = name
@cached_property
def from_user_page(self):
user_identifier = ""
if self.__id == "NoID":
raise UserNoIDException("User id が NoID のときはUserページの情報を取りに行かないで下さい")
if self.__id is not None:
user_identifier = self.__id
elif self.user_url is not None:
user_identifier = self.user_url.split("/")[4]
response = ReadyForConnection.call(objects_kind="users", object_id=user_identifier, param=None, method="GET")
return html_parser.UserPageParser(response.text).parse()
@cached_property
def _id(self):
if self.__id is not None:
return self.__id
elif self.user_url is not None:
return self.user_url.split("/")[4]
@property
def name(self):
if self.setted_name is not None:
return self.setted_name
else:
return self.from_user_page["name"]
@property
def url(self):
if self.user_url is not None:
return self.user_url
else:
return "{domain}/{users}/{id}".format(
domain="https://readyfor.jp",
users="users",
id=self.id
)
@property
def biography(self):
return self.from_user_page["biography"]
@property
def sns_links(self):
return self.from_user_page["sns_links"]
| {
"content_hash": "822b4dd628e516b540e9b6a1bac7d9f9",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 117,
"avg_line_length": 33.0625,
"alnum_prop": 0.5888468809073724,
"repo_name": "TOSUKUi/readyfor-api",
"id": "15aa074c5070d7792d7d96f83af97fe17c447450",
"size": "2190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "readyforapi/user.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "700290"
},
{
"name": "Python",
"bytes": "98376"
}
],
"symlink_target": ""
} |
package com.gemstone.gemfire.admin;
/**
* Provides configuration information relating to the health of an
* entire GemFire distributed system.
*
* <P>
*
* If any of the following criteria is
* true, then the distributed system is considered to be in
* {@link GemFireHealth#OKAY_HEALTH OKAY_HEALTH}.
*
* <UL>
*
* </UL>
*
* If any of the following criteria is true, then the distributed
* system is considered to be in {@link GemFireHealth#POOR_HEALTH
* POOR_HEALTH}.
*
* <UL>
*
* <LI>Too many application members {@linkplain
* #getMaxDepartedApplications unexpectedly leave} the distributed
* system.</LI>
*
* <LI>Too many application members {@linkplain
* #getMaxDepartedApplications unexpectedly leave} the distributed
* system.</LI>
*
* </UL>
*
* @author David Whitlock
*
* @since 3.5
* @deprecated as of 7.0 use the {@link com.gemstone.gemfire.management} package instead
* */
public interface DistributedSystemHealthConfig {
/** The default maximum number of application members that can
* unexceptedly leave a healthy the distributed system. */
public static final long DEFAULT_MAX_DEPARTED_APPLICATIONS = 10;
/////////////////////// Instance Methods ///////////////////////
/**
* Returns the maximum number of application members that can
* unexceptedly leave a healthy the distributed system.
*
* @see #DEFAULT_MAX_DEPARTED_APPLICATIONS
*/
public long getMaxDepartedApplications();
/**
* Sets the maximum number of application members that can
* unexceptedly leave a healthy the distributed system.
*
* @see #getMaxDepartedApplications
*/
public void setMaxDepartedApplications(long maxDepartedApplications);
}
| {
"content_hash": "23794cb30603c88e97e6236cafb3bbc5",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 88,
"avg_line_length": 27.532258064516128,
"alnum_prop": 0.7024018746338606,
"repo_name": "sshcherbakov/incubator-geode",
"id": "3f671dd269b42e6ce4226c9b53495c99f6d7c1c0",
"size": "2509",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "gemfire-core/src/main/java/com/gemstone/gemfire/admin/DistributedSystemHealthConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1741"
},
{
"name": "CSS",
"bytes": "54202"
},
{
"name": "Groovy",
"bytes": "4066"
},
{
"name": "HTML",
"bytes": "124114"
},
{
"name": "Java",
"bytes": "26687060"
},
{
"name": "JavaScript",
"bytes": "315581"
},
{
"name": "Scala",
"bytes": "237708"
},
{
"name": "Shell",
"bytes": "11132"
}
],
"symlink_target": ""
} |
/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { action } from '@storybook/addon-actions';
import cloneDeep from 'lodash/cloneDeep';
import List from './List.component';
import { columnChooserService } from './Toolbar/ColumnChooserButton';
function MyCustomRow(props) {
return (
<div style={props.style}>
<h1 style={{ fontSize: 16 }}>{props.parent.props.collection[props.index].name}</h1>
<ul>
<li>style: {JSON.stringify(props.style)}</li>
<li>index: {props.index}</li>
<li>isScrolling: {props.isScrolling.toString()}</li>
</ul>
</div>
);
}
// eslint-disable-next-line react/prop-types
function ListColumnChooser({ list, ...rest }) {
const [columnsChooser, setColumnsChooser] = useState(list.columns);
const onSubmit = (_, newColumnsChooser) => {
setColumnsChooser(newColumnsChooser);
};
const enrichedList = {
...list,
columns: columnChooserService.mergeWithColumnChooserCollection(list.columns, columnsChooser),
};
const columnChooser = {
columns: columnsChooser,
onSubmit,
nbLockedLeftItems: 2,
};
return <List {...rest} list={enrichedList} columnChooser={columnChooser} />;
}
/**
* Cell renderer that displays hello + text
*/
function CellWithHello({ cellData }) {
return <div>hello {cellData} !</div>;
}
CellWithHello.displayName = 'VirtualizedList(CellWithHello)';
CellWithHello.propTypes = {
cellData: PropTypes.string,
};
const selected = [
{
id: 2,
name: 'Foo',
created: '2016-09-22',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-json-o',
},
];
const overlayAction = {
id: 'overlay-button',
overlayId: 'overlay',
label: 'overlay',
icon: 'talend-pencil',
onClick: action('overlay.open'),
overlayComponent: <div>Overlay</div>,
overlayPlacement: 'bottom',
preventScrolling: true,
};
const actions = [
{
id: 'edit',
label: 'edit',
icon: 'talend-pencil',
onClick: action('onEdit'),
},
{
id: 'delete',
label: 'delete',
icon: 'talend-trash',
onClick: action('onDelete'),
},
{
id: 'related',
displayMode: 'dropdown',
label: 'related items',
icon: 'talend-folder',
items: [
{
label: 'document 1',
onClick: action('document 1 click'),
},
{
label: 'document 2',
onClick: action('document 2 click'),
},
],
pullRight: true,
},
];
const lotsOfActions = [
{
id: 'edit',
label: 'edit',
icon: 'talend-pencil',
onClick: action('onEdit'),
},
{
id: 'delete',
label: 'delete',
icon: 'talend-trash',
onClick: action('onDelete'),
},
{
id: 'copy',
label: 'copy',
icon: 'talend-files-o',
onClick: action('onCopy'),
},
{
id: 'parameters',
label: 'efit parameters',
icon: 'talend-cog',
onClick: action('onEditParameters'),
},
{
id: 'related',
displayMode: 'dropdown',
label: 'related items',
icon: 'talend-folder',
items: [
{
label: 'document 1',
onClick: action('document 1 click'),
},
{
label: 'document 2',
onClick: action('document 2 click'),
},
],
pullRight: true,
},
];
const persistentActions = [
{
id: 'edit',
label: 'edit',
icon: 'talend-apache',
onClick: action('onEdit'),
},
];
const props = {
id: 'talend',
displayMode: 'table',
list: {
columns: [
{ key: 'id', label: 'Id', order: 1 },
{ key: 'name', label: 'Name', order: 2 },
{ key: 'author', label: 'Author', order: 3 },
{ key: 'created', label: 'Created', order: 6 },
{
key: 'modified',
label: 'Modified',
order: 4,
header: 'icon',
data: { iconName: 'talend-scheduler' },
},
{ key: 'icon', label: 'Icon', hidden: true, order: 5 },
],
items: [
{
id: 0,
name: 'Title with actions',
created: '2016-09-22',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-s3-o',
display: 'text',
className: 'item-0-class',
},
{
id: 1,
name: 'Title with a lot of actions',
created: '2016-09-22',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
actions: lotsOfActions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-1-class',
},
{
id: 2,
name:
'Title with super super super super super super super super super super super super super super super super super super super super super super super super super super super super super super long title oh yeah',
created: '2016-09-22',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-1-class',
},
{
id: 3,
name: 'Title in input mode',
created: '2016-09-22',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-json-o',
display: 'input',
className: 'item-2-class',
},
{
persistentActions,
id: 4,
name: 'Super long title to trigger overflow on tile rendering',
created: '2016-09-22',
modified: '2016-09-22',
author:
'Jean-Pierre DUPONT with super super super super super super super super super super super super super super super super super super super super super super super long name, but there was not enough long text',
className: 'item-3-class',
},
],
titleProps: {
key: 'name',
iconKey: 'icon',
displayModeKey: 'display',
onClick: action('onTitleClick'),
onEditCancel: action('onEditCancel'),
onEditSubmit: action('onEditSubmit'),
},
itemProps: {
classNameKey: 'className',
},
},
toolbar: {
actionBar: {
actions: {
left: [
{
id: 'add',
label: 'Add Folder',
bsStyle: 'info',
icon: 'talend-plus-circle',
onClick: action('add.onClick'),
},
{
displayMode: 'splitDropdown',
label: 'Add File',
icon: 'talend-folder',
onClick: action('onAdd'),
items: [
{
label: 'From Local',
onClick: action('From Local click'),
},
{
label: 'From Remote',
onClick: action('From Remote click'),
},
],
emptyDropdownLabel: 'No option',
},
],
},
},
display: {
onChange: action('display.onChange'),
},
sort: {
field: 'name',
onChange: action('sort.onChange'),
options: [
{ id: 'id', name: 'Id' },
{ id: 'name', name: 'Name With Multiple Words' },
],
},
filter: {
docked: true,
onBlur: action('filter.onBlur'),
onClear: action('filter.onClear'),
onFocus: action('filter.onFocus'),
onFilter: action('filter.onFilter'),
onToggle: action('filter.onToggle'),
placeholder: 'search for something',
},
},
};
const referenceDatetime = Date.now();
const minusThreeHours = referenceDatetime - 3600 * 3 * 1000;
const minusTwoHours = referenceDatetime - 3600 * 2 * 1000;
const minusOneHours = referenceDatetime - 3600 * 1 * 1000;
const minusThreeMin = referenceDatetime - 60 * 3 * 1000;
const propsWithVirtualized = {
id: 'talend',
displayMode: 'table',
virtualized: true,
list: {
columns: [
{ key: 'id', label: 'Id' },
{ key: 'name', label: 'Name' },
{ key: 'author', label: 'Author' },
{
key: 'created',
label: 'Created',
type: 'datetime',
data: { mode: 'format', pattern: 'HH:mm:ss YYYY-MM-DD' },
},
{
key: 'modified',
label: 'Modified',
type: 'datetime',
data: { mode: 'ago' },
},
],
items: [
{
id: 0,
name: 'Title with actions',
created: 1518596913333,
modified: minusThreeHours,
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-0-class',
},
{
persistentActions,
id: 1,
name: 'Title in input mode',
created: 1518596913333,
modified: minusTwoHours,
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-json-o',
display: 'input',
className: 'item-1-class',
},
{
persistentActions,
id: 2,
name: 'Super long title to trigger overflow on tile rendering',
created: 1518596913333,
modified: minusOneHours,
author: 'Jean-Pierre DUPONT',
className: 'item-2-class',
},
{
persistentActions,
id: 3,
name: 'Title',
created: 1518596913333,
modified: minusThreeMin,
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-3-class',
},
{
persistentActions,
id: 4,
name: 'Item with no created and modified dates',
created: '',
modified: '',
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-4-class',
},
{
persistentActions,
id: 5,
name: 'Item with invalid created and modified dates',
created: 'not parsable date',
modified: 'not parsable date',
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-5-class',
},
],
titleProps: {
key: 'name',
iconKey: 'icon',
displayModeKey: 'display',
onClick: action('onTitleClick'),
onEditCancel: action('onEditCancel'),
onEditSubmit: action('onEditSubmit'),
},
itemProps: {
classNameKey: 'className',
},
},
};
const propsWithResizable = {
id: 'talend',
displayMode: 'table',
virtualized: true,
list: {
columns: [
{ key: 'id', label: 'Id', width: 85 },
{ key: 'name', label: 'Name', width: 600, resizable: true, header: 'resizable' },
{ key: 'author', label: 'Author', width: 600, resizable: true, header: 'resizable' },
{
key: 'modified',
label: 'Modified',
type: 'datetime',
data: { mode: 'ago' },
width: 135,
resizable: true,
},
],
items: [
{
id: 0,
name: 'Title with actions',
created: 1518596913333,
modified: minusThreeHours,
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-0-class',
},
{
persistentActions,
id: 1,
name: 'Title in input mode',
created: 1518596913333,
modified: minusTwoHours,
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-json-o',
display: 'input',
className: 'item-1-class',
},
{
persistentActions,
id: 2,
name: 'Super long title to trigger overflow on tile rendering',
created: 1518596913333,
modified: minusOneHours,
author: 'Jean-Pierre DUPONT',
className: 'item-2-class',
},
{
persistentActions,
id: 3,
name: 'Title',
created: 1518596913333,
modified: minusThreeMin,
author: 'Jean-Pierre DUPONT',
actions,
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-3-class',
},
],
titleProps: {
key: 'name',
iconKey: 'icon',
displayModeKey: 'display',
onClick: action('onTitleClick'),
onEditCancel: action('onEditCancel'),
onEditSubmit: action('onEditSubmit'),
},
itemProps: {
classNameKey: 'className',
},
},
};
const itemPropsForItems = {
classNameKey: 'className',
onOpen: action('onItemOpen'),
onSelect: action('onItemSelect'),
onToggle: action('onItemToggle'),
onToggleAll: action('onToggleAll'),
isSelected: item => !!selected.find(next => next.id === item.id),
onCancel: action('onTitleEditCancel'),
onChange: action('onTitleChange'),
onSubmit: action('onTitleEditSubmit'),
};
const sort = {
field: 'modified',
isDescending: false,
onChange: action('sort.onChange'),
};
function getActionsProps() {
const columnActionsProps = cloneDeep(props);
const actionsColumn = {
key: 'columnActions',
label: 'Actions', // label should be set for screen readers
hideHeader: true, // header will created with a sr-only class, so it will be hidden
};
columnActionsProps.list.columns.splice(2, 0, actionsColumn);
columnActionsProps.list.items = columnActionsProps.list.items.map((item, index) => ({
columnActions: [
{
id: `favorite-action-${index}`,
label: 'favorite',
icon: 'talend-star',
className: 'favorite',
onClick: action('onFavorite'),
},
{
id: `certify-action-${index}`,
label: 'certify',
icon: 'talend-badge',
className: 'certify',
onClick: action('onCertify'),
},
],
...item,
}));
return columnActionsProps;
}
const okIcon = {
label: 'OK!',
icon: 'talend-star',
onClick: () => {},
};
const warningIcon = {
label: 'Oh no!',
icon: 'talend-warning',
onClick: () => {},
};
const getIcon = item => {
switch (item.cat) {
case 'fluffy':
return okIcon;
case 'fat':
return warningIcon;
default:
return null;
}
};
const itemsForListWithIcons = [
{
id: 0,
name: 'Title 1',
status: 'ok',
cat: 'fluffy',
},
{
id: 1,
name: 'Title 2',
status: 'warning',
cat: 'fat',
},
{
id: 2,
name: 'Title 3',
status: 'random',
cat: 'regular',
},
];
const ListTemplate = args => {
const [propsMemo, setState] = React.useState(args.listProps);
const { patch, listProps } = args;
React.useEffect(() => {
if (patch && listProps) {
setState(patch(listProps));
}
}, [patch, listProps]);
if (!propsMemo) {
return <div />;
}
return (
<div style={{ height: '70vh' }} className="virtualized-list">
<h1>List</h1>
<p>{args.message}</p>
{args.children ? args.children : <List {...propsMemo} />}
</div>
);
};
export default {
title: 'Data/List/List',
};
export const TableDisplay = () => (
<ListTemplate
message="Display the list in table mode. This is the default mode."
listProps={props}
/>
);
export const TableWithNumber = () => (
<ListTemplate
message="Display the list in table mode with the total number of items."
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.toolbar.itemsNumber = {
totalItems: customProps.list.items.length,
label: `${customProps.list.items.length} users`,
};
return customProps;
}}
/>
);
export const TableIcons = () => (
<ListTemplate
message="Display with icons in status"
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.columns = [
{ key: 'id', label: 'Id' },
{ key: 'name', label: 'Name' },
{ key: 'status', label: 'Status', type: 'texticon', data: { getIcon } },
{ key: 'cat', label: 'Cat' },
];
customProps.list.items = itemsForListWithIcons;
return customProps;
}}
/>
);
export const LargeDisplay = () => (
<ListTemplate
message="displayMode large"
listProps={props}
patch={newProps => {
return {
...newProps,
rowHeight: 140,
displayMode: 'large',
};
}}
/>
);
export const LargeArrayOfActions = () => (
<ListTemplate
message="Display the list in table mode using arrays of actions"
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
const separatorActions = [
{
id: 'monitoring',
label: 'monitor something',
'data-feature': 'list.item.monitor',
icon: 'talend-line-charts',
onClick: action('onMonitor'),
hideLabel: true,
},
];
customProps.list.items = customProps.list.items.map(item => ({
...item,
actions: [separatorActions, actions],
}));
return customProps;
}}
/>
);
export const LargeDisplayOverridesByRownRenderers = () => (
<ListTemplate
message="Display large"
listProps={props}
patch={newProps => {
return {
...newProps,
rowHeight: 116,
displayMode: 'large',
rowRenderers: { LARGE: MyCustomRow },
};
}}
/>
);
export const LargeDisplayWithIcons = () => (
<ListTemplate
message="Display large with icons"
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.columns = [
{ key: 'id', label: 'Id' },
{ key: 'name', label: 'Name' },
{ key: 'status', label: 'Status', type: 'texticon', data: { getIcon } },
{ key: 'cat', label: 'Cat' },
];
customProps.list.items = itemsForListWithIcons;
return customProps;
}}
/>
);
export const EmptyTable = () => (
<ListTemplate
message="Empty"
listProps={props}
patch={newProps => {
const emptyListProps = cloneDeep(newProps);
emptyListProps.list.items = [];
return emptyListProps;
}}
/>
);
export const EmptyLarge = () => (
<ListTemplate
message="Empty List display large"
listProps={props}
patch={newProps => {
const emptyListProps = cloneDeep(newProps);
emptyListProps.list.items = [];
emptyListProps.displayMode = 'large';
return emptyListProps;
}}
/>
);
export const EmptyListCustom = () => (
<ListTemplate
message="Empty list with custom renderer"
listProps={props}
patch={newProps => {
const customEmptyRendererListProps = cloneDeep(newProps);
customEmptyRendererListProps.list.items = [];
customEmptyRendererListProps.list.noRowsRenderer = () => (
<span className="tc-virtualizedlist-no-result" role="status" aria-live="polite">
I'm a custom NoRowsRenderer
</span>
);
return customEmptyRendererListProps;
}}
/>
);
export const ListInProgressTable = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const loadingListProps = cloneDeep(newProps);
loadingListProps.list.inProgress = true;
return loadingListProps;
}}
/>
);
export const ListInProgressLarge = () => (
<ListTemplate
message="Display large"
listProps={props}
patch={newProps => {
const loadingListProps = cloneDeep(newProps);
loadingListProps.list.inProgress = true;
loadingListProps.displayMode = 'large';
return loadingListProps;
}}
/>
);
export const ColumnActions = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={() => {
return getActionsProps();
}}
/>
);
export const Selection = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={newProps => {
const selectedItemsProps = cloneDeep(newProps);
selectedItemsProps.toolbar.actionBar = {
selected: 1,
multiSelectActions: {
left: [
{
id: 'remove',
label: 'Delete selection',
icon: 'talend-trash',
onClick: action('remove'),
},
],
},
};
selectedItemsProps.list.itemProps = itemPropsForItems;
return selectedItemsProps;
}}
/>
);
export const SelectionWithNumberOfItems = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={newProps => {
const selectedItemsProps = cloneDeep(newProps);
selectedItemsProps.toolbar.actionBar = {
selected: 1,
hideCount: true,
multiSelectActions: {
left: [
{
id: 'remove',
label: 'Delete selection',
icon: 'talend-trash',
onClick: action('remove'),
},
],
},
};
selectedItemsProps.list.itemProps = itemPropsForItems;
selectedItemsProps.toolbar.itemsNumber = {
totalItems: selectedItemsProps.list.items.length,
label: `${selectedItemsProps.list.items.length} books`,
labelSelected: `${selectedItemsProps.toolbar.actionBar.selected}/${selectedItemsProps.list.items.length} books`,
};
return selectedItemsProps;
}}
/>
);
export const SelectionLarge = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={newProps => {
const selectedItemsProps = cloneDeep(newProps);
selectedItemsProps.toolbar.actionBar.multiSelectActions = {
left: [
{
id: 'remove',
label: 'Delete selection',
icon: 'talend-trash',
onClick: action('remove'),
},
],
};
selectedItemsProps.list.itemProps = itemPropsForItems;
return selectedItemsProps;
}}
/>
);
export const Activation = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={newProps => {
const selectedItemsProps = cloneDeep(newProps);
selectedItemsProps.list.itemProps.isActive = item => item.id === 0;
selectedItemsProps.list.itemProps.onRowClick = action('onRowClick');
return selectedItemsProps;
}}
/>
);
export const NoToolbar = () => (
<ListTemplate
message="A column can contains only actions that appear on mouseover."
listProps={props}
patch={newProps => {
const tprops = cloneDeep(newProps);
tprops.toolbar = undefined;
return tprops;
}}
/>
);
export const SortList = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const tprops = cloneDeep(newProps);
// disable sort on column author
const authorColumn = tprops.list.columns.find(e => e.key === 'author');
authorColumn.disableSort = true;
tprops.list.sort = sort;
return tprops;
}}
/>
);
export const SortLargeList = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const tprops = cloneDeep(newProps);
// disable sort on column author
const authorColumn = tprops.list.columns.find(e => e.key === 'author');
authorColumn.disableSort = true;
tprops.list.sort = sort;
tprops.displayMode = 'large';
return tprops;
}}
/>
);
export const CustomCellRenderer = () => (
<ListTemplate
message="CellWithHello"
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.columns = [
{ key: 'id', label: 'Id' },
{ key: 'name', label: 'Name' },
{ key: 'status', label: 'Status', type: 'hello' },
{ key: 'cat', label: 'Cat' },
];
customProps.list.items = itemsForListWithIcons;
customProps.list.cellDictionary = { hello: { cellRenderer: CellWithHello } };
return customProps;
}}
/>
);
export const FilterDefault = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.items = [customProps.list.items[0]];
customProps.toolbar.filter.docked = false;
return customProps;
}}
/>
);
export const FilterHighlited = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.items = [customProps.list.items[0]];
customProps.toolbar.filter.docked = false;
customProps.toolbar.filter.highlight = true;
return customProps;
}}
/>
);
export const FilterDebounce = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.items = [customProps.list.items[0]];
customProps.toolbar.filter.docked = false;
customProps.toolbar.filter.debounceTimeout = 300;
return customProps;
}}
/>
);
export const TitleWithoutClick = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.titleProps.onClick = null;
return customProps;
}}
/>
);
export const HiddenHeaderLabels = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.list.columns[0].hideHeader = true;
return customProps;
}}
/>
);
export const ListCellRenderer = () => (
<ListTemplate message="datetime pattern" listProps={propsWithVirtualized} />
);
export const ListResizable = () => <ListTemplate listProps={propsWithResizable} />;
export const TableWithActionOverlay = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const items = [...Array(100)].map((_, index) => ({
id: index,
name: 'Title with actions',
created: 1518596913333,
modified: minusThreeHours,
author: 'Jean-Pierre DUPONT',
actions: [overlayAction, ...actions],
icon: 'talend-file-xls-o',
display: 'text',
className: 'item-0-class',
}));
return {
...newProps,
list: {
...props.list,
items,
},
};
}}
/>
);
export const TableWithColumnChooser = () => (
<ListTemplate listProps={{}}>
<ListColumnChooser {...props} />
</ListTemplate>
);
export const PaginationToBeDeprecated = () => (
<ListTemplate
listProps={props}
patch={newProps => {
const customProps = cloneDeep(newProps);
customProps.toolbar.pagination = {
itemsPerPage: 5,
totalResults: 10,
onChange: action('pagination.onChange'),
};
return customProps;
}}
/>
);
| {
"content_hash": "25955424b6aca2910df91f8d23713d27",
"timestamp": "",
"source": "github",
"line_count": 1055,
"max_line_length": 217,
"avg_line_length": 22.949763033175355,
"alnum_prop": 0.6292747397984471,
"repo_name": "Talend/ui",
"id": "9a1f945a8f6b0cb5864b26b0b6b41ce61846e5b7",
"size": "24212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/components/src/List/List.stories.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "809"
},
{
"name": "Groovy",
"bytes": "9150"
},
{
"name": "HTML",
"bytes": "183895"
},
{
"name": "Java",
"bytes": "338"
},
{
"name": "JavaScript",
"bytes": "4781212"
},
{
"name": "SCSS",
"bytes": "699775"
},
{
"name": "Shell",
"bytes": "62"
},
{
"name": "TypeScript",
"bytes": "1291286"
}
],
"symlink_target": ""
} |
package com.Da_Technomancer.crossroads.API.alchemy;
import javax.annotation.Nullable;
import com.Da_Technomancer.crossroads.API.magic.MagicUnit;
public interface IElementReagent extends IReagent{
public MagicUnit getAlignment();
/**
* 0: Primary
* 1: Secondary
* 2: Tertiary
*/
public byte getLevel();
@Nullable
public IElementReagent getSecondaryBase();
}
| {
"content_hash": "88e21524d0668dffc411aaf343b503de",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 58,
"avg_line_length": 18.095238095238095,
"alnum_prop": 0.75,
"repo_name": "Da-Technomancer/Crossroads",
"id": "92ec9ab69eac6af4f7e4e0f804dd00c5af348320",
"size": "380",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.12-Schism",
"path": "src/main/java/com/Da_Technomancer/crossroads/API/alchemy/IElementReagent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2072999"
}
],
"symlink_target": ""
} |
local config = require("lapis.config")
config({"development", "production"}, {
port = 3176,
secret = require('secret'),
mysql = {
backend = "resty_mysql", -- or luasql
host = "127.0.0.1",
user = "wordpress",
password = "wordpress",
database = "wordpress",
}
})
config("production", {
code_cache = 'on',
logging = {queries = false, requests = false},
})
| {
"content_hash": "be9a78e06b45008eb7ddc6054297eb7c",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 50,
"avg_line_length": 21.72222222222222,
"alnum_prop": 0.5856777493606138,
"repo_name": "starius/wordpress-lapis",
"id": "9f12f293c15e1ded1e13d1077511dae45de95537",
"size": "391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/config.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "13629"
},
{
"name": "Makefile",
"bytes": "23"
},
{
"name": "MoonScript",
"bytes": "5867"
},
{
"name": "Nginx",
"bytes": "504"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_27) on Fri Mar 28 15:13:22 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Deprecated List (guacamole-common 0.9.0 API)</title>
<meta name="date" content="2014-03-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Deprecated List (guacamole-common 0.9.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">FRAMES</a></li>
<li><a href="deprecated-list.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">FRAMES</a></li>
<li><a href="deprecated-list.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014. All Rights Reserved.</small></p>
<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-75289145-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
</body>
</html>
| {
"content_hash": "cfc0eb45d779a6aaa40102e548159429",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 102,
"avg_line_length": 30.76923076923077,
"alnum_prop": 0.63125,
"repo_name": "mike-jumper/incubator-guacamole-website",
"id": "0a1941208da3bf9f444e3a8a47efb88437d96137",
"size": "4000",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/0.9.0/guacamole-common/deprecated-list.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12886"
},
{
"name": "HTML",
"bytes": "37702"
},
{
"name": "JavaScript",
"bytes": "439018"
},
{
"name": "Perl",
"bytes": "2217"
},
{
"name": "Ruby",
"bytes": "660"
},
{
"name": "Shell",
"bytes": "4849"
}
],
"symlink_target": ""
} |
// SERVER-10927
// This is to make sure that temp collections get cleaned up on promotion to primary
var replTest = new ReplSetTest({name: 'testSet', nodes: 3});
var nodes = replTest.nodeList();
printjson(nodes);
// We need an arbiter to ensure that the primary doesn't step down when we restart the secondary
replTest.startSet();
replTest.initiate({
"_id": "testSet",
"members": [
{"_id": 0, "host": nodes[0]},
{"_id": 1, "host": nodes[1]},
{"_id": 2, "host": nodes[2], "arbiterOnly": true}
]
});
var master = replTest.getPrimary();
var second = replTest.getSecondary();
var masterId = replTest.getNodeId(master);
var secondId = replTest.getNodeId(second);
var masterDB = master.getDB('test');
var secondDB = second.getDB('test');
// set up collections
masterDB.runCommand({create: 'temp1', temp: true});
masterDB.temp1.ensureIndex({x: 1});
masterDB.runCommand({create: 'temp2', temp: 1});
masterDB.temp2.ensureIndex({x: 1});
masterDB.runCommand({create: 'keep1', temp: false});
masterDB.runCommand({create: 'keep2', temp: 0});
masterDB.runCommand({create: 'keep3'});
assert.writeOK(masterDB.keep4.insert({}, {writeConcern: {w: 2}}));
// make sure they exist on primary and secondary
function countCollection(mydb, nameFilter) {
var result = mydb.runCommand("listCollections", {filter: {name: nameFilter}});
assert.commandWorked(result);
return new DBCommandCursor(mydb.getMongo(), result).itcount();
}
function countIndexesFor(mydb, nameFilter) {
var result = mydb.runCommand("listCollections", {filter: {name: nameFilter}});
assert.commandWorked(result);
var arr = new DBCommandCursor(mydb.getMongo(), result).toArray();
var total = 0;
for (var i = 0; i < arr.length; i++) {
var coll = arr[i];
total += mydb.getCollection(coll.name).getIndexes().length;
}
return total;
}
assert.eq(countCollection(masterDB, /temp\d$/), 2); // collections
assert.eq(countIndexesFor(masterDB, /temp\d$/), 4); // indexes (2 _id + 2 x)
assert.eq(countCollection(masterDB, /keep\d$/), 4);
assert.eq(countCollection(secondDB, /temp\d$/), 2); // collections
assert.eq(countIndexesFor(secondDB, /temp\d$/), 4); // indexes (2 _id + 2 x)
assert.eq(countCollection(secondDB, /keep\d$/), 4);
// restart secondary and reconnect
replTest.restart(secondId, {}, /*wait=*/true);
// wait for the secondary to achieve secondary status
assert.soon(function() {
try {
res = second.getDB("admin").runCommand({replSetGetStatus: 1});
return res.myState == 2;
} catch (e) {
return false;
}
}, "took more than a minute for the secondary to become secondary again", 60 * 1000);
// make sure restarting secondary didn't drop collections
assert.eq(countCollection(secondDB, /temp\d$/), 2); // collections
assert.eq(countIndexesFor(secondDB, /temp\d$/), 4); // indexes (2 _id + 2 x)
assert.eq(countCollection(secondDB, /keep\d$/), 4);
// step down primary and make sure former secondary (now primary) drops collections
try {
master.adminCommand({replSetStepDown: 50, force: true});
} catch (e) {
// ignoring socket errors since they sometimes, but not always, fire after running that command.
}
assert.soon(function() {
return secondDB.isMaster().ismaster;
}, '', 75 * 1000); // must wait for secondary to be willing to promote self
assert.eq(countCollection(secondDB, /temp\d$/), 0); // collections
assert.eq(countIndexesFor(secondDB, /temp\d$/), 0); // indexes (2 _id + 2 x)
assert.eq(countCollection(secondDB, /keep\d$/), 4);
// check that former primary dropped collections
replTest.awaitReplication();
assert.eq(countCollection(masterDB, /temp\d$/), 0); // collections
assert.eq(countIndexesFor(masterDB, /temp\d$/), 0); // indexes (2 _id + 2 x)
assert.eq(countCollection(masterDB, /keep\d$/), 4);
replTest.stopSet();
| {
"content_hash": "2eb0a8eec634164f57906ce71cf8da8a",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 100,
"avg_line_length": 37.00961538461539,
"alnum_prop": 0.6822551312029098,
"repo_name": "christkv/mongo-shell",
"id": "ccf566add021b62c3d7a41b77b434f1df0ee2ebf",
"size": "3849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/jstests/replsets/temp_namespace.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "392"
},
{
"name": "JavaScript",
"bytes": "6633558"
},
{
"name": "Makefile",
"bytes": "422"
}
],
"symlink_target": ""
} |
package org.apache.spark.shuffle.hash
import org.apache.spark._
import org.apache.spark.shuffle._
/**
* Hash Shuffle适合中小型规模的数据计算
* A ShuffleManager using hashing, that creates one output file per reduce partition on each
* mapper (possibly reusing these across waves of tasks).
* 一个ShuffleManager使用哈希,每个mapper上的reduce分区创建一个输出文件(可能会重复使用这些跨越任务)
*/
private[spark] class HashShuffleManager(conf: SparkConf) extends ShuffleManager {
private val fileShuffleBlockResolver = new FileShuffleBlockResolver(conf)
/* Register a shuffle with the manager and obtain a handle for it to pass to tasks.
* 与manager注册一个shuffle,并获得一个句柄来传递给任务*/
override def registerShuffle[K, V, C](
shuffleId: Int,
numMaps: Int,
dependency: ShuffleDependency[K, V, C]): ShuffleHandle = {
new BaseShuffleHandle(shuffleId, numMaps, dependency)
}
/**
* Get a reader for a range of reduce partitions (startPartition to endPartition-1, inclusive).
* Called on executors by reduce tasks.
* 获取一系列读取减少分区(startPartition到endPartition-1包括)通过reduce任务指定执行程序
*/
override def getReader[K, C](
handle: ShuffleHandle,
startPartition: Int,
endPartition: Int,
context: TaskContext): ShuffleReader[K, C] = {
new HashShuffleReader(
handle.asInstanceOf[BaseShuffleHandle[K, _, C]], startPartition, endPartition, context)
}
/** Get a writer for a given partition. Called on executors by map tasks.
* 获取一个给定写的分区,通过Map任务调用执行器,mapId对应RDD的partionsID*/
override def getWriter[K, V](handle: ShuffleHandle, mapId: Int, context: TaskContext)
: ShuffleWriter[K, V] = {
new HashShuffleWriter(//mapId对应RDD的partionsID
shuffleBlockResolver, handle.asInstanceOf[BaseShuffleHandle[K, V, _]], mapId, context)
}
/** Remove a shuffle's metadata from the ShuffleManager.
* 从ShuffleManager中删除shuffle的元数据 */
override def unregisterShuffle(shuffleId: Int): Boolean = {
shuffleBlockResolver.removeShuffle(shuffleId)
}
override def shuffleBlockResolver: FileShuffleBlockResolver = {
fileShuffleBlockResolver
}
/** Shut down this ShuffleManager.
* 关闭这个ShuffleManager*/
override def stop(): Unit = {
shuffleBlockResolver.stop()
}
}
| {
"content_hash": "52de8354c25e889de619cb2c7c1a957e",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 97,
"avg_line_length": 34.546875,
"alnum_prop": 0.7354138398914518,
"repo_name": "tophua/spark1.52",
"id": "c35792f38003a0314080ca631d7eed84226af33d",
"size": "3259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/scala/org/apache/spark/shuffle/hash/HashShuffleManager.scala",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "26914"
},
{
"name": "C",
"bytes": "1493"
},
{
"name": "CSS",
"bytes": "15314"
},
{
"name": "Dockerfile",
"bytes": "4597"
},
{
"name": "HiveQL",
"bytes": "2018996"
},
{
"name": "Java",
"bytes": "1763581"
},
{
"name": "JavaScript",
"bytes": "68648"
},
{
"name": "Makefile",
"bytes": "7771"
},
{
"name": "Python",
"bytes": "1552537"
},
{
"name": "R",
"bytes": "452786"
},
{
"name": "Roff",
"bytes": "23131"
},
{
"name": "SQLPL",
"bytes": "3603"
},
{
"name": "Scala",
"bytes": "16031983"
},
{
"name": "Shell",
"bytes": "147300"
},
{
"name": "Thrift",
"bytes": "2016"
},
{
"name": "q",
"bytes": "154646"
}
],
"symlink_target": ""
} |
<?php
namespace PhpUnitsOfMeasure\PhysicalQuantity;
use PhpUnitsOfMeasure\AbstractPhysicalQuantity;
use PhpUnitsOfMeasure\UnitOfMeasure;
class Area extends AbstractPhysicalQuantity
{
protected static $unitDefinitions;
protected static function initialize()
{
// Meters squared
$metersquared = UnitOfMeasure::nativeUnitFactory('m^2');
$metersquared->addAlias('m²');
$metersquared->addAlias('meter squared');
$metersquared->addAlias('square meter');
$metersquared->addAlias('square meters');
$metersquared->addAlias('meters squared');
$metersquared->addAlias('metre squared');
$metersquared->addAlias('metres squared');
static::addUnit($metersquared);
// Millimeter squared
$newUnit = UnitOfMeasure::linearUnitFactory('mm^2', 1e-6);
$newUnit->addAlias('mm²');
$newUnit->addAlias('millimeter squared');
$newUnit->addAlias('square millimeter');
$newUnit->addAlias('square millimeters');
$newUnit->addAlias('millimeters squared');
$newUnit->addAlias('millimetre squared');
$newUnit->addAlias('millimetres squared');
static::addUnit($newUnit);
// Centimeter squared
$newUnit = UnitOfMeasure::linearUnitFactory('cm^2', 1e-4);
$newUnit->addAlias('cm²');
$newUnit->addAlias('centimeter squared');
$newUnit->addAlias('square centimeter');
$newUnit->addAlias('square centimeters');
$newUnit->addAlias('centimeters squared');
$newUnit->addAlias('centimetre squared');
$newUnit->addAlias('centimetres squared');
static::addUnit($newUnit);
// Decimeter squared
$newUnit = UnitOfMeasure::linearUnitFactory('dm^2', 1e-2);
$newUnit->addAlias('dm²');
$newUnit->addAlias('decimeter squared');
$newUnit->addAlias('square decimeters');
$newUnit->addAlias('square decimeter');
$newUnit->addAlias('decimeters squared');
$newUnit->addAlias('decimetre squared');
$newUnit->addAlias('decimetres squared');
static::addUnit($newUnit);
// Kilometer squared
$newUnit = UnitOfMeasure::linearUnitFactory('km^2', 1e6);
$newUnit->addAlias('km²');
$newUnit->addAlias('kilometer squared');
$newUnit->addAlias('kilometers squared');
$newUnit->addAlias('square kilometer');
$newUnit->addAlias('square kilometers');
$newUnit->addAlias('kilometre squared');
$newUnit->addAlias('kilometres squared');
static::addUnit($newUnit);
// Foot squared
$newUnit = UnitOfMeasure::linearUnitFactory('ft^2', 9.290304e-2);
$newUnit->addAlias('ft²');
$newUnit->addAlias('foot squared');
$newUnit->addAlias('square foot');
$newUnit->addAlias('square feet');
$newUnit->addAlias('feet squared');
static::addUnit($newUnit);
// Inch squared
$newUnit = UnitOfMeasure::linearUnitFactory('in^2', 6.4516e-4);
$newUnit->addAlias('in²');
$newUnit->addAlias('inch squared');
$newUnit->addAlias('square inch');
$newUnit->addAlias('square inches');
$newUnit->addAlias('inches squared');
static::addUnit($newUnit);
// Mile squared
$newUnit = UnitOfMeasure::linearUnitFactory('mi^2', 2.589988e6);
$newUnit->addAlias('mi²');
$newUnit->addAlias('mile squared');
$newUnit->addAlias('miles squared');
$newUnit->addAlias('square mile');
$newUnit->addAlias('square miles');
static::addUnit($newUnit);
// Yard squared
$newUnit = UnitOfMeasure::linearUnitFactory('yd^2', 8.361274e-1);
$newUnit->addAlias('yd²');
$newUnit->addAlias('yard squared');
$newUnit->addAlias('yards squared');
$newUnit->addAlias('square yard');
$newUnit->addAlias('square yards');
static::addUnit($newUnit);
// Are
$newUnit = UnitOfMeasure::linearUnitFactory('a', 100);
$newUnit->addAlias('are');
$newUnit->addAlias('ares');
static::addUnit($newUnit);
// Decare
$newUnit = UnitOfMeasure::linearUnitFactory('daa', 1000);
$newUnit->addAlias('decare');
$newUnit->addAlias('decares');
static::addUnit($newUnit);
// Hectare
$newUnit = UnitOfMeasure::linearUnitFactory('ha', 10000);
$newUnit->addAlias('hectare');
$newUnit->addAlias('hectares');
static::addUnit($newUnit);
// International Acre
$newUnit = UnitOfMeasure::linearUnitFactory('ac', 4046.8564224);
$newUnit->addAlias('acre');
$newUnit->addAlias('acres');
static::addUnit($newUnit);
}
}
| {
"content_hash": "0ba2f8366a76f5e542f3d7e00a19e418",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 73,
"avg_line_length": 37.3828125,
"alnum_prop": 0.613166144200627,
"repo_name": "triplepoint/php-units-of-measure",
"id": "dfccd2466fae97892309fa64f054446b74aca7fa",
"size": "4794",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "source/PhysicalQuantity/Area.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "124465"
}
],
"symlink_target": ""
} |
set -e
echo -- Setup directories --
cargo clean
mkdir -p ../target/artifacts
echo -- Build the Docker build image --
docker build -f Dockerfile.linux-build -t pact-ffi-build .
echo -- Build the release artifacts --
docker run -t --rm --user "$(id -u)":"$(id -g)" -v $(pwd)/..:/workspace -w /workspace/pact_ffi pact-ffi-build -c 'cargo build --release'
gzip -c ../target/release/libpact_ffi.so > ../target/artifacts/libpact_ffi-linux-x86_64.so.gz
openssl dgst -sha256 -r ../target/artifacts/libpact_ffi-linux-x86_64.so.gz > ../target/artifacts/libpact_ffi-linux-x86_64.so.gz.sha256
gzip -c ../target/release/libpact_ffi.a > ../target/artifacts/libpact_ffi-linux-x86_64.a.gz
openssl dgst -sha256 -r ../target/artifacts/libpact_ffi-linux-x86_64.a.gz > ../target/artifacts/libpact_ffi-linux-x86_64.a.gz.sha256
echo -- Generate the header files --
rustup toolchain install nightly
rustup component add rustfmt --toolchain nightly
rustup run nightly cbindgen \
--config cbindgen.toml \
--crate pact_ffi \
--output include/pact.h
rustup run nightly cbindgen \
--config cbindgen-c++.toml \
--crate pact_ffi \
--output include/pact-cpp.h
cp include/*.h ../target/artifacts
echo -- Build the musl release artifacts --
sudo apt install musl-tools
rustup target add x86_64-unknown-linux-musl
cargo build --release --target=x86_64-unknown-linux-musl
gzip -c ../target/x86_64-unknown-linux-musl/release/libpact_ffi.a > ../target/artifacts/libpact_ffi-linux-x86_64-musl.a.gz
openssl dgst -sha256 -r ../target/artifacts/libpact_ffi-linux-x86_64-musl.a.gz > ../target/artifacts/libpact_ffi-linux-x86_64-musl.a.gz.sha256
echo -- Build the aarch64 release artifacts --
cargo install cross
cross build --target aarch64-unknown-linux-gnu --release
gzip -c ../target/aarch64-unknown-linux-gnu/release/libpact_ffi.so > ../target/artifacts/libpact_ffi-linux-aarch64.so.gz
openssl dgst -sha256 -r ../target/artifacts/libpact_ffi-linux-aarch64.so.gz > ../target/artifacts/libpact_ffi-linux-aarch64.so.gz.sha256
gzip -c ../target/aarch64-unknown-linux-gnu/release/libpact_ffi.a > ../target/artifacts/libpact_ffi-linux-aarch64.a.gz
openssl dgst -sha256 -r ../target/artifacts/libpact_ffi-linux-aarch64.a.gz > ../target/artifacts/libpact_ffi-linux-aarch64.a.gz.sha256
| {
"content_hash": "c04730f34420d32f42ccf29428ecc5b7",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 142,
"avg_line_length": 52.48837209302326,
"alnum_prop": 0.740363314133806,
"repo_name": "pact-foundation/pact-reference",
"id": "b62b5b265ed955321b888eeae7d5566d6dd6d6d7",
"size": "2273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rust/pact_ffi/release-linux.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "18057"
},
{
"name": "C++",
"bytes": "368"
},
{
"name": "CMake",
"bytes": "29946"
},
{
"name": "Dockerfile",
"bytes": "1503"
},
{
"name": "Groovy",
"bytes": "38073"
},
{
"name": "JavaScript",
"bytes": "6027"
},
{
"name": "M4",
"bytes": "11483"
},
{
"name": "Makefile",
"bytes": "91078"
},
{
"name": "PHP",
"bytes": "13000"
},
{
"name": "Python",
"bytes": "6359"
},
{
"name": "Ruby",
"bytes": "7696"
},
{
"name": "Rust",
"bytes": "4187515"
},
{
"name": "Shell",
"bytes": "99220"
}
],
"symlink_target": ""
} |
import collections
from supriya import CalculationRate
from supriya.ugens.PureUGen import PureUGen
class AllpassL(PureUGen):
"""
A linear interpolating allpass delay line unit generator.
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> allpass_l = supriya.ugens.AllpassL.ar(source=source)
>>> allpass_l
AllpassL.ar()
"""
### CLASS VARIABLES ###
__documentation_section__ = "Delay UGens"
_ordered_input_names = collections.OrderedDict(
[
("source", None),
("maximum_delay_time", 0.2),
("delay_time", 0.2),
("decay_time", 1.0),
]
)
_valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)
| {
"content_hash": "c5f51f35277b98b367ea678a4a10f05a",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 79,
"avg_line_length": 22.606060606060606,
"alnum_prop": 0.5884718498659517,
"repo_name": "Pulgama/supriya",
"id": "07b214eafb0cfe8cbc549c1b86600ce4679a6c48",
"size": "746",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "supriya/ugens/AllpassL.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6712"
},
{
"name": "CSS",
"bytes": "446"
},
{
"name": "HTML",
"bytes": "1083"
},
{
"name": "JavaScript",
"bytes": "6163"
},
{
"name": "Makefile",
"bytes": "6775"
},
{
"name": "Python",
"bytes": "2790612"
},
{
"name": "Shell",
"bytes": "569"
}
],
"symlink_target": ""
} |
<?php
/**
* class ResizerAction
*
* This class implements interface to connect resizer extension as certain
* controller action.
*
* @category Extensions
* @package resizer
* @author Bogdan Burim <[email protected]>
* @copyright 2013 Bogdan Burim
*/
class ResizerAction extends CAction
{
/*
* public $options
*
* Extension's configurable options
*/
public $options = array();
public function run()
{
$defaults = array(
'action_name' => Yii::app()->controller->action->id,
'cache_dir' => Yii::getPathOfAlias('webroot') . '/assets/',
'base_dir' => Yii::getPathOfAlias('webroot') . '/',
);
$settings = array_merge($defaults, $this->options);
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
defined('RSZR_DIMENSIONS_DELIMITER') or define('RSZR_DIMENSIONS_DELIMITER', 'x');
defined('RSZR_ORIGINALS_BASE_PATH') or define('RSZR_ORIGINALS_BASE_PATH', $settings['base_dir']);
defined('RSZR_CACHED_IMAGES_PATH') or define('RSZR_CACHED_IMAGES_PATH', $settings['cache_dir']);
defined('RSZR_URI_EXPLODE_DELIMITER') or define('RSZR_URI_EXPLODE_DELIMITER', $settings['action_name']);
// Include core file
require(dirname(__FILE__) . DS . 'index.php');
}
} | {
"content_hash": "592dadd23871b9cf49b23c2184905e6f",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 112,
"avg_line_length": 31.068181818181817,
"alnum_prop": 0.5940014630577908,
"repo_name": "akaidrive2014/persseleb",
"id": "d1aeb3d1365d1b62f2692f2e192ad73010741a05",
"size": "1868",
"binary": false,
"copies": "2",
"ref": "refs/heads/DEVELOPMENT",
"path": "protected/extensions/resizer/ResizerAction.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "5267"
},
{
"name": "Batchfile",
"bytes": "583"
},
{
"name": "CSS",
"bytes": "1779541"
},
{
"name": "CoffeeScript",
"bytes": "80643"
},
{
"name": "Go",
"bytes": "14150"
},
{
"name": "HTML",
"bytes": "10052036"
},
{
"name": "JavaScript",
"bytes": "6111102"
},
{
"name": "Makefile",
"bytes": "2203"
},
{
"name": "PHP",
"bytes": "4466748"
},
{
"name": "Python",
"bytes": "11688"
},
{
"name": "Ruby",
"bytes": "198"
},
{
"name": "Shell",
"bytes": "3690"
}
],
"symlink_target": ""
} |
@interface FeedTableViewCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UIImageView *imgViewFeed;
@property (nonatomic, strong) IBOutlet UILabel *lblTitle;
@property (nonatomic, strong) IBOutlet UILabel *lblDetail;
@end
| {
"content_hash": "9b23bdd92e0e050ac686daa080739c54",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 64,
"avg_line_length": 30.625,
"alnum_prop": 0.7755102040816326,
"repo_name": "yunas/FacebookFeeds",
"id": "8ea35da69e1dda9a86ac6fe5f96654d2b10c2c8b",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MySocialFeeds/CustomCells/FeedTableViewCell/FeedTableViewCell.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5002"
},
{
"name": "Objective-C",
"bytes": "517691"
}
],
"symlink_target": ""
} |
package examples;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.FileSystem;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.parsetools.JsonParser;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.WriteStream;
import io.vertx.ext.auth.authentication.TokenCredentials;
import io.vertx.ext.auth.authentication.UsernamePasswordCredentials;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.client.predicate.ErrorConverter;
import io.vertx.ext.web.client.predicate.ResponsePredicate;
import io.vertx.ext.web.client.predicate.ResponsePredicateResult;
import io.vertx.ext.web.codec.BodyCodec;
import io.vertx.ext.web.multipart.MultipartForm;
import java.util.function.Function;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class WebClientExamples {
public void create(Vertx vertx) {
WebClient client = WebClient.create(vertx);
}
public void createFromOptions(Vertx vertx) {
WebClientOptions options = new WebClientOptions()
.setUserAgent("My-App/1.2.3");
options.setKeepAlive(false);
WebClient client = WebClient.create(vertx, options);
}
public void wrap(HttpClient httpClient) {
WebClient client = WebClient.wrap(httpClient);
}
public void simpleGetAndHead(Vertx vertx) {
WebClient client = WebClient.create(vertx);
// Send a GET request
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.send()
.onSuccess(response -> System.out
.println("Received response with status code" + response.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
// Send a HEAD request
client
.head(8080, "myserver.mycompany.com", "/some-uri")
.send()
.onSuccess(response -> System.out
.println("Received response with status code" + response.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void simpleGetWithParams(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.addQueryParam("param", "param_value")
.send()
.onSuccess(response -> System.out
.println("Received response with status code" + response.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void simpleGetWithInitialParams(WebClient client) {
HttpRequest<Buffer> request = client
.get(
8080,
"myserver.mycompany.com",
"/some-uri?param1=param1_value¶m2=param2_value");
// Add param3
request.addQueryParam("param3", "param3_value");
// Overwrite param2
request.setQueryParam("param2", "another_param2_value");
}
public void simpleGetOverwritePreviousParams(WebClient client) {
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri");
// Add param1
request.addQueryParam("param1", "param1_value");
// Overwrite param1 and add param2
request.uri("/some-uri?param1=param1_value¶m2=param2_value");
}
public void multiGet(WebClient client) {
HttpRequest<Buffer> get = client
.get(8080, "myserver.mycompany.com", "/some-uri");
get
.send()
.onSuccess(res -> {
// OK
});
// Same request again
get
.send()
.onSuccess(res -> {
// OK
});
}
public void multiGetCopy(WebClient client) {
HttpRequest<Buffer> get = client
.get(8080, "myserver.mycompany.com", "/some-uri");
get
.send()
.onSuccess(res -> {
// OK
});
// The "get" request instance remains unmodified
get
.copy()
.putHeader("a-header", "with-some-value")
.send()
.onSuccess(res -> {
// OK
});
}
public void timeout(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.timeout(5000)
.send()
.onSuccess(res -> {
// OK
})
.onFailure(err -> {
// Might be a timeout when cause is java.util.concurrent.TimeoutException
});
}
public void sendBuffer(WebClient client, Buffer buffer) {
// Send a buffer to the server using POST, the content-length
// header will be set for you
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendBuffer(buffer)
.onSuccess(res -> {
// OK
});
}
public void sendStream(WebClient client, FileSystem fs) {
fs.open("content.txt", new OpenOptions(), fileRes -> {
if (fileRes.succeeded()) {
ReadStream<Buffer> fileStream = fileRes.result();
String fileLen = "1024";
// Send the file to the server using POST
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.putHeader("content-length", fileLen)
.sendStream(fileStream)
.onSuccess(res -> {
// OK
})
;
}
});
}
public void sendStreamChunked(WebClient client, ReadStream<Buffer> stream) {
// When the stream len is unknown sendStream sends the file to the
// server using chunked transfer encoding
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendStream(stream)
.onSuccess(res -> {
// OK
});
}
public void sendJsonObject(WebClient client) {
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendJsonObject(
new JsonObject()
.put("firstName", "Dale")
.put("lastName", "Cooper"))
.onSuccess(res -> {
// OK
});
}
static class User {
String firstName;
String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
public void sendJsonPOJO(WebClient client) {
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendJson(new User("Dale", "Cooper"))
.onSuccess(res -> {
// OK
});
}
public void sendForm(WebClient client) {
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("firstName", "Dale");
form.set("lastName", "Cooper");
// Submit the form as a form URL encoded body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendForm(form)
.onSuccess(res -> {
// OK
});
}
public void sendMultipart(WebClient client) {
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("firstName", "Dale");
form.set("lastName", "Cooper");
// Submit the form as a multipart form body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.putHeader("content-type", "multipart/form-data")
.sendForm(form)
.onSuccess(res -> {
// OK
});
}
public void sendMultipartWithFileUpload(WebClient client) {
MultipartForm form = MultipartForm.create()
.attribute("imageDescription", "a very nice image")
.binaryFileUpload(
"imageFile",
"image.jpg",
"/path/to/image",
"image/jpeg");
// Submit the form as a multipart form body
client
.post(8080, "myserver.mycompany.com", "/some-uri")
.sendMultipartForm(form)
.onSuccess(res -> {
// OK
});
}
public void sendHeaders1(WebClient client) {
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri");
MultiMap headers = request.headers();
headers.set("content-type", "application/json");
headers.set("other-header", "foo");
}
public void sendHeaders2(WebClient client) {
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri");
request.putHeader("content-type", "application/json");
request.putHeader("other-header", "foo");
}
public void addBasicAccessAuthentication(WebClient client) {
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.authentication(new UsernamePasswordCredentials("myid", "mypassword"));
}
public void addBearerTokenAuthentication(WebClient client) {
HttpRequest<Buffer> request = client
.get(8080, "myserver.mycompany.com", "/some-uri")
.authentication(new TokenCredentials("myBearerToken"));
}
public void receiveResponse(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAsJsonObject(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.jsonObject())
.send()
.onSuccess(res -> {
JsonObject body = res.body();
System.out.println(
"Received response with status code" +
res.statusCode() +
" with body " +
body);
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAsJsonPOJO(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.json(User.class))
.send()
.onSuccess(res -> {
User user = res.body();
System.out.println(
"Received response with status code" +
res.statusCode() +
" with body " +
user.getFirstName() +
" " +
user.getLastName());
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAsWriteStream(WebClient client, WriteStream<Buffer> writeStream) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.pipe(writeStream))
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAsJsonStream(WebClient client) {
JsonParser parser = JsonParser.newParser().objectValueMode();
parser.handler(event -> {
JsonObject object = event.objectValue();
System.out.println("Got " + object.encode());
});
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.jsonStream(parser))
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAndDiscard(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.as(BodyCodec.none())
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void receiveResponseAsBufferDecodeAsJsonObject(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.send()
.onSuccess(res -> {
// Decode the body as a json object
JsonObject body = res.bodyAsJsonObject();
System.out.println(
"Received response with status code" +
res.statusCode() +
" with body " +
body);
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void manualSanityChecks(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.send()
.onSuccess(res -> {
if (
res.statusCode() == 200 &&
res.getHeader("content-type").equals("application/json")) {
// Decode the body as a json object
JsonObject body = res.bodyAsJsonObject();
System.out.println(
"Received response with status code" +
res.statusCode() +
" with body " +
body);
} else {
System.out.println("Something went wrong " + res.statusCode());
}
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void usingPredicates(WebClient client) {
// Check CORS header allowing to do POST
Function<HttpResponse<Void>, ResponsePredicateResult> methodsPredicate =
resp -> {
String methods = resp.getHeader("Access-Control-Allow-Methods");
if (methods != null) {
if (methods.contains("POST")) {
return ResponsePredicateResult.success();
}
}
return ResponsePredicateResult.failure("Does not work");
};
// Send pre-flight CORS request
client
.request(
HttpMethod.OPTIONS,
8080,
"myserver.mycompany.com",
"/some-uri")
.putHeader("Origin", "Server-b.com")
.putHeader("Access-Control-Request-Method", "POST")
.expect(methodsPredicate)
.send()
.onSuccess(res -> {
// Process the POST request now
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void usingPredefinedPredicates(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.expect(ResponsePredicate.SC_SUCCESS)
.expect(ResponsePredicate.JSON)
.send()
.onSuccess(res -> {
// Safely decode the body as a json object
JsonObject body = res.bodyAsJsonObject();
System.out.println(
"Received response with status code" +
res.statusCode() +
" with body " +
body);
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void usingSpecificStatus(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.expect(ResponsePredicate.status(200, 202))
.send()
.onSuccess(res -> {
// ....
});
}
public void usingSpecificContentType(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.expect(ResponsePredicate.contentType("some/content-type"))
.send()
.onSuccess(res -> {
// ....
});
}
private static class MyCustomException extends Exception {
private final String code;
public MyCustomException(String message) {
super(message);
code = null;
}
public MyCustomException(String code, String message) {
super(message);
this.code = code;
}
}
public void predicateCustomError() {
ResponsePredicate predicate = ResponsePredicate.create(
ResponsePredicate.SC_SUCCESS,
result -> new MyCustomException(result.message()));
}
public void predicateCustomErrorWithBody() {
ErrorConverter converter = ErrorConverter.createFullBody(result -> {
// Invoked after the response body is fully received
HttpResponse<Buffer> response = result.response();
if (response
.getHeader("content-type")
.equals("application/json")) {
// Error body is JSON data
JsonObject body = response.bodyAsJsonObject();
return new MyCustomException(
body.getString("code"),
body.getString("message"));
}
// Fallback to defaut message
return new MyCustomException(result.message());
});
ResponsePredicate predicate = ResponsePredicate
.create(ResponsePredicate.SC_SUCCESS, converter);
}
public void testClientDisableFollowRedirects(Vertx vertx) {
// Change the default behavior to not follow redirects
WebClient client = WebClient
.create(vertx, new WebClientOptions().setFollowRedirects(false));
}
public void testClientChangeMaxRedirects(Vertx vertx) {
// Follow at most 5 redirections
WebClient client = WebClient
.create(vertx, new WebClientOptions().setMaxRedirects(5));
}
public void testClientChangeMaxRedirects(WebClient client) {
client
.get(8080, "myserver.mycompany.com", "/some-uri")
.followRedirects(false)
.send()
.onSuccess(res -> {
// Obtain response
System.out.println("Received response with status code" + res.statusCode());
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void testOverrideRequestSSL(WebClient client) {
client
.get(443, "myserver.mycompany.com", "/some-uri")
.ssl(true)
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void testAbsRequestSSL(WebClient client) {
client
.getAbs("https://myserver.mycompany.com:4043/some-uri")
.send()
.onSuccess(res ->
System.out.println("Received response with status code" + res.statusCode()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void testSocketAddress(WebClient client) {
// Creates the unix domain socket address to access the Docker API
SocketAddress serverAddress = SocketAddress
.domainSocketAddress("/var/run/docker.sock");
// We still need to specify host and port so the request
// HTTP header will be localhost:8080
// otherwise it will be a malformed HTTP request
// the actual value does not matter much for this example
client
.request(
HttpMethod.GET,
serverAddress,
8080,
"localhost",
"/images/json")
.expect(ResponsePredicate.SC_ACCEPTED)
.as(BodyCodec.jsonObject())
.send()
.onSuccess(res ->
System.out.println("Current Docker images" + res.body()))
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
}
| {
"content_hash": "6dedd409f93a0ad87dae7b3527133185",
"timestamp": "",
"source": "github",
"line_count": 639,
"max_line_length": 95,
"avg_line_length": 29.3943661971831,
"alnum_prop": 0.6248203162434116,
"repo_name": "InfoSec812/vertx-web",
"id": "11c34b189bf544fc50e565295a7f7b1c21bfe3de",
"size": "19403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vertx-web-client/src/main/java/examples/WebClientExamples.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CoffeeScript",
"bytes": "5450"
},
{
"name": "FreeMarker",
"bytes": "479"
},
{
"name": "Groovy",
"bytes": "1727"
},
{
"name": "HTML",
"bytes": "8166"
},
{
"name": "Java",
"bytes": "1248330"
},
{
"name": "JavaScript",
"bytes": "74295"
},
{
"name": "Kotlin",
"bytes": "15538"
},
{
"name": "Makefile",
"bytes": "1420"
},
{
"name": "Python",
"bytes": "1029979"
},
{
"name": "Ruby",
"bytes": "3197"
}
],
"symlink_target": ""
} |
package de.otto.jsonhome.converter;
import de.otto.jsonhome.model.DirectLink;
import de.otto.jsonhome.model.HrefVar;
import de.otto.jsonhome.model.ResourceLink;
import de.otto.jsonhome.model.TemplatedLink;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Converter used to convert a ResourceLink into a json-home resource.
*
* @author Guido Steinacker
* @since 14.10.12
*/
public final class ResourceLinkConverter {
public static Map<String, Map<String, Object>> toRepresentation(final ResourceLink resourceLink,
final JsonHomeMediaType mediaType) {
if (resourceLink.isDirectLink()) {
return directLinkToJsonHome(resourceLink.asDirectLink(), mediaType);
} else {
return templatedLinkToJsonHome(resourceLink.asTemplatedLink(), mediaType);
}
}
public static Map<String, Map<String, Object>> templatedLinkToJsonHome(final TemplatedLink resourceLink,
final JsonHomeMediaType mediaType) {
final Map<String,String> jsonHrefVars = new LinkedHashMap<>();
for (final HrefVar hrefVar : resourceLink.getHrefVars()) {
jsonHrefVars.put(hrefVar.getVar(), hrefVar.getVarType().toString());
}
final Map<String, Object> map = new LinkedHashMap<>();
map.put("href-template", resourceLink.getHrefTemplate());
map.put("href-vars", jsonHrefVars);
map.put("hints", HintsConverter.toRepresentation(resourceLink.getHints(), mediaType));
return Collections.singletonMap(resourceLink.getLinkRelationType().toString(), map);
}
public static Map<String, Map<String, Object>> directLinkToJsonHome(final DirectLink resourceLink,
final JsonHomeMediaType mediaType) {
final Map<String, Object> map = new LinkedHashMap<>();
map.put("href", resourceLink.getHref().toString());
map.put("hints", HintsConverter.toRepresentation(resourceLink.getHints(), mediaType));
return Collections.singletonMap(resourceLink.getLinkRelationType().toString(), map);
}
}
| {
"content_hash": "734aa823abff0b3ec1661d7e4227dcfb",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 111,
"avg_line_length": 42.83018867924528,
"alnum_prop": 0.6519823788546255,
"repo_name": "otto-de/jsonhome",
"id": "1b5309505b511a159c72638bcd7fbff58d51494c",
"size": "2865",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsonhome-core/src/main/java/de/otto/jsonhome/converter/ResourceLinkConverter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "236"
},
{
"name": "Java",
"bytes": "512301"
}
],
"symlink_target": ""
} |
var express = require('express');
// load cores
var misc = require('../../core/lib/misc');
// load modules
var Site = require('../../module/site');
var Teamblog = require('../../module/teamblog');
var Account = require('../../module/account');
// load locals
var app = require('./app.json');
var menu = require('./menu');
// init
var router = express.Router();
var routeTable = misc.getRouteData();
var appLocals = Site.exposeAppLocals(app.locals, menu);
// middleware
router.use(Account.middleware.exposeLocals);
// bind static page
router.all(routeTable.root, Teamblog.index);
router.all('/about', Site.redirect(routeTable.root));
// bind module
router.use('/account', Account.site);
router.use('/blog', Teamblog.route);
module.exports = {
config: app.config,
exposeLocals: appLocals,
router: router,
};
| {
"content_hash": "7219b0883c991b08e76aef1f086e9bd9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 55,
"avg_line_length": 23.6,
"alnum_prop": 0.6828087167070218,
"repo_name": "soomtong/blititor",
"id": "11252f1a3cb02cdc238d69859c7340c8f6de684e",
"size": "843",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/furion/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "73803"
},
{
"name": "HTML",
"bytes": "170570"
},
{
"name": "JavaScript",
"bytes": "367608"
}
],
"symlink_target": ""
} |
import os
import logging
import logging.handlers
import time, datetime
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_security.forms import LoginForm
from wtforms import StringField
from wtforms.validators import InputRequired
from flask import Flask, request, g, render_template
from flask_mail import Mail
from backend.modules.api import api_blueprint
from backend.modules.render_frontend import frontend_blueprint
from backend.modules.uploads import upload_blueprint
from backend.modules.admin import admin_blueprint
from backend.modules.manipulate_db import manipulate_db
from backend.modules.view import view_blueprint
from backend.modules.user_management import user_blueprint
from configurations import DB_URL, UPLOAD_FOLDER, STATIC_FOLDER, TEMPLATE_FOLDER, PDF_FOLDER, THUMB_FOLDER, LOG_FOLDER, \
LOG_LEVEL, EMAIL_SENDER, MAIL_SERVER, MAIL_PORT, MAIL_USE_SSL, MAIL_USERNAME, SECURITY_PASSWORD_SALT, SECRET, BEHIND_PROXY
from backend.db_controller.db import db
from backend.db_controller.db import users, role
from flask_security import Security, SQLAlchemyUserDatastore
logger_initialized = False
# Update Login form to enable login via E-Mail and Username
class ExtendedLoginForm(LoginForm):
email = StringField('Username of Email Address', [InputRequired()])
app = Flask(__name__,
static_folder=STATIC_FOLDER,
template_folder=TEMPLATE_FOLDER)
# if run behind a proxy, use this magic to observe necessary header from the proxy for secure
# HTTPS responses from the app
if BEHIND_PROXY:
app.wsgi_app = ProxyFix(app.wsgi_app)
@app.teardown_appcontext
def shutdown_session(exception=None):
"""
Ensure cloing open db connection
"""
db.session.remove()
# add continue and break to jinja loops
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
# add static and template folder to config
app.config['STATIC_FOLDER'] = STATIC_FOLDER
app.config['TEMPLATE_FOLDER'] = TEMPLATE_FOLDER
# secret key for flask-security
app.config['SECRET_KEY'] = SECRET
# Password salt
#app.config['SECURITY_PASSWORD_SALT'] = '123456789'
app.config['SECURITY_PASSWORD_SALT'] = SECURITY_PASSWORD_SALT
app.config['SECURITY_RECOVERABLE'] = True
# add credentials to connect to MYSQL
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
# jsonify as UTF-8. Using the default value 'TRUE' we get problems with german Umlaute.
app.config['JSON_AS_ASCII'] = False
'''By default Flask will serialize JSON objects in a way that the keys are ordered.
This is done in order to ensure that independent of the hash seed of the dictionary the return value will be consistent to not trash external HTTP caches.
You can override the default behavior by changing this variable.
This is not recommended but might give you a performance improvement on the cost of cacheability.'''
# app.config["JSON_SORT_KEYS"] = False
# init app to SQLAlchemy
db.init_app(app)
## Login via username not email
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('username', 'email')
# E-Mail subjects
app.config['SECURITY_EMAIL_SUBJECT_PASSWORD_RESET'] = '[SciBib] Password reset instructions'
app.config['SECURITY_EMAIL_SUBJECT_REGISTER'] = '[SciBib] Welcome'
app.config['SECURITY_EMAIL_SUBJECT_PASSWORD_NOTICE'] = '[SciBib] Your password has been reset'
app.config['SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE'] = '[SciBib] Your password has been changed'
app.config['SECURITY_EMAIL_SUBJECT_CONFIRM'] = '[SciBib] Please confirm your email'
## Flask Security Change Password URL
app.config['SECURITY_CHANGEABLE'] = True
app.config['SECURITY_CHANGE_URL'] = '/change-password'
## Redirect to adminarea after login
app.config['SECURITY_POST_LOGIN_VIEW'] = '/adminarea'
### Flask-Mail config
app.config['MAIL_SERVER'] = MAIL_SERVER
app.config['MAIL_PORT'] = MAIL_PORT
app.config['MAIL_USE_SSL'] = MAIL_USE_SSL
app.config['MAIL_USERNAME'] = MAIL_USERNAME
## Flask upload folder
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['PDF_FOLDER'] = PDF_FOLDER
app.config['THUMB_FOLDER'] = THUMB_FOLDER
# Set E-Mail Sender Account
app.config['SECURITY_EMAIL_SENDER'] = EMAIL_SENDER
# Init Flask Mail
mail = Mail(app)
# User datastore
user_datastore = SQLAlchemyUserDatastore(db, users, role)
# add Flask security
security = Security(app, user_datastore, login_form=ExtendedLoginForm)
# register mode to run app
app.config.from_object('configurations.DevelopmentConfig')
# register blueprints
app.register_blueprint(api_blueprint)
app.register_blueprint(frontend_blueprint)
app.register_blueprint(admin_blueprint)
app.register_blueprint(upload_blueprint)
app.register_blueprint(manipulate_db)
app.register_blueprint(view_blueprint)
app.register_blueprint(user_blueprint)
@app.route('/error')
def render_error_page():
"""
Render error page
@return: the error page to render
@rtype: unicode string
"""
return render_template('public/error.html')
def init_logging():
"""
Initialize logging for the app.
Creates a new var folder and starts a logger.
"""
# init logger using syslog
os.makedirs(os.path.dirname(LOG_FOLDER), exist_ok=True)
handler = logging.handlers.WatchedFileHandler(LOG_FOLDER)
handler.setFormatter(logging.Formatter(fmt='%(asctime)s pid/%(process)d %(message)s'))
handler.setLevel(LOG_LEVEL)
app.logger.addHandler(handler)
app.logger.info("Initialized file logging.")
@app.before_request
def start_timer():
"""
Store the time of the request to calculate the request duration. Request duration is added to the logs.
"""
g.start = time.time()
@app.after_request
def log_request(response):
"""
Log request to file and just forward the response unaltered.
@param response: the response object of the request
@type response: HTTP response
@return: just forward the response
@rtype: HTT response
"""
if request.path == '/favicon.ico' or request.path == '/favicon':
return response
if request.path.startswith('/static'):
return response
now = time.time()
duration = round(now - g.start, 2)
timestamp = datetime.datetime.fromtimestamp(now).isoformat()
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
host = request.host.split(':', 1)[0]
args = dict(request.args)
log_params = [
('method', request.method, 'blue'),
('path', request.path, 'blue'),
('status', response.status_code, 'yellow'),
('duration', duration, 'green'),
('time', timestamp, 'magenta'),
('ip', ip, 'red'),
('host', host, 'red'),
('params', args, 'blue')
]
request_id = request.headers.get('X-Request-ID')
if request_id:
log_params.append(('request_id', request_id, 'yellow'))
app.logger.info(" ".join("{}={}".format(name, value)) for name, value, _ in log_params)
return response
@app.teardown_request
def log_request_error(error=None):
"""
Log errors in requests.
"""
if error:
app.logger.error(str(error))
def main():
init_logging()
app.logger.info("Starting process.")
app.run(host="0.0.0.0")
if __name__ == '__main__':
main() | {
"content_hash": "03baaa12389d0cc5808fb04677cd16ab",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 155,
"avg_line_length": 33.02764976958525,
"alnum_prop": 0.7227570810659969,
"repo_name": "UKN-DBVIS/SciBib",
"id": "05657a0a338efa3d89eb1eac1a989b144a7cd278",
"size": "7953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/main.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "270"
},
{
"name": "Batchfile",
"bytes": "937"
},
{
"name": "CSS",
"bytes": "51336"
},
{
"name": "JavaScript",
"bytes": "216864"
},
{
"name": "PHP",
"bytes": "326356"
},
{
"name": "Shell",
"bytes": "1444"
}
],
"symlink_target": ""
} |
<?php
namespace lukisongroup\controllers\dashboard;
use Yii;
use yii\filters\AccessControl;
use app\models\dashboard\Umum;
use app\models\dashboard\UmumSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* DashboardController implements the CRUD actions for Dashboard model.
*/
class GeneralController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
/*
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
*/
}
/**
* Lists all Dashboard models.
* @return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
public function actionTabsData()
{ $html = $this->renderPartial('tabContent');
return Json::encode($html);
}
/*
public function actionIndex($id)
{
return $this->render('index', [
'model' => $this->findModel($id),
]);
}
*/
/**
* by ptr.nov
* Dashboard Sarana Sinar Surya
*/
public function actionSss($id)
{
return $this->render('sss', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard Arta Lipat ganda
*/
public function actionAlg($id)
{
return $this->render('alg', [
'model' => $this->findModel($id),
]);
$this->redirect(['view', 'id' => $model->BRG_ID]);
}
/**
* by ptr.nov
* Dashboard Efembi Sukses Makmur
*/
public function actionEsm($id)
{
return $this->render('esm', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard Gosent
*/
public function actionGsn($id)
{
return $this->render('gsn', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard Accounting Dept
*/
public function actionAcct($id)
{
return $this->render('acct', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard HRD Dept
*/
public function actionHrd($id)
{
return $this->render('hrd', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard Marketing Dept
*/
public function actionMrk($id)
{
return $this->render('mrk', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard General Affair Dept
*/
public function actionGa($id)
{
return $this->render('ga', [
'model' => $this->findModel($id),
]);
}
/**
* by ptr.nov
* Dashboard IT Dept
*/
public function actionIt($id)
{
return $this->render('it', [
'model' => $this->findModel($id),
]);
}
/**
* Displays a single Dashboard model.
* @param string $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Dashboard model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Dashboard();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->CORP_ID]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Dashboard model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->CORP_ID]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Dashboard model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param string $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Dashboard model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return Dashboard the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Umum::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| {
"content_hash": "76f520e1d72b04ac3d2a635fa0c24be3",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 85,
"avg_line_length": 24.428,
"alnum_prop": 0.45144915670542,
"repo_name": "ptrnov/wan",
"id": "5d9f0c2b78ceea8c88b4a864249a70764c49977e",
"size": "6107",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modulprj/controllers/dashboard/GeneralController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "748987"
},
{
"name": "HTML",
"bytes": "33356"
},
{
"name": "JavaScript",
"bytes": "257269"
},
{
"name": "PHP",
"bytes": "2208149"
}
],
"symlink_target": ""
} |
NSValueTransformerName const MGSMutableColourSchemeFromPlistTransformerName = @"MGSMutableColourSchemeFromPlistTransformer";
@implementation MGSMutableColourSchemeFromPlistTransformer
+ (void)load
{
MGSMutableColourSchemeFromPlistTransformer *reg = [[MGSMutableColourSchemeFromPlistTransformer alloc] init];
[NSValueTransformer setValueTransformer:reg forName:MGSMutableColourSchemeFromPlistTransformerName];
}
+ (Class)transformedValueClass
{
return [MGSMutableColourScheme class];
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
- (id)transformedValue:(id)value
{
if (!value || ![value isKindOfClass:[NSDictionary class]])
return nil;
return [[MGSMutableColourScheme alloc] initWithPropertyList:value error:nil];
}
- (id)reverseTransformedValue:(id)value
{
if (!value || ![value isKindOfClass:[MGSColourScheme class]])
return nil;
return [value propertyListRepresentation];
}
@end
| {
"content_hash": "ad5df1a3d586894224d548a39da2c85f",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 124,
"avg_line_length": 22.642857142857142,
"alnum_prop": 0.7728706624605678,
"repo_name": "shysaur/Fragaria",
"id": "d87cd57d498a41e12b7f0b6e2c1381e03074e6e4",
"size": "1162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fragaria/MGSMutableColourSchemeFromPlistTransformer.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "910"
},
{
"name": "ASP",
"bytes": "1485"
},
{
"name": "ActionScript",
"bytes": "1133"
},
{
"name": "Assembly",
"bytes": "506"
},
{
"name": "Awk",
"bytes": "437"
},
{
"name": "Batchfile",
"bytes": "260"
},
{
"name": "C",
"bytes": "2046"
},
{
"name": "C#",
"bytes": "83"
},
{
"name": "C++",
"bytes": "7081"
},
{
"name": "CSS",
"bytes": "1399"
},
{
"name": "CoffeeScript",
"bytes": "403"
},
{
"name": "ColdFusion",
"bytes": "86"
},
{
"name": "Common Lisp",
"bytes": "1448"
},
{
"name": "Csound Document",
"bytes": "173"
},
{
"name": "D",
"bytes": "324"
},
{
"name": "Eiffel",
"bytes": "375"
},
{
"name": "Erlang",
"bytes": "2746"
},
{
"name": "Fortran",
"bytes": "6261"
},
{
"name": "HTML",
"bytes": "2656"
},
{
"name": "Haskell",
"bytes": "5166"
},
{
"name": "Java",
"bytes": "7120"
},
{
"name": "JavaScript",
"bytes": "3649"
},
{
"name": "LilyPond",
"bytes": "2966"
},
{
"name": "Lua",
"bytes": "981"
},
{
"name": "MATLAB",
"bytes": "2001"
},
{
"name": "OCaml",
"bytes": "4274"
},
{
"name": "Objective-C",
"bytes": "782916"
},
{
"name": "PHP",
"bytes": "940"
},
{
"name": "Pascal",
"bytes": "1412"
},
{
"name": "Perl",
"bytes": "1621"
},
{
"name": "Python",
"bytes": "478"
},
{
"name": "R",
"bytes": "668"
},
{
"name": "Rich Text Format",
"bytes": "350"
},
{
"name": "Ruby",
"bytes": "14066"
},
{
"name": "Scala",
"bytes": "1541"
},
{
"name": "Shell",
"bytes": "4929"
},
{
"name": "Stata",
"bytes": "2948"
},
{
"name": "Swift",
"bytes": "2147"
},
{
"name": "Tcl",
"bytes": "1722"
},
{
"name": "TeX",
"bytes": "2114"
},
{
"name": "VBScript",
"bytes": "938"
},
{
"name": "VHDL",
"bytes": "830"
},
{
"name": "Verilog",
"bytes": "274"
}
],
"symlink_target": ""
} |
<header class="banner">
<div class="container">
<div class="nav-container">
<a class="brand" href="<?= esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a>
<nav class="nav-primary">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
endif;
?>
</nav>
</div>
</div>
</header> | {
"content_hash": "a7e88f3aa3b9bbcc34992dfc120f598d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 91,
"avg_line_length": 30.571428571428573,
"alnum_prop": 0.5116822429906542,
"repo_name": "smpetrey/leahconstantine.com",
"id": "980549cba4fbfbf256134751758abffa7ac95ca9",
"size": "428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/app/themes/l-theme/templates/header.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "559906"
},
{
"name": "JavaScript",
"bytes": "1835754"
},
{
"name": "PHP",
"bytes": "10414634"
}
],
"symlink_target": ""
} |
<?php
/**
* @class SearchPostsTopTest
* =========================
*
* Creates a user with three posts, then creates three other users to give
* those posts 1, 2, and 3 upvotes. Then gets the posts from the API and makes
* sure they come back in the correct order.
*
* Ryff API <http://www.github.com/RyffProject/ryff-api>
* Released under the Apache License 2.0.
*/
class SearchPostsTopTest extends Test {
/**
* Overrides abstract function in Test.
*
* @return string
*/
public function get_message() {
return "Search Posts Top test";
}
/**
* Overrides abstract function in Test.
*/
protected function setup() {
$this->state["user"] = $this->env->get_test_user();
$this->state["users"] = array();
$this->state["posts"] = array();
$this->state["num_posts"] = 3;
$this->state["tag"] = $this->env->get_word();
//Create a few other users to upvote the posts
for ($i = 0; $i < $this->state["num_posts"]; $i++) {
$this->state["users"][] = $this->env->get_test_user();
}
//Create the posts and upvote them
for ($i = 0; $i < $this->state["num_posts"]; $i++) {
$post = $this->env->get_test_post(
$this->state["user"]->id,
array(), array($this->state["tag"])
);
for ($j = 0; $j < $this->state["num_posts"] - $i; $j++) {
Upvote::add($post->id, $this->state["users"][$j]->id);
}
$this->state["posts"][] = $post;
}
}
/**
* Overrides abstract function in Test.
*
* @return boolean
*/
protected function test() {
$output = true;
$results = $this->env->post_to_api(
"search-posts-top",
array("tags" => $this->state["tag"])
);
if (!$results) {
$output = false;
} else if (property_exists($results, "error")) {
echo "{$results->error}\n";
echo "Failed to search top posts.\n";
$output = false;
} else if (count($results->posts) !== $this->state["num_posts"]) {
echo "Failed to get the correct number of top posts.\n";
$output = false;
} else if ($results->posts[0]->id !== $this->state["posts"][0]->id ||
$results->posts[1]->id !== $this->state["posts"][1]->id ||
$results->posts[2]->id !== $this->state["posts"][2]->id) {
echo "Failed to get the top posts in the correct order.\n";
$output = false;
}
return $output;
}
/**
* Overrides abstract function in Test.
*/
protected function teardown() {
User::delete($this->state["user"]->id);
foreach ($this->state["users"] as $user) {
User::delete($user->id);
}
}
}
| {
"content_hash": "d7cec120ba7afdb517d6a8824086bd71",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 78,
"avg_line_length": 32.07692307692308,
"alnum_prop": 0.4933196300102775,
"repo_name": "RyffProject/ryff-api",
"id": "1fab006bbbd727e661778db21ef3a4cc43e7faff",
"size": "2919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/tests/api_tests/SearchPostsTopTest.class.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "649"
},
{
"name": "PHP",
"bytes": "387780"
}
],
"symlink_target": ""
} |
// Copyright (c) 2011-2016 The PlanBcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_BITCOINUNITS_H
#define BITCOIN_QT_BITCOINUNITS_H
#include "amount.h"
#include <QAbstractListModel>
#include <QString>
// U+2009 THIN SPACE = UTF-8 E2 80 89
#define REAL_THIN_SP_CP 0x2009
#define REAL_THIN_SP_UTF8 "\xE2\x80\x89"
#define REAL_THIN_SP_HTML " "
// U+200A HAIR SPACE = UTF-8 E2 80 8A
#define HAIR_SP_CP 0x200A
#define HAIR_SP_UTF8 "\xE2\x80\x8A"
#define HAIR_SP_HTML " "
// U+2006 SIX-PER-EM SPACE = UTF-8 E2 80 86
#define SIXPEREM_SP_CP 0x2006
#define SIXPEREM_SP_UTF8 "\xE2\x80\x86"
#define SIXPEREM_SP_HTML " "
// U+2007 FIGURE SPACE = UTF-8 E2 80 87
#define FIGURE_SP_CP 0x2007
#define FIGURE_SP_UTF8 "\xE2\x80\x87"
#define FIGURE_SP_HTML " "
// QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces
// correctly. Workaround is to display a space in a small font. If you
// change this, please test that it doesn't cause the parent span to start
// wrapping.
#define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>"
// Define THIN_SP_* variables to be our preferred type of thin space
#define THIN_SP_CP REAL_THIN_SP_CP
#define THIN_SP_UTF8 REAL_THIN_SP_UTF8
#define THIN_SP_HTML HTML_HACK_SP
/** Planbcoin unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class PlanbcoinUnits: public QAbstractListModel
{
Q_OBJECT
public:
explicit PlanbcoinUnits(QObject *parent);
/** Planbcoin units.
@note Source: https://en.planbcoin.it/wiki/Units . Please add only sensible ones
*/
enum Unit
{
PBC,
mPBC,
uPBC
};
enum SeparatorStyle
{
separatorNever,
separatorStandard,
separatorAlways
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Short name
static QString name(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Format as string (with unit)
static QString formatWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Format as HTML string (with unit)
static QString formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign=false, SeparatorStyle separators=separatorStandard);
//! Parse string to coin amount
static bool parse(int unit, const QString &value, CAmount *val_out);
//! Gets title for amount column including current display unit if optionsModel reference available */
static QString getAmountColumnTitle(int unit);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
///@}
static QString removeSpaces(QString text)
{
text.remove(' ');
text.remove(QChar(THIN_SP_CP));
#if (THIN_SP_CP != REAL_THIN_SP_CP)
text.remove(QChar(REAL_THIN_SP_CP));
#endif
return text;
}
//! Return maximum number of base units (Satoshis)
static CAmount maxMoney();
private:
QList<PlanbcoinUnits::Unit> unitlist;
};
typedef PlanbcoinUnits::Unit PlanbcoinUnit;
#endif // BITCOIN_QT_BITCOINUNITS_H
| {
"content_hash": "aa68379dc27dda2dae417cf5448ad936",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 137,
"avg_line_length": 31.28125,
"alnum_prop": 0.6895604395604396,
"repo_name": "planbcoin/planbcoin",
"id": "e2838cead7f3c9bb9db1cfe54b3f532a963ffd88",
"size": "4004",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/planbcoinunits.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28452"
},
{
"name": "C",
"bytes": "692639"
},
{
"name": "C++",
"bytes": "5272684"
},
{
"name": "HTML",
"bytes": "21860"
},
{
"name": "Java",
"bytes": "30306"
},
{
"name": "M4",
"bytes": "191906"
},
{
"name": "Makefile",
"bytes": "112818"
},
{
"name": "Objective-C",
"bytes": "3767"
},
{
"name": "Objective-C++",
"bytes": "7235"
},
{
"name": "Protocol Buffer",
"bytes": "2336"
},
{
"name": "Python",
"bytes": "1197315"
},
{
"name": "QMake",
"bytes": "758"
},
{
"name": "Shell",
"bytes": "57700"
}
],
"symlink_target": ""
} |
@var add= auth.hasPermission("sys:dict:add");
<div class="tabbable">
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#home"> <i
class="green ace-icon fa fa-list-alt bigger-120"></i> 字典列表
</a></li>
@if(add){
<li class=""><a data-toggle="tab" href="#profile">
<i class="green ace-icon fa fa-plus bigger-120"></i> 字典添加
</a></li>
@}
</ul>
<div class="tab-content">
<div id="home" class="tab-pane active clearfix">
<form action="${ctxPath}/dict/list" method="post" id="search-form" target="list-page" class="clearfix">
<div class="pull-left width-25">
<label>类型:</label>
@var allDict = dict.getAllDictType();
<#select name="type" width="60%">
<option value="">全部</option>
@for(type in allDict){
<option value="${type!}">
${type!}
</option>
@}
</#select>
</div>
<div class="pull-left width-30">
<label>描述:</label>
<input type="text" class="width-80" name="description"/>
</div>
<div class="pull-left"><span class="btn btn-info btn-sm " id="search-btn">查 询</span></div>
</form>
<hr/>
<div id="list-page"></div>
<script type="text/javascript">
$("#search-form").getPageList({'submitBtnId':'search-btn'})
</script>
</div>
@if(add){
<div id="profile" class="tab-pane">
<form action="${ctxPath!}/dict/save" method="post" id="dict-save-form">
<div class="center padding-10">
<label>键值:</label>
<input type="text" class="width-50" name="value" datatype="*" nullmsg="请输入键值!"/>
</div>
<div class="center padding-10">
<label>标签:</label>
<input type="text" class="width-50" name="label" datatype="*" nullmsg="请输入标签!"/>
</div>
<div class="center padding-10">
<label>类型:</label>
<input type="text" class="width-50" name="type" datatype="*" nullmsg="请输入类型!"/>
</div>
<div class="center padding-10">
<label>排序:</label>
<input type="text" class="width-50" name="sort"/>
</div>
<div class="center padding-10" >
<label style="vertical-align: top;">描述:</label>
<textarea class="width-50" name="description"></textarea>
</div>
<div class="margin-t15">
<span class="btn btn-info btn-block bigger-120" id="dict-save-btn">保 存</span>
</div>
</form>
</div>
@}
</div>
</div>
<#save isHide="yes" subBtnId="dict-save-btn" formId="dict-save-form" />
| {
"content_hash": "7813beb045ebfa66ea96168d7322b169",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 106,
"avg_line_length": 32.62162162162162,
"alnum_prop": 0.5857497928748965,
"repo_name": "gto5516172/test",
"id": "c9f85078e38cda2830c813994fcc465c12a6f7a6",
"size": "2520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ec_pdm/src/main/webapp/WEB-INF/views/sys/dict/dict.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "351662"
},
{
"name": "HTML",
"bytes": "826575"
},
{
"name": "Java",
"bytes": "834795"
},
{
"name": "JavaScript",
"bytes": "1847404"
},
{
"name": "PHP",
"bytes": "751"
}
],
"symlink_target": ""
} |
require "representable/render/nil/version"
require "representable/definition"
module Representable
module Render
module Nil
def self.included(base)
base.class_eval do
def initialize(sym, options={})
@name = sym.to_s
@options = options
@options[:default] ||= [] if array?
@options[:render_nil] = true if @options[:render_nil].nil?
end
end
end
end
end
end
Representable::Definition.send(:include, Representable::Render::Nil)
| {
"content_hash": "3e0284a133b56d226c21f8c35b5db165",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 70,
"avg_line_length": 25.61904761904762,
"alnum_prop": 0.6003717472118959,
"repo_name": "allenwei/representable-render-nil",
"id": "fdd7ee6d3656768db01c034219ff6fa310ca710c",
"size": "538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/representable/render/nil.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2907"
}
],
"symlink_target": ""
} |
goog.provide('p3rf.perfkit.explorer.components.dashboard.config.DashboardConfigModel');
goog.scope(function() {
const explorer = p3rf.perfkit.explorer;
/**
* See module docstring for more information about purpose and usage.
*
* @constructor
* @extends {IBaseOptimizer}
*/
explorer.components.dashboard.config.DashboardConfigModel = class {
constructor() {
/**
* A dictionary of config models provided by extensions.
* @export {{string, {IExplorerExtension}}}
*/
this.ext = {};
}
/**
* Adds the specified extension model.
* @param {IExplorerExtension} extension The extension model to add.
*/
addExtension(extension, replace=false) {
if (goog.string.isEmptySafe(extension.id)) {
throw new Error('The provided extension does not have a valid id.');
}
if (!replace && goog.isDefAndNotNull(this.ext[extension.id])) {
throw new Error('The extension ' + extension.id + ' is already registered.');
}
this.ext[extension.id] = extension;
}
}
});
| {
"content_hash": "d59adea5843d1bf840dd8caf07bc46db",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 87,
"avg_line_length": 26.214285714285715,
"alnum_prop": 0.6303360581289736,
"repo_name": "dq922/PerfKitExplorer",
"id": "8764f65c1085df6965c51060486225aad15af52d",
"size": "1871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/dashboard/config/dashboard-config-model.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "932"
},
{
"name": "CSS",
"bytes": "25322"
},
{
"name": "HTML",
"bytes": "87083"
},
{
"name": "JavaScript",
"bytes": "889475"
},
{
"name": "Python",
"bytes": "244630"
},
{
"name": "Shell",
"bytes": "738"
}
],
"symlink_target": ""
} |
using System;
using System.Windows.Forms;
using SlideshowScreenSaver.Lib;
namespace SlideshowScreenSaver
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
// 多重起動禁止
if (Utility.CreateMutex(Application.ProductName))
{
// スクリーンセーバをコマンドラインによってい切り分けて起動
Utility.RunScreenSaver<MainForm, OptionForm>();
}
}
}
}
| {
"content_hash": "83a77fb287925e23cb75043750034e27",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 52,
"avg_line_length": 18.869565217391305,
"alnum_prop": 0.652073732718894,
"repo_name": "Harurow/SlideshowScreenSaver",
"id": "b30500c26a4d795d36312e0c581c41ae3782cae6",
"size": "550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SlideshowScreenSaver/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "88"
},
{
"name": "C#",
"bytes": "31400"
}
],
"symlink_target": ""
} |
=========
Changelog
=========
Version 0.3.2
=============
- Add ImageBase class (moved from pytesmo)
- Fixing documentation
Version 0.3.1
=============
- Updating pyscaffold version to
Version 0.3.0
=============
- New GriddedBase class
- Slight changes in the method names
Version 0.2.0
=============
- Support of ioclass keyword arguments
- Fix iteration inconsistency
Version 0.1
===========
- First developer release
| {
"content_hash": "c361419860265278049ab791ebb01b13",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 42,
"avg_line_length": 13.935483870967742,
"alnum_prop": 0.6087962962962963,
"repo_name": "christophreimer/pygeobase",
"id": "a792f506ff1e1d8bd063055594d2a31abc840731",
"size": "432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGES.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "33610"
}
],
"symlink_target": ""
} |
namespace Snippets4.Scheduling.Saga
{
using System;
using NServiceBus;
using NServiceBus.Saga;
#region ScheduleTaskSaga
class MySaga : Saga<MySagaData>,
IAmStartedByMessages<StartSaga>, // Saga is started by a message at endpoint startup
IHandleTimeouts<ExecuteTask> // task that gets executed when the scheduled time is up.
{
public override void ConfigureHowToFindSaga()
{
// To ensure that there is only one saga instance per the task name,
// regardless of if the endpoint is restarted or not.
ConfigureMapping<StartSaga>(message => message.TaskName)
.ToSaga(sagaData => sagaData.TaskName);
}
public void Handle(StartSaga message)
{
Data.TaskName = message.TaskName;
// Check to avoid that if the saga is already started, we don't initiate any more tasks
// as those timeout messages will arrive when the specified time is up.
if (!Data.IsTaskAlreadyScheduled)
{
// Setup a timeout for the specified interval for the task to be executed.
RequestTimeout<ExecuteTask>(TimeSpan.FromMinutes(5));
Data.IsTaskAlreadyScheduled = true;
}
}
public void Timeout(ExecuteTask state)
{
// Action that gets executed when the specified time is up
Bus.Send(new CallLegacySystem());
// Reschedule the task
RequestTimeout<ExecuteTask>(TimeSpan.FromMinutes(5));
}
}
// Associated saga data
public class MySagaData : ContainSagaData
{
[Unique]
public string TaskName { get; set; }
public bool IsTaskAlreadyScheduled { get; set; }
}
// Message that starts the saga
public class StartSaga : ICommand
{
public string TaskName { get; set; }
}
// timeout class
class ExecuteTask
{
}
#endregion
}
| {
"content_hash": "2271618c990e09e85691ef1bab2f1f9d",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 100,
"avg_line_length": 31.296875,
"alnum_prop": 0.6110833749375936,
"repo_name": "WojcikMike/docs.particular.net",
"id": "d2e258a997ba374745ca0636c76ea2a0b4811c7c",
"size": "2005",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Snippets/Snippets_4/Scheduling/Saga/SchedulerSaga.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "779873"
},
{
"name": "PowerShell",
"bytes": "7937"
}
],
"symlink_target": ""
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MsTestExampleSignatureBuilder.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Text.RegularExpressions;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.MsTest
{
public class MsTestExampleSignatureBuilder
{
public Regex Build(ScenarioOutline scenarioOutline, string[] row)
{
// We don't actually need this regex-based thing for MsTest results.
// It sucks that we have to provide one.
return new Regex(string.Empty);
}
}
} | {
"content_hash": "dd935d95ba9cbcd46929581d13f5d76f",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 121,
"avg_line_length": 40.270270270270274,
"alnum_prop": 0.6013422818791946,
"repo_name": "dirkrombauts/pickles",
"id": "52939a02e70a865d1d4cb13b6ae69fd12aaa9672",
"size": "1492",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "src/Pickles/Pickles.TestFrameworks/MsTest/MsTestExampleSignatureBuilder.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4540"
},
{
"name": "C#",
"bytes": "1639707"
},
{
"name": "CSS",
"bytes": "19236"
},
{
"name": "F#",
"bytes": "19107"
},
{
"name": "Gherkin",
"bytes": "99506"
},
{
"name": "HTML",
"bytes": "39622"
},
{
"name": "JavaScript",
"bytes": "302896"
},
{
"name": "PowerShell",
"bytes": "7839"
},
{
"name": "Ruby",
"bytes": "1725"
},
{
"name": "Smalltalk",
"bytes": "2632"
},
{
"name": "XSLT",
"bytes": "10348"
}
],
"symlink_target": ""
} |
%% Tensors
% Tensors are extensions of multidimensional arrays with additional
% operations defined on them. Here we explain the basics of creating and
% working with tensors.
%% Creating a tensor from an array
% The |tensor| command converts a (multidimensional) array to a tensor
% object.
M = ones(4,3,2); %<-- A 4 x 3 x 2 array.
X = tensor(M) %<-- Convert to a tensor object.
%%
% Optionally, you can specify a different shape for the tensor, so long as
% the input array has the right number of elements.
X = tensor(M,[2 3 4]) %<-- M has 24 elements.
%% Creating a one-dimensional tensor
% The tensor class explicitly supports order-one tensors as well as
% trailing singleton dimensions, but the size must be explicit in the
% constructor. By default, a column array produces a 2-way tensor.
X = tensor(rand(5,1)) %<-- Creates a 2-way tensor.
%%
% This is fixed by specifying the size explicitly.
X = tensor(rand(5,1),5) %<-- Creates a 1-way tensor.
%% Specifying trailing singleton dimensions in a tensor
% Likewise, trailing singleton dimensions must be explictly specified.
Y = tensor(rand(4,3,1)) %<-- Creates a 2-way tensor.
%%
Y = tensor(rand(4,3,1),[4 3 1]) %<-- Creates a 3-way tensor.
%%
% Unfortunately, the |whos| command does not report the size of 1D
% objects correctly (last checked for MATLAB 2006a).
whos X Y %<-- Doesn't report the right size for X!
%% The constituent parts of a tensor
X = tenrand([4 3 2]); %<-- Create data.
X.data %<-- The array.
%%
X.size %<-- The size.
%% Creating a tensor from its constituent parts
Y = tensor(X.data,X.size) %<-- Copies X.
%% Creating an empty tensor
% An empty constructor exists, primarily to support loading previously
% saved data in MAT-files.
X = tensor %<-- Creates an empty tensor.
%% Use tenone to create a tensor of all ones
X = tenones([3 4 2]) %<-- Creates a 3 x 4 x 2 tensor of ones.
%% Use tenzeros to create a tensor of all zeros
X = tenzeros([1 4 2]) %<-- Creates a 1 x 4 x 2 tensor of zeros.
%% Use tenrand to create a random tensor
X = tenrand([5 4 2]) %<-- Creates a random 5 x 4 x 2 tensor.
%% Use squeeze to remove singleton dimensions from a tensor
squeeze(Y) %<-- Removes singleton dimensions.
%% Use double to convert a tensor to a (multidimensional) array
double(Y) %<-- Converts Y to a standard MATLAB array.
%%
Y.data %<-- Same thing.
%% Use ndims and size to get the size of a tensor
ndims(Y) %<-- Number of dimensions (or ways).
%%
size(Y) %<-- Row vector with the sizes of all dimension.
%%
size(Y,3) %<-- Size of a single dimension.
%% Subscripted reference for a tensor
X = tenrand([3 4 2 1]); %<-- Create a 3 x 4 x 2 x 1 random tensor.
X(1,1,1,1) %<-- Extract a single element.
%%
% It is possible to extract a subtensor that contains a single element.
% Observe that singleton dimensions are *not* dropped unless they are
% specifically specified, e.g., as above.
X(1,1,1,:) %<-- Produces a tensor of order 1 and size 1.
%%
% In general, specified dimensions are dropped from the result. Here we
% specify the second and third dimension.
X(:,1,1,:) %<-- Produces a tensor of size 3 x 1.
%%
% Moreover, the subtensor is automatically renumbered/resized in the same
% way that MATLAB works for arrays except that singleton dimensions are
% handled explicitly.
X(1:2,[2 4],1,:) %<-- Produces a tensor of size 2 x 2 x 1.
%%
% It's also possible to extract a list of elements by passing in an array
% of subscripts or a column array of linear indices.
subs = [1,1,1,1; 3,4,2,1]; X(subs) %<-- Extract 2 values by subscript.
%%
inds = [1; 24]; X(inds) %<-- Same thing with linear indices.
%%
% The difference between extracting a subtensor and a list of linear
% indices is ambiguous for 1-dimensional tensors. We can specify 'extract'
% as a second argument whenever we are using a list of subscripts.
X = tenrand(10); %<-- Create a random tensor.
X([1:6]') %<-- Extract a subtensor.
%%
X([1:6]','extract') %<-- Same thing *but* result is a vector.
%% Subscripted assignment for a tensor
% We can assign a single element, an entire subtensor, or a list of values
% for a tensor.
X = tenrand([3,4,2]); %<-- Create some data.
X(1,1,1) = 0 %<-- Replaces the (1,1,1) element.
%%
X(1:2,1:2,1) = ones(2,2) %<-- Replaces a 2 x 2 subtensor.
%%
X([1 1 1;1 1 2]) = [5;7] %<-- Replaces the (1,1,1) and (1,1,2) elements.
%%
X([1;13]) = [5;7] %<-- Same as above using linear indices.
%%
% It is possible to *grow* the tensor automatically by assigning elements
% outside the original range of the tensor.
X(1,1,3) = 1 %<-- Grows the size of the tensor.
%% Using end for the last array index.
X(end,end,end) %<-- Same as X(3,4,3).
%%
X(1,1,1:end-1) %<-- Same as X(1,1,1:2).
%%
% It is also possible to use |end| to index past the end of an array.
X(1,1,end+1) = 5 %<-- Same as X(1,1,4).
%% Use find for subscripts of nonzero elements of a tensor
% The |find| function returns a list of nonzero *subscripts* for a tensor.
% Note that differs from the standard version, which returns linear
% indices.
X = tensor(floor(3*rand(2,2,2))) %<-- Generate some data.
%%
[S,V] = find(X) %<-- Find all the nonzero subscripts and values.
%%
S = find(X >= 2) %<-- Find subscripts of values >= 2.
%%
V = X(S) %<-- Extract the corresponding values from X.
%% Basic operations (plus, minus, and, or, etc.) on a tensor
% The tensor object supports many basic operations, illustrated here.
A = tensor(floor(3*rand(2,3,2)))
B = tensor(floor(3*rand(2,3,2)))
%%
A & B %<-- Calls and.
%%
A | B %<-- Calls or.
%%
xor(A,B) %<-- Calls xor.
%%
A==B %<-- Calls eq.
%%
A~=B %<-- Calls neq.
%%
A>B %<-- Calls gt.
%%
A>=B %<-- Calls ge.
%%
A<B %<-- Calls lt.
%%
A<=B %<-- Calls le.
%%
~A %<-- Calls not.
%%
+A %<-- Calls uplus.
%%
-A %<-- Calls uminus.
%%
A+B %<-- Calls plus.
%%
A-B %<-- Calls minus.
%%
A.*B %<-- Calls times.
%%
5*A %<-- Calls mtimes.
%%
A.^B %<-- Calls power.
%%
A.^2 %<-- Calls power.
%%
A.\B %<-- Calls ldivide.
%%
A./2 %<-- Calls rdivide.
%%
A./B %<-- Calls rdivide (but beware divides by zero!)
%% Using tenfun for elementwise operations on one or more tensors
% The function |tenfun| applies a specified function to a number of
% tensors. This can be used for any function that is not predefined for
% tensors.
tenfun(@(x)+1,A) %<-- Increment every element of A by one.
%%
tenfun(@max,A,B) %<-- Max of A and B, elementwise.
%%
C = tensor(floor(5*rand(2,3,2))) %<-- Create another tensor.
tenfun(@median,A,B,C) %<-- Elementwise means for A, B, and C.
%% Use permute to reorder the modes of a tensor
X = tensor(1:24,[3 4 2]) %<-- Create a tensor.
%%
permute(X,[3 2 1]) %<-- Reverse the modes.
%%
% Permuting a 1-dimensional tensor works correctly.
X = tensor(1:4,4); %<-- Create a 1-way tensor.
permute(X,1) %<-- Call permute with *only* one dimension.
%% Displaying a tensor
% The function |disp| can be used to display a tensor and correctly
% displays very small and large elements.
X = tensor(1:24,[3 4 2]); %<-- Create a 3 x 4 x 2 tensor.
X(:,:,1) = X(:,:,1) * 1e15; %<-- Make the first slice very large.
X(:,:,2) = X(:,:,2) * 1e-15; %<-- Make the second slice very small.
disp(X)
| {
"content_hash": "eeb30ddc4bb71bcf75dbaebff79d5ee2",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 74,
"avg_line_length": 37.47422680412371,
"alnum_prop": 0.6471801925722146,
"repo_name": "iqbalu/3D_Pose_Estimation_CVPR2016",
"id": "681bce908092f28bdd83a69916154c301514fc61",
"size": "7270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools_intern/toolboxes/tensor_toolbox/doc/A1_tensor_doc.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3751"
},
{
"name": "C",
"bytes": "188196"
},
{
"name": "C++",
"bytes": "2016823"
},
{
"name": "CMake",
"bytes": "12832"
},
{
"name": "CSS",
"bytes": "3682"
},
{
"name": "HTML",
"bytes": "340919"
},
{
"name": "Limbo",
"bytes": "42"
},
{
"name": "M",
"bytes": "4133"
},
{
"name": "Makefile",
"bytes": "26071"
},
{
"name": "Matlab",
"bytes": "5856729"
},
{
"name": "Mercury",
"bytes": "520"
},
{
"name": "Objective-C",
"bytes": "6778"
},
{
"name": "Protocol Buffer",
"bytes": "662"
},
{
"name": "Shell",
"bytes": "20881"
},
{
"name": "TeX",
"bytes": "12883"
},
{
"name": "XSLT",
"bytes": "15892"
}
],
"symlink_target": ""
} |
package org.thymeleaf.examples.springboot3.stsm.mvc.web.conversion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.Formatter;
public class DateFormatter implements Formatter<Date> {
@Autowired
private MessageSource messageSource;
public DateFormatter() {
super();
}
public Date parse(final String text, final Locale locale) throws ParseException {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.parse(text);
}
public String print(final Date object, final Locale locale) {
final SimpleDateFormat dateFormat = createDateFormat(locale);
return dateFormat.format(object);
}
private SimpleDateFormat createDateFormat(final Locale locale) {
final String format = this.messageSource.getMessage("date.format", null, locale);
final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
return dateFormat;
}
}
| {
"content_hash": "432ce40d47e0c945e710c9c8f74a409b",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 89,
"avg_line_length": 29.48780487804878,
"alnum_prop": 0.7419354838709677,
"repo_name": "thymeleaf/thymeleaf",
"id": "b900868e3ebd83b5f1232b3d2f87282dbe0b7552",
"size": "2040",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.1-master",
"path": "examples/springboot3/thymeleaf-examples-springboot3-stsm-mvc/src/main/java/org/thymeleaf/examples/springboot3/stsm/mvc/web/conversion/DateFormatter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "831981"
},
{
"name": "Java",
"bytes": "6999351"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die('Restricted access');
?><form action="<?php echo JRoute::_('index.php?option=com_acymailing&ctrl='.$this->ctrl); ?>" method="post" name="adminForm" id="adminForm" autocomplete="off" <?php if(in_array($this->type, array('news', 'autonews'))){
if(!isset($this->app) || $this->app->isAdmin()) echo 'style="width:42%;min-width:480px;float:left;margin-right:15px;"';
} ?>>
<div class="<?php if(!isset($this->app) || $this->app->isAdmin()){
echo 'acyblockoptions';
}else{
echo 'onelineblockoptions';
} ?> acyblock_newsletter" id="sendatest">
<span class="acyblocktitle"><?php echo acymailing_translation('SEND_TEST'); ?></span>
<table width="100%">
<tr>
<td valign="top" width="100px;" nowrap="nowrap">
<?php echo acymailing_translation('SEND_TEST_TO'); ?>
</td>
<td>
<?php echo $this->testreceiverType->display($this->infos->test_selection, $this->infos->test_group, $this->infos->test_emails); ?>
</td>
</tr>
<tr>
<td nowrap="nowrap">
<?php echo acymailing_translation('SEND_VERSION'); ?>
</td>
<td>
<?php if($this->mail->html){
echo JHTML::_('acyselect.booleanlist', 'test_html', '', $this->infos->test_html, acymailing_translation('HTML'), acymailing_translation('JOOMEXT_TEXT'));
}else{
echo acymailing_translation('JOOMEXT_TEXT');
echo '<input type="hidden" name="test_html" value="0" />';
} ?>
</td>
</tr>
<tr>
<td valign="top"><?php echo acymailing_translation('SEND_COMMENT'); ?></td>
<td>
<div><textarea placeholder="<?php echo acymailing_translation('SEND_COMMENT_DESC'); ?>" name="commentTest" id="commentTest" style="width:90%;height:80px;"><?php echo JRequest::getString('commentTest', ''); ?></textarea></div>
</td>
</tr>
<tr>
<td>
</td>
<td style="padding-top:10px;">
<button type="submit" class="acymailing_button" onclick="var val = document.getElementById('message_receivers').value; if(val != ''){ setUser(val); }"><?php echo acymailing_translation('SEND_TEST') ?></button>
</td>
</tr>
</table>
</div>
<input type="hidden" name="cid[]" value="<?php echo $this->mail->mailid; ?>"/>
<input type="hidden" name="option" value="<?php echo ACYMAILING_COMPONENT; ?>"/>
<?php if(!empty($this->lists)){
$firstList = reset($this->lists);
$myListId = $firstList->listid;
}else{
$myListId = JRequest::getInt('listid', 0);
}
if(!empty($myListId)){
?> <input type="hidden" name="listid" value="<?php echo $myListId; ?>"/> <?php } ?>
<input type="hidden" name="task" value="sendtest"/>
<input type="hidden" name="ctrl" value="<?php echo $this->ctrl; ?>"/>
<?php echo JHTML::_('form.token'); ?>
</form>
| {
"content_hash": "a22e2b6c5f8cadc53148e4b2900e9dc0",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 230,
"avg_line_length": 41.676923076923075,
"alnum_prop": 0.6183093392395718,
"repo_name": "yaelduckwen/libriastore",
"id": "670240b04fa2a05d46a8a8a5af2fdfceebb14d81",
"size": "2917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "joomla/administrator/components/com_acymailing/views/newsletter/tmpl/test.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "44"
},
{
"name": "CSS",
"bytes": "2779463"
},
{
"name": "HTML",
"bytes": "26380"
},
{
"name": "JavaScript",
"bytes": "2813038"
},
{
"name": "PHP",
"bytes": "24821947"
},
{
"name": "PLpgSQL",
"bytes": "2393"
},
{
"name": "SQLPL",
"bytes": "17688"
}
],
"symlink_target": ""
} |
<?php
/**
* <auto-generated>
* This code was generated by Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
* </auto-generated>
*/
namespace Mozu\Api\Clients\Commerce\Shipping\Admin;
use Mozu\Api\MozuClient;
use Mozu\Api\Urls\Commerce\Shipping\Admin\CarrierConfigurationUrl;
/**
* Use the Carriers resource to configure and manage your supported shipping carrier configurations.
*/
class CarrierConfigurationClient {
/**
* Retrieves a list of carrier configurations and their details according to any specified facets, filter criteria, and sort options.
*
* @param string $filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
* @param int $pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param string $sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.
* @param int $startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.
* @return MozuClient
*/
public static function getConfigurationsClient($startIndex = null, $pageSize = null, $sortBy = null, $filter = null, $responseFields = null)
{
$url = CarrierConfigurationUrl::getConfigurationsUrl($filter, $pageSize, $responseFields, $sortBy, $startIndex);
$mozuClient = new MozuClient();
$mozuClient->withResourceUrl($url);
return $mozuClient;
}
/**
* Retrieves the details of the specified carrier configuration.
*
* @param string $carrierId The unique identifier of the carrier.
* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @return MozuClient
*/
public static function getConfigurationClient($carrierId, $responseFields = null)
{
$url = CarrierConfigurationUrl::getConfigurationUrl($carrierId, $responseFields);
$mozuClient = new MozuClient();
$mozuClient->withResourceUrl($url);
return $mozuClient;
}
/**
* Creates a new carrier configuration.
*
* @param string $carrierId The unique identifier of the carrier.
* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param CarrierConfiguration $carrierConfiguration Properties of a carrier configured in the shipping admin.
* @return MozuClient
*/
public static function createConfigurationClient($carrierConfiguration, $carrierId, $responseFields = null)
{
$url = CarrierConfigurationUrl::createConfigurationUrl($carrierId, $responseFields);
$mozuClient = new MozuClient();
$mozuClient->withResourceUrl($url)->withBody($carrierConfiguration);
return $mozuClient;
}
/**
* Updates the details of the specified carrier configuration.
*
* @param string $carrierId The unique identifier of the carrier.
* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param CarrierConfiguration $carrierConfiguration Properties of a carrier configured in the shipping admin.
* @return MozuClient
*/
public static function updateConfigurationClient($carrierConfiguration, $carrierId, $responseFields = null)
{
$url = CarrierConfigurationUrl::updateConfigurationUrl($carrierId, $responseFields);
$mozuClient = new MozuClient();
$mozuClient->withResourceUrl($url)->withBody($carrierConfiguration);
return $mozuClient;
}
/**
* Deletes the specified carrier configuration.
*
* @param string $carrierId The unique identifier of the carrier configuration.
*/
public static function deleteConfigurationClient($carrierId)
{
$url = CarrierConfigurationUrl::deleteConfigurationUrl($carrierId);
$mozuClient = new MozuClient();
$mozuClient->withResourceUrl($url);
return $mozuClient;
}
}
?>
| {
"content_hash": "7838af670d684fd1568faa13b16e8ece",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 277,
"avg_line_length": 47.873873873873876,
"alnum_prop": 0.751411366202484,
"repo_name": "Mozu/mozu-php-sdk",
"id": "8380f3622e0175dcee754281fbf442268884f8ad",
"size": "5314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Clients/Commerce/Shipping/Admin/CarrierConfigurationClient.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "3510959"
}
],
"symlink_target": ""
} |
// Implement atoi which converts a string to an integer.
// The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
// The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
// If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
// If no valid conversion could be performed, a zero value is returned.
// Note:
// Only the space character ' ' is considered as whitespace character.
// Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
// Example 1:
// Input: "42"
// Output: 42
// Example 2:
// Input: " -42"
// Output: -42
// Explanation: The first non-whitespace character is '-', which is the minus sign.
// Then take as many numerical digits as possible, which gets 42.
// Example 3:
// Input: "4193 with words"
// Output: 4193
// Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
// Example 4:
// Input: "words and 987"
// Output: 0
// Explanation: The first non-whitespace character is 'w', which is not a numerical
// digit or a +/- sign. Therefore no valid conversion could be performed.
// Example 5:
// Input: "-91283472332"
// Output: -2147483648
// Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
// Thefore INT_MIN (−231) is returned.
/**
* 将字符串转化为整数,注意是否超过给定的范围
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
let match = str.match(/^ *([+-]{0,1}[0-9]+)/);
return match ? Math.min(2147483647, Math.max(-2147483648, match[1])) : 0;
}; | {
"content_hash": "120211a97689cc908f3918af61727479",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 297,
"avg_line_length": 43.64705882352941,
"alnum_prop": 0.7115902964959568,
"repo_name": "lanpong/LeetCode",
"id": "56c56973269a1937556fcfc54dc7745cd8dee09b",
"size": "2278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JavaScript/8-string-to-integer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "12093"
},
{
"name": "Python",
"bytes": "34067"
}
],
"symlink_target": ""
} |
namespace agi {
class Ngraph;
//A class to handle iteration over edges of a certain type
//The pointer = 1+type+num_types*edge_id
class PinIterator {
friend class Ngraph;
lid_t* loc;
lid_t* end;
PinIterator(lid_t* l,lid_t* e)
:loc(l),end(e) {}
void iterate() {loc++;}
};
}
#endif
| {
"content_hash": "d4cd0f3dceccc3bc955cd8c4146f720a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 58,
"avg_line_length": 15.842105263157896,
"alnum_prop": 0.6411960132890365,
"repo_name": "SCOREC/EnGPar",
"id": "1d140ce43674bc0e1b0d952b25372e4297cc0b11",
"size": "397",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "agi/Iterators/PinIterator.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "446"
},
{
"name": "C++",
"bytes": "398355"
},
{
"name": "CMake",
"bytes": "43030"
},
{
"name": "Fortran",
"bytes": "25863"
},
{
"name": "Shell",
"bytes": "7666"
}
],
"symlink_target": ""
} |
package com.yueny.demo.job.scheduler.tbschedulejob.runner;
import java.io.Serializable;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections4.CollectionUtils;
import com.yueny.demo.job.bo.ModifyDemoBo;
import com.yueny.demo.job.scheduler.base.BaseTask;
import com.yueny.demo.job.service.IDataPrecipitationService;
import com.yueny.rapid.lang.json.JsonUtil;
import com.yueny.rapid.lang.util.UuidUtil;
import com.yueny.rapid.lang.util.time.SystemClock;
import com.yueny.superclub.util.crypt.util.TripleDesEncryptUtil;
/**
* 处理中交易的状态重置
*
* @author yueny09 <[email protected]>
*
* @DATE 2016年11月16日 下午1:39:13
*
*/
public class HandlingDataSingleDealTaskRunner extends BaseTask implements Callable<Integer>, Serializable {
private static Random rn = new Random();
/**
*
*/
private static final long serialVersionUID = -7975387809977577316L;
private final IDataPrecipitationService dataPrecipitationService;
/**
* 任务号
*/
private final String taskId;
/**
* 保存任务所需要的数据
*/
private final List<Long> ts;
public HandlingDataSingleDealTaskRunner(final List<Long> ts, final IDataPrecipitationService dataPrecip) {
this.ts = ts;
this.dataPrecipitationService = dataPrecip;
taskId = UuidUtil.getSimpleUuid();
}
@Override
public Integer call() throws Exception {
if (CollectionUtils.isEmpty(ts)) {
return 0;
}
int current = 0;
final long start = SystemClock.now();
for (final Long id : ts) {
final ModifyDemoBo demoBo = dataPrecipitationService.findById(id);
final String json = JsonUtil.toJson(demoBo);
TripleDesEncryptUtil.tripleDesEncrypt(json);
try {
TimeUnit.MILLISECONDS.sleep(20);
} catch (final InterruptedException e) {
e.printStackTrace();
}
demoBo.setType("Y");
dataPrecipitationService.update(demoBo);
current++;
}
final long end = SystemClock.now();
logger.debug("任务号:{} 耗时:{}秒, 返回:{}, 总数据:{}条.", taskId, (end - start) / 1000, current, ts.size());
return current;
}
}
| {
"content_hash": "af279f7653807c67947ff3efe958bc17",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 107,
"avg_line_length": 27.0625,
"alnum_prop": 0.7122401847575057,
"repo_name": "yueny/pra",
"id": "f33f4494aa1ea1549c005047a3b43af5578aa670",
"size": "2245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "job/tbschedulejob/src/main/java/com/yueny/demo/job/scheduler/tbschedulejob/runner/HandlingDataSingleDealTaskRunner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "721477"
},
{
"name": "FreeMarker",
"bytes": "16071"
},
{
"name": "HTML",
"bytes": "72010"
},
{
"name": "Java",
"bytes": "1399374"
},
{
"name": "JavaScript",
"bytes": "824745"
},
{
"name": "Shell",
"bytes": "5967"
}
],
"symlink_target": ""
} |
var App; //global App object
new Promise(function(resolve, reject) {
App = new ApplicationBuilder({
onconstruct : function () {
console.log("Constructor", this, arguments);
},
onready : function () {
var App = this;
App.modulePath('..//../../constructors');
App.require(["lib", "extensions/prototype"], function (lib) {
lib.lib(); //loads all application-prototype modules
App.modulePath('/scripts/modules'); //specifying module path for retrieving modules
});
}
});
});
| {
"content_hash": "762fea8acd84df3c08c4912071f34bec",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 87,
"avg_line_length": 29.705882352941178,
"alnum_prop": 0.6534653465346535,
"repo_name": "eugeniumegherea/MIDPS-lab-5",
"id": "b0952ba19763a90a5ff4a8317cb18b4755bd12b4",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/scripts/application-prototype/docs/examples/application-prototype-initialize/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7910"
},
{
"name": "HTML",
"bytes": "16806"
},
{
"name": "JavaScript",
"bytes": "121574"
},
{
"name": "Smarty",
"bytes": "638"
}
],
"symlink_target": ""
} |
// see README.mkd for mor information
package main
import (
"github.com/jteeuwen/glfw"
"github.com/banthar/gl"
"github.com/banthar/glu"
"log"
"fmt"
"image/color"
)
// Represent a vector with color information
type Vector struct {
X, Y, Z float32
Color color.Color
}
// Return the string representation of the vector coords
func (v *Vector) Coords() string {
return fmt.Sprintf("(%.2f,%.2f,%.2f)", v.X, v.Y, v.Z)
}
// Return the string representation of the vector color.
// If the color is a pre-defined return the name, otherwise return the color components
func (v *Vector) ColorName() string {
if v.Color == color.Black {
return "Black"
} else if v.Color == color.White {
return "White"
} else if v.Color == color.Transparent {
return "Transparent"
} else if v.Color == color.Opaque {
return "Opaque"
} else {
r,g,b,a := v.Color.RGBA()
return fmt.Sprintf("[%d,%d,%d,%d]",r,g,b,a)
}
return ""
}
// Represents a collection of vectors with color information
type Mesh struct {
V []*Vector
}
// Render the mesh
// The V array must be a multiple of 3 since it uses triangles to render the mesh.
// If two or more triangles share the same edge the user can pass the same pointer twice
func (m *Mesh) Render() {
count := 0
gl.Begin(gl.TRIANGLES)
for _, v := range(m.V) {
if count % 3 == 0 && count > 0 {
gl.End()
gl.Begin(gl.TRIANGLES)
count = 0
}
gl.Color3f(1,0,0)
gl.Vertex3f(v.X, v.Y, v.Z)
count++
}
if count > 0 {
gl.End()
}
}
type Render interface {
Render()
}
var (
// used when the user press Esc to exit
// buffered in one unit to avoid locking on channel send
exit chan int = make(chan int,1)
)
func main() {
log.Printf("Starting glfw window")
err := glfw.Init()
if err != nil {
log.Fatalf("Error while starting glfw library: %v", err)
}
defer glfw.Terminate()
err = glfw.OpenWindow(256,256, 8,8,8, 0, 0, 0, glfw.Windowed)
if err != nil {
log.Fatalf("Error while opening glfw window: %v", err)
}
defer glfw.CloseWindow()
glfw.SetSwapInterval(1) //vsync on
glfw.SetWindowTitle("Colored Triangle")
InitGL()
glfw.SetWindowSizeCallback(func(w,h int){ InitGLWindow(w,h) })
glfw.SetKeyCallback(func(key,state int){ HandleKey(key,state) })
// create a mesh with 3 vertices (a triangle)
m := &Mesh{make([]*Vector,3)}
m.V[0] = &Vector{0,1,0, color.NRGBA{1, 0, 0, 0}}
m.V[1] = &Vector{-1,-1,0, color.NRGBA{0, 1, 0, 0}}
m.V[2] = &Vector{1, -1, 0, color.NRGBA{0, 0, 1, 0}}
run := true
for run && glfw.WindowParam(glfw.Opened) == 1 {
select {
case exitCode := <-exit:
log.Printf("Received exit code: %d", exitCode)
run = false
default:
Draw(m)
}
}
}
func HandleKey(key, state int) {
switch key {
case glfw.KeyEsc:
exit <- 0
}
}
// Initialize the OpenGL configuration with the information from the current window.
func InitGLWindow(w,h int) {
gl.Viewport(0,0,w,h)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
glu.Perspective(45.0, float64(w)/float64(h), 0.1, 100.0)
gl.MatrixMode(gl.MODELVIEW)
gl.LoadIdentity()
}
// Initialize the OpenGL configuration that don't depend on window parameters
func InitGL() {
gl.ShadeModel(gl.SMOOTH)
gl.ClearColor(0,0,0,0)
gl.ClearDepth(1)
gl.Enable(gl.DEPTH_TEST)
gl.DepthFunc(gl.LEQUAL)
gl.Hint(gl.PERSPECTIVE_CORRECTION_HINT, gl.NICEST)
}
// Render stuff
func Draw(r Render) {
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.LoadIdentity()
gl.Translatef(-1.5, 0, -6)
/*
gl.Begin(gl.TRIANGLES)
gl.Color3f(1, 0, 0)
gl.Vertex3f(0, 1, 0)
gl.Color3f(1, 0, 0)
gl.Vertex3f(-1, -1, 0)
gl.Color3f(1, 0, 0)
gl.Vertex3f(1, -1, 0)
gl.End()
*/
r.Render()
glfw.SwapBuffers()
}
| {
"content_hash": "a1a1de15cfcc451e5516f08aed8b50a4",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 88,
"avg_line_length": 21.80952380952381,
"alnum_prop": 0.6604803493449781,
"repo_name": "andrebq/tinygl",
"id": "639526558abc3cbfdd41fdc45d6dde7dbc13b625",
"size": "3664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "experiments/scene/scene.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2807"
},
{
"name": "Go",
"bytes": "5650"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Ekskluzywyne meble na zamówienie do każdego wnętrza">
<meta name="author" content="WebADDer">
<title>Industrive - ekskluzywne meble na zamówienie</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/modern-business.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><img src="img/logoexc.png" id="logo"></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">Strona główna</a>
</li>
<li>
<a href="onas.html">O nas</a>
</li>
<li>
<a href="galeria.html">Galeria</a>
</li>
<li>
<a href="kontakt.html">Kontakt</a>
</li>
<li>
<a href="faq.html">FAQ</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Portfolio Item
<small>Subheading</small>
</h1>
<ol class="breadcrumb">
<li><a href="index.html">Strona główna</a>
</li>
<li class="active">Portfolio Item</li>
</ol>
</div>
</div>
<!-- /.row -->
<!-- Portfolio Item Row -->
<div class="row">
<div class="col-md-8">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img class="img-responsive" src="img/meblegaleria/1.jpg" alt="">
</div>
<div class="item">
<img class="img-responsive" src="img/meblegaleria/2.jpg" alt="">
</div>
<div class="item">
<img class="img-responsive" src="img/meblegaleria/3.jpg" alt="">
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
<div class="col-md-4">
<h3>Project Description</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae. Sed dui lorem, adipiscing in adipiscing et, interdum nec metus. Mauris ultricies, justo eu convallis placerat, felis enim.</p>
<h3>Project Details</h3>
<ul>
<li>Lorem Ipsum</li>
<li>Dolor Sit Amet</li>
<li>Consectetur</li>
<li>Adipiscing Elit</li>
</ul>
</div>
</div>
<!-- /.row -->
<!-- Related Projects Row -->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header">Related Projects</h3>
</div>
<div class="col-sm-3 col-xs-6">
<a href="#">
<img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt="">
</a>
</div>
<div class="col-sm-3 col-xs-6">
<a href="#">
<img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt="">
</a>
</div>
<div class="col-sm-3 col-xs-6">
<a href="#">
<img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt="">
</a>
</div>
<div class="col-sm-3 col-xs-6">
<a href="#">
<img class="img-responsive img-hover img-related" src="http://placehold.it/500x300" alt="">
</a>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Industrive 2017</p>
<p style="font-size: 9px">Zdjęcia na stronie pochodzą z internetu i są przykładami możliwych realizacji.</p>
</div>
</div>
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "191b89cc3de90ac5e91bcc9c0d490d32",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 268,
"avg_line_length": 37.34848484848485,
"alnum_prop": 0.46531440162271803,
"repo_name": "Aderrro/Aderrro.github.io",
"id": "d2d348a0a137fcc029ce6347a6f726024549454d",
"size": "7408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "portfolio-item.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "112477"
},
{
"name": "HTML",
"bytes": "229306"
},
{
"name": "JavaScript",
"bytes": "43126"
},
{
"name": "PHP",
"bytes": "1267"
}
],
"symlink_target": ""
} |
ActionController::Base.session = {
:key => '_semantix_session',
:secret => '4f69221b37860083e9ad1522ce0afba8e8655bc9c35913226be78fa1b179bd22d96e76cb4889c2d8ee0ad614986c387f0e12a42c67b6fad04a9192ef0890aa8a'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store
| {
"content_hash": "b63b86ce120f3dfb296764dd2a073d45",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 148,
"avg_line_length": 53.77777777777778,
"alnum_prop": 0.7913223140495868,
"repo_name": "leenookx/semantix",
"id": "9bb9daaf5b35537957b19d2791a6492dafa1e487",
"size": "801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/initializers/session_store.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "23976"
},
{
"name": "Ruby",
"bytes": "79990"
},
{
"name": "Shell",
"bytes": "371"
}
],
"symlink_target": ""
} |
<?php
// No direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html');
// JHtml::_('bootstrap.tooltip');
// JHtml::_('behavior.multiselect');
// JHtml::_('formbehavior.chosen', 'select');
$user = JFactory::getUser();
$userId = $user->get('id');
$listOrder = $this->state->get('list.ordering');
$listDirn = $this->state->get('list.direction');
$canCreate = $user->authorise('core.create', 'com_akrecipes');
$canEdit = $user->authorise('core.edit', 'com_akrecipes');
$canCheckin = $user->authorise('core.manage', 'com_akrecipes');
$canChange = $user->authorise('core.edit.state', 'com_akrecipes');
$canDelete = $user->authorise('core.delete', 'com_akrecipes');
$image = $this->item->brand_image;
if (strpos($image, '/') === 0 ) {
$image = substr($image, 1);
}
?>
<?php if ($this->item) : ?>
<div id="ak_brandpage" class="brandpage">
<?php if ($this->params->get('show_page_heading')) : ?>
<div class="page-header">
<h1> <?php echo $this->escape($this->params->get('page_heading')); ?> </h1>
</div>
<?php else: ?>
<div class="page-header">
<h1><?php echo $this->item->brand_name ; ?></h1>
</div>
<?php endif; ?>
<div class="container-fluid">
<?php if ($this->params->get('brandpage_show_brand_profile')) : ?>
<div class="row brandProfile">
<?php if ($this->params->get('brandpage_show_brand_image')) :?>
<div class="col-md-2 col-xs-12 brandImage">
<img class="img-thumbnail" src="<?php echo $image ; ?>" alt="<?php echo $this->item->brand_name ; ?>"></img>
</div>
<?php endif ; ?>
<?php if ($this->params->get('brandpage_show_brand_description')) : ?>
<div class="col-md-10 col-xs-10 brandDescription">
<p>
<?php echo $this->item->brand_description ; ?>
</p>
<?php if ($this->params->get('brandpage_show_brand_url')) : ?>
<p>
<a href="<?php echo $this->item->brand_url ; ?>" title="<?php echo $this->item->brand_description ; ?>" target="_blank">
<?php echo $this->item->brand_name ; ?><i class="fa fa-external-link"></i>
</a>
</p>
<?php endif ; ?>
</div>
<?php endif ; ?>
</div>
<?php endif ; ?>
<?php
$columns = $this->params->get('brandpage_num_columns',4) ;
$rows = count($this->recipes)/$columns ;
$this->colspan = (int) 12/$columns;
$counter = 0;
?>
<div class="brandRecipes">
<?php
$recipe_count = count($this->recipes);
?>
<h2>Recipes by <?php echo $this->item->brand_name ; ?></h2>
<?php foreach ($this->recipes as $key => $recipe) : ?>
<?php $rowcount = ((int) $key % (int) $columns) + 1; ?>
<?php if ($rowcount == 1) : ?>
<div class="row"><!-- begin row -->
<?php endif ; ?>
<?php
$this->recipe = $recipe ;
echo $this->loadTemplate('recipe');
?>
<?php if (($rowcount == $columns) or ($counter == $recipe_count)) : ?>
</div><!-- end row -->
<?php endif; ?>
<?php $counter++ ; ?>
<?php endforeach ; ?>
</div><!-- end brandRecipes -->
</div><!-- end containerfluid -->
<?php echo $this->pagination->getListFooter(); ?>
</div> <!-- end brand page -->
<?php
else:
echo JText::_('COM_AKRECIPES_ITEM_NOT_LOADED');
endif;
?> | {
"content_hash": "9df75d3572a47e4f4b2273c319ff536e",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 129,
"avg_line_length": 30.63888888888889,
"alnum_prop": 0.5521305530371714,
"repo_name": "rutvikd/ak-recipes",
"id": "544402ea4ba78550ab3aa0110ec363cf2c7f999c",
"size": "3536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com_akrecipes-1.0.1/site/views/brand/tmpl/default.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "300248"
},
{
"name": "HTML",
"bytes": "10562"
},
{
"name": "JavaScript",
"bytes": "177835"
},
{
"name": "PHP",
"bytes": "6358610"
},
{
"name": "Shell",
"bytes": "257"
}
],
"symlink_target": ""
} |
package com.adrbtk.exchange;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.adrbtk.exchange.model.Data;
import com.adrbtk.exchange.model.Organization;
import com.adrbtk.exchange.model.Request;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list);
Data data = null;
try {
AsyncTask<String, Void, Data> task = new GetTask().execute("ru");
data = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
final List<Organization> finalData = new ArrayList<>();
for (Organization orrg : data.organizations) {
if (orrg.currencies.containsKey("USD")) {
if (!isNOtAdded(finalData, orrg)) {
finalData.add(orrg);
}
}
}
listView.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return finalData.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Organization curOrg = finalData.get(i);
View iv = getLayoutInflater().inflate(R.layout.list_item, viewGroup, false);
TextView org = ((TextView) iv.findViewById(R.id.organization));
org.setText(curOrg.title);
Typeface tf = Typeface.createFromAsset(getAssets(), "digital-7 (mono).ttf");
String bid = curOrg.currencies.get("USD").bid;
String ask = curOrg.currencies.get("USD").ask;
TextView askView = (TextView) iv.findViewById(R.id.ask);
askView.setTypeface(tf);
askView.setText(ask.substring(0, ask.length() - 2));
TextView bidView = (TextView) iv.findViewById(R.id.bid);
bidView.setTypeface(tf);
bidView.setText(bid.substring(0, bid.length() - 2));
return iv;
}
});
TextView dateView = (TextView) findViewById(R.id.date);
dateView.setTypeface(Typeface.createFromAsset(getAssets(), "digital-7 (mono).ttf"));
dateView.setText(data.date);
}
private boolean isNOtAdded(List<Organization> list, Organization org2) {
for (Organization org1 : list) {
String[] split1 = org1.title.split(" ");
String[] split2 = org2.title.split(" ");
if (split1[0].equals(split2[0])) {
org1.title = split1[0];
return true;
}
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class GetTask extends AsyncTask<String, Void, Data> {
@Override
protected Data doInBackground(String... params) {
return Request.get("ru");
}
}
}
| {
"content_hash": "a39cad65e956241989be515d5004e92d",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 92,
"avg_line_length": 30.261194029850746,
"alnum_prop": 0.5822441430332922,
"repo_name": "adrbtk/Exchange",
"id": "23e1fff7b57d12eaea9f23787d514e23f649e2e3",
"size": "4055",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/adrbtk/exchange/MainActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5942"
}
],
"symlink_target": ""
} |
FOUNDATION_EXPORT double Auth0VersionNumber;
//! Project version string for Auth0.
FOUNDATION_EXPORT const unsigned char Auth0VersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Auth0/PublicHeader.h>
#import <Auth0/A0ChallengeGenerator.h>
| {
"content_hash": "6f0f02af23ee163cb0708ca932d3e7c3",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 130,
"avg_line_length": 39.5,
"alnum_prop": 0.8069620253164557,
"repo_name": "Vadimkomis/Myclok",
"id": "63d3e4d517f0eed9c95bd946d3d3f191b098b655",
"size": "1526",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "Pods/Auth0/Auth0/Auth0.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "519"
},
{
"name": "Swift",
"bytes": "27905"
}
],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-service',
templateUrl: './service.component.html',
styleUrls: ['./service.component.scss']
})
export class ServiceComponent implements OnInit {
constructor(private fb: FormBuilder, private router: Router) { }
salon_services =
[
{
'group_name': 'Manicure',
'description': 'manicure description',
'service_list': [{
'name': 'Regular Manicure',
'price': '15',
'time': '30'
}, {
'name': 'Shellac/Gel Polish Manicure',
'price': '30',
'time': '60'
}, {
'name': 'Paraffin Manicure',
'price': '20',
'time': '15'
}]
},
{
'group_name': 'ACRYLIC NAILS',
'description': 'manicure description',
'service_list': [{
'name': 'Full Set Acrylic',
'price': '25',
'time': '60'
}, {
'name': 'Refill Acrylic',
'price': '15',
'time': '60'
}]
}
]
ngOnInit() {
}
}
| {
"content_hash": "c5a54c951d3b58df026de9857d63c785",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 85,
"avg_line_length": 23.42,
"alnum_prop": 0.5294619982920581,
"repo_name": "salonhelps/dashboard",
"id": "86b4994d52845572524cd6f4f9d9adc9c025e822",
"size": "1171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/pages/service/service.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2217"
},
{
"name": "HTML",
"bytes": "14400"
},
{
"name": "JavaScript",
"bytes": "1884"
},
{
"name": "TypeScript",
"bytes": "33035"
}
],
"symlink_target": ""
} |
<?php
$serverrootpath = $_SERVER['DOCUMENT_ROOT'];
$includepath = $_SERVER['DOCUMENT_ROOT'] . "/portal/includes";
$rootpath = "/portal";
include("$serverrootpath/includes/db.inc.php");
include("$includepath/common.php");
user_protect();
$result = QueryWS1("SELECT TOP 100 a.DisplayAlias, (SELECT SUM(b.PostRating) FROM PPPosts b WHERE b.PPLoginID = a.PPLoginID) AS PostKarma FROM PlayerPortalLogin a WHERE a.Approved = 1 ORDER BY PostKarma DESC, RegDate ASC");
$result2 = QueryWS1("SELECT TOP 100 a.DisplayAlias, (SELECT SUM(b.CommentRating) FROM PPComments b WHERE b.PPLoginID = a.PPLoginID) AS CommentKarma FROM PlayerPortalLogin a WHERE a.Approved = 1 ORDER BY CommentKarma DESC, RegDate ASC");
//keep at bottom
include "$includepath/base.php";
?>
<?php startblock('title') ?>
Top Portal Karma
<?php endblock() ?>
<?php startblock('header') ?>
Top Portal Karma
<?php endblock() ?>
<?php startblock('additionalScripts') ?>
<?php endblock() ?>
<?php startblock('breadcrumbs') ?>
<li><a href="<?php echo $rootpath; ?>">Home</a></li> <span class="divider">/</span>
<li class="active">Top Portal Karma</a>
<?php endblock() ?>
<?php startblock('containerContent') ?>
<div class="row-fluid">
<div class="span6">
<div class="widget">
<h2>
<div class="pull-right guildlistdiv">
<a href="#" class="collapse"><i class="icon-chevron-up icon-white"></i></a>
</div>
Posts
</h2>
<div class="widget-inner">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Rank</th>
<th>User</th>
<th>Karma</th>
</tr>
</thead>
<tbody>
<?php
for ( $i = 0; $i < Num_Rows($result); $i++ ) {
$displayalias = Result($result, $i, "DisplayAlias");
$postkarma = Result($result, $i, "PostKarma");
$rank = $i + 1;
if ($postkarma != "") {
echo "<tr>";
echo "<td>$rank</td>";
echo "<td><a href='$rootpath/userprofile.php?username=$displayalias'>$displayalias</a></td>";
echo "<td>$postkarma</td>";
echo "</tr>";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="span6">
<div class="widget">
<h2>
<div class="pull-right guildlistdiv">
<a href="#" class="collapse"><i class="icon-chevron-up icon-white"></i></a>
</div>
Comments
</h2>
<div class="widget-inner">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Rank</th>
<th>User</th>
<th>Karma</th>
</tr>
</thead>
<tbody>
<?php
for ( $i = 0; $i < Num_Rows($result2); $i++ ) {
$displayalias = Result($result2, $i, "DisplayAlias");
$commentkarma = Result($result2, $i, "CommentKarma");
$rank = $i + 1;
if ($commentkarma != "") {
echo "<tr>";
echo "<td>$rank</td>";
echo "<td><a href='$rootpath/userprofile.php?username=$displayalias'>$displayalias</a></td>";
echo "<td>$commentkarma</td>";
echo "</tr>";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php endblock() ?> | {
"content_hash": "e65606eb7a13baaf8a4578dfd4093fef",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 237,
"avg_line_length": 28.591304347826085,
"alnum_prop": 0.5535279805352799,
"repo_name": "frodesigns/helbreath-player-portal",
"id": "7d89764db28347178bf5b66a9f4120c2401f4eab",
"size": "3288",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "topkarma.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10183"
},
{
"name": "JavaScript",
"bytes": "78324"
},
{
"name": "PHP",
"bytes": "767419"
}
],
"symlink_target": ""
} |
process.env.DATABASE_URL = 'postgres://localhost:5432/simple_book_store_test';
const chai = require('chai');
const expect = chai.expect;
const chaiHttp = require('chai-http');
const app = require('../../src/server');
chai.use(chaiHttp);
const request = chai.request;
context('Book routes', function () {
describe('/', function () {
it('Should render the home page', function () {
return request(app)
.get('/')
.then(response => {
expect(response).to.have.status(200);
});
});
});
describe('/books/search', function () {
it('Should render the search page when given a search term', function () {
return request(app)
.get("/books/search?search='harry'")
.then(response => {
expect(response).to.have.status(200);
});
});
});
describe('/books/create', function () {
it('Should respond with 401 when not an admin', function () {
return request(app)
.get('/books/create')
.then(response => {
expect(response).to.have.status(401);
})
.catch(error => {
expect(error.response).to.have.status(401);
});
});
it('Should render the page when user is an admin', function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.get('/books/create')
.then(response => {
expect(response).to.have.status(200);
});
});
});
it('Should respond with a 401 when a user that is not an admin tries to create a book', function () {
return request(app)
.post('/books/create')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ title: 'New Book',
price: 3.43,
image: 'http://NewImage.jpg',
inStock: 30,
isbn: 'New ISBN',
publisher: 'New Publisher',
firstName0: 'First Author',
lastName0: 'First Author',
firstName1: 'Second Author',
lastName1: 'Second Author',
genre0: 'First genre',
genre1: 'Second genre', })
.then(response => {
expect(response).to.have.status(401);
})
.catch(error => {
expect(error.response).to.have.status(401);
});
});
it('Should redirect to the newly created book page if user is an admin', function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.post('/books/create')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ title: 'New Book',
price: 3.43,
image: 'http://NewImage.jpg',
inStock: 30,
isbn: 'New ISBN',
publisher: 'New Publisher',
firstName0: 'First Author',
lastName0: 'First Author',
firstName1: 'Second Author',
lastName1: 'Second Author',
genre0: 'First genre',
genre1: 'Second genre', })
.then(response => {
expect(response.redirects[0]).to.match(/\/books\/4/);
});
});
});
it('Should render the create page with a message if the image url does not start with http or end with .jpg or .png', function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.post('/books/create')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ title: 'New Book',
price: 3.43,
image: 'NewImage',
inStock: 30,
isbn: 'New ISBN',
publisher: 'New Publisher',
firstName0: 'First Author',
lastName0: 'First Author',
firstName1: 'Second Author',
lastName1: 'Second Author',
genre0: 'First genre',
genre1: 'Second genre', })
.then(response => {
expect(response.res.text).to.include('Please input a valid image');
});
});
});
});
describe('/books/:id', function () {
it('Should render a page with a single books information', function () {
return request(app)
.get('/books/1')
.then(response => {
expect(response).to.have.status(200);
});
});
it('Should have a status of 401 if a user tries to delete a book and is not an admin', function () {
return request(app)
.delete('/books/1')
.then(response => {
expect(response).to.have.status(401);
})
.catch(error => {
expect(error.response).to.have.status(401);
});
});
it(`Should respond with 'Book with id 1 was deleted' if the user is an admin`, function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.delete('/books/1')
.then(response => {
expect(response.res.text).to.include('Book with id 1 was deleted');
});
});
});
});
describe('/books/:id/edit', function () {
it('Should have a status of 401 if a user is not a clerk or admin', function () {
return request(app)
.get('/books/1/edit')
.then(response => {
expect(response).to.have.status(401);
})
.catch(error => {
expect(error.response).to.have.status(401);
});
});
it('Should render a page if a user is an admin', function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.get('/books/1/edit')
.then(response => {
expect(response).to.have.status(200);
});
});
});
it('Should redirect to the single book page after an admin has edited a book', function () {
let agent = chai.request.agent(app);
return agent.post('/login')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ login: 'bob',
password: 'badpassword', })
.then(response => {
return agent.put('/books/1/edit')
.set('content-type', 'application/x-www-form-urlencoded')
.send({ title: 'Edited Book',
price: 3.43,
image: 'EditedImage',
inStock: 30,
isbn: 'Edited ISBN',
publisher: 'Edited Publisher',
firstName0: 'First Author',
lastName0: 'First Author',
firstName1: 'Second Author',
lastName1: 'Second Author',
genre0: 'First genre',
genre1: 'Second genre', })
.then(response => {
expect(response.redirects[0]).to.match(/\/books\/1/);
});
});
});
});
});
| {
"content_hash": "6bb9a0e973e812fab5a6d9e2154aaf20",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 135,
"avg_line_length": 33.14035087719298,
"alnum_prop": 0.5304393859184754,
"repo_name": "pkallas/Simple_Book_Store",
"id": "3f9b60f6609cbd7949ca4250ac01f099fb010086",
"size": "7556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/end-to-end/books.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8348"
},
{
"name": "HTML",
"bytes": "13447"
},
{
"name": "JavaScript",
"bytes": "60899"
}
],
"symlink_target": ""
} |
Kind of continue from the other gist [how to install LAMP on an Amazon AMI](https://gist.github.com/1105007)
##Install git
```
sudo yum install git-core
```
##Create ssh directory since it doesn't exists by default on the Amazon AMI
```
sudo mkdir /var/www/.ssh
sudo chown -R apache:apache /var/www/.ssh/
```
##Generate key for apache user
```
sudo -Hu apache ssh-keygen -t rsa # chose "no passphrase"
sudo cat /var/www/.ssh/id_rsa.pub
# Add the key as a "deploy key" at https://github.com/you/myapp/admin
```
##Get the repo
```
cd /var/www/
sudo chown -R apache:apache html
sudo -Hu apache git clone [email protected]:yourUsername/yourApp.git html
```
##Setup the update script
```
sudo -Hu apache nano html/update.php
```
```
<?php `git pull`; ?>
```
##Set up service hook in github
1. Go to Repository Administration for your repo (http://github.com/username/repository/admin)
2. Click Service Hooks, and you'll see a list of available services. Select Post-Receive URL.
3. Enter the URL for your update script (e.g. http://example.com/update.php) and click Update Settings.
##Sources
* [ec2-webapp / INSTALL.md](https://github.com/rsms/ec2-webapp/blob/master/INSTALL.md#readme)
* [How to deploy your code from GitHub automatically](http://writing.markchristian.org/how-to-deploy-your-code-from-github-automatic)
| {
"content_hash": "ace0f10f8c3e0a24fc65c72838c298fa",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 133,
"avg_line_length": 26.058823529411764,
"alnum_prop": 0.7223476297968398,
"repo_name": "denovo/notes",
"id": "5c3332df7caaa6db297266c2c5a4fb35630bcc89",
"size": "1329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Install-git.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@implementation TestEntity (CoreDataProperties)
@dynamic someNumber;
@dynamic someString;
@dynamic related;
@dynamic manyRelated;
@end
| {
"content_hash": "29485ffe8e9d2dbc1e2807a825d44499",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 47,
"avg_line_length": 17.125,
"alnum_prop": 0.8102189781021898,
"repo_name": "PendarLabs/PLFetchedObjectsController",
"id": "cff68faa45319b02bca7363a4335bd6fdb76c91a",
"size": "515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PLFetchedObjectsControllerTests/TestEntity+CoreDataProperties.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "38299"
},
{
"name": "Ruby",
"bytes": "2544"
}
],
"symlink_target": ""
} |
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* Class User
* @package App
*/
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
| {
"content_hash": "01b88f74826ec7cf24e7aedbeb1ed5b0",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 55,
"avg_line_length": 16.636363636363637,
"alnum_prop": 0.5865209471766849,
"repo_name": "crip-home/href",
"id": "7e1edf9ec4a60527d628113c240a9baffd0cc2fb",
"size": "549",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/User.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "HTML",
"bytes": "17567"
},
{
"name": "PHP",
"bytes": "150643"
},
{
"name": "Vue",
"bytes": "19456"
}
],
"symlink_target": ""
} |
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
moduleId: module.id,
selector: 'my-heroes',
templateUrl: 'heroes.component.html',
styleUrls: ['heroes.component.css']
})
/* ?? learn more about pipe: https://angular.io/docs/ts/latest/guide/pipes.html (e.g: {{selectedHero.name | uppercase}} is my hero)
*/
export class HeroesComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(
private router:Router,
private heroService: HeroService) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
this.getHeroes();
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
gotoDetail(): void {
this.router.navigate(['/detail', this.selectedHero.id]);
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.create(name)
.then(hero => { // ?? why hero here: possible: the create function return a Hero type object, the then callback function catch it, then push into the 2 way binding model (to update the list in client)
this.heroes.push(hero);
this.selectedHero = null;
})
}
delete(hero: Hero): void {
this.heroService
.delete(hero.id)
.then(() => {
this.heroes = this.heroes.filter(h => h !== hero); // remove deleted hero from 2 way binding model
if (this.selectedHero === hero) { this.selectedHero = null; } // remove selected flag
});
}
}
| {
"content_hash": "89266ee5314b44a8fbe9aa5a6b419ad4",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 208,
"avg_line_length": 28.081967213114755,
"alnum_prop": 0.6339754816112084,
"repo_name": "namnguyenvn/quickstart-angular-2",
"id": "0506968295569afae2db335a146e90d91c5fb8c9",
"size": "1713",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/heroes.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5184"
},
{
"name": "HTML",
"bytes": "2221"
},
{
"name": "JavaScript",
"bytes": "13536"
},
{
"name": "TypeScript",
"bytes": "14250"
}
],
"symlink_target": ""
} |
declare module 'react-bootstrap' {
declare class Grid extends ReactComponent { render():any; }
declare class Row extends ReactComponent { render():any; }
declare class Col extends ReactComponent { render():any; }
declare class Button extends ReactComponent { render():any; }
declare class Input extends ReactComponent { render():any; }
}
| {
"content_hash": "f69fef67786f1608966e0f4c1b3548a5",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 63,
"avg_line_length": 43.625,
"alnum_prop": 0.7392550143266475,
"repo_name": "saem/hairpiece",
"id": "9ce9ee678b58ba85242998fa0ef74bae966fc57a",
"size": "349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/interfaces/react-bootstrap.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "92"
},
{
"name": "Elm",
"bytes": "236638"
},
{
"name": "Erlang",
"bytes": "2003"
},
{
"name": "HTML",
"bytes": "943"
},
{
"name": "JavaScript",
"bytes": "194779"
},
{
"name": "Shell",
"bytes": "413"
}
],
"symlink_target": ""
} |
var vows = require('vows');
var assert = require('assert');
var util = require('util');
var foodspotting = require('passport-foodspotting');
vows.describe('passport-foodspotting').addBatch({
'module': {
'should report a version': function (x) {
assert.isString(foodspotting.version);
},
},
}).export(module);
| {
"content_hash": "07cffd342385230aa07e95542b665a9f",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 52,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6567164179104478,
"repo_name": "jaredhanson/passport-foodspotting",
"id": "8e43afa530fddbd02d567cc49ed2fce59ee52017",
"size": "335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6580"
}
],
"symlink_target": ""
} |
* Provides an example to show how generate a vector in FPGA and to write it in HOST memory using optimized memcpy.
* To maximixe memcpy performance, data is written in 4KB chunks (MAX_BURST size) to maximize bandwidth.
Files hierarchy:
```
hls_vector_generator
├── Makefile General Makefile used to automatically prepare the final files
├── README.md Documentation file for this example
|
├── sw Software directory containing application called from POWER host and software action
| ├── snap_vector_generator.c APPLICATION which calls the hardware(software) action
| ├── action_create_vector.c SW version of the action
| └── Makefile Makefile to compile the software files
|
├── include Common directory to sw and hw
| └── action_create_vector.h COMMON HEADER file used by the application and the software/hardware action.
|
└── hw Hardware directory containing the hardware action
├── action_create_vector.cpp HARDWARE ACTION which will be executed on FPGA and is called by the application
├── action_create_vector.H header file containing hardware action parameters
└── Makefile Makefile to compile the hardware action using Vivado HLS synthesizer
```
| {
"content_hash": "a82b6c9cb270fb27f2790cd89b213444",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 119,
"avg_line_length": 58.78260869565217,
"alnum_prop": 0.6693786982248521,
"repo_name": "open-power/snap",
"id": "97c5014c658af20cc35c8f7624290b8af316a3b0",
"size": "1456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "actions/hls_vector_generator/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "5265"
},
{
"name": "C",
"bytes": "783707"
},
{
"name": "C++",
"bytes": "224125"
},
{
"name": "Makefile",
"bytes": "141074"
},
{
"name": "Perl",
"bytes": "3964"
},
{
"name": "Python",
"bytes": "30570"
},
{
"name": "Shell",
"bytes": "269595"
},
{
"name": "SystemVerilog",
"bytes": "126239"
},
{
"name": "Tcl",
"bytes": "195808"
},
{
"name": "VHDL",
"bytes": "247477"
},
{
"name": "Verilog",
"bytes": "152134"
}
],
"symlink_target": ""
} |
#region Apache Notice
#endregion
using System;
using System.Xml.Serialization;
using IBatisNet.Common.Utilities.Objects.Members;
using IBatisNet.DataMapper.Configuration.Sql.Dynamic.Handlers;
namespace IBatisNet.DataMapper.Configuration.Sql.Dynamic.Elements
{
/// <summary>
/// Represent an isNotEqual sql tag element.
/// </summary>
[Serializable]
[XmlRoot("isNotEqual", Namespace = "http://ibatis.apache.org/mapping")]
public sealed class IsNotEqual : Conditional
{
/// <summary>
/// Initializes a new instance of the <see cref="IsNotEqual"/> class.
/// </summary>
/// <param name="accessorFactory">The accessor factory.</param>
public IsNotEqual(AccessorFactory accessorFactory)
{
this.Handler = new IsNotEqualTagHandler(accessorFactory);
}
}
}
| {
"content_hash": "a28fc90d976ba2db09a490d4522465b7",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 77,
"avg_line_length": 30.392857142857142,
"alnum_prop": 0.6792009400705052,
"repo_name": "chookrib/Castle.Facilities.IBatisNet",
"id": "fba81b355d61aaf158d42e6564e60ceffa265a3e",
"size": "1786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/IBatisNet.DataMapper/Configuration/Sql/Dynamic/Elements/IsNotEqual.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "612"
},
{
"name": "C#",
"bytes": "1911845"
},
{
"name": "PLpgSQL",
"bytes": "1244"
}
],
"symlink_target": ""
} |
body {
font-family: -apple-system, "Helvetica Neue", Helvetica, sans-serif;
}
.header {
padding: 1px 0;
margin-bottom: 10px;
background: #192e40;
color: #fff;
}
.header h1 {
text-align: center;
margin: 15px 0;
cursor: default;
user-select: none;
-webkit-user-select: none;
}
.app-actions {
text-align: right;
margin-bottom: 15px;
}
.hosts-list {
list-style: none;
padding: 0;
}
.hosts-list li {
margin-bottom: 15px;
}
.btn-save-hosts .text-saving, .btn-save-hosts .text-saved, .btn-save-hosts .text-error {
display: none;
}
.btn-save-hosts .glyphicon::before {
content: "\e202";
}
.btn-save-hosts.saving:hover {
background: #337ab7;
}
.btn-save-hosts.saving .glyphicon {
animation-name: spin;
animation-duration: 2000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.btn-save-hosts.saving .glyphicon::before {
content: "\e019";
}
.btn-save-hosts.saving .text, .btn-save-hosts.saving .text-saved {
display: none;
}
.btn-save-hosts.saving .text-saving {
display: inline;
}
.btn-save-hosts.saved .glyphicon::before {
content: "\e013";
}
.btn-save-hosts.saved .text {
display: none;
}
.btn-save-hosts.saved .text-saved {
display: inline;
}
.btn-save-hosts.error .glyphicon::before {
content: "\e101";
}
.btn-save-hosts.error .text {
display: none;
}
.btn-save-hosts.error .text-error {
display: inline;
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
} | {
"content_hash": "bace46a39553afa0f435d3d47d01aa0e",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 88,
"avg_line_length": 17.96385542168675,
"alnum_prop": 0.6720321931589537,
"repo_name": "LouWii/hosts-file-edit",
"id": "e8dd4f768012431c6d63eca4d66d25a98a9b91d7",
"size": "1491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/stylesheets/application.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1491"
},
{
"name": "HTML",
"bytes": "3172"
},
{
"name": "JavaScript",
"bytes": "12492"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
<id>com.furthurr.labelHtml</id>
<name>labelHtml</name>
<version>1.0</version>
<publisher>furthurr</publisher>
<url>http://</url>
<description/>
<copyright>2014 by furthurr</copyright>
<icon>appicon.png</icon>
<fullscreen>false</fullscreen>
<navbar-hidden>false</navbar-hidden>
<analytics>true</analytics>
<guid>9ae2156c-a937-40b1-9222-953096033988</guid>
<property name="ti.ui.defaultunit" type="string">dp</property>
<ios>
<plist>
<dict>
<key>UISupportedInterfaceOrientations~iphone</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIRequiresPersistentWiFi</key>
<false/>
<key>UIPrerenderedIcon</key>
<false/>
<key>UIStatusBarHidden</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
</dict>
</plist>
</ios>
<android xmlns:android="http://schemas.android.com/apk/res/android"/>
<mobileweb>
<precache/>
<splash>
<enabled>true</enabled>
<inline-css-images>true</inline-css-images>
</splash>
<theme>default</theme>
</mobileweb>
<modules/>
<deployment-targets>
<target device="android">true</target>
<target device="blackberry">false</target>
<target device="ipad">false</target>
<target device="iphone">true</target>
<target device="mobileweb">false</target>
</deployment-targets>
<sdk-version>3.4.1.GA</sdk-version>
<plugins>
<plugin version="1.0">ti.alloy</plugin>
</plugins>
</ti:app>
| {
"content_hash": "a6543c947f03ed4e599cb7d470d18cae",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 77,
"avg_line_length": 36.693548387096776,
"alnum_prop": 0.5736263736263736,
"repo_name": "furthurr/labelHtml",
"id": "9e41fe5eacf483f5bbc26b6a93cb5340080c2c4c",
"size": "2275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tiapp.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1276"
},
{
"name": "JavaScript",
"bytes": "6214"
},
{
"name": "Python",
"bytes": "5251"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.knime.org/2008/09/XMLConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.knime.org/2008/09/XMLConfig http://www.knime.org/XMLConfig_2008_09.xsd" key="table_meta_info">
<entry key="table_ID" type="xint" value="4"/>
<entry key="table_type" type="xstring" value="container_table"/>
<entry key="table_file_name" type="xstring" value="data.zip"/>
</config>
| {
"content_hash": "851ab8a12ae99d7010468d0db5c4d309",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 234,
"avg_line_length": 76.33333333333333,
"alnum_prop": 0.7161572052401747,
"repo_name": "3D-e-Chem/tycho-knime-node-archetype",
"id": "7f438a2e46fbe47365de6db97abfe098a92c9a1e",
"size": "458",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/resources/archetype-resources/tests/src/knime/simple-test/Table Creator (#3)/port_1/data.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14432"
}
],
"symlink_target": ""
} |
package org.ofbiz.minilang.method.envops;
import java.util.LinkedList;
import java.util.List;
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.MiniLangValidate;
import org.ofbiz.minilang.SimpleMethod;
import org.ofbiz.minilang.method.MethodContext;
import org.ofbiz.minilang.method.MethodOperation;
import org.w3c.dom.Element;
/**
* Implements the <list-to-list> element.
*
* @see <a href="https://cwiki.apache.org/confluence/display/OFBADMIN/Mini-language+Reference#Mini-languageReference-{{%3Clisttolist%3E}}">Mini-language Reference</a>
*/
public final class ListToList extends MethodOperation {
private final FlexibleMapAccessor<List<Object>> listFma;
private final FlexibleMapAccessor<List<Object>> toListFma;
public ListToList(Element element, SimpleMethod simpleMethod) throws MiniLangException {
super(element, simpleMethod);
if (MiniLangValidate.validationOn()) {
MiniLangValidate.attributeNames(simpleMethod, element, "to-list", "list");
MiniLangValidate.requiredAttributes(simpleMethod, element, "to-list", "list");
MiniLangValidate.expressionAttributes(simpleMethod, element, "to-list", "list");
MiniLangValidate.noChildElements(simpleMethod, element);
}
toListFma = FlexibleMapAccessor.getInstance(element.getAttribute("to-list"));
listFma = FlexibleMapAccessor.getInstance(element.getAttribute("list"));
}
@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
List<Object> fromList = listFma.get(methodContext.getEnvMap());
if (fromList != null) {
List<Object> toList = toListFma.get(methodContext.getEnvMap());
if (toList == null) {
toList = new LinkedList<Object>();
toListFma.put(methodContext.getEnvMap(), toList);
}
toList.addAll(fromList);
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("<list-to-list ");
sb.append("to-list=\"").append(this.toListFma).append("\" ");
sb.append("list=\"").append(this.listFma).append("\" />");
return sb.toString();
}
/**
* A factory for the <list-to-list> element.
*/
public static final class ListToListFactory implements Factory<ListToList> {
@Override
public ListToList createMethodOperation(Element element, SimpleMethod simpleMethod) throws MiniLangException {
return new ListToList(element, simpleMethod);
}
@Override
public String getName() {
return "list-to-list";
}
}
}
| {
"content_hash": "f06f5feebc26c92a594871ca841af858",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 166,
"avg_line_length": 38.136986301369866,
"alnum_prop": 0.6788793103448276,
"repo_name": "ofbizfriends/vogue",
"id": "7343374db5f32a6c3da4e191c7976f7f10b0fecd",
"size": "3745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/minilang/src/org/ofbiz/minilang/method/envops/ListToList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "40071"
},
{
"name": "CSS",
"bytes": "1136748"
},
{
"name": "Groff",
"bytes": "4118"
},
{
"name": "Groovy",
"bytes": "1517025"
},
{
"name": "HTML",
"bytes": "24245"
},
{
"name": "Java",
"bytes": "14674842"
},
{
"name": "JavaScript",
"bytes": "3060483"
},
{
"name": "Makefile",
"bytes": "22007"
},
{
"name": "PHP",
"bytes": "150"
},
{
"name": "Ruby",
"bytes": "2533"
},
{
"name": "Shell",
"bytes": "67707"
},
{
"name": "XSLT",
"bytes": "1712"
}
],
"symlink_target": ""
} |
package org.radargun.stages.cache.background;
import org.radargun.Operation;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.stages.cache.generators.KeyGenerator;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.Transactional;
import java.util.Random;
/**
* Common operations for all logic types.
*
* @author Radim Vansa <[email protected]>
*/
public abstract class AbstractLogic implements Logic {
protected static final Operation GET_NULL = BasicOperations.GET.derive("Null");
protected final Log log = LogFactory.getLog(getClass());
protected final boolean trace = log.isTraceEnabled();
protected BackgroundOpsManager manager;
protected KeyGenerator keyGenerator;
protected final int operations;
protected final int transactionSize;
protected Stressor stressor;
protected Transactional.Transaction ongoingTx;
protected AbstractLogic(BackgroundOpsManager manager) {
this.manager = manager;
this.keyGenerator = manager.getKeyGenerator();
this.transactionSize = manager.getGeneralConfiguration().getTransactionSize();
this.operations = manager.getGeneralConfiguration().puts + manager.getGeneralConfiguration().gets + manager.getGeneralConfiguration().removes;
}
@Override
public void finish() {
if (transactionSize > 0 && ongoingTx != null) {
try {
ongoingTx.rollback();
} catch (Exception e) {
log.error("Error while ending transaction", e);
}
}
}
@Override
public void setStressor(Stressor stressor) {
this.stressor = stressor;
}
public Operation getOperation(Random rand) {
int r = rand.nextInt(operations);
if (r < manager.getGeneralConfiguration().gets) {
return BasicOperations.GET;
} else if (r < manager.getGeneralConfiguration().gets + manager.getGeneralConfiguration().puts) {
return BasicOperations.PUT;
} else return BasicOperations.REMOVE;
}
}
| {
"content_hash": "d11271c862e0cd189608aea7625ddeff",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 148,
"avg_line_length": 32.854838709677416,
"alnum_prop": 0.7191948944526264,
"repo_name": "Danny-Hazelcast/radargun",
"id": "07238ed0bf60a7e0d1cc40638700d8703cd2ce7f",
"size": "2037",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/radargun/stages/cache/background/AbstractLogic.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1494472"
},
{
"name": "Protocol Buffer",
"bytes": "178"
},
{
"name": "Python",
"bytes": "625"
},
{
"name": "Shell",
"bytes": "30072"
}
],
"symlink_target": ""
} |
Jasny's MVC basics for PHP
==========================
Includes a router, a controller base class and a class for loading views.
### What is MVC?
The Model View Controller pattern splits the user interface interaction into three distinct roles. Each with it's own
responsibility.
> View: "Hey, controller, the user just told me he wants item 4 deleted."
> Controller: "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get item 4 and
> do whatever you do to delete it."
> Model: "Item 4... got it. It's deleted. Back to you, Controller."
> Controller: "Here, I'll collect the new set of data. Back to you, view."
> View: "Cool, I'll show the new set to the user now."
- [Andres Jaan Tack @ stackoverflow](http://stackoverflow.com/a/1015853/1160754)
| {
"content_hash": "76be25a46b8324bc0bf68adabc450309",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 120,
"avg_line_length": 44.111111111111114,
"alnum_prop": 0.7065491183879093,
"repo_name": "jasny/mvc",
"id": "ed8dc9389934933298866c2ad400baf3068e36c6",
"size": "794",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "4244"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Altus.Suffūz
{
public static class ValueTypesEx
{
public static int Clamp(this int value, int min)
{
return value < min ? min : value;
}
public static int Clamp(this int value, int min, int max)
{
return value < min ? min : value > max ? max : value;
}
public static byte[] GetBytes(this decimal dec)
{
//Load four 32 bit integers from the Decimal.GetBits function
Int32[] bits = decimal.GetBits(dec);
//Create a temporary list to hold the bytes
List<byte> bytes = new List<byte>();
//iterate each 32 bit integer
foreach (Int32 i in bits)
{
//add the bytes of the current 32bit integer
//to the bytes list
bytes.AddRange(BitConverter.GetBytes(i));
}
//return the bytes list as an array
return bytes.ToArray();
}
public static decimal ToDecimal(this byte[] bytes)
{
//check that it is even possible to convert the array
if (bytes.Count() != 16)
throw new Exception("A decimal must be created from exactly 16 bytes");
//make an array to convert back to int32's
Int32[] bits = new Int32[4];
for (int i = 0; i <= 15; i += 4)
{
//convert every 4 bytes into an int32
bits[i / 4] = BitConverter.ToInt32(bytes, i);
}
//Use the decimal's new constructor to
//create an instance of decimal
return new decimal(bits);
}
}
}
| {
"content_hash": "2ab7bcbd8c3358216a6db9bcb1b319dc",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 87,
"avg_line_length": 32.92727272727273,
"alnum_prop": 0.5378244064053009,
"repo_name": "odinhaus/Suffuz",
"id": "1d040d64096f41ff98ad199098957a0de17e5526",
"size": "1814",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Altus.Suffūz/ValueTypesEx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1294617"
},
{
"name": "JavaScript",
"bytes": "122396"
}
],
"symlink_target": ""
} |
package net.sourceforge.jwbf.core.actions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import net.sourceforge.jwbf.GAssert;
import net.sourceforge.jwbf.core.actions.RequestBuilder.HashCodeEqualsMemoizingSupplier;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
public class RequestBuilderTest {
@Test
public void testBuild() {
assertEquals("a", new RequestBuilder("a") //
.build());
assertEquals("/a?b=c", new RequestBuilder("/a") //
.param("b", "c") //
.build());
assertEquals("/a?b=e&d=c", new RequestBuilder("/a") //
.param(null, (String) null) //
.param("b", "e") //
.param("d", "c") //
.build());
assertEquals("/a?b=c&llun=None&q=None", new RequestBuilder("/a") //
.param("llun", (String) null) //
.param("b", "c") //
.param("q", "") //
.param("", "z") //
.param("", Suppliers.ofInstance("t")) //
.buildPost().getRequest());
assertEquals("/a?b=1&c=e&d=e", new RequestBuilder("/a") //
.param("d", "e") //
.param(null, "null") //
.param("b", 1) //
.param("c", "e") //
.buildGet().getRequest());
assertEquals("/a?a=true&b=false", new RequestBuilder("/a") //
.param("a", true) //
.param("b", false) //
.buildGet().getRequest());
}
private String lazyVal = "AAA";
@Test
public void testLazyBuild() {
// GIVEN
Supplier<String> lazyParamValue = new Supplier<String>() {
@Override
public String get() {
return lazyVal;
}
};
// WHEN
Get result = new RequestBuilder("/a").param("a", lazyParamValue).buildGet();
lazyVal = "OOO";
// THEN
assertEquals("/a?a=OOO", result.getRequest());
}
private String lazyValMemo = "bbb";
@Test
public void testLazyBuildMemorize() {
// GIVEN
Supplier<String> lazyParamValue = new Supplier<String>() {
@Override
public String get() {
return lazyValMemo;
}
};
// WHEN
Get result = new RequestBuilder("/a").param("a", lazyParamValue).buildGet();
// assertEquals("/a?a=bbb UTF-8", result.toString()); // XXX fail
lazyValMemo = "OOO";
// THEN
assertEquals("/a?a=OOO", result.getRequest());
lazyValMemo = "bbb";
assertEquals("/a?a=OOO", result.getRequest());
}
@Test
public void testRegenerateNewBuilderGet() {
// GIVEN
Get get = RequestBuilder.of("/index.html") //
.param("a", "b") //
.buildGet();
// WHEN
RequestBuilder builder = get.toBuilder();
Get newGet = builder.buildGet();
// THEN
assertEquals("/index.html?a=b UTF-8", get.toString());
assertEquals(get, newGet);
}
@Test
public void testRegenerateNewBuilderPost() {
// GIVEN
Post post = RequestBuilder.of("/index.html") //
.param("a", "b") //
.buildPost();
// WHEN
RequestBuilder builder = post.toBuilder();
Post newPost = builder.buildPost();
// THEN
assertEquals(post, newPost);
}
@Test
public void testRegenerateNewBuilderPostWithParams() {
// GIVEN
Post post = RequestBuilder.of("/index.html") //
.param("a", "b") //
.postParam("c", "d") //
.buildPost() //
;
// WHEN
RequestBuilder builder = post.toBuilder();
Post newPost = builder.buildPost();
// THEN
assertEquals("/index.html?a=b UTF-8 {c=d}", post.toString());
assertEquals(post, newPost);
assertEquals("/index.html?a=b&c=e UTF-8 {c=d}",
builder.param("c", "e").buildPost().toString());
}
@Test
public void testRegenerateNewBuilderPostWithOtherParams() {
// GIVEN
Post post = RequestBuilder.of("/index.php") //
.param("c", "d") //
.postParam("e", "f") //
.buildPost() //
;
// WHEN
RequestBuilder builder = post.toBuilder();
Post newPost = builder.buildPost();
// THEN
assertEquals("/index.php?c=d UTF-8 {e=f}", post.toString());
assertEquals(post, newPost);
}
@Test
public void testRegenerateNewBuilderWithEmptyParams() {
// GIVEN
Post post = RequestBuilder.of("/index.php") //
.param("c", "") //
.postParam("e", "") //
.param("f") //
.postParam("g") //
.postParam(null, (String) null) //
.postParam(null, "null") //
.postParam("llun", (String) null) //
.buildPost() //
;
// WHEN
RequestBuilder builder = post.toBuilder();
Post newPost = builder.buildPost();
// THEN
assertEquals("/index.php?c=None&f= UTF-8 {e=, g=, llun=}", post.toString());
assertEquals(post, newPost);
}
@Test
public void testBuildPostWithParams() {
// GIVEN
Post post = RequestBuilder.of("/index.html") //
.param("a", "b") //
.buildPost() //
.postParam("c", "d") //
;
Post post2 = RequestBuilder.of("/index.html") //
.param(new ParamTuple("a", "b")) //
.postParam(new ParamTuple("c", "d")) //
.buildPost() //
;
// WHEN / THEN
assertEquals(post, post2);
}
@Test
@Ignore
public void testBuildWithParamTuples() {
// GIVEN
ParamTuple<String> a = new ParamTuple("a", 4);
ParamTuple b = new ParamTuple("c", 4);
// WHEN
Post post2 = RequestBuilder.of("/") //
//.param(a) // TODO test for both
.postParam(b) // TODO - " -
.buildPost() //
;
// THEN
assertEquals("/", post2.getRequest());
ImmutableMap<String, Object> params = post2.getParams();
ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of("c", "4");
GAssert.assertEquals(expected, params);
}
@Test(expected = IllegalStateException.class)
public void testMemoizer_only_compare_with_same_type() {
// GIVEN
Supplier<String> supplier = Suppliers.ofInstance("A");
HashCodeEqualsMemoizingSupplier<String> a = new HashCodeEqualsMemoizingSupplier<>(supplier);
// WHEN // THEN
a.equals(new Object());
fail();
}
@Test(expected = IllegalStateException.class)
public void testMemoizer_compare_null() {
// GIVEN
Supplier<String> supplier = Suppliers.ofInstance("A");
HashCodeEqualsMemoizingSupplier<String> a = new HashCodeEqualsMemoizingSupplier<>(supplier);
// WHEN // THEN
a.equals(null);
fail();
}
}
| {
"content_hash": "0ae409585ef162e3e8fd23c72a5c3251",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 96,
"avg_line_length": 26.176706827309236,
"alnum_prop": 0.5806996011046334,
"repo_name": "Hunsu/jwbf",
"id": "3ac9b5486dbf3b3a44e54ece30507dcc4cfa4d05",
"size": "6518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/net/sourceforge/jwbf/core/actions/RequestBuilderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "611944"
},
{
"name": "Shell",
"bytes": "935"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.