text
stringlengths 2
1.04M
| meta
dict |
---|---|
package org.gradle.api.artifacts.dsl;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.query.ArtifactResolutionQuery;
import java.util.Map;
/**
* <p>A {@code DependencyHandler} is used to declare dependencies. Dependencies are grouped into
* configurations (see {@link org.gradle.api.artifacts.Configuration}).</p>
*
* <p>To declare a specific dependency for a configuration you can use the following syntax:</p>
*
* <pre>
* dependencies {
* <i>configurationName</i> <i>dependencyNotation1</i>, <i>dependencyNotation2</i>, ...
* }
* </pre>
*
* <p>Example shows a basic way of declaring dependencies.
* <pre autoTested=''>
* apply plugin: 'java'
* //so that we can use 'compile', 'testCompile' for dependencies
*
* dependencies {
* //for dependencies found in artifact repositories you can use
* //the group:name:version notation
* compile 'commons-lang:commons-lang:2.6'
* testCompile 'org.mockito:mockito:1.9.0-rc1'
*
* //map-style notation:
* compile group: 'com.google.code.guice', name: 'guice', version: '1.0'
*
* //declaring arbitrary files as dependencies
* compile files('hibernate.jar', 'libs/spring.jar')
*
* //putting all jars from 'libs' onto compile classpath
* compile fileTree('libs')
* }
* </pre>
*
* <h2>Advanced dependency configuration</h2>
* <p>To do some advanced configuration on a dependency when it is declared, you can additionally pass a configuration closure:</p>
*
* <pre>
* dependencies {
* <i>configurationName</i>(<i>dependencyNotation</i>){
* <i>configStatement1</i>
* <i>configStatement2</i>
* }
* }
* </pre>
*
* Examples of advanced dependency declaration including:
* <ul>
* <li>Forcing certain dependency version in case of the conflict.</li>
* <li>Excluding certain dependencies by name, group or both.
* More details about per-dependency exclusions can be found in
* docs for {@link org.gradle.api.artifacts.ModuleDependency#exclude(java.util.Map)}.</li>
* <li>Avoiding transitive dependencies for certain dependency.</li>
* </ul>
*
* <pre autoTested=''>
* apply plugin: 'java' //so that I can declare 'compile' dependencies
*
* dependencies {
* compile('org.hibernate:hibernate:3.1') {
* //in case of versions conflict '3.1' version of hibernate wins:
* force = true
*
* //excluding a particular transitive dependency:
* exclude module: 'cglib' //by artifact name
* exclude group: 'org.jmock' //by group
* exclude group: 'org.unwanted', module: 'iAmBuggy' //by both name and group
*
* //disabling all transitive dependencies of this dependency
* transitive = false
* }
* }
* </pre>
*
* More examples of advanced configuration, useful when dependency module has multiple artifacts:
* <ul>
* <li>Declaring dependency to a specific configuration of the module.</li>
* <li>Explicit specification of the artifact. See also {@link org.gradle.api.artifacts.ModuleDependency#artifact(groovy.lang.Closure)}.</li>
* </ul>
*
* <pre autoTested=''>
* apply plugin: 'java' //so that I can declare 'compile' dependencies
*
* dependencies {
* //configuring dependency to specific configuration of the module
* compile configuration: 'someConf', group: 'org.someOrg', name: 'someModule', version: '1.0'
*
* //configuring dependency on 'someLib' module
* compile(group: 'org.myorg', name: 'someLib', version:'1.0') {
* //explicitly adding the dependency artifact:
* artifact {
* //useful when some artifact properties unconventional
* name = 'someArtifact' //artifact name different than module name
* extension = 'someExt'
* type = 'someType'
* classifier = 'someClassifier'
* }
* }
* }
* </pre>
*
* <h2>Dependency notations</h2>
*
* <p>There are several supported dependency notations. These are described below. For each dependency declared this
* way, a {@link Dependency} object is created. You can use this object to query or further configure the
* dependency.</p>
*
* <p>You can also always add instances of
* {@link org.gradle.api.artifacts.Dependency} directly:</p>
*
* <code><i>configurationName</i> <instance></code>
*
* <h3>External dependencies</h3>
*
* <p>There are two notations supported for declaring a dependency on an external module.
* One is a string notation formatted this way:</p>
*
* <code><i>configurationName</i> "<i>group</i>:<i>name</i>:<i>version</i>:<i>classifier</i>@<i>extension</i>"</code>
*
* <p>The other is a map notation:</p>
*
* <code><i>configurationName</i> group: <i>group</i>:, name: <i>name</i>, version: <i>version</i>, classifier:
* <i>classifier</i>, ext: <i>extension</i></code>
*
* <p>In both notations, all properties, except name, are optional.</p>
*
* <p>External dependencies are represented by a {@link
* org.gradle.api.artifacts.ExternalModuleDependency}.</p>
*
* <pre autoTested=''>
* apply plugin: 'java'
* //so that we can use 'compile', 'testCompile' for dependencies
*
* dependencies {
* //for dependencies found in artifact repositories you can use
* //the string notation, e.g. group:name:version
* compile 'commons-lang:commons-lang:2.6'
* testCompile 'org.mockito:mockito:1.9.0-rc1'
*
* //map notation:
* compile group: 'com.google.code.guice', name: 'guice', version: '1.0'
* }
* </pre>
*
* <h3>Project dependencies</h3>
*
* <p>To add a project dependency, you use the following notation:
* <p><code><i>configurationName</i> project(':someProject')</code>
*
* <p>The notation <code>project(':projectA')</code> is similar to the syntax you use
* when configuring a projectA in a multi-module gradle project.
*
* <p>By default, when you declare dependency to projectA, you actually declare dependency to the 'default' configuration of the projectA.
* If you need to depend on a specific configuration of projectA, use map notation for projects:
* <p><code><i>configurationName</i> project(path: ':projectA', configuration: 'someOtherConfiguration')</code>
*
* <p>Project dependencies are represented using a {@link org.gradle.api.artifacts.ProjectDependency}.
*
* <h3>File dependencies</h3>
*
* <p>You can also add a dependency using a {@link org.gradle.api.file.FileCollection}:</p>
* <code><i>configurationName</i> files('a file')</code>
*
* <pre autoTested=''>
* apply plugin: 'java'
* //so that we can use 'compile', 'testCompile' for dependencies
*
* dependencies {
* //declaring arbitrary files as dependencies
* compile files('hibernate.jar', 'libs/spring.jar')
*
* //putting all jars from 'libs' onto compile classpath
* compile fileTree('libs')
* }
* </pre>
*
* <p>File dependencies are represented using a {@link org.gradle.api.artifacts.SelfResolvingDependency}.</p>
*
* <h3>Dependencies to other configurations</h3>
*
* <p>You can add a dependency using a {@link org.gradle.api.artifacts.Configuration}.</p>
*
* <p>When the configuration is from the same project as the target configuration, the target configuration is changed
* to extend from the provided configuration.</p>
*
* <p>When the configuration is from a different project, a project dependency is added.</p>
*
* <h3>Gradle distribution specific dependencies</h3>
*
* <p>It is possible to depend on certain Gradle APIs or libraries that Gradle ships with.
* It is particularly useful for Gradle plugin development. Example:</p>
*
* <pre autoTested=''>
* //Our Gradle plugin is written in groovy
* apply plugin: 'groovy'
* //now we can use the 'compile' configuration for declaring dependencies
*
* dependencies {
* //we will use the Groovy version that ships with Gradle:
* compile localGroovy()
*
* //our plugin requires Gradle API interfaces and classes to compile:
* compile gradleApi()
*
* //we will use the Gradle test-kit to test build logic:
* testCompile gradleTestKit()
* }
* </pre>
*
* <h3>Client module dependencies</h3>
*
* <p>To add a client module to a configuration you can use the notation:</p>
*
* <pre>
* <i>configurationName</i> module(<i>moduleNotation</i>) {
* <i>module dependencies</i>
* }
* </pre>
*
* The module notation is the same as the dependency notations described above, except that the classifier property is
* not available. Client modules are represented using a {@link org.gradle.api.artifacts.ClientModule}.
*/
public interface DependencyHandler {
/**
* Adds a dependency to the given configuration.
*
* @param configurationName The name of the configuration.
* @param dependencyNotation
*
* The dependency notation, in one of the notations described above.
* @return The dependency.
*/
Dependency add(String configurationName, Object dependencyNotation);
/**
* Adds a dependency to the given configuration, and configures the dependency using the given closure.
*
* @param configurationName The name of the configuration.
* @param dependencyNotation The dependency notation, in one of the notations described above.
* @param configureClosure The closure to use to configure the dependency.
* @return The dependency.
*/
Dependency add(String configurationName, Object dependencyNotation, Closure configureClosure);
/**
* Creates a dependency without adding it to a configuration.
*
* @param dependencyNotation The dependency notation, in one of the notations described above.
* @return The dependency.
*/
Dependency create(Object dependencyNotation);
/**
* Creates a dependency without adding it to a configuration, and configures the dependency using
* the given closure.
*
* @param dependencyNotation The dependency notation, in one of the notations described above.
* @param configureClosure The closure to use to configure the dependency.
* @return The dependency.
*/
Dependency create(Object dependencyNotation, Closure configureClosure);
/**
* Creates a dependency on a client module.
*
* @param notation The module notation, in one of the notations described above.
* @return The dependency.
*/
Dependency module(Object notation);
/**
* Creates a dependency on a client module. The dependency is configured using the given closure before it is
* returned.
*
* @param notation The module notation, in one of the notations described above.
* @param configureClosure The closure to use to configure the dependency.
* @return The dependency.
*/
Dependency module(Object notation, Closure configureClosure);
/**
* Creates a dependency on a project.
*
* @param notation The project notation, in one of the notations described above.
* @return The dependency.
*/
Dependency project(Map<String, ?> notation);
/**
* Creates a dependency on the API of the current version of Gradle.
*
* @return The dependency.
*/
Dependency gradleApi();
/**
* Creates a dependency on the <a href="http://docs.gradle.org/current/docs/userguide/test_kit.html">Gradle test-kit</a> API.
*
* @return The dependency.
* @since 2.6
*/
@Incubating
Dependency gradleTestKit();
/**
* Creates a dependency on the Groovy that is distributed with the current version of Gradle.
*
* @return The dependency.
*/
Dependency localGroovy();
/**
* Returns the component metadata handler for this project. The returned handler can be used for adding rules
* that modify the metadata of depended-on software components.
*
* @return the component metadata handler for this project
* @since 1.8
*/
@Incubating
ComponentMetadataHandler getComponents();
/**
* Configures component metadata for this project.
*
* <p>This method executes the given action against the {@link org.gradle.api.artifacts.dsl.ComponentMetadataHandler} for this project.
*
* @param configureAction the action to use to configure module metadata
* @since 1.8
*/
@Incubating
void components(Action<? super ComponentMetadataHandler> configureAction);
/**
* Returns the component module metadata handler for this project. The returned handler can be used for adding rules
* that modify the metadata of depended-on software components.
*
* @return the component module metadata handler for this project
* @since 2.2
*/
@Incubating
ComponentModuleMetadataHandler getModules();
/**
* Configures module metadata for this project.
*
* <p>This method executes the given action against the {@link org.gradle.api.artifacts.dsl.ComponentModuleMetadataHandler} for this project.
*
* @param configureAction the action to use to configure module metadata
* @since 2.2
*/
@Incubating
void modules(Action<? super ComponentModuleMetadataHandler> configureAction);
/**
* Creates an artifact resolution query.
*
* @since 2.0
*/
@Incubating
ArtifactResolutionQuery createArtifactResolutionQuery();
}
| {
"content_hash": "88d84bea7736c45f9186e70eae0fdefb",
"timestamp": "",
"source": "github",
"line_count": 372,
"max_line_length": 145,
"avg_line_length": 35.836021505376344,
"alnum_prop": 0.686445127897382,
"repo_name": "FinishX/coolweather",
"id": "7e62f594c03390c24a5a4357c5fe51e379229543",
"size": "13946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/gradle-2.8/src/core/org/gradle/api/artifacts/dsl/DependencyHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "277"
},
{
"name": "C",
"bytes": "97569"
},
{
"name": "C++",
"bytes": "912105"
},
{
"name": "CSS",
"bytes": "105486"
},
{
"name": "CoffeeScript",
"bytes": "201"
},
{
"name": "GAP",
"bytes": "212"
},
{
"name": "Groovy",
"bytes": "1162135"
},
{
"name": "HTML",
"bytes": "35827007"
},
{
"name": "Java",
"bytes": "12908568"
},
{
"name": "JavaScript",
"bytes": "195155"
},
{
"name": "Objective-C",
"bytes": "2977"
},
{
"name": "Objective-C++",
"bytes": "442"
},
{
"name": "Scala",
"bytes": "12789"
},
{
"name": "Shell",
"bytes": "5398"
}
],
"symlink_target": ""
} |
title: aoq31
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: q31
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "7dd073d464d22a73a88039980ebdd1da",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6656716417910448,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "172c7ad95c88c5010bc1d028533dfa3acc22c20b",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/aoq31.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
"""
Package install information
"""
import ast
import os
import re
from setuptools import find_packages, setup
# Cannot use "from cloudbridge import get_version" because that would try to
# import the six package which may not be installed yet.
reg = re.compile(r'__version__\s*=\s*(.+)')
with open(os.path.join('cloudbridge', '__init__.py')) as f:
for line in f:
m = reg.match(line)
if m:
version = ast.literal_eval(m.group(1))
break
REQS_BASE = [
'bunch>=1.0.1',
'six>=1.10.0',
'retrying>=1.3.3'
]
REQS_AWS = ['boto3']
REQS_AZURE = ['msrest>=0.4.7',
'msrestazure>=0.4.7',
'azure-common>=1.1.5',
'azure-mgmt-resource>=1.0.0rc1',
'azure-mgmt-compute>=1.0.0rc1',
'azure-mgmt-network>=1.0.0rc1',
'azure-mgmt-storage>=1.0.0rc1',
'azure-storage>=0.34.0',
'pysftp>=0.2.9']
REQS_OPENSTACK = [
'python-novaclient==7.0.0',
'python-glanceclient>=2.5.0,<=2.6.0',
'python-cinderclient>=1.9.0,<=2.0.1',
'python-swiftclient>=3.2.0,<=3.3.0',
'python-neutronclient>=6.0.0,<=6.1.0',
'python-keystoneclient>=3.13.0'
]
REQS_FULL = REQS_BASE + REQS_AWS + REQS_AZURE + REQS_OPENSTACK
# httpretty is required with/for moto 1.0.0 or AWS tests fail
REQS_DEV = ([
'tox>=2.1.1',
'moto>=1.1.11',
'sphinx>=1.3.1',
'flake8>=3.3.0',
'flake8-import-order>=0.12'] + REQS_FULL
)
setup(
name='cloudbridge',
version=version,
description='A simple layer of abstraction over multiple cloud providers.',
author='Galaxy and GVL Projects',
author_email='[email protected]',
url='http://cloudbridge.readthedocs.org/',
install_requires=REQS_FULL,
extras_require={
':python_version=="2.7"': ['py2-ipaddress'],
':python_version=="3"': ['py2-ipaddress'],
'full': REQS_FULL,
'dev': REQS_DEV
},
packages=find_packages(),
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'],
test_suite="test"
)
| {
"content_hash": "dab90bec1c190e120f0d9f9910805beb",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 79,
"avg_line_length": 32.91954022988506,
"alnum_prop": 0.5673882681564246,
"repo_name": "ms-azure-cloudbroker/cloudbridge",
"id": "947a6bad7b035e96c149acea17b7e3c6a6f02ffd",
"size": "2864",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "658216"
}
],
"symlink_target": ""
} |
package com.azure.spring.data.cosmos.repository.integration;
import com.azure.cosmos.models.CompositePath;
import com.azure.cosmos.models.CompositePathSortOrder;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.IndexingPolicy;
import com.azure.spring.data.cosmos.IntegrationTestCollectionManager;
import com.azure.spring.data.cosmos.core.CosmosTemplate;
import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate;
import com.azure.spring.data.cosmos.domain.CompositeIndexEntity;
import com.azure.spring.data.cosmos.repository.TestRepositoryConfig;
import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation;
import com.azure.spring.data.cosmos.repository.support.SimpleCosmosRepository;
import com.azure.spring.data.cosmos.repository.support.SimpleReactiveCosmosRepository;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestRepositoryConfig.class)
public class CompositeIndexIT {
@ClassRule
public static final IntegrationTestCollectionManager collectionManager = new IntegrationTestCollectionManager();
@Autowired
CosmosTemplate template;
@Autowired
ReactiveCosmosTemplate reactiveTemplate;
CosmosEntityInformation<CompositeIndexEntity, String> information = new CosmosEntityInformation<>(CompositeIndexEntity.class);
@Before
public void setup() {
collectionManager.ensureContainersCreatedAndEmpty(template, CompositeIndexEntity.class);
}
@Test
public void canSetCompositeIndex() {
new SimpleCosmosRepository<>(information, template);
CosmosContainerProperties properties = template.getContainerProperties(information.getContainerName());
List<List<CompositePath>> indexes = properties.getIndexingPolicy().getCompositeIndexes();
assertThat(indexes.get(0).get(0).getPath()).isEqualTo("/fieldOne");
assertThat(indexes.get(0).get(0).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(0).get(1).getPath()).isEqualTo("/fieldTwo");
assertThat(indexes.get(0).get(1).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(1).get(0).getPath()).isEqualTo("/fieldThree");
assertThat(indexes.get(1).get(0).getOrder()).isEqualTo(CompositePathSortOrder.DESCENDING);
assertThat(indexes.get(1).get(1).getPath()).isEqualTo("/fieldFour");
assertThat(indexes.get(1).get(1).getOrder()).isEqualTo(CompositePathSortOrder.DESCENDING);
}
@Test
public void canSetCompositeIndexReactive() {
new SimpleReactiveCosmosRepository<>(information, reactiveTemplate);
CosmosContainerProperties properties = reactiveTemplate.getContainerProperties(information.getContainerName()).block();
List<List<CompositePath>> indexes = properties.getIndexingPolicy().getCompositeIndexes();
assertThat(indexes.get(0).get(0).getPath()).isEqualTo("/fieldOne");
assertThat(indexes.get(0).get(0).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(0).get(1).getPath()).isEqualTo("/fieldTwo");
assertThat(indexes.get(0).get(1).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(1).get(0).getPath()).isEqualTo("/fieldThree");
assertThat(indexes.get(1).get(0).getOrder()).isEqualTo(CompositePathSortOrder.DESCENDING);
assertThat(indexes.get(1).get(1).getPath()).isEqualTo("/fieldFour");
assertThat(indexes.get(1).get(1).getOrder()).isEqualTo(CompositePathSortOrder.DESCENDING);
}
@Test
public void canUpdateCompositeIndex() {
// initialize policy on entity
new SimpleCosmosRepository<>(information, template);
// set new index policy
IndexingPolicy newIndexPolicy = new IndexingPolicy();
List<List<CompositePath>> newCompositeIndex = new ArrayList<>();
List<CompositePath> innerList = new ArrayList<>();
innerList.add(new CompositePath().setPath("/fieldOne"));
innerList.add(new CompositePath().setPath("/fieldFour"));
newCompositeIndex.add(innerList);
newIndexPolicy.setCompositeIndexes(newCompositeIndex);
// apply new index policy
CosmosEntityInformation<CompositeIndexEntity, String> spyEntityInformation = Mockito.spy(information);
Mockito.doReturn(newIndexPolicy).when(spyEntityInformation).getIndexingPolicy();
new SimpleCosmosRepository<>(spyEntityInformation, template);
// retrieve new policy
CosmosContainerProperties properties = template.getContainerProperties(information.getContainerName());
List<List<CompositePath>> indexes = properties.getIndexingPolicy().getCompositeIndexes();
// assert
assertThat(indexes.size()).isEqualTo(1);
assertThat(indexes.get(0).get(0).getPath()).isEqualTo("/fieldOne");
assertThat(indexes.get(0).get(0).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(0).get(1).getPath()).isEqualTo("/fieldFour");
assertThat(indexes.get(0).get(1).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
}
@Test
public void canUpdateCompositeIndexReactive() {
// initialize policy on entity
new SimpleReactiveCosmosRepository<>(information, reactiveTemplate);
// set new index policy
IndexingPolicy newIndexPolicy = new IndexingPolicy();
List<List<CompositePath>> newCompositeIndex = new ArrayList<>();
List<CompositePath> innerList = new ArrayList<>();
innerList.add(new CompositePath().setPath("/fieldOne"));
innerList.add(new CompositePath().setPath("/fieldFour"));
newCompositeIndex.add(innerList);
newIndexPolicy.setCompositeIndexes(newCompositeIndex);
// apply new index policy
CosmosEntityInformation<CompositeIndexEntity, String> spyEntityInformation = Mockito.spy(information);
Mockito.doReturn(newIndexPolicy).when(spyEntityInformation).getIndexingPolicy();
new SimpleReactiveCosmosRepository<>(spyEntityInformation, reactiveTemplate);
// retrieve new policy
CosmosContainerProperties properties = reactiveTemplate.getContainerProperties(information.getContainerName()).block();
List<List<CompositePath>> indexes = properties.getIndexingPolicy().getCompositeIndexes();
// assert
assertThat(indexes.size()).isEqualTo(1);
assertThat(indexes.get(0).get(0).getPath()).isEqualTo("/fieldOne");
assertThat(indexes.get(0).get(0).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
assertThat(indexes.get(0).get(1).getPath()).isEqualTo("/fieldFour");
assertThat(indexes.get(0).get(1).getOrder()).isEqualTo(CompositePathSortOrder.ASCENDING);
}
}
| {
"content_hash": "7b7d57d4e5ac221acc791e403d65b2e7",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 130,
"avg_line_length": 49.8013698630137,
"alnum_prop": 0.7451519735937285,
"repo_name": "Azure/azure-sdk-for-java",
"id": "9ce99c562511233a39e34605548c307ad3a7f2cf",
"size": "7368",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/cosmos/azure-spring-data-cosmos-test/src/test/java/com/azure/spring/data/cosmos/repository/integration/CompositeIndexIT.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
package uk.gov.hmrc.ct.accounts.frs102.boxes
import uk.gov.hmrc.ct.accounts.frs102.calculations.TotalFixedAssetsCalculator
import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever
import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtOptionalInteger}
case class AC48(value: Option[Int]) extends CtBoxIdentifier(name = "Total fixed assets (current PoA)") with CtOptionalInteger
object AC48 extends Calculated[AC48, Frs102AccountsBoxRetriever] with TotalFixedAssetsCalculator {
override def calculate(boxRetriever: Frs102AccountsBoxRetriever): AC48 = {
import boxRetriever._
calculateCurrentTotalFixedAssets(ac42(), ac44())
}
}
| {
"content_hash": "10b1fa3288120d13aefd7f91d30f3d72",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 125,
"avg_line_length": 39.1764705882353,
"alnum_prop": 0.8123123123123123,
"repo_name": "pncampbell/ct-calculations",
"id": "9bebecdf8c997cfb9025274b3b8be5e0250296eb",
"size": "1269",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/scala/uk/gov/hmrc/ct/accounts/frs102/boxes/AC48.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "3080866"
}
],
"symlink_target": ""
} |
using CommunityToolkit.Mvvm.ComponentModel;
using MvvmDialogs;
namespace Demo.CustomDialogTypeLocator.ComponentA
{
public class MyDialogVM : ObservableObject, IModalDialogViewModel
{
private bool? dialogResult;
public bool? DialogResult
{
get => dialogResult;
private set => SetProperty(ref dialogResult, value);
}
}
}
| {
"content_hash": "7bbed4a98174a8ce2c4d8481bc3d2125",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 24.375,
"alnum_prop": 0.6666666666666666,
"repo_name": "FantasticFiasco/mvvm-dialogs",
"id": "ff4b4f8ec6ec63992863a537ef862c02b453335e",
"size": "392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Demo.CustomDialogTypeLocator/ComponentA/MyDialogVM.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "126371"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class EmitMetadata : EmitMetadataTestBase
{
[Fact]
public void InstantiatedGenerics()
{
string source = @"
public class A<T>
{
public class B : A<T>
{
internal class C : B
{}
protected B y1;
protected A<D>.B y2;
}
public class H<S>
{
public class I : A<T>.H<S>
{}
}
internal A<T> x1;
internal A<D> x2;
}
public class D
{
public class K<T>
{
public class L : K<T>
{}
}
}
namespace NS1
{
class E : D
{}
}
class F : A<D>
{}
class G : A<NS1.E>.B
{}
class J : A<D>.H<D>
{}
public class M
{}
public class N : D.K<M>
{}
";
CompileAndVerify(source, symbolValidator: module =>
{
var baseLine = System.Xml.Linq.XElement.Load(new StringReader(Resources.EmitSimpleBaseLine1));
System.Xml.Linq.XElement dumpXML = DumpTypeInfo(module);
Assert.Equal(baseLine.ToString(), dumpXML.ToString());
}, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void StringArrays()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
System.Console.WriteLine(65536);
arrayField = new string[] {""string1"", ""string2""};
System.Console.WriteLine(arrayField[1]);
System.Console.WriteLine(arrayField[0]);
}
static string[] arrayField;
}
";
CompileAndVerify(source, expectedOutput: @"
65536
string2
string1
"
);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FieldRVA()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
byte[] a = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.Console.WriteLine(a[0]);
System.Console.WriteLine(a[8]);
}
}
";
CompileAndVerify(source, expectedOutput: @"
1
9
"
);
}
[Fact]
public void AssemblyRefs1()
{
var metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1;
var metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2;
string source = @"
public class Test : C107
{
}
";
CompileAndVerifyWithMscorlib40(source, new[] { metadataTestLib1, metadataTestLib2 }, assemblyValidator: (assembly) =>
{
var refs = assembly.Modules[0].ReferencedAssemblies.OrderBy(r => r.Name).ToArray();
Assert.Equal(2, refs.Length);
Assert.Equal(refs[0].Name, "MDTestLib1", StringComparer.OrdinalIgnoreCase);
Assert.Equal(refs[1].Name, "mscorlib", StringComparer.OrdinalIgnoreCase);
});
}
[Fact]
public void AssemblyRefs2()
{
string sources = @"
public class Test : Class2
{
}
";
CompileAndVerifyWithMscorlib40(sources, new[] { TestReferences.SymbolsTests.MultiModule.Assembly }, assemblyValidator: (assembly) =>
{
var refs2 = assembly.Modules[0].ReferencedAssemblies.Select(r => r.Name);
Assert.Equal(2, refs2.Count());
Assert.Contains("MultiModule", refs2, StringComparer.OrdinalIgnoreCase);
Assert.Contains("mscorlib", refs2, StringComparer.OrdinalIgnoreCase);
var peFileReader = assembly.GetMetadataReader();
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.File));
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.ModuleRef));
});
}
[WorkItem(687434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687434")]
[Fact()]
public void Bug687434()
{
CompileAndVerify(
"public class C { }",
verify: Verification.Fails,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.NetModule));
}
[Fact, WorkItem(529006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529006")]
public void AddModule()
{
var netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(filePath: Path.GetFullPath("netModule1.netmodule"));
var netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2).GetReference(filePath: Path.GetFullPath("netModule2.netmodule"));
string source = @"
public class Test : Class1
{
}
";
// modules not supported in ref emit
CompileAndVerify(source, new[] { netModule1, netModule2 }, assemblyValidator: (assembly) =>
{
Assert.Equal(3, assembly.Modules.Length);
var reader = assembly.GetMetadataReader();
Assert.Equal(2, reader.GetTableRowCount(TableIndex.File));
var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1));
var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2));
Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name));
Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name));
Assert.False(file1.HashValue.IsNil);
Assert.False(file2.HashValue.IsNil);
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef));
var moduleRefName = reader.GetModuleReference(MetadataTokens.ModuleReferenceHandle(1)).Name;
Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName));
var actual = from h in reader.ExportedTypes
let et = reader.GetExportedType(h)
select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{(int)et.Attributes:X4}";
AssertEx.Equal(new[]
{
".Class1 0x26000001 (AssemblyFile) 0x0001",
".Class3 0x27000001 (ExportedType) 0x0002",
"NS1.Class4 0x26000001 (AssemblyFile) 0x0001",
".Class7 0x27000003 (ExportedType) 0x0002",
".Class2 0x26000002 (AssemblyFile) 0x0001"
}, actual);
});
}
[Fact]
public void ImplementingAnInterface()
{
string source = @"
public interface I1
{}
public class A : I1
{
}
public interface I2
{
void M2();
}
public interface I3
{
void M3();
}
abstract public class B : I2, I3
{
public abstract void M2();
public abstract void M3();
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = module.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
Assert.Equal(TypeKind.Interface, i1.TypeKind);
Assert.Equal(TypeKind.Interface, i2.TypeKind);
Assert.Equal(TypeKind.Interface, i3.TypeKind);
Assert.Equal(TypeKind.Class, classA.TypeKind);
Assert.Equal(TypeKind.Class, classB.TypeKind);
Assert.Same(i1, classA.Interfaces().Single());
var interfaces = classB.Interfaces();
Assert.Same(i2, interfaces[0]);
Assert.Same(i3, interfaces[1]);
Assert.Equal(1, i2.GetMembers("M2").Length);
Assert.Equal(1, i3.GetMembers("M3").Length);
});
}
[Fact]
public void InterfaceOrder()
{
string source = @"
interface I1 : I2, I5 { }
interface I2 : I3, I4 { }
interface I3 { }
interface I4 { }
interface I5 : I6, I7 { }
interface I6 { }
interface I7 { }
class C : I1 { }
";
CompileAndVerify(source, symbolValidator: module =>
{
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
var i4 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I4");
var i5 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I5");
var i6 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I6");
var i7 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I7");
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
// Order is important - should be pre-order depth-first with declaration order at each level
Assert.True(i1.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i2, i3, i4, i5, i6, i7)));
Assert.True(i2.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i3, i4)));
Assert.False(i3.Interfaces().Any());
Assert.False(i4.Interfaces().Any());
Assert.True(i5.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i6, i7)));
Assert.False(i6.Interfaces().Any());
Assert.False(i7.Interfaces().Any());
Assert.True(c.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i1, i2, i3, i4, i5, i6, i7)));
});
}
[Fact]
public void ExplicitGenericInterfaceImplementation()
{
CompileAndVerify(@"
class S
{
class C<T>
{
public interface I
{
void m(T x);
}
}
abstract public class D : C<int>.I
{
void C<int>.I.m(int x)
{
}
}
}
");
}
[Fact]
public void TypeWithAbstractMethod()
{
string source = @"
abstract public class A
{
public abstract A[] M1(ref System.Array p1);
public abstract A[,] M2(System.Boolean p2);
public abstract A[,,] M3(System.Char p3);
public abstract void M4(System.SByte p4,
System.Single p5,
System.Double p6,
System.Int16 p7,
System.Int32 p8,
System.Int64 p9,
System.IntPtr p10,
System.String p11,
System.Byte p12,
System.UInt16 p13,
System.UInt32 p14,
System.UInt64 p15,
System.UIntPtr p16);
public abstract void M5<T, S>(T p17, S p18);
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var m1 = classA.GetMembers("M1").OfType<MethodSymbol>().Single();
var m2 = classA.GetMembers("M2").OfType<MethodSymbol>().Single();
var m3 = classA.GetMembers("M3").OfType<MethodSymbol>().Single();
var m4 = classA.GetMembers("M4").OfType<MethodSymbol>().Single();
var m5 = classA.GetMembers("M5").OfType<MethodSymbol>().Single();
var method1Ret = (ArrayTypeSymbol)m1.ReturnType.TypeSymbol;
var method2Ret = (ArrayTypeSymbol)m2.ReturnType.TypeSymbol;
var method3Ret = (ArrayTypeSymbol)m3.ReturnType.TypeSymbol;
Assert.True(method1Ret.IsSZArray);
Assert.Same(classA, method1Ret.ElementType.TypeSymbol);
Assert.Equal(2, method2Ret.Rank);
Assert.Same(classA, method2Ret.ElementType.TypeSymbol);
Assert.Equal(3, method3Ret.Rank);
Assert.Same(classA, method3Ret.ElementType.TypeSymbol);
Assert.True(classA.IsAbstract);
Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility);
var parameter1 = m1.Parameters.Single();
var parameter1Type = parameter1.Type.TypeSymbol;
Assert.Equal(RefKind.Ref, parameter1.RefKind);
Assert.Same(module.GetCorLibType(SpecialType.System_Array), parameter1Type);
Assert.Same(module.GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type.TypeSymbol);
Assert.Same(module.GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type.TypeSymbol);
var method4ParamTypes = m4.Parameters.Select(p => p.Type.TypeSymbol).ToArray();
Assert.Same(module.GetCorLibType(SpecialType.System_Void), m4.ReturnType.TypeSymbol);
Assert.Same(module.GetCorLibType(SpecialType.System_SByte), method4ParamTypes[0]);
Assert.Same(module.GetCorLibType(SpecialType.System_Single), method4ParamTypes[1]);
Assert.Same(module.GetCorLibType(SpecialType.System_Double), method4ParamTypes[2]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int16), method4ParamTypes[3]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int32), method4ParamTypes[4]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int64), method4ParamTypes[5]);
Assert.Same(module.GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes[6]);
Assert.Same(module.GetCorLibType(SpecialType.System_String), method4ParamTypes[7]);
Assert.Same(module.GetCorLibType(SpecialType.System_Byte), method4ParamTypes[8]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt16), method4ParamTypes[9]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt32), method4ParamTypes[10]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt64), method4ParamTypes[11]);
Assert.Same(module.GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes[12]);
Assert.True(m5.IsGenericMethod);
Assert.Same(m5.TypeParameters[0], m5.Parameters[0].Type.TypeSymbol);
Assert.Same(m5.TypeParameters[1], m5.Parameters[1].Type.TypeSymbol);
Assert.Equal(6, ((PEModuleSymbol)module).Module.GetMetadataReader().TypeReferences.Count);
});
}
[Fact]
public void Types()
{
string source = @"
sealed internal class B
{}
static class C
{
public class D{}
internal class E{}
protected class F{}
private class G{}
protected internal class H{}
class K{}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classB = module.GlobalNamespace.GetTypeMembers("B").Single();
Assert.True(classB.IsSealed);
Assert.Equal(Accessibility.Internal, classB.DeclaredAccessibility);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.True(classC.IsStatic);
Assert.Equal(Accessibility.Internal, classC.DeclaredAccessibility);
var classD = classC.GetTypeMembers("D").Single();
var classE = classC.GetTypeMembers("E").Single();
var classF = classC.GetTypeMembers("F").Single();
var classH = classC.GetTypeMembers("H").Single();
Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, classE.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, classH.DeclaredAccessibility);
if (isFromSource)
{
var classG = classC.GetTypeMembers("G").Single();
var classK = classC.GetTypeMembers("K").Single();
Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, classK.DeclaredAccessibility);
}
var peModuleSymbol = module as PEModuleSymbol;
if (peModuleSymbol != null)
{
Assert.Equal(5, peModuleSymbol.Module.GetMetadataReader().TypeReferences.Count);
}
};
CompileAndVerify(source, options: TestOptions.ReleaseDll, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Fields()
{
string source = @"
public class A
{
public int F1;
internal volatile int F2;
protected internal string F3;
protected float F4;
private double F5;
char F6;
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var f1 = classA.GetMembers("F1").OfType<FieldSymbol>().Single();
var f2 = classA.GetMembers("F2").OfType<FieldSymbol>().Single();
var f3 = classA.GetMembers("F3").OfType<FieldSymbol>().Single();
var f4 = classA.GetMembers("F4").OfType<FieldSymbol>().Single();
Assert.False(f1.IsVolatile);
Assert.Equal(0, f1.Type.CustomModifiers.Length);
Assert.True(f2.IsVolatile);
Assert.Equal(1, f2.Type.CustomModifiers.Length);
CustomModifier mod = f2.Type.CustomModifiers[0];
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, f2.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, f3.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, f4.DeclaredAccessibility);
if (isFromSource)
{
var f5 = classA.GetMembers("F5").OfType<FieldSymbol>().Single();
var f6 = classA.GetMembers("F6").OfType<FieldSymbol>().Single();
Assert.Equal(Accessibility.Private, f5.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, f6.DeclaredAccessibility);
}
Assert.False(mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", mod.Modifier.ToTestDisplayString());
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void Constructors()
{
string source =
@"namespace N
{
abstract class C
{
static C() {}
protected C() {}
}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("N.C");
var ctor = (MethodSymbol)type.GetMembers(".ctor").SingleOrDefault();
var cctor = (MethodSymbol)type.GetMembers(".cctor").SingleOrDefault();
Assert.NotNull(ctor);
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name);
Assert.Equal(MethodKind.Constructor, ctor.MethodKind);
Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility);
Assert.True(ctor.IsDefinition);
Assert.False(ctor.IsStatic);
Assert.False(ctor.IsAbstract);
Assert.False(ctor.IsSealed);
Assert.False(ctor.IsVirtual);
Assert.False(ctor.IsOverride);
Assert.False(ctor.IsGenericMethod);
Assert.False(ctor.IsExtensionMethod);
Assert.True(ctor.ReturnsVoid);
Assert.False(ctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString());
Assert.Equal(0, ctor.TypeParameters.Length);
Assert.Equal("Void", ctor.ReturnType.Name);
if (isFromSource)
{
Assert.NotNull(cctor);
Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name);
Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind);
Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility);
Assert.True(cctor.IsDefinition);
Assert.True(cctor.IsStatic);
Assert.False(cctor.IsAbstract);
Assert.False(cctor.IsSealed);
Assert.False(cctor.IsVirtual);
Assert.False(cctor.IsOverride);
Assert.False(cctor.IsGenericMethod);
Assert.False(cctor.IsExtensionMethod);
Assert.True(cctor.ReturnsVoid);
Assert.False(cctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString());
Assert.Equal(0, cctor.TypeArguments.Length);
Assert.Equal(0, cctor.Parameters.Length);
Assert.Equal("Void", cctor.ReturnType.Name);
}
else
{
Assert.Null(cctor);
}
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void ConstantFields()
{
string source =
@"class C
{
private const int I = -1;
internal const int J = I;
protected internal const object O = null;
public const string S = ""string"";
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
if (isFromSource)
{
CheckConstantField(type, "I", Accessibility.Private, SpecialType.System_Int32, -1);
}
CheckConstantField(type, "J", Accessibility.Internal, SpecialType.System_Int32, -1);
CheckConstantField(type, "O", Accessibility.ProtectedOrInternal, SpecialType.System_Object, null);
CheckConstantField(type, "S", Accessibility.Public, SpecialType.System_String, "string");
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckConstantField(NamedTypeSymbol type, string name, Accessibility declaredAccessibility, SpecialType fieldType, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
Assert.Equal(field.DeclaredAccessibility, declaredAccessibility);
Assert.Equal(field.Type.SpecialType, fieldType);
Assert.Equal(field.ConstantValue, value);
}
//the test for not importing internal members is elsewhere
[Fact]
public void DoNotImportPrivateMembers()
{
string source =
@"namespace Namespace
{
public class Public { }
internal class Internal { }
}
class Types
{
public class Public { }
internal class Internal { }
protected class Protected { }
protected internal class ProtectedInternal { }
private class Private { }
}
class Fields
{
public object Public = null;
internal object Internal = null;
protected object Protected = null;
protected internal object ProtectedInternal = null;
private object Private = null;
}
class Methods
{
public void Public() { }
internal void Internal() { }
protected void Protected() { }
protected internal void ProtectedInternal() { }
private void Private() { }
}
class Properties
{
public object Public { get; set; }
internal object Internal { get; set; }
protected object Protected { get; set; }
protected internal object ProtectedInternal { get; set; }
private object Private { get; set; }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var nmspace = module.GlobalNamespace.GetMember<NamespaceSymbol>("Namespace");
Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault());
Assert.NotNull(nmspace.GetTypeMembers("Internal").SingleOrDefault());
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, true);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, false);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckPrivateMembers(NamedTypeSymbol type, bool isFromSource, bool importPrivates)
{
Symbol member;
member = type.GetMembers("Public").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Internal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Protected").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("ProtectedInternal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Private").SingleOrDefault();
if (isFromSource || importPrivates)
{
Assert.NotNull(member);
}
else
{
Assert.Null(member);
}
}
[Fact]
public void GenericBaseTypeResolution()
{
string source =
@"class Base<T, U>
{
}
class Derived<T, U> : Base<T, U>
{
}";
Action<ModuleSymbol> validator = module =>
{
var derivedType = module.GlobalNamespace.GetTypeMembers("Derived").Single();
Assert.Equal(derivedType.Arity, 2);
var baseType = derivedType.BaseType();
Assert.Equal(baseType.Name, "Base");
Assert.Equal(baseType.Arity, 2);
Assert.Equal(derivedType.BaseType(), baseType);
Assert.Same(baseType.TypeArguments()[0], derivedType.TypeParameters[0]);
Assert.Same(baseType.TypeArguments()[1], derivedType.TypeParameters[1]);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void ImportExplicitImplementations()
{
string source =
@"interface I
{
void Method();
object Property { get; set; }
}
class C : I
{
void I.Method() { }
object I.Property { get; set; }
}";
Action<ModuleSymbol> validator = module =>
{
// Interface
var type = module.GlobalNamespace.GetTypeMembers("I").Single();
var method = (MethodSymbol)type.GetMembers("Method").Single();
Assert.NotNull(method);
var property = (PropertySymbol)type.GetMembers("Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
// Implementation
type = module.GlobalNamespace.GetTypeMembers("C").Single();
method = (MethodSymbol)type.GetMembers("I.Method").Single();
Assert.NotNull(method);
property = (PropertySymbol)type.GetMembers("I.Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void Properties()
{
string source =
@"public class C
{
public int P1 { get { return 0; } set { } }
internal int P2 { get { return 0; } }
protected internal int P3 { get { return 0; } }
protected int P4 { get { return 0; } }
private int P5 { set { } }
int P6 { get { return 0; } }
public int P7 { private get { return 0; } set { } }
internal int P8 { get { return 0; } private set { } }
protected int P9 { get { return 0; } private set { } }
protected internal int P10 { protected get { return 0; } set { } }
protected internal int P11 { internal get { return 0; } set { } }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
// Ensure member names are unique.
var memberNames = members.Select(member => member.Name).Distinct().ToList();
Assert.Equal(memberNames.Count, members.Length);
var c = members.First(member => member.Name == ".ctor");
Assert.NotNull(c);
var p1 = (PropertySymbol)members.First(member => member.Name == "P1");
var p2 = (PropertySymbol)members.First(member => member.Name == "P2");
var p3 = (PropertySymbol)members.First(member => member.Name == "P3");
var p4 = (PropertySymbol)members.First(member => member.Name == "P4");
var p7 = (PropertySymbol)members.First(member => member.Name == "P7");
var p8 = (PropertySymbol)members.First(member => member.Name == "P8");
var p9 = (PropertySymbol)members.First(member => member.Name == "P9");
var p10 = (PropertySymbol)members.First(member => member.Name == "P10");
var p11 = (PropertySymbol)members.First(member => member.Name == "P11");
var privateOrNotApplicable = isFromSource ? Accessibility.Private : Accessibility.NotApplicable;
CheckPropertyAccessibility(p1, Accessibility.Public, Accessibility.Public, Accessibility.Public);
CheckPropertyAccessibility(p2, Accessibility.Internal, Accessibility.Internal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p3, Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p4, Accessibility.Protected, Accessibility.Protected, Accessibility.NotApplicable);
CheckPropertyAccessibility(p7, Accessibility.Public, privateOrNotApplicable, Accessibility.Public);
CheckPropertyAccessibility(p8, Accessibility.Internal, Accessibility.Internal, privateOrNotApplicable);
CheckPropertyAccessibility(p9, Accessibility.Protected, Accessibility.Protected, privateOrNotApplicable);
CheckPropertyAccessibility(p10, Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.ProtectedOrInternal);
CheckPropertyAccessibility(p11, Accessibility.ProtectedOrInternal, Accessibility.Internal, Accessibility.ProtectedOrInternal);
if (isFromSource)
{
var p5 = (PropertySymbol)members.First(member => member.Name == "P5");
var p6 = (PropertySymbol)members.First(member => member.Name == "P6");
CheckPropertyAccessibility(p5, Accessibility.Private, Accessibility.NotApplicable, Accessibility.Private);
CheckPropertyAccessibility(p6, Accessibility.Private, Accessibility.Private, Accessibility.NotApplicable);
}
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void SetGetOnlyAutopropsInConstructors()
{
var comp = CreateCompilationWithMscorlib45(@"using System;
class C
{
public int P1 { get; }
public static int P2 { get; }
public C()
{
P1 = 10;
}
static C()
{
P2 = 11;
}
static void Main()
{
Console.Write(C.P2);
var c = new C();
Console.Write(c.P1);
}
}", options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1110");
}
[Fact]
public void AutoPropInitializersClass()
{
var comp = CreateCompilation(@"using System;
class C
{
public int P { get; set; } = 1;
public string Q { get; set; } = ""test"";
public decimal R { get; } = 300;
public static char S { get; } = 'S';
static void Main()
{
var c = new C();
Console.Write(c.P);
Console.Write(c.Q);
Console.Write(c.R);
Console.Write(C.S);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var p = type.GetMember<SourcePropertySymbol>("P");
var pBack = p.BackingField;
Assert.False(pBack.IsReadOnly);
Assert.False(pBack.IsStatic);
Assert.Equal(pBack.Type.SpecialType, SpecialType.System_Int32);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.False(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(qBack.Type.SpecialType, SpecialType.System_String);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(rBack.Type.SpecialType, SpecialType.System_Decimal);
var s = type.GetMember<SourcePropertySymbol>("S");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(sBack.Type.SpecialType, SpecialType.System_Char);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300S");
}
[Fact]
public void AutoPropInitializersStruct()
{
var comp = CreateCompilation(@"
using System;
struct S
{
public readonly int P;
public string Q { get; }
public decimal R { get; }
public static char T { get; } = 'T';
public S(int p)
{
P = p;
Q = ""test"";
R = 300;
}
static void Main()
{
var s = new S(1);
Console.Write(s.P);
Console.Write(s.Q);
Console.Write(s.R);
Console.Write(S.T);
s = new S();
Console.Write(s.P);
Console.Write(s.Q ?? ""null"");
Console.Write(s.R);
Console.Write(S.T);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S");
var p = type.GetMember<SourceMemberFieldSymbol>("P");
Assert.False(p.HasInitializer);
Assert.True(p.IsReadOnly);
Assert.False(p.IsStatic);
Assert.Equal(p.Type.SpecialType, SpecialType.System_Int32);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.True(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(qBack.Type.SpecialType, SpecialType.System_String);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(rBack.Type.SpecialType, SpecialType.System_Decimal);
var s = type.GetMember<SourcePropertySymbol>("T");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(sBack.Type.SpecialType, SpecialType.System_Char);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300T0null0T");
}
/// <summary>
/// Private accessors of a virtual property should not be virtual.
/// </summary>
[Fact]
public void PrivatePropertyAccessorNotVirtual()
{
string source = @"
class C
{
public virtual int P { get; private set; }
public virtual int Q { get; internal set; }
}
class D : C
{
public override int Q { internal set { } }
}
class E : D
{
public override int Q { get { return 0; } }
}
class F : E
{
public override int P { get { return 0; } }
public override int Q { internal set { } }
}
class Program
{
static void Main()
{
}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
bool checkValidProperties = (type is PENamedTypeSymbol);
var propertyP = (PropertySymbol)type.GetMembers("P").Single();
if (isFromSource)
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.Private);
Assert.False(propertyP.SetMethod.IsVirtual);
Assert.False(propertyP.SetMethod.IsOverride);
}
else
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.Null(propertyP.SetMethod);
}
Assert.True(propertyP.GetMethod.IsVirtual);
Assert.False(propertyP.GetMethod.IsOverride);
var propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.Public, Accessibility.Internal);
Assert.True(propertyQ.GetMethod.IsVirtual);
Assert.False(propertyQ.GetMethod.IsOverride);
Assert.True(propertyQ.SetMethod.IsVirtual);
Assert.False(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
type = module.GlobalNamespace.GetTypeMembers("F").Single();
propertyP = (PropertySymbol)type.GetMembers("P").Single();
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.False(propertyP.GetMethod.IsVirtual);
Assert.True(propertyP.GetMethod.IsOverride);
propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
// Derived property should be public even though the only
// declared accessor on the derived property is internal.
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.NotApplicable, Accessibility.Internal);
Assert.False(propertyQ.SetMethod.IsVirtual);
Assert.True(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
// Overridden property should be E but overridden
// accessor should be D.set_Q.
var overriddenProperty = module.GlobalNamespace.GetTypeMembers("E").Single().GetMembers("Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenProperty, propertyQ.OverriddenProperty);
var overriddenAccessor = module.GlobalNamespace.GetTypeMembers("D").Single().GetMembers("set_Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenAccessor, propertyQ.SetMethod.OverriddenMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void InterfaceProperties()
{
string source = @"
interface I
{
int P { get; set; }
}
public class C : I
{
int I.P { get { return 0; } set { } }
}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
var ip = (PropertySymbol)members.First(member => member.Name == "I.P");
CheckPropertyAccessibility(ip, Accessibility.Private, Accessibility.Private, Accessibility.Private);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private static void CheckPropertyAccessibility(PropertySymbol property, Accessibility propertyAccessibility, Accessibility getterAccessibility, Accessibility setterAccessibility)
{
var type = property.Type;
Assert.NotEqual(type.PrimitiveTypeCode, Microsoft.Cci.PrimitiveTypeCode.Void);
Assert.Equal(propertyAccessibility, property.DeclaredAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.GetMethod, getterAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.SetMethod, setterAccessibility);
}
private static void CheckPropertyAccessorAccessibility(PropertySymbol property, Accessibility propertyAccessibility, MethodSymbol accessor, Accessibility accessorAccessibility)
{
if (accessor == null)
{
Assert.Equal(accessorAccessibility, Accessibility.NotApplicable);
}
else
{
var containingType = property.ContainingType;
Assert.Equal(property, accessor.AssociatedSymbol);
Assert.Equal(containingType, accessor.ContainingType);
Assert.Equal(containingType, accessor.ContainingSymbol);
var method = containingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessorAccessibility, accessor.DeclaredAccessibility);
}
}
// Property/method override should succeed (and should reference
// the correct base method, even if there is a method/property
// with the same name in an intermediate class.
[WorkItem(538720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538720")]
[Fact]
public void TestPropertyOverrideGet()
{
PropertyOverrideGet(@"
class A
{
public virtual int P { get { return 0; } }
}
class B : A
{
public virtual int get_P() { return 0; }
}
class C : B
{
public override int P { get { return 0; } }
}
");
PropertyOverrideGet(@"
class A
{
public virtual int get_P() { return 0; }
}
class B : A
{
public virtual int P { get { return 0; } }
}
class C : B
{
public override int get_P() { return 0; }
}
");
}
private void PropertyOverrideGet(string source)
{
Action<ModuleSymbol> validator = module =>
{
var typeA = module.GlobalNamespace.GetTypeMembers("A").Single();
Assert.NotNull(typeA);
var getMethodA = (MethodSymbol)typeA.GetMembers("get_P").Single();
Assert.NotNull(getMethodA);
Assert.True(getMethodA.IsVirtual);
Assert.False(getMethodA.IsOverride);
var typeC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.NotNull(typeC);
var getMethodC = (MethodSymbol)typeC.GetMembers("get_P").Single();
Assert.NotNull(getMethodC);
Assert.False(getMethodC.IsVirtual);
Assert.True(getMethodC.IsOverride);
Assert.Same(getMethodC.OverriddenMethod, getMethodA);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void AutoProperties()
{
string source = @"
class A
{
public int P { get; private set; }
internal int Q { get; set; }
}
class B<T>
{
protected internal T P { get; set; }
}
class C : B<string>
{
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMember("A");
var p = classA.GetProperty("P");
VerifyAutoProperty(p, isFromSource);
var q = classA.GetProperty("Q");
VerifyAutoProperty(q, isFromSource);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
p = classC.BaseType().GetProperty("P");
VerifyAutoProperty(p, isFromSource);
Assert.Equal(p.Type.SpecialType, SpecialType.System_String);
Assert.Equal(p.GetMethod.AssociatedSymbol, p);
};
CompileAndVerify(
source,
sourceSymbolValidator: validator(true),
symbolValidator: validator(false),
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
}
private static void VerifyAutoProperty(PropertySymbol property, bool isFromSource)
{
if (isFromSource)
{
if (property is SourcePropertySymbol sourceProperty)
{
Assert.True(sourceProperty.IsAutoProperty);
}
}
else
{
var backingField = property.ContainingType.GetField(GeneratedNames.MakeBackingFieldName(property.Name));
var attribute = backingField.GetAttributes().Single();
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attribute.AttributeClass.ToTestDisplayString());
Assert.Empty(attribute.AttributeConstructor.Parameters);
}
VerifyAutoPropertyAccessor(property, property.GetMethod);
VerifyAutoPropertyAccessor(property, property.SetMethod);
}
private static void VerifyAutoPropertyAccessor(PropertySymbol property, MethodSymbol accessor)
{
if (accessor != null)
{
var method = property.ContainingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessor.AssociatedSymbol, property);
Assert.False(accessor.IsImplicitlyDeclared, "MethodSymbol.IsImplicitlyDeclared should be false for auto property accessors");
}
}
[Fact]
public void EmptyEnum()
{
string source = "enum E {}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int32);
Assert.Equal(1, type.GetMembers().Length);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void NonEmptyEnum()
{
string source =
@"enum E : short
{
A,
B = 0x02,
C,
D,
E = B | D,
F = C,
G,
}
";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int16);
Assert.Equal(8, type.GetMembers().Length);
CheckEnumConstant(type, "A", (short)0);
CheckEnumConstant(type, "B", (short)2);
CheckEnumConstant(type, "C", (short)3);
CheckEnumConstant(type, "D", (short)4);
CheckEnumConstant(type, "E", (short)6);
CheckEnumConstant(type, "F", (short)3);
CheckEnumConstant(type, "G", (short)4);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private void CheckEnumConstant(NamedTypeSymbol type, string name, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
// TODO: DeclaredAccessibility should be NotApplicable.
//Assert.Equal(field.DeclaredAccessibility, Accessibility.NotApplicable);
Assert.Equal(field.Type.TypeSymbol, type);
Assert.Equal(field.ConstantValue, value);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
var fieldDefinition = (Microsoft.Cci.IFieldDefinition)field;
Assert.False(fieldDefinition.IsSpecialName);
Assert.False(fieldDefinition.IsRuntimeSpecial);
}
}
private void CheckEnumType(NamedTypeSymbol type, Accessibility declaredAccessibility, SpecialType underlyingType)
{
Assert.Equal(type.BaseType().SpecialType, SpecialType.System_Enum);
Assert.Equal(type.EnumUnderlyingType.SpecialType, underlyingType);
Assert.Equal(type.DeclaredAccessibility, declaredAccessibility);
Assert.True(type.IsSealed);
// value__ field should not be exposed from type, even though it is public,
// since we want to prevent source from accessing the field directly.
var field = type.GetMembers(WellKnownMemberNames.EnumBackingFieldName).SingleOrDefault() as FieldSymbol;
Assert.Null(field);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
field = sourceType.EnumValueField;
Assert.NotNull(field);
Assert.Equal(field.Name, WellKnownMemberNames.EnumBackingFieldName);
Assert.False(field.IsStatic);
Assert.False(field.IsConst);
Assert.False(field.IsReadOnly);
Assert.Equal(field.DeclaredAccessibility, Accessibility.Public); // Dev10: value__ is public
Assert.Equal(field.Type.TypeSymbol, type.EnumUnderlyingType);
var module = new PEAssemblyBuilder((SourceAssemblySymbol)sourceType.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var typeDefinition = (Microsoft.Cci.ITypeDefinition)type;
var fieldDefinition = typeDefinition.GetFields(context).First();
Assert.Same(fieldDefinition, field); // Dev10: value__ field is the first field.
Assert.True(fieldDefinition.IsSpecialName);
Assert.True(fieldDefinition.IsRuntimeSpecial);
context.Diagnostics.Verify();
}
}
[Fact]
public void GenericMethods()
{
string source = @"
public class A
{
public static void Main()
{
System.Console.WriteLine(""GenericMethods"");
//B.Test<int>();
//C<int>.Test<int>();
}
}
public class B
{
public static void Test<T>()
{
System.Console.WriteLine(""Test<T>"");
}
}
public class C<T>
{
public static void Test<S>()
{
System.Console.WriteLine(""C<T>.Test<S>"");
}
}
";
CompileAndVerify(source, expectedOutput: "GenericMethods\r\n");
}
[Fact]
public void GenericMethods2()
{
string source = @"
class A
{
public static void Main()
{
TC1 x = new TC1();
System.Console.WriteLine(x.GetType());
TC2<byte> y = new TC2<byte>();
System.Console.WriteLine(y.GetType());
TC3<byte>.TC4 z = new TC3<byte>.TC4();
System.Console.WriteLine(z.GetType());
}
}
class TC1
{
void TM1<T1>()
{
TM1<T1>();
}
void TM2<T2>()
{
TM2<int>();
}
}
class TC2<T3>
{
void TM3<T4>()
{
TM3<T4>();
TM3<T4>();
}
void TM4<T5>()
{
TM4<int>();
TM4<int>();
}
static void TM5<T6>(T6 x)
{
TC2<int>.TM5(x);
}
static void TM6<T7>(T7 x)
{
TC2<int>.TM6(1);
}
void TM9()
{
TM9();
TM9();
}
}
class TC3<T8>
{
public class TC4
{
void TM7<T9>()
{
TM7<T9>();
TM7<int>();
}
static void TM8<T10>(T10 x)
{
TC3<int>.TC4.TM8(x);
TC3<int>.TC4.TM8(1);
}
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput:
@"TC1
TC2`1[System.Byte]
TC3`1+TC4[System.Byte]
");
verifier.VerifyIL("TC1.TM1<T1>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM1<T1>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC1.TM2<T2>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM2<int>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM3<T4>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM3<T4>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM3<T4>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM4<T5>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM4<int>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM4<int>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM5<T6>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<int>.TM5<T6>(T6)""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM6<T7>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void TC2<int>.TM6<int>(int)""
IL_0006: ret
}
");
}
[Fact]
public void Generics3()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
C1<Byte, Byte> x1 = new C1<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte> x2 = new C1<Byte, Byte>.C2<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte> x3 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte> x4 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte>();
C1<Byte, Byte>.C5 x5 = new C1<Byte, Byte>.C5();
}
}
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2> where C3T2 : C1T1
{
public class C4<C4T1>
{
}
}
public C1<int, C2T2>.C5 V1;
public C1<C2T1, C2T2>.C5 V2;
public C1<int, int>.C5 V3;
public C2<Byte, Byte> V4;
public C1<C1T2, C1T1>.C2<C2T1, C2T2> V5;
public C1<C1T2, C1T1>.C2<C2T2, C2T1> V6;
public C1<C1T2, C1T1>.C2<Byte, int> V7;
public C2<C2T1, C2T2> V8;
public C2<Byte, C2T2> V9;
void Test12(C2<int, int> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V9;
}
void Test11(C1<int, int>.C2<Byte, Byte> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V8;
}
void Test6(C1<C1T2, C1T1>.C2<C2T1, C2T2> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V5;
}
void Test7(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V6;
}
void Test8(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V7;
}
void Test9(C1<int, Byte>.C2<C2T2, C2T1> x)
{
C1<Byte, int>.C2<Byte, int> y = x.V7;
}
void Test10(C1<C1T1, C1T2>.C2<C2T2, C2T1> x)
{
C1<C1T2, C1T1>.C2<Byte, int> y = x.V7;
}
}
public class C5
{
}
void Test1(C2<C1T1, int> x)
{
C1<int, int>.C5 y = x.V1;
}
void Test2(C2<C1T1, C1T2> x)
{
C5 y = x.V2;
}
void Test3(C2<C1T2, C1T1> x)
{
C1<int, int>.C5 y = x.V3;
}
void Test4(C1<int, int>.C2<C1T1, C1T2> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V4;
}
}
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_UnsupportedOrdering1()
{
CompileAndVerify(@"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
}
");
}
[Fact]
public void RefEmit_UnsupportedOrdering1_EP()
{
string source = @"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
public static void Main()
{
System.Console.Write(1234);
}
}";
CompileAndVerify(source, expectedOutput: @"1234");
}
[Fact]
public void RefEmit_UnsupportedOrdering2()
{
CompileAndVerify(@"
class B<T> where T : A {}
class A : B<A> {}
");
}
[Fact]
public void RefEmit_MembersOfOpenGenericType()
{
CompileAndVerify(@"
class C<T>
{
void goo()
{
System.Collections.Generic.Dictionary<int, T> d = new System.Collections.Generic.Dictionary<int, T>();
}
}
");
}
[Fact]
public void RefEmit_ListOfValueTypes()
{
string source = @"
using System.Collections.Generic;
class A
{
struct S { }
List<S> f;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedSelfReference()
{
string source = @"
class A<T>
{
class B {
}
A<int>.B x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedGenericSelfReference()
{
string source = @"
class A<T>
{
public class B<S> {
public class C<U,V> {
}
}
A<int>.B<double>.C<string, bool> x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Cycle()
{
string source = @"
public class B : I<C> { }
public class C : I<B> { }
public interface I<T> { }
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedMemberReference()
{
string source = @"
class A<T>
{
public A()
{
A<int>.method();
int a = A<string>.field;
new A<double>();
}
public static void method()
{
}
public static int field;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_NestedGenericTypeReferences()
{
string source = @"
class A<T>
{
public class H<S>
{
A<T>.H<S> x;
}
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering2()
{
// order:
// E <(value type field) E.C.N2 <(value type field) N3
string source = @"
public class E
{
public class C {
public struct N2
{
public N3 n1;
}
}
C.N2 n2;
}
public struct N3
{
E f;
int g;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering3()
{
string source = @"
using System.Collections.Generic;
public class E
{
public struct N2
{
public List<N3> n1; // E.N2 doesn't depend on E.N3 since List<> isn't a value type
}
public struct N3
{
}
N2 n2;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_IL1()
{
CompileAndVerify(@"
class C
{
public static void Main()
{
int i = 0, j, k = 2147483647;
long l = 0, m = 9200000000000000000L;
int b = -10;
byte c = 200;
float f = 3.14159F;
double d = 2.71828;
string s = ""abcdef"";
bool x = true;
System.Console.WriteLine(i);
System.Console.WriteLine(k);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(f);
System.Console.WriteLine(d);
System.Console.WriteLine(s);
System.Console.WriteLine(x);
}
}
", expectedOutput: @"
0
2147483647
-10
200
3.14159
2.71828
abcdef
True
");
}
[WorkItem(540581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540581")]
[Fact]
public void RefEmit_DependencyGraphAndCachedTypeReferences()
{
var source = @"
using System;
interface I1<T>
{
void Method(T x);
}
interface I2<U>
{
void Method(U x);
}
interface I3<W> : I1<W>, I2<W>
{
void Method(W x);
}
class Implicit2 : I3<string> // Implicit2 depends on I3<string>
{
public void Method(string x) { }
}
class Test
{
public static void Main()
{
I3<string> i = new Implicit2();
}
}
";
// If I3<string> in Main body is resolved first and stored in a cache,
// the fact that Implicit2 depends on I3<string> isn't recorded if we pull
// I3<string> from cache at the beginning of ResolveType method.
CompileAndVerify(source);
}
[Fact]
public void CheckRef()
{
string source = @"
public abstract class C
{
public abstract int M(int x, ref int y, out int z);
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
var m = c.GetMembers("M").Single() as MethodSymbol;
Assert.Equal(RefKind.None, m.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, m.Parameters[1].RefKind);
Assert.Equal(RefKind.Out, m.Parameters[2].RefKind);
});
}
[Fact]
public void OutArgument()
{
string source = @"
class C
{
static void Main() { double d; double.TryParse(null, out d); }
}
";
CompileAndVerify(source);
}
[Fact]
public void CreateInstance()
{
string source = @"
class C
{
static void Main() { System.Activator.CreateInstance<int>(); }
}
";
CompileAndVerify(source);
}
[Fact]
public void DelegateRoundTrip()
{
string source = @"delegate int MyDel(
int x,
// ref int y, // commented out until 4264 is fixed.
// out int z, // commented out until 4264 is fixed.
int w);";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol;
var invoke = myDel.DelegateInvokeMethod;
var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol;
Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length);
Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind);
Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.TypeSymbol.ToTestDisplayString());
for (int i = 0; i < invoke.Parameters.Length; i++)
{
Assert.Equal(invoke.Parameters[i].Type.TypeSymbol, beginInvoke.Parameters[i].Type.TypeSymbol);
Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind);
}
Assert.Equal("System.AsyncCallback", beginInvoke.Parameters[invoke.Parameters.Length].Type.TypeSymbol.ToTestDisplayString());
Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.TypeSymbol.ToTestDisplayString());
var invokeReturn = invoke.ReturnType.TypeSymbol;
var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol;
var endInvokeReturn = endInvoke.ReturnType.TypeSymbol;
Assert.Equal(invokeReturn, endInvokeReturn);
int k = 0;
for (int i = 0; i < invoke.Parameters.Length; i++)
{
if (invoke.Parameters[i].RefKind != RefKind.None)
{
Assert.Equal(invoke.Parameters[i].Type, endInvoke.Parameters[k].Type);
Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind);
}
}
Assert.Equal("System.IAsyncResult", endInvoke.Parameters[k++].Type.TypeSymbol.ToTestDisplayString());
Assert.Equal(k, endInvoke.Parameters.Length);
});
}
[Fact]
public void StaticClassRoundTrip()
{
string source = @"
public static class C
{
private static string msg = ""Hello"";
private static void Goo()
{
System.Console.WriteLine(msg);
}
public static void Main()
{
Goo();
}
}
";
CompileAndVerify(source,
symbolValidator: module =>
{
var global = module.GlobalNamespace;
var classC = global.GetMember<NamedTypeSymbol>("C");
Assert.True(classC.IsStatic, "Expected C to be static");
Assert.False(classC.IsAbstract, "Expected C to be non-abstract"); //even though it is abstract in metadata
Assert.False(classC.IsSealed, "Expected C to be non-sealed"); //even though it is sealed in metadata
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.InstanceConstructorName).Length); //since C is static
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); //since we don't import private members
});
}
[Fact]
public void DoNotImportInternalMembers()
{
string sources =
@"public class Fields
{
public int Public;
internal int Internal;
}
public class Methods
{
public void Public() {}
internal void Internal() {}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol m) =>
{
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource);
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource);
};
CompileAndVerify(sources, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Issue4695()
{
string source = @"
using System;
class Program
{
sealed class Cache
{
abstract class BucketwiseBase<TArg> where TArg : class
{
internal abstract void Default(TArg arg);
}
class BucketwiseBase<TAccumulator, TArg> : BucketwiseBase<TArg> where TArg : class
{
internal override void Default(TArg arg = null) { }
}
public string GetAll()
{
new BucketwiseBase<object, object>().Default(); // Bad image format thrown here on legacy compiler
return ""OK"";
}
}
static void Main(string[] args)
{
Console.WriteLine(new Cache().GetAll());
}
}
";
CompileAndVerify(source, expectedOutput: "OK");
}
private void CheckInternalMembers(NamedTypeSymbol type, bool isFromSource)
{
Assert.NotNull(type.GetMembers("Public").SingleOrDefault());
var member = type.GetMembers("Internal").SingleOrDefault();
if (isFromSource)
Assert.NotNull(member);
else
Assert.Null(member);
}
[WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")]
[Fact]
public void EmitWithNoResourcesAllPlatforms()
{
var comp = CreateCompilation("class Test { static void Main() { } }");
VerifyEmitWithNoResources(comp, Platform.AnyCpu);
VerifyEmitWithNoResources(comp, Platform.AnyCpu32BitPreferred);
VerifyEmitWithNoResources(comp, Platform.Arm); // broken before fix
VerifyEmitWithNoResources(comp, Platform.Itanium); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X64); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X86);
}
private void VerifyEmitWithNoResources(CSharpCompilation comp, Platform platform)
{
var options = TestOptions.ReleaseExe.WithPlatform(platform);
CompileAndVerify(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_" + platform.ToString()).WithOptions(options));
}
[Fact]
public unsafe void PEHeaders1()
{
var options = EmitOptions.Default.WithFileAlignment(0x2000);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C {}", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.ReleaseDll.WithDeterministic(true),
assemblyName: "46B9C2B2-B7A0-45C5-9EF9-28DDF739FD9E").EmitToStream(options);
peStream.Position = 0;
var peReader = new PEReader(peStream);
var peHeaders = peReader.PEHeaders;
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32, peHeader.Magic);
Assert.Equal(0x0000237E, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00004000, peHeader.BaseOfData);
Assert.Equal(0x00002000, peHeader.SizeOfHeaders);
Assert.Equal(0x00002000, peHeader.SizeOfCode);
Assert.Equal(0x00001000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00006000, peHeader.SizeOfImage);
Assert.Equal(0x00002000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00001000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, peHeader.DllCharacteristics);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x2000, peHeader.FileAlignment);
Assert.Equal(0x10000000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(4, peHeader.MajorSubsystemVersion);
Assert.Equal(0, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x2000, peHeader.SizeOfHeaders);
Assert.Equal(0x4000, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0xc, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2008, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2310, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0x2000, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x8, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0x232C, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x4f, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
int importAddressTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportAddressTableDirectory, out importAddressTableDirectoryOffset));
Assert.Equal(0x2000, importAddressTableDirectoryOffset);
var importAddressTableDirectoryBytes = new byte[peHeader.ImportAddressTableDirectory.Size];
peStream.Position = importAddressTableDirectoryOffset;
peStream.Read(importAddressTableDirectoryBytes, 0, importAddressTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x60, 0x23, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}, importAddressTableDirectoryBytes);
int importTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportTableDirectory, out importTableDirectoryOffset));
Assert.Equal(0x232C, importTableDirectoryOffset);
var importTableDirectoryBytes = new byte[peHeader.ImportTableDirectory.Size];
peStream.Position = importTableDirectoryOffset;
peStream.Read(importTableDirectoryBytes, 0, importTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x54, 0x23, 0x00, 0x00, // RVA
0x00, 0x00, 0x00, 0x00, // 0
0x00, 0x00, 0x00, 0x00, // 0
0x6E, 0x23, 0x00, 0x00, // name RVA
0x00, 0x20, 0x00, 0x00, // ImportAddressTableDirectory RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x60, 0x23, 0x00, 0x00, // hint RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, // hint
(byte)'_', (byte)'C', (byte)'o', (byte)'r', (byte)'D', (byte)'l', (byte)'l', (byte)'M', (byte)'a', (byte)'i', (byte)'n', 0x00,
(byte)'m', (byte)'s', (byte)'c', (byte)'o', (byte)'r', (byte)'e', (byte)'e', (byte)'.', (byte)'d', (byte)'l', (byte)'l', 0x00,
0x00
}, importTableDirectoryBytes);
var entryPointSectionIndex = peHeaders.GetContainingSectionIndex(peHeader.AddressOfEntryPoint);
Assert.Equal(0, entryPointSectionIndex);
peStream.Position = peHeaders.SectionHeaders[0].PointerToRawData + peHeader.AddressOfEntryPoint - peHeaders.SectionHeaders[0].VirtualAddress;
byte[] startupStub = new byte[8];
peStream.Read(startupStub, 0, startupStub.Length);
AssertEx.Equal(new byte[] { 0xFF, 0x25, 0x00, 0x20, 0x00, 0x10, 0x00, 0x00 }, startupStub);
Assert.Equal(Characteristics.Dll | Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.I386, coffHeader.Machine);
Assert.Equal(2, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(0xe0, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-609170495, coffHeader.TimeDateStamp);
Assert.Equal(0, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2058, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02b8, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(2, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x2000, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x2000, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(900, sections[0].VirtualSize);
Assert.Equal(".reloc", sections[1].Name);
Assert.Equal(0, sections[1].NumberOfLineNumbers);
Assert.Equal(0, sections[1].NumberOfRelocations);
Assert.Equal(0, sections[1].PointerToLineNumbers);
Assert.Equal(0x4000, sections[1].PointerToRawData);
Assert.Equal(0, sections[1].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead, sections[1].SectionCharacteristics);
Assert.Equal(0x2000, sections[1].SizeOfRawData);
Assert.Equal(0x4000, sections[1].VirtualAddress);
Assert.Equal(12, sections[1].VirtualSize);
var relocBlock = peReader.GetSectionData(sections[1].VirtualAddress);
var relocBytes = new byte[sections[1].VirtualSize];
Marshal.Copy((IntPtr)relocBlock.Pointer, relocBytes, 0, relocBytes.Length);
AssertEx.Equal(new byte[] { 0, 0x20, 0, 0, 0x0c, 0, 0, 0, 0x80, 0x33, 0, 0 }, relocBytes);
}
[Fact]
public void PEHeaders2()
{
var options = EmitOptions.Default.
WithFileAlignment(512).
WithBaseAddress(0x123456789ABCDEF).
WithHighEntropyVirtualAddressSpace(true).
WithSubsystemVersion(SubsystemVersion.WindowsXP);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C { static void Main() { } }", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.DebugExe.WithPlatform(Platform.X64).WithDeterministic(true),
assemblyName: "B37A4FCD-ED76-4924-A2AD-298836056E00").EmitToStream(options);
peStream.Position = 0;
var peHeaders = new PEHeaders(peStream);
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32Plus, peHeader.Magic);
Assert.Equal(0x00000000, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00000000, peHeader.BaseOfData);
Assert.Equal(0x00000200, peHeader.SizeOfHeaders);
Assert.Equal(0x00000400, peHeader.SizeOfCode);
Assert.Equal(0x00002000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00004000, peHeader.SizeOfImage);
Assert.Equal(0x00000000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00004000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x0400000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x200, peHeader.FileAlignment);
Assert.Equal(0x0123456789ac0000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(5, peHeader.MajorSubsystemVersion);
Assert.Equal(1, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x200, peHeader.SizeOfHeaders);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2000, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2324, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
Assert.Equal(Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.Amd64, coffHeader.Machine);
Assert.Equal(1, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(240, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-862605524, coffHeader.TimeDateStamp);
Assert.Equal(0x06000001, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2054, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02d0, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(1, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x200, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x400, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(832, sections[0].VirtualSize);
}
[Fact]
public void InParametersShouldHaveMetadataIn_TypeMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public void M(in int a, [In]in int b, [In]int c, int d) {}
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_IndexerMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public int this[in int a, [In]in int b, [In]int c, int d] => 0;
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("get_Item").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_Delegates()
{
var text = @"
using System.Runtime.InteropServices;
public delegate void D(in int a, [In]in int b, [In]int c, int d);
public class C
{
public void M()
{
N((in int a, in int b, int c, int d) => {});
}
public void N(D lambda) { }
}
";
CompileAndVerify(text,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
sourceSymbolValidator: module =>
{
var parameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
},
symbolValidator: module =>
{
var delegateParameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, delegateParameters.Length);
Assert.True(delegateParameters[0].IsMetadataIn);
Assert.True(delegateParameters[1].IsMetadataIn);
Assert.True(delegateParameters[2].IsMetadataIn);
Assert.False(delegateParameters[3].IsMetadataIn);
var lambdaParameters = module.GlobalNamespace.GetTypeMember("C").GetTypeMember("<>c").GetMethod("<M>b__0_0").Parameters;
Assert.Equal(4, lambdaParameters.Length);
Assert.True(lambdaParameters[0].IsMetadataIn);
Assert.True(lambdaParameters[1].IsMetadataIn);
Assert.False(lambdaParameters[2].IsMetadataIn);
Assert.False(lambdaParameters[3].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_LocalFunctions()
{
var text = @"
using System.Runtime.InteropServices;
public class C
{
public void M()
{
void local(in int a, int c) { }
}
}
";
CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("C").GetMember("<M>g__local|0_0").GetParameters();
Assert.Equal(2, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.False(parameters[1].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_ExternMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
[DllImport(""Other.dll"")]
public static extern void M(in int a, [In]in int b, [In]int c, int d);
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_NoPIA()
{
var comAssembly = CreateCompilationWithMscorlib40(@"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""test.dll"")]
[assembly: Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
[ComImport()]
[Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
public interface T
{
void M(in int a, [In]in int b, [In]int c, int d);
}");
CompileAndVerify(comAssembly, symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
var code = @"
class User
{
public void M(T obj)
{
obj.M(1, 2, 3, 4);
}
}";
CompileAndVerify(
source: code,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
references: new[] { comAssembly.EmitToImageReference(embedInteropTypes: true) },
symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
}
[Fact]
public void ExtendingInParametersFromParentWithoutInAttributeWorksWithoutErrors()
{
var reference = CompileIL(@"
.class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class public auto ansi beforefieldinit Parent extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual instance void M (
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) a,
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) b,
int32 c,
int32 d) cil managed
{
.param [1] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.param [2] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.maxstack 8
IL_0000: nop
IL_0001: ldstr ""Parent called""
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void[mscorlib] System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}");
var comp = CreateCompilation(@"
using System;
using System.Runtime.InteropServices;
public class Child : Parent
{
public override void M(in int a, [In]in int b, [In]int c, int d)
{
base.M(a, b, c, d);
Console.WriteLine(""Child called"");
}
}
public static class Program
{
public static void Main()
{
var obj = new Child();
obj.M(1, 2, 3, 4);
}
}", new[] { reference }, TestOptions.ReleaseExe);
var parentParameters = comp.GetTypeByMetadataName("Parent").GetMethod("M").GetParameters();
Assert.Equal(4, parentParameters.Length);
Assert.False(parentParameters[0].IsMetadataIn);
Assert.False(parentParameters[1].IsMetadataIn);
Assert.False(parentParameters[2].IsMetadataIn);
Assert.False(parentParameters[3].IsMetadataIn);
var expectedOutput =
@"Parent called
Child called";
CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: module =>
{
var childParameters = module.ContainingAssembly.GetTypeByMetadataName("Child").GetMethod("M").GetParameters();
Assert.Equal(4, childParameters.Length);
Assert.True(childParameters[0].IsMetadataIn);
Assert.True(childParameters[1].IsMetadataIn);
Assert.True(childParameters[2].IsMetadataIn);
Assert.False(childParameters[3].IsMetadataIn);
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_OutAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(out int a, [Out] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataOut);
Assert.True(sourceParentParameters[1].IsMetadataOut);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(out int a, [Out] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataOut);
Assert.True(interfaceParameters[1].IsMetadataOut);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataOut);
Assert.False(proxyChildParameters[1].IsMetadataOut); // User placed attributes are not copied.
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_InAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(in int a, [In] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataIn);
Assert.True(sourceParentParameters[1].IsMetadataIn);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(in int a, [In] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataIn);
Assert.True(interfaceParameters[1].IsMetadataIn);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataIn);
Assert.False(proxyChildParameters[1].IsMetadataIn); // User placed attributes are not copied.
});
}
}
}
| {
"content_hash": "514719ece0d98a7038dba2c6fee0ad2b",
"timestamp": "",
"source": "github",
"line_count": 2908,
"max_line_length": 213,
"avg_line_length": 36.690852819807425,
"alnum_prop": 0.6024817942397631,
"repo_name": "jcouv/roslyn",
"id": "cec2f32e87a9426662006c20df42d4d8319f8b21",
"size": "106699",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "8647"
},
{
"name": "C#",
"bytes": "112580996"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "Dockerfile",
"bytes": "1905"
},
{
"name": "F#",
"bytes": "508"
},
{
"name": "PowerShell",
"bytes": "108269"
},
{
"name": "Shell",
"bytes": "22747"
},
{
"name": "Smalltalk",
"bytes": "622"
},
{
"name": "Visual Basic",
"bytes": "68681825"
}
],
"symlink_target": ""
} |
import { Routes, RouterModule } from '@angular/router';
import { TransactionsComponent } from './transactions.component';
import { ListTransactionsComponent } from './components/listTransactions/list-transactions.component';
// noinspection TypeScriptValidateTypes
const routes: Routes = [
{
path: '',
component: TransactionsComponent,
children: [
],
},
];
export const routing = RouterModule.forChild(routes);
| {
"content_hash": "6582194e765b915b5fe3cc15f4cb7123",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 102,
"avg_line_length": 25.58823529411765,
"alnum_prop": 0.728735632183908,
"repo_name": "tcomax/landswoop-frontend",
"id": "986835d26c96a5c46a98b32b8089c6fe990192cf",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/pages/transactions/transactions.routing.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "152647"
},
{
"name": "HTML",
"bytes": "106577"
},
{
"name": "JavaScript",
"bytes": "2083"
},
{
"name": "Shell",
"bytes": "153"
},
{
"name": "TypeScript",
"bytes": "379089"
}
],
"symlink_target": ""
} |
import os
import uuid
import mock
from barbican.common import resources
from barbican.model import models
from barbican.model import repositories
from barbican.tests.api.controllers import test_acls
from barbican.tests.api import test_resources_policy as test_policy
from barbican.tests import utils
order_repo = repositories.get_order_repository()
project_repo = repositories.get_project_repository()
ca_repo = repositories.get_ca_repository()
project_ca_repo = repositories.get_project_ca_repository()
container_repo = repositories.get_container_repository()
generic_key_meta = {
'name': 'secretname',
'algorithm': 'AES',
'bit_length': 256,
'mode': 'cbc',
'payload_content_type': 'application/octet-stream'
}
class WhenCreatingOrdersUsingOrdersResource(utils.BarbicanAPIBaseTestCase):
def test_can_create_a_new_order(self):
resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(resp.status_int, 202)
# Make sure we get a valid uuid for the order
uuid.UUID(order_uuid)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
def test_order_creation_should_allow_unknown_algorithm(self):
meta = {
'bit_length': 128,
'algorithm': 'unknown'
}
resp, _ = create_order(
self.app,
order_type='key',
meta=meta
)
self.assertEqual(resp.status_int, 202)
def test_order_creation_should_fail_without_a_type(self):
resp, _ = create_order(
self.app,
meta=generic_key_meta,
expect_errors=True
)
self.assertEqual(resp.status_int, 400)
def test_order_creation_should_fail_without_metadata(self):
resp, _ = create_order(
self.app,
order_type='key',
expect_errors=True
)
self.assertEqual(resp.status_int, 400)
def test_order_create_should_fail_w_unsupported_payload_content_type(self):
meta = {
'bit_length': 128,
'algorithm': 'aes',
'payload_content_type': 'something_unsupported'
}
resp, _ = create_order(
self.app,
order_type='key',
meta=meta,
expect_errors=True
)
self.assertEqual(resp.status_int, 400)
def test_order_creation_should_fail_with_bogus_content(self):
resp = self.app.post(
'/orders/',
'random_stuff',
headers={'Content-Type': 'application/json'},
expect_errors=True
)
self.assertEqual(resp.status_int, 400)
def test_order_creation_should_fail_with_empty_dict(self):
resp = self.app.post_json(
'/orders/',
{},
headers={'Content-Type': 'application/json'},
expect_errors=True
)
self.assertEqual(resp.status_int, 400)
def test_order_creation_should_fail_without_content_type_header(self):
resp = self.app.post(
'/orders/',
'doesn\'t matter. headers are validated first',
expect_errors=True,
)
self.assertEqual(resp.status_int, 415)
class WhenGettingOrdersListUsingOrdersResource(utils.BarbicanAPIBaseTestCase):
def test_can_get_a_list_of_orders(self):
# Make sure we have atleast one order to created
resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(resp.status_int, 202)
# Get the list of orders
resp = self.app.get(
'/orders/',
headers={'Content-Type': 'application/json'}
)
self.assertEqual(200, resp.status_int)
self.assertIn('total', resp.json)
self.assertGreater(len(resp.json.get('orders')), 0)
def test_pagination_attributes_not_available_with_empty_order_list(self):
params = {'name': 'no_orders_with_this_name'}
resp = self.app.get(
'/orders/',
params
)
self.assertEqual(200, resp.status_int)
self.assertEqual(0, len(resp.json.get('orders')))
class WhenGettingOrDeletingOrders(utils.BarbicanAPIBaseTestCase):
def test_can_get_order(self):
# Make sure we have a order to retrieve
create_resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(202, create_resp.status_int)
# Retrieve the order
get_resp = self.app.get('/orders/{0}/'.format(order_uuid))
self.assertEqual(200, get_resp.status_int)
def test_can_delete_order(self):
# Make sure we have a order to retrieve
create_resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(202, create_resp.status_int)
delete_resp = self.app.delete('/orders/{0}'.format(order_uuid))
self.assertEqual(204, delete_resp.status_int)
def test_get_call_on_non_existant_order_should_give_404(self):
bogus_uuid = uuid.uuid4()
resp = self.app.get(
'/orders/{0}'.format(bogus_uuid),
expect_errors=True
)
self.assertEqual(404, resp.status_int)
def test_delete_call_on_non_existant_order_should_give_404(self):
bogus_uuid = uuid.uuid4()
resp = self.app.delete(
'/orders/{0}'.format(bogus_uuid),
expect_errors=True
)
self.assertEqual(404, resp.status_int)
@utils.parameterized_test_case
class WhenPuttingAnOrderWithMetadata(utils.BarbicanAPIBaseTestCase):
def setUp(self):
# Temporarily mock the queue until we can figure out a better way
# TODO(jvrbanac): Remove dependence on mocks
self.update_order_mock = mock.MagicMock()
repositories.OrderRepo.update_order = self.update_order_mock
super(WhenPuttingAnOrderWithMetadata, self).setUp()
def _create_generic_order_for_put(self):
"""Create a real order to modify and perform PUT actions on
This makes sure that a project exists for our order and that there
is an order within the database. This is a little hacky due to issues
testing certificate order types.
"""
# Create generic order
resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(202, resp.status_int)
# Modify the order in the DB to allow actions to be performed
order_model = order_repo.get(order_uuid, self.project_id)
order_model.type = 'certificate'
order_model.status = models.States.PENDING
order_model.meta = {'nope': 'nothing'}
order_model.save()
repositories.commit()
return order_uuid
def test_putting_on_a_order(self):
order_uuid = self._create_generic_order_for_put()
body = {
'type': 'certificate',
'meta': {'nope': 'thing'}
}
resp = self.app.put_json(
'/orders/{0}'.format(order_uuid),
body,
headers={'Content-Type': 'application/json'}
)
self.assertEqual(204, resp.status_int)
self.assertEqual(1, self.update_order_mock.call_count)
@utils.parameterized_dataset({
'bogus_content': ['bogus'],
'bad_order_type': ['{"type": "secret", "meta": {}}'],
})
def test_return_400_on_put_with(self, body):
order_uuid = self._create_generic_order_for_put()
resp = self.app.put(
'/orders/{0}'.format(order_uuid),
body,
headers={'Content-Type': 'application/json'},
expect_errors=True
)
self.assertEqual(400, resp.status_int)
def test_return_400_on_put_when_order_is_active(self):
order_uuid = self._create_generic_order_for_put()
# Put the order in a active state to prevent modification
order_model = order_repo.get(order_uuid, self.project_id)
order_model.status = models.States.ACTIVE
order_model.save()
repositories.commit()
resp = self.app.put_json(
'/orders/{0}'.format(order_uuid),
{'type': 'certificate', 'meta': {}},
headers={'Content-Type': 'application/json'},
expect_errors=True
)
self.assertEqual(400, resp.status_int)
class WhenCreatingOrders(utils.BarbicanAPIBaseTestCase):
def test_should_add_new_order(self):
order_meta = {
'name': 'secretname',
'expiration': '2114-02-28T17:14:44.180394',
'algorithm': 'AES',
'bit_length': 256,
'mode': 'cbc',
'payload_content_type': 'application/octet-stream'
}
create_resp, order_uuid = create_order(
self.app,
order_type='key',
meta=order_meta
)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual('key', order.type)
self.assertEqual(order.meta, order_meta)
def test_should_return_400_when_creating_with_empty_json(self):
resp = self.app.post_json('/orders/', {}, expect_errors=True)
self.assertEqual(400, resp.status_int,)
def test_should_return_415_when_creating_with_blank_body(self):
resp = self.app.post('/orders/', '', expect_errors=True)
self.assertEqual(415, resp.status_int)
class WhenCreatingCertificateOrders(utils.BarbicanAPIBaseTestCase):
def setUp(self):
super(WhenCreatingCertificateOrders, self).setUp()
self.certificate_meta = {
'request': 'XXXXXX'
}
# Make sure we have a project
self.project = resources.get_or_create_project(self.project_id)
# Create CA's in the db
self.available_ca_ids = []
for i in range(2):
ca_information = {
'plugin_name': 'plugin_name',
'plugin_ca_id': 'plugin_name ca_id1',
'name': 'plugin name',
'description': 'Master CA for default plugin',
'ca_signing_certificate': 'XXXXX',
'intermediates': 'YYYYY'
}
ca_model = models.CertificateAuthority(ca_information)
ca = ca_repo.create_from(ca_model)
self.available_ca_ids.append(ca.id)
repositories.commit()
def test_can_create_new_cert_order(self):
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=self.certificate_meta
)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
def test_can_add_new_cert_order_with_ca_id(self):
self.certificate_meta['ca_id'] = self.available_ca_ids[0]
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=self.certificate_meta
)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
def test_can_add_new_cert_order_with_ca_id_project_ca_defined(self):
# Create a Project CA and add it
project_ca_model = models.ProjectCertificateAuthority(
self.project.id,
self.available_ca_ids[0]
)
project_ca_repo.create_from(project_ca_model)
repositories.commit()
# Attempt to create an order
self.certificate_meta['ca_id'] = self.available_ca_ids[0]
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=self.certificate_meta
)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
def test_create_w_invalid_ca_id_should_fail(self):
self.certificate_meta['ca_id'] = 'bogus_ca_id'
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=self.certificate_meta,
expect_errors=True
)
self.assertEqual(400, create_resp.status_int)
def test_create_should_fail_when_ca_not_in_defined_project_ca_ids(self):
# Create a Project CA and add it
project_ca_model = models.ProjectCertificateAuthority(
self.project.id,
self.available_ca_ids[0]
)
project_ca_repo.create_from(project_ca_model)
repositories.commit()
# Make sure we set the ca_id to an id not defined in the project
self.certificate_meta['ca_id'] = self.available_ca_ids[1]
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=self.certificate_meta,
expect_errors=True
)
self.assertEqual(403, create_resp.status_int)
class WhenCreatingStoredKeyOrders(utils.BarbicanAPIBaseTestCase,
test_policy.BaseTestCase):
def setUp(self):
super(WhenCreatingStoredKeyOrders, self).setUp()
# Make sure we have a project
self.project = resources.get_or_create_project(self.project_id)
self.creator_user_id = 'creatorUserId'
def test_can_create_new_stored_key_order(self):
container_name = 'rsa container name'
container_type = 'rsa'
secret_refs = []
resp, container_id = create_container(
self.app,
name=container_name,
container_type=container_type,
secret_refs=secret_refs
)
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'https://localhost/v1/containers/' + container_id
}
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=stored_key_meta
)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_uuid, self.project_id)
self.assertIsInstance(order, models.Order)
def _setup_acl_order_context_and_create_order(
self, add_acls=False, read_project_access=True, order_roles=None,
order_user=None, expect_errors=False):
"""Helper method to setup acls, order context and return created order.
Create order uses actual oslo policy enforcer instead of being None.
Create ACLs for container if 'add_acls' is True.
Make container private when 'read_project_access' is False.
"""
container_name = 'rsa container name'
container_type = 'rsa'
secret_refs = []
self.app.extra_environ = {
'barbican.context': self._build_context(self.project_id,
user=self.creator_user_id)
}
_, container_id = create_container(
self.app,
name=container_name,
container_type=container_type,
secret_refs=secret_refs
)
if add_acls:
test_acls.manage_acls(
self.app, 'containers', container_id,
read_user_ids=['u1', 'u3', 'u4'],
read_project_access=read_project_access,
is_update=False)
self.app.extra_environ = {
'barbican.context': self._build_context(
self.project_id, roles=order_roles, user=order_user,
is_admin=False, policy_enforcer=self.policy_enforcer)
}
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'https://localhost/v1/containers/' + container_id
}
return create_order(
self.app,
order_type='certificate',
meta=stored_key_meta,
expect_errors=expect_errors
)
def test_can_create_new_stored_key_order_no_acls_and_policy_check(self):
"""Create stored key order with actual policy enforcement logic.
Order can be created as long as order project and user roles are
allowed in policy. In the test, user requesting order has container
project and has 'creator' role. Order should be created regardless
of what user id is.
"""
create_resp, order_id = self._setup_acl_order_context_and_create_order(
add_acls=False, read_project_access=True, order_roles=['creator'],
order_user='anyUserId', expect_errors=False)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_id, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual('anyUserId', order.creator_id)
def test_should_fail_for_user_observer_role_no_acls_and_policy_check(self):
"""Should not allow create order when user doesn't have necessary role.
Order can be created as long as order project and user roles are
allowed in policy. In the test, user requesting order has container
project but has 'observer' role. Create order should fail as expected
role is 'admin' or 'creator'.
"""
create_resp, _ = self._setup_acl_order_context_and_create_order(
add_acls=False, read_project_access=True, order_roles=['observer'],
order_user='anyUserId', expect_errors=True)
self.assertEqual(403, create_resp.status_int)
def test_can_create_order_with_private_container_and_creator_user(self):
"""Create order using private container with creator user.
Container has been marked private via ACLs. Still creator of container
should be able to create stored key order using that container
successfully.
"""
create_resp, order_id = self._setup_acl_order_context_and_create_order(
add_acls=True, read_project_access=False, order_roles=['creator'],
order_user=self.creator_user_id, expect_errors=False)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_id, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual(self.creator_user_id, order.creator_id)
def test_can_create_order_with_private_container_and_acl_user(self):
"""Create order using private container with acl user.
Container has been marked private via ACLs. So *generally* project user
should not be able to create stored key order using that container.
But here it can create order as that user is defined in read ACL user
list. Here project user means user which has 'creator' role in the
container project. Order project is same as container.
"""
create_resp, order_id = self._setup_acl_order_context_and_create_order(
add_acls=True, read_project_access=False, order_roles=['creator'],
order_user='u3', expect_errors=False)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_id, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual('u3', order.creator_id)
def test_should_raise_with_private_container_and_project_user(self):
"""Create order should fail using private container for project user.
Container has been marked private via ACLs. So project user should not
be able to create stored key order using that container. Here project
user means user which has 'creator' role in the container project.
Order project is same as container. If container was not marked
private, this user would have been able to create order. See next test.
"""
create_resp, _ = self._setup_acl_order_context_and_create_order(
add_acls=True, read_project_access=False, order_roles=['creator'],
order_user='anyProjectUser', expect_errors=True)
self.assertEqual(403, create_resp.status_int)
def test_can_create_order_with_non_private_acls_and_project_user(self):
"""Create order using non-private container with project user.
Container has not been marked private via ACLs. So project user should
be able to create stored key order using that container successfully.
Here project user means user which has 'creator' role in the container
project. Order project is same as container.
"""
create_resp, order_id = self._setup_acl_order_context_and_create_order(
add_acls=True, read_project_access=True, order_roles=['creator'],
order_user='anyProjectUser', expect_errors=False)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_id, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual('anyProjectUser', order.creator_id)
def test_can_create_order_with_non_private_acls_and_creator_user(self):
"""Create order using non-private container with creator user.
Container has not been marked private via ACLs. So user who created
container should be able to create stored key order using that
container successfully. Order project is same as container.
"""
create_resp, order_id = self._setup_acl_order_context_and_create_order(
add_acls=True, read_project_access=True, order_roles=['creator'],
order_user=self.creator_user_id, expect_errors=False)
self.assertEqual(202, create_resp.status_int)
order = order_repo.get(order_id, self.project_id)
self.assertIsInstance(order, models.Order)
self.assertEqual(self.creator_user_id, order.creator_id)
def test_should_raise_with_bad_container_ref(self):
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'bad_ref'
}
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=stored_key_meta,
expect_errors=True
)
self.assertEqual(400, create_resp.status_int)
def test_should_raise_with_container_not_found(self):
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'https://localhost/v1/containers/not_found'
}
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=stored_key_meta,
expect_errors=True
)
self.assertEqual(400, create_resp.status_int)
def test_should_raise_with_container_wrong_type(self):
container_name = 'generic container name'
container_type = 'generic'
secret_refs = []
resp, container_id = create_container(
self.app,
name=container_name,
container_type=container_type,
secret_refs=secret_refs
)
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'https://localhost/v1/containers/' + container_id
}
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=stored_key_meta,
expect_errors=True
)
self.assertEqual(400, create_resp.status_int)
def test_should_raise_with_container_no_access(self):
stored_key_meta = {
'request_type': 'stored-key',
'subject_dn': 'cn=barbican-server,o=example.com',
'container_ref': 'https://localhost/v1/containers/no_access'
}
create_resp, order_uuid = create_order(
self.app,
order_type='certificate',
meta=stored_key_meta,
expect_errors=True
)
self.assertEqual(400, create_resp.status_int)
class WhenPerformingUnallowedOperations(utils.BarbicanAPIBaseTestCase):
def test_should_not_allow_put_orders(self):
resp = self.app.put_json('/orders/', expect_errors=True)
self.assertEqual(405, resp.status_int)
def test_should_not_allow_delete_orders(self):
resp = self.app.delete('/orders/', expect_errors=True)
self.assertEqual(405, resp.status_int)
def test_should_not_allow_post_order_by_id(self):
# Create generic order so we don't get a 404 on POST
resp, order_uuid = create_order(
self.app,
order_type='key',
meta=generic_key_meta
)
self.assertEqual(202, resp.status_int)
resp = self.app.post_json(
'/orders/{0}'.format(order_uuid),
{},
expect_errors=True
)
self.assertEqual(405, resp.status_int)
# ----------------------- Helper Functions ---------------------------
def create_order(app, order_type=None, meta=None, expect_errors=False):
# TODO(jvrbanac): Once test resources is split out, refactor this
# and similar functions into a generalized helper module and reduce
# duplication.
request = {
'type': order_type,
'meta': meta
}
cleaned_request = {key: val for key, val in request.items()
if val is not None}
resp = app.post_json(
'/orders/',
cleaned_request,
expect_errors=expect_errors
)
created_uuid = None
if resp.status_int == 202:
order_ref = resp.json.get('order_ref', '')
_, created_uuid = os.path.split(order_ref)
return (resp, created_uuid)
def create_container(app, name=None, container_type=None, secret_refs=None,
expect_errors=False, headers=None):
request = {
'name': name,
'type': container_type,
'secret_refs': secret_refs if secret_refs else []
}
cleaned_request = {key: val for key, val in request.items()
if val is not None}
resp = app.post_json(
'/containers/',
cleaned_request,
expect_errors=expect_errors,
headers=headers
)
created_uuid = None
if resp.status_int == 201:
container_ref = resp.json.get('container_ref', '')
_, created_uuid = os.path.split(container_ref)
return (resp, created_uuid)
| {
"content_hash": "5af9513710bf6e1df6569a0b26016165",
"timestamp": "",
"source": "github",
"line_count": 762,
"max_line_length": 79,
"avg_line_length": 35.5485564304462,
"alnum_prop": 0.6035883047844064,
"repo_name": "cneill/barbican",
"id": "0ececcaf0b2a8b28d1f2abd4707fa2dfb91c28d0",
"size": "27672",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "barbican/tests/api/controllers/test_orders.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "API Blueprint",
"bytes": "1590"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "1736702"
},
{
"name": "Shell",
"bytes": "15822"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.migrationhubstrategyrecommendations.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum VersionControl {
GITHUB("GITHUB"),
GITHUB_ENTERPRISE("GITHUB_ENTERPRISE");
private String value;
private VersionControl(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return VersionControl corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static VersionControl fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (VersionControl enumEntry : VersionControl.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| {
"content_hash": "ee8646469826cd6b47efa8acdee41a90",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 91,
"avg_line_length": 25.367346938775512,
"alnum_prop": 0.6178600160901045,
"repo_name": "aws/aws-sdk-java",
"id": "065b64d695314e813753445508be307ca35a16a1",
"size": "1823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-migrationhubstrategyrecommendations/src/main/java/com/amazonaws/services/migrationhubstrategyrecommendations/model/VersionControl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { expect, should } from 'chai';
import Icon from '../Icon';
import styles from '../Icon.css';
describe('icon-test-describe----------', () => {
it('icon can render', () => {
const props = {
size:36,
name:'account',
color:'#3a98e0'
}
let app = shallow(
<Icon {...props} />
);
expect(app.find(`.${styles['Icon']}`).length).to.equal(1);
});
});
| {
"content_hash": "3715e47659f41449c76b563c23e92a27",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 62,
"avg_line_length": 21.636363636363637,
"alnum_prop": 0.5399159663865546,
"repo_name": "heifade/quark-ui",
"id": "7f67bb3499ef62637a933417457594cc85afb288",
"size": "476",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/components/icon/test/Icon.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3389704"
},
{
"name": "HTML",
"bytes": "1276"
},
{
"name": "JavaScript",
"bytes": "1358724"
}
],
"symlink_target": ""
} |
package org.apache.camel.example.bam;
/**
* Main class to make it easy to run this example.
*
* @version
*/
public final class Main {
private Main() {
// do nothing here
}
public static void main(String[] args) throws Exception {
org.apache.camel.spring.Main.main(args);
}
} | {
"content_hash": "1e45f637fa3bfa937009104f7d38357d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 61,
"avg_line_length": 17.5,
"alnum_prop": 0.6222222222222222,
"repo_name": "guharoytamajit/apache-camel",
"id": "09b5afbc966146ea1295b22252a982308379f4b8",
"size": "1118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/camel-example-bam/src/main/java/org/apache/camel/example/bam/Main.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "372999"
},
{
"name": "Shell",
"bytes": "4001"
},
{
"name": "XQuery",
"bytes": "937"
}
],
"symlink_target": ""
} |
/*
// Intel(R) Integrated Performance Primitives. Cryptography Primitives.
// Operations over GF(p).
//
// Context:
// ippsGFpSqr()
//
*/
#include "owndefs.h"
#include "owncp.h"
#include "pcpgfpstuff.h"
#include "pcpgfpxstuff.h"
#include "pcphash.h"
#include "pcphash_rmf.h"
#include "pcptool.h"
/*F*
// Name: ippsGFpSqr
//
// Purpose: Square of GF element
//
// Returns: Reason:
// ippStsNullPtrErr NULL == pGFp
// NULL == pA
// NULL == pR
//
// ippStsContextMatchErr invalid pGFp->idCtx
// invalid pA->idCtx
// invalid pR->idCtx
//
// ippStsOutOfRangeErr GFPE_ROOM() != GFP_FELEN()
//
// ippStsNoErr no error
//
// Parameters:
// pA Pointer to the context of the source finite field element.
// pR Pointer to the context of the result finite field element.
// pGFp Pointer to the context of the finite field.
//
*F*/
IPPFUN(IppStatus, ippsGFpSqr,(const IppsGFpElement* pA,
IppsGFpElement* pR, IppsGFpState* pGFp))
{
IPP_BAD_PTR3_RET(pA, pR, pGFp);
IPP_BADARG_RET( !GFP_VALID_ID(pGFp), ippStsContextMatchErr );
IPP_BADARG_RET( !GFPE_VALID_ID(pA), ippStsContextMatchErr );
IPP_BADARG_RET( !GFPE_VALID_ID(pR), ippStsContextMatchErr );
{
gsModEngine* pGFE = GFP_PMA(pGFp);
IPP_BADARG_RET( (GFPE_ROOM(pA)!=GFP_FELEN(pGFE)) || (GFPE_ROOM(pR)!=GFP_FELEN(pGFE)), ippStsOutOfRangeErr);
GFP_METHOD(pGFE)->sqr(GFPE_DATA(pR), GFPE_DATA(pA), pGFE);
return ippStsNoErr;
}
}
| {
"content_hash": "10292b912ca08ea9e06e08be039bf301",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 113,
"avg_line_length": 28.983050847457626,
"alnum_prop": 0.5608187134502924,
"repo_name": "Intel-EPID-SDK/epid-sdk",
"id": "f75a3c3dba94da59cc610e850c359bf895bf7ccf",
"size": "2457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ext/ipp-crypto/sources/ippcp/pcpgfpsqr.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2514793"
},
{
"name": "Batchfile",
"bytes": "1513"
},
{
"name": "C",
"bytes": "12206600"
},
{
"name": "C++",
"bytes": "3886712"
},
{
"name": "CMake",
"bytes": "169664"
},
{
"name": "Makefile",
"bytes": "4525"
},
{
"name": "POV-Ray SDL",
"bytes": "10723"
},
{
"name": "Python",
"bytes": "430736"
},
{
"name": "Shell",
"bytes": "10087"
},
{
"name": "Starlark",
"bytes": "13532"
}
],
"symlink_target": ""
} |
package eu.phisikus.plotka.conf.providers
import eu.phisikus.plotka.conf.model.{BasicNodeConfiguration, BasicPeerConfiguration}
import scala.io.Source
/**
* Contains values matching the example test configuration files
*/
private[providers] object TestConfigurationExamples {
val ConfigurationFile = "test_configuration"
val CustomConfigurationFile = "custom_settings"
lazy val TestCustomConfigurationText: String = Source
.fromResource(CustomConfigurationFile + ".conf")
.getLines
.map(line => line + "\n")
.mkString
val ExpectedPeerConfiguration = List(
BasicPeerConfiguration("node1.network", 2048),
BasicPeerConfiguration("node2.network")
)
val ExpectedConfiguration = BasicNodeConfiguration("node0.network", 2828, "10.0.0.1", ExpectedPeerConfiguration)
}
| {
"content_hash": "19cab748a8cf7406c11a9ce2a2aee34b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 114,
"avg_line_length": 32.2,
"alnum_prop": 0.7664596273291926,
"repo_name": "phisikus/plotka",
"id": "dc1c427b9bafda1252c4a37a25d7de002c84446e",
"size": "805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/src/test/scala/eu/phisikus/plotka/conf/providers/TestConfigurationExamples.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Scala",
"bytes": "82275"
}
],
"symlink_target": ""
} |
(function(win, $){
//singleton
var CircleGeneratorSingleton = (function(){
var instance;
function init(){
//private vars
var _aCircles = [], //keep track of circles
_stageSection = $('.advert'); //stage where circles are placed
//create the circle
function create(left, top){
var circle = $('<div class="circle"></div>');
_position(circle, left, top);
return circle;
}
//position the circle. private function.
function _position(circle, left, top){
circle.css('left',left);
circle.css('top',top);
}
//add the circle
function add(circle){
_stageSection.append(circle);
_aCircles.push(circle);
}
//tests us what index we are in
function index(){
return _aCircles.length;
}
//list all public functions
return {
index:index,
create:create,
add:add
};
}
return {
getInstance: function(){
if (!instance){
instance = init();
}
return instance;
}
};
})();
$(win.document).ready(function(){
//onclick, create a circle, position it and add it to the section.
$('.advert').click(function(e){
//var circle = $('<div class="circle"></div>');
// circle.css('left',e.pageX-25);
// circle.css('top',e.pageY-25);
//$('.advert').append(circle);
//get the singleton instance
var cg = CircleGeneratorSingleton.getInstance();
var circle = cg.create(e.pageX-25, e.pageY-25);//create the circle
cg.add(circle);//add it to the stage
});
//extra logic after the document.ready.
$(document).keypress(function(e){
if(e.key == 'a'){
var cg = CircleGeneratorSingleton.getInstance();
var circle = cg.create(Math.floor(Math.random() * 600),
Math.floor(Math.random() * 600));
cg.add(circle);
}
});
});
})(window, jQuery); | {
"content_hash": "5400ff77566fc2389b657ace8021dd9a",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 78,
"avg_line_length": 29.395061728395063,
"alnum_prop": 0.4607307853842923,
"repo_name": "JeremyChenCodes/JavaScript",
"id": "74b314e1a8b01fcd62259cf99ff8ba0aa552c111",
"size": "2464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Design-patterns/Singleton/js/script.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16977"
},
{
"name": "HTML",
"bytes": "31573"
},
{
"name": "JavaScript",
"bytes": "305013"
}
],
"symlink_target": ""
} |
namespace WavFile;
/// <summary>
/// WAV channel information.
/// </summary>
public struct WavChannel
{
private readonly string _longName;
private readonly string _shortName;
private readonly WavChannelMask _mask;
/// <summary>
/// Gets wav channel long name.
/// </summary>
public string LongName
{
get { return _longName; }
}
/// <summary>
/// Gets wav channel short name.
/// </summary>
public string ShortName
{
get { return _shortName; }
}
/// <summary>
/// Gets wav channel mask.
/// </summary>
public WavChannelMask Mask
{
get { return _mask; }
}
/// <summary>
/// Initializes new instance of the <see cref="WavChannel"/> struct.
/// </summary>
/// <param name="longName">The wav channel long name.</param>
/// <param name="shortName">The wav channel short name.</param>
/// <param name="mask">The wav channel mask.</param>
public WavChannel(string longName, string shortName, WavChannelMask mask)
{
_longName = longName;
_shortName = shortName;
_mask = mask;
}
} | {
"content_hash": "a1a9e6e48b7bb9ec1033341e57da168b",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 77,
"avg_line_length": 23.367346938775512,
"alnum_prop": 0.5895196506550219,
"repo_name": "wieslawsoltes/SimpleWavSplitter",
"id": "87217225aeb4b283702e7f0c84d7c7e7cd4884f4",
"size": "1147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/WavFile/WavChannel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "207"
},
{
"name": "C#",
"bytes": "42685"
},
{
"name": "CSS",
"bytes": "2369"
},
{
"name": "HTML",
"bytes": "3084"
},
{
"name": "JavaScript",
"bytes": "3"
},
{
"name": "PowerShell",
"bytes": "2964"
},
{
"name": "Shell",
"bytes": "2286"
}
],
"symlink_target": ""
} |
*, *::before, *::after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
height: 100%; /* makes sure HTML takes up all of browser window */
font-size: 100%;
}
body {
background-image: url(../assets/images/blurred_backgrounds/blur_bg_3.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center center;
background-size: cover;
font-family: 'Open Sans'; /* sets font to "Open Sans" */
color: white; /* sets text color white */
min-height: 100%; /* height of body must be min 100% */
padding-bottom: 200px;
}
.navbar {
position: relative;
padding: 0.5rem;
background-color: rgba(101,18,95,0.5);
z-index: 1;
}
.navbar .logo {
position: relative;
left: 2rem;
cursor: pointer;
}
.navbar .links-container {
display: table;
position: absolute;
top: 0;
right: 0;
height: 100px;
color: white;
text-decoration: none;
}
.links-container .navbar-link {
display: table-cell;
position: relative;
height: 100%;
padding-left: 1rem;
padding-right: 1rem;
vertical-align: middle;
color: white;
font-size: 0.625rem;
letter-spacing: 0.05rem;
font-weight: 700;
text-transform: uppercase;
text-decoration: none;
cursor: pointer;
}
.links-container .navbar-link:hover {
color: rgb(233,50,117);
}
.links-container .navbar-link:active {
color: rgb(233,50,117);
background-color: white;
}
.container {
margin: 0 auto;
max-width: 64rem;
}
.container.narrow {
max-width: 56rem;
}
/*Medium and small screens (640px) */
@media (min-width: 640px) {
html {font-size: 112%; }
.column {
float: left;
padding-left: 1rem;
padding-right: 1rem;
}
.column-full { width: 100%; }
.column.two-thirds { width: 66.7%; }
.column.half { width: 50%; }
.column.third { width: 33.3%; }
.column.fourth { width: 25%; }
.column.flow-opposite { float: right; }
}
/* Large screens (1024px) */
@media (min-width: 1024px) {
html { font-size: 120%; }
}
.clearfix::before,
.clearfix::after {
content: " ";
display: table;
}
.clearfix::after {
clear: both;
} | {
"content_hash": "98a9b96935f7a3aa4ea6965fa4471852",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 78,
"avg_line_length": 19.52991452991453,
"alnum_prop": 0.600875273522976,
"repo_name": "thomaslawton91/bloc-jams-angular",
"id": "73556025d6c12dfb67af7ff371da6f0a4b754762",
"size": "2285",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/styles/main.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9306"
},
{
"name": "HTML",
"bytes": "6952"
},
{
"name": "JavaScript",
"bytes": "17230"
}
],
"symlink_target": ""
} |
TODO: Write a gem description
## Installation
Add this line to your application's Gemfile:
gem 'phire'
And then execute:
$ bundle
Or install it yourself as:
$ gem install phire
## Usage
TODO: Write usage instructions here
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {
"content_hash": "45df4ddc6866b46ab041716f5ddf796f",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 64,
"avg_line_length": 17.85185185185185,
"alnum_prop": 0.7116182572614108,
"repo_name": "jschank/phire",
"id": "405f4883c6d4b092e780363a62dec1f067d732cf",
"size": "491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7821"
}
],
"symlink_target": ""
} |
using namespace std;
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
//
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(200,0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong DraftCoin will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
| {
"content_hash": "813063f8fc72d2d1e64957676b27ab36",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 172,
"avg_line_length": 33.71875,
"alnum_prop": 0.5903614457831325,
"repo_name": "btcdraft/draftcoin",
"id": "512fde6185c97f76ecdb21402548201dc79748c2",
"size": "3563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/timedata.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "32908"
},
{
"name": "C++",
"bytes": "13677801"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Dockerfile",
"bytes": "793"
},
{
"name": "HTML",
"bytes": "50620"
},
{
"name": "Makefile",
"bytes": "169794"
},
{
"name": "NSIS",
"bytes": "5930"
},
{
"name": "Objective-C",
"bytes": "1439"
},
{
"name": "Objective-C++",
"bytes": "3517"
},
{
"name": "Python",
"bytes": "54359"
},
{
"name": "QMake",
"bytes": "15382"
},
{
"name": "Roff",
"bytes": "12730"
},
{
"name": "Shell",
"bytes": "13176"
}
],
"symlink_target": ""
} |
module.exports = require('./lib/slag')
| {
"content_hash": "2b7581ffed800ed07adb2d4147b535c9",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 38,
"avg_line_length": 39,
"alnum_prop": 0.6923076923076923,
"repo_name": "stagas/slag",
"id": "bdef5d51c8e400463e55f36d1652355bbcfd22df",
"size": "39",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10575"
}
],
"symlink_target": ""
} |
package com.wnafee.vector.compat;
import android.graphics.Path;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
public class PathParser {
static final String LOGTAG = PathParser.class.getSimpleName();
/**
* @param pathData The string representing a path, the same as "d" string in svg file.
* @return the generated Path object.
*/
public static Path createPathFromPathData(String pathData) {
Path path = new Path();
PathDataNode[] nodes = createNodesFromPathData(pathData);
if (nodes != null) {
PathDataNode.nodesToPath(nodes, path);
return path;
}
return null;
}
/**
* @param pathData The string representing a path, the same as "d" string in svg file.
* @return an array of the PathDataNode.
*/
public static PathDataNode[] createNodesFromPathData(String pathData) {
if (pathData == null) {
return null;
}
int start = 0;
int end = 1;
ArrayList<PathDataNode> list = new ArrayList<PathDataNode>();
while (end < pathData.length()) {
end = nextStart(pathData, end);
String s = pathData.substring(start, end).trim();
if (s.length() > 0) {
float[] val = getFloats(s);
addNode(list, s.charAt(0), val);
}
start = end;
end++;
}
if ((end - start) == 1 && start < pathData.length()) {
addNode(list, pathData.charAt(start), new float[0]);
}
return list.toArray(new PathDataNode[list.size()]);
}
/**
* @param source The array of PathDataNode to be duplicated.
* @return a deep copy of the <code>source</code>.
*/
public static PathDataNode[] deepCopyNodes(PathDataNode[] source) {
if (source == null) {
return null;
}
PathDataNode[] copy = new PathDataNode[source.length];
for (int i = 0; i < source.length; i ++) {
copy[i] = new PathDataNode(source[i]);
}
return copy;
}
/**
* @param nodesFrom The source path represented in an array of PathDataNode
* @param nodesTo The target path represented in an array of PathDataNode
* @return whether the <code>nodesFrom</code> can morph into <code>nodesTo</code>
*/
public static boolean canMorph(PathDataNode[] nodesFrom, PathDataNode[] nodesTo) {
if (nodesFrom == null || nodesTo == null) {
return false;
}
if (nodesFrom.length != nodesTo.length) {
return false;
}
for (int i = 0; i < nodesFrom.length; i ++) {
if (nodesFrom[i].mType != nodesTo[i].mType
|| nodesFrom[i].mParams.length != nodesTo[i].mParams.length) {
return false;
}
}
return true;
}
/**
* Update the target's data to match the source.
* Before calling this, make sure canMorph(target, source) is true.
*
* @param target The target path represented in an array of PathDataNode
* @param source The source path represented in an array of PathDataNode
*/
public static void updateNodes(PathDataNode[] target, PathDataNode[] source) {
for (int i = 0; i < source.length; i ++) {
target[i].mType = source[i].mType;
for (int j = 0; j < source[i].mParams.length; j ++) {
target[i].mParams[j] = source[i].mParams[j];
}
}
}
private static int nextStart(String s, int end) {
char c;
while (end < s.length()) {
c = s.charAt(end);
if (((c - 'A') * (c - 'Z') <= 0) || (((c - 'a') * (c - 'z') <= 0))) {
return end;
}
end++;
}
return end;
}
private static void addNode(ArrayList<PathDataNode> list, char cmd, float[] val) {
list.add(new PathDataNode(cmd, val));
}
private static class ExtractFloatResult {
// We need to return the position of the next separator and whether the
// next float starts with a '-'.
int mEndPosition;
boolean mEndWithNegSign;
}
/**
* Parse the floats in the string.
* This is an optimized version of parseFloat(s.split(",|\\s"));
*
* @param s the string containing a command and list of floats
* @return array of floats
*/
private static float[] getFloats(String s) {
if (s.charAt(0) == 'z' | s.charAt(0) == 'Z') {
return new float[0];
}
try {
float[] results = new float[s.length()];
int count = 0;
int startPosition = 1;
int endPosition = 0;
ExtractFloatResult result = new ExtractFloatResult();
int totalLength = s.length();
// The startPosition should always be the first character of the
// current number, and endPosition is the character after the current
// number.
while (startPosition < totalLength) {
extract(s, startPosition, result);
endPosition = result.mEndPosition;
if (startPosition < endPosition) {
results[count++] = Float.parseFloat(
s.substring(startPosition, endPosition));
}
if (result.mEndWithNegSign) {
// Keep the '-' sign with next number.
startPosition = endPosition;
} else {
startPosition = endPosition + 1;
}
}
return Arrays.copyOf(results, count);
} catch (NumberFormatException e) {
Log.e(LOGTAG, "error in parsing \"" + s + "\"");
throw e;
}
}
/**
* Calculate the position of the next comma or space or negative sign
* @param s the string to search
* @param start the position to start searching
* @param result the result of the extraction, including the position of the
* the starting position of next number, whether it is ending with a '-'.
*/
private static void extract(String s, int start, ExtractFloatResult result) {
// Now looking for ' ', ',' or '-' from the start.
int currentIndex = start;
boolean foundSeparator = false;
result.mEndWithNegSign = false;
for (; currentIndex < s.length(); currentIndex++) {
char currentChar = s.charAt(currentIndex);
switch (currentChar) {
case ' ':
case ',':
foundSeparator = true;
break;
case '-':
if (currentIndex != start) {
foundSeparator = true;
result.mEndWithNegSign = true;
}
break;
}
if (foundSeparator) {
break;
}
}
// When there is nothing found, then we put the end position to the end
// of the string.
result.mEndPosition = currentIndex;
}
/**
* Each PathDataNode represents one command in the "d" attribute of the svg
* file.
* An array of PathDataNode can represent the whole "d" attribute.
*/
public static class PathDataNode {
private char mType;
private float[] mParams;
private PathDataNode(char type, float[] params) {
mType = type;
mParams = params;
}
private PathDataNode(PathDataNode n) {
mType = n.mType;
mParams = Arrays.copyOf(n.mParams, n.mParams.length);
}
/**
* Convert an array of PathDataNode to Path.
*
* @param node The source array of PathDataNode.
* @param path The target Path object.
*/
public static void nodesToPath(PathDataNode[] node, Path path) {
float[] current = new float[4];
char previousCommand = 'm';
for (int i = 0; i < node.length; i++) {
addCommand(path, current, previousCommand, node[i].mType, node[i].mParams);
previousCommand = node[i].mType;
}
}
/**
* The current PathDataNode will be interpolated between the
* <code>nodeFrom</code> and <code>nodeTo</code> according to the
* <code>fraction</code>.
*
* @param nodeFrom The start value as a PathDataNode.
* @param nodeTo The end value as a PathDataNode
* @param fraction The fraction to interpolate.
*/
public void interpolatePathDataNode(PathDataNode nodeFrom,
PathDataNode nodeTo, float fraction) {
for (int i = 0; i < nodeFrom.mParams.length; i++) {
mParams[i] = nodeFrom.mParams[i] * (1 - fraction)
+ nodeTo.mParams[i] * fraction;
}
}
private static void addCommand(Path path, float[] current,
char previousCmd, char cmd, float[] val) {
int incr = 2;
float currentX = current[0];
float currentY = current[1];
float ctrlPointX = current[2];
float ctrlPointY = current[3];
float reflectiveCtrlPointX;
float reflectiveCtrlPointY;
switch (cmd) {
case 'z':
case 'Z':
path.close();
return;
case 'm':
case 'M':
case 'l':
case 'L':
case 't':
case 'T':
incr = 2;
break;
case 'h':
case 'H':
case 'v':
case 'V':
incr = 1;
break;
case 'c':
case 'C':
incr = 6;
break;
case 's':
case 'S':
case 'q':
case 'Q':
incr = 4;
break;
case 'a':
case 'A':
incr = 7;
break;
}
for (int k = 0; k < val.length; k += incr) {
switch (cmd) {
case 'm': // moveto - Start a new sub-path (relative)
path.rMoveTo(val[k + 0], val[k + 1]);
currentX += val[k + 0];
currentY += val[k + 1];
break;
case 'M': // moveto - Start a new sub-path
path.moveTo(val[k + 0], val[k + 1]);
currentX = val[k + 0];
currentY = val[k + 1];
break;
case 'l': // lineto - Draw a line from the current point (relative)
path.rLineTo(val[k + 0], val[k + 1]);
currentX += val[k + 0];
currentY += val[k + 1];
break;
case 'L': // lineto - Draw a line from the current point
path.lineTo(val[k + 0], val[k + 1]);
currentX = val[k + 0];
currentY = val[k + 1];
break;
case 'z': // closepath - Close the current subpath
case 'Z': // closepath - Close the current subpath
path.close();
break;
case 'h': // horizontal lineto - Draws a horizontal line (relative)
path.rLineTo(val[k + 0], 0);
currentX += val[k + 0];
break;
case 'H': // horizontal lineto - Draws a horizontal line
path.lineTo(val[k + 0], currentY);
currentX = val[k + 0];
break;
case 'v': // vertical lineto - Draws a vertical line from the current point (r)
path.rLineTo(0, val[k + 0]);
currentY += val[k + 0];
break;
case 'V': // vertical lineto - Draws a vertical line from the current point
path.lineTo(currentX, val[k + 0]);
currentY = val[k + 0];
break;
case 'c': // curveto - Draws a cubic Bézier curve (relative)
path.rCubicTo(val[k + 0], val[k + 1], val[k + 2], val[k + 3],
val[k + 4], val[k + 5]);
ctrlPointX = currentX + val[k + 2];
ctrlPointY = currentY + val[k + 3];
currentX += val[k + 4];
currentY += val[k + 5];
break;
case 'C': // curveto - Draws a cubic Bézier curve
path.cubicTo(val[k + 0], val[k + 1], val[k + 2], val[k + 3],
val[k + 4], val[k + 5]);
currentX = val[k + 4];
currentY = val[k + 5];
ctrlPointX = val[k + 2];
ctrlPointY = val[k + 3];
break;
case 's': // smooth curveto - Draws a cubic Bézier curve (reflective cp)
reflectiveCtrlPointX = 0;
reflectiveCtrlPointY = 0;
if (previousCmd == 'c' || previousCmd == 's'
|| previousCmd == 'C' || previousCmd == 'S') {
reflectiveCtrlPointX = currentX - ctrlPointX;
reflectiveCtrlPointY = currentY - ctrlPointY;
}
path.rCubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY,
val[k + 0], val[k + 1],
val[k + 2], val[k + 3]);
ctrlPointX = currentX + val[k + 0];
ctrlPointY = currentY + val[k + 1];
currentX += val[k + 2];
currentY += val[k + 3];
break;
case 'S': // shorthand/smooth curveto Draws a cubic Bézier curve(reflective cp)
reflectiveCtrlPointX = currentX;
reflectiveCtrlPointY = currentY;
if (previousCmd == 'c' || previousCmd == 's'
|| previousCmd == 'C' || previousCmd == 'S') {
reflectiveCtrlPointX = 2 * currentX - ctrlPointX;
reflectiveCtrlPointY = 2 * currentY - ctrlPointY;
}
path.cubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY,
val[k + 0], val[k + 1], val[k + 2], val[k + 3]);
ctrlPointX = val[k + 0];
ctrlPointY = val[k + 1];
currentX = val[k + 2];
currentY = val[k + 3];
break;
case 'q': // Draws a quadratic Bézier (relative)
path.rQuadTo(val[k + 0], val[k + 1], val[k + 2], val[k + 3]);
ctrlPointX = currentX + val[k + 0];
ctrlPointY = currentY + val[k + 1];
currentX += val[k + 2];
currentY += val[k + 3];
break;
case 'Q': // Draws a quadratic Bézier
path.quadTo(val[k + 0], val[k + 1], val[k + 2], val[k + 3]);
ctrlPointX = val[k + 0];
ctrlPointY = val[k + 1];
currentX = val[k + 2];
currentY = val[k + 3];
break;
case 't': // Draws a quadratic Bézier curve(reflective control point)(relative)
reflectiveCtrlPointX = 0;
reflectiveCtrlPointY = 0;
if (previousCmd == 'q' || previousCmd == 't'
|| previousCmd == 'Q' || previousCmd == 'T') {
reflectiveCtrlPointX = currentX - ctrlPointX;
reflectiveCtrlPointY = currentY - ctrlPointY;
}
path.rQuadTo(reflectiveCtrlPointX, reflectiveCtrlPointY,
val[k + 0], val[k + 1]);
ctrlPointX = currentX + reflectiveCtrlPointX;
ctrlPointY = currentY + reflectiveCtrlPointY;
currentX += val[k + 0];
currentY += val[k + 1];
break;
case 'T': // Draws a quadratic Bézier curve (reflective control point)
reflectiveCtrlPointX = currentX;
reflectiveCtrlPointY = currentY;
if (previousCmd == 'q' || previousCmd == 't'
|| previousCmd == 'Q' || previousCmd == 'T') {
reflectiveCtrlPointX = 2 * currentX - ctrlPointX;
reflectiveCtrlPointY = 2 * currentY - ctrlPointY;
}
path.quadTo(reflectiveCtrlPointX, reflectiveCtrlPointY,
val[k + 0], val[k + 1]);
ctrlPointX = reflectiveCtrlPointX;
ctrlPointY = reflectiveCtrlPointY;
currentX = val[k + 0];
currentY = val[k + 1];
break;
case 'a': // Draws an elliptical arc
// (rx ry x-axis-rotation large-arc-flag sweep-flag x y)
drawArc(path,
currentX,
currentY,
val[k + 5] + currentX,
val[k + 6] + currentY,
val[k + 0],
val[k + 1],
val[k + 2],
val[k + 3] != 0,
val[k + 4] != 0);
currentX += val[k + 5];
currentY += val[k + 6];
ctrlPointX = currentX;
ctrlPointY = currentY;
break;
case 'A': // Draws an elliptical arc
drawArc(path,
currentX,
currentY,
val[k + 5],
val[k + 6],
val[k + 0],
val[k + 1],
val[k + 2],
val[k + 3] != 0,
val[k + 4] != 0);
currentX = val[k + 5];
currentY = val[k + 6];
ctrlPointX = currentX;
ctrlPointY = currentY;
break;
}
previousCmd = cmd;
}
current[0] = currentX;
current[1] = currentY;
current[2] = ctrlPointX;
current[3] = ctrlPointY;
}
private static void drawArc(Path p,
float x0,
float y0,
float x1,
float y1,
float a,
float b,
float theta,
boolean isMoreThanHalf,
boolean isPositiveArc) {
/* Convert rotation angle from degrees to radians */
double thetaD = Math.toRadians(theta);
/* Pre-compute rotation matrix entries */
double cosTheta = Math.cos(thetaD);
double sinTheta = Math.sin(thetaD);
/* Transform (x0, y0) and (x1, y1) into unit space */
/* using (inverse) rotation, followed by (inverse) scale */
double x0p = (x0 * cosTheta + y0 * sinTheta) / a;
double y0p = (-x0 * sinTheta + y0 * cosTheta) / b;
double x1p = (x1 * cosTheta + y1 * sinTheta) / a;
double y1p = (-x1 * sinTheta + y1 * cosTheta) / b;
/* Compute differences and averages */
double dx = x0p - x1p;
double dy = y0p - y1p;
double xm = (x0p + x1p) / 2;
double ym = (y0p + y1p) / 2;
/* Solve for intersecting unit circles */
double dsq = dx * dx + dy * dy;
if (dsq == 0.0) {
Log.w(LOGTAG, " Points are coincident");
return; /* Points are coincident */
}
double disc = 1.0 / dsq - 1.0 / 4.0;
if (disc < 0.0) {
Log.w(LOGTAG, "Points are too far apart " + dsq);
float adjust = (float) (Math.sqrt(dsq) / 1.99999);
drawArc(p, x0, y0, x1, y1, a * adjust,
b * adjust, theta, isMoreThanHalf, isPositiveArc);
return; /* Points are too far apart */
}
double s = Math.sqrt(disc);
double sdx = s * dx;
double sdy = s * dy;
double cx;
double cy;
if (isMoreThanHalf == isPositiveArc) {
cx = xm - sdy;
cy = ym + sdx;
} else {
cx = xm + sdy;
cy = ym - sdx;
}
double eta0 = Math.atan2((y0p - cy), (x0p - cx));
double eta1 = Math.atan2((y1p - cy), (x1p - cx));
double sweep = (eta1 - eta0);
if (isPositiveArc != (sweep >= 0)) {
if (sweep > 0) {
sweep -= 2 * Math.PI;
} else {
sweep += 2 * Math.PI;
}
}
cx *= a;
cy *= b;
double tcx = cx;
cx = cx * cosTheta - cy * sinTheta;
cy = tcx * sinTheta + cy * cosTheta;
arcToBezier(p, cx, cy, a, b, x0, y0, thetaD, eta0, sweep);
}
/**
* Converts an arc to cubic Bezier segments and records them in p.
*
* @param p The target for the cubic Bezier segments
* @param cx The x coordinate center of the ellipse
* @param cy The y coordinate center of the ellipse
* @param a The radius of the ellipse in the horizontal direction
* @param b The radius of the ellipse in the vertical direction
* @param e1x E(eta1) x coordinate of the starting point of the arc
* @param e1y E(eta2) y coordinate of the starting point of the arc
* @param theta The angle that the ellipse bounding rectangle makes with horizontal plane
* @param start The start angle of the arc on the ellipse
* @param sweep The angle (positive or negative) of the sweep of the arc on the ellipse
*/
private static void arcToBezier(Path p,
double cx,
double cy,
double a,
double b,
double e1x,
double e1y,
double theta,
double start,
double sweep) {
// Taken from equations at: http://spaceroots.org/documents/ellipse/node8.html
// and http://www.spaceroots.org/documents/ellipse/node22.html
// Maximum of 45 degrees per cubic Bezier segment
int numSegments = Math.abs((int) Math.ceil(sweep * 4 / Math.PI));
double eta1 = start;
double cosTheta = Math.cos(theta);
double sinTheta = Math.sin(theta);
double cosEta1 = Math.cos(eta1);
double sinEta1 = Math.sin(eta1);
double ep1x = (-a * cosTheta * sinEta1) - (b * sinTheta * cosEta1);
double ep1y = (-a * sinTheta * sinEta1) + (b * cosTheta * cosEta1);
double anglePerSegment = sweep / numSegments;
for (int i = 0; i < numSegments; i++) {
double eta2 = eta1 + anglePerSegment;
double sinEta2 = Math.sin(eta2);
double cosEta2 = Math.cos(eta2);
double e2x = cx + (a * cosTheta * cosEta2) - (b * sinTheta * sinEta2);
double e2y = cy + (a * sinTheta * cosEta2) + (b * cosTheta * sinEta2);
double ep2x = -a * cosTheta * sinEta2 - b * sinTheta * cosEta2;
double ep2y = -a * sinTheta * sinEta2 + b * cosTheta * cosEta2;
double tanDiff2 = Math.tan((eta2 - eta1) / 2);
double alpha =
Math.sin(eta2 - eta1) * (Math.sqrt(4 + (3 * tanDiff2 * tanDiff2)) - 1) / 3;
double q1x = e1x + alpha * ep1x;
double q1y = e1y + alpha * ep1y;
double q2x = e2x - alpha * ep2x;
double q2y = e2y - alpha * ep2y;
p.cubicTo((float) q1x,
(float) q1y,
(float) q2x,
(float) q2y,
(float) e2x,
(float) e2y);
eta1 = eta2;
e1x = e2x;
e1y = e2y;
ep1x = ep2x;
ep1y = ep2y;
}
}
}
}
| {
"content_hash": "12e099696291723e39d01b6ac83af519",
"timestamp": "",
"source": "github",
"line_count": 638,
"max_line_length": 99,
"avg_line_length": 41.24921630094044,
"alnum_prop": 0.43621993388304137,
"repo_name": "zhongchin/zhiyou",
"id": "14b8a9f9bf940d4763d5395f3da0fa7b1aa283be",
"size": "26944",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vectorcompat/src/main/java/com/wnafee/vector/compat/PathParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "387358"
}
],
"symlink_target": ""
} |
package ru.stqa.pft.addressbook.rf;
import org.openqa.selenium.remote.BrowserType;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;
import ru.stqa.pft.addressbook.model.GroupData;
import java.io.IOException;
/**
* Created by SK on 16.06.2016.
*/
public class AddressbookKeywords {
public static final String ROBOT_LIBRARY_SCOPE="GLOBAL";
private ApplicationManager app;
public void initApplicationManager () throws IOException {
app = new ApplicationManager(System.getProperty("browser", BrowserType.CHROME));
app.init();
}
public void stopApplicationManager () {
app.stop();
app = null;
}
public int getGroupCount () {
app.goTo().groupPage();
return app.group().count();
}
public void createGroup (String name, String header, String footer) {
app.goTo().groupPage();
app.group().create(new GroupData().withName(name).withHeader(header).withFooter(footer));
}
}
| {
"content_hash": "cb20de83d7c20b252730f0c25115cb4d",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 93,
"avg_line_length": 25.44736842105263,
"alnum_prop": 0.6990692864529473,
"repo_name": "SergeyKharkovshchenko/java_pft",
"id": "4e2ad5c9b623a7b969d053e69e1c2220279fb524",
"size": "967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/rf/AddressbookKeywords.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12449"
}
],
"symlink_target": ""
} |
/**
* The DataSource utility provides a common configurable interface for widgets
* to access a variety of data, from JavaScript arrays to online servers over
* XHR.
*
* @module datasource
* @requires yahoo, event
* @optional xhr
* @title DataSource Utility
* @beta
*/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The DataSource class defines and manages a live set of data for widgets to
* interact with. Examples of live databases include in-memory
* local data such as a JavaScript array, a JavaScript function, or JSON, or
* remote data such as data retrieved through an XHR connection.
*
* @class DataSource
* @uses YAHOO.util.EventProvider
* @constructor
* @param oLiveData {Object} Pointer to live database
* @param oConfigs {Object} (optional) Object literal of configuration values
*/
YAHOO.util.DataSource = function(oLiveData, oConfigs) {
// Set any config params passed in to override defaults
if(oConfigs && (oConfigs.constructor == Object)) {
for(var sConfig in oConfigs) {
if(sConfig) {
this[sConfig] = oConfigs[sConfig];
}
}
}
if(!oLiveData) {
YAHOO.log("Could not instantiate DataSource due to invalid live database.","error",this.toString());
return;
}
if(YAHOO.lang.isArray(oLiveData)) {
this.dataType = YAHOO.util.DataSource.TYPE_JSARRAY;
}
else if(YAHOO.lang.isString(oLiveData)) {
this.dataType = YAHOO.util.DataSource.TYPE_XHR;
}
else if(YAHOO.lang.isFunction(oLiveData)) {
this.dataType = YAHOO.util.DataSource.TYPE_JSFUNCTION;
}
else if(YAHOO.lang.isObject(oLiveData)) {
this.dataType = YAHOO.util.DataSource.TYPE_JSON;
}
else {
this.dataType = YAHOO.util.DataSource.TYPE_UNKNOWN;
}
this.liveData = oLiveData;
//totalRecords
this.totalRecords = 0;
// Validate and initialize public configs
var maxCacheEntries = this.maxCacheEntries;
if(!YAHOO.lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
maxCacheEntries = 0;
}
// Initialize local cache
if(maxCacheEntries > 0 && !this._aCache) {
this._aCache = [];
YAHOO.log("Cache initialized","info",this.toString());
}
this._sName = "instance" + YAHOO.util.DataSource._nIndex;
YAHOO.util.DataSource._nIndex++;
YAHOO.log("DataSource initialized", "info", this.toString());
/////////////////////////////////////////////////////////////////////////////
//
// Custom Events
//
/////////////////////////////////////////////////////////////////////////////
/**
* Fired when a request is made to the local cache.
*
* @event cacheRequestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("cacheRequestEvent");
/**
* Fired when data is retrieved from the local cache.
*
* @event getCachedResponseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("cacheResponseEvent");
/**
* Fired when a request is sent to the live data source.
*
* @event requestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("requestEvent");
/**
* Fired when live data source sends response.
*
* @event responseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The raw response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseEvent");
/**
* Fired when response is parsed.
*
* @event responseParseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseParseEvent");
/**
* Fired when response is cached.
*
* @event responseCacheEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseCacheEvent");
/**
* Fired when an error is encountered with the live data source.
*
* @event dataErrorEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
* @param oArgs.message {String} The error message.
*/
this.createEvent("dataErrorEvent");
/**
* Fired when the local cache is flushed.
*
* @event cacheFlushEvent
*/
this.createEvent("cacheFlushEvent");
};
YAHOO.augment(YAHOO.util.DataSource, YAHOO.util.EventProvider);
/////////////////////////////////////////////////////////////////////////////
//
// Public constants
//
/////////////////////////////////////////////////////////////////////////////
/**
* Type is unknown.
*
* @property TYPE_UNKNOWN
* @type Number
* @final
* @default -1
*/
YAHOO.util.DataSource.TYPE_UNKNOWN = -1;
/**
* Type is a JavaScript Array.
*
* @property TYPE_JSARRAY
* @type Number
* @final
* @default 0
*/
YAHOO.util.DataSource.TYPE_JSARRAY = 0;
/**
* Type is a JavaScript Function.
*
* @property TYPE_JSFUNCTION
* @type Number
* @final
* @default 1
*/
YAHOO.util.DataSource.TYPE_JSFUNCTION = 1;
/**
* Type is hosted on a server via an XHR connection.
*
* @property TYPE_XHR
* @type Number
* @final
* @default 2
*/
YAHOO.util.DataSource.TYPE_XHR = 2;
/**
* Type is JSON.
*
* @property TYPE_JSON
* @type Number
* @final
* @default 3
*/
YAHOO.util.DataSource.TYPE_JSON = 3;
/**
* Type is XML.
*
* @property TYPE_XML
* @type Number
* @final
* @default 4
*/
YAHOO.util.DataSource.TYPE_XML = 4;
/**
* Type is plain text.
*
* @property TYPE_TEXT
* @type Number
* @final
* @default 5
*/
YAHOO.util.DataSource.TYPE_TEXT = 5;
/**
* Error message for invalid data responses.
*
* @property ERROR_DATAINVALID
* @type String
* @final
* @default "Invalid data"
*/
YAHOO.util.DataSource.ERROR_DATAINVALID = "Invalid data";
/**
* Error message for null data responses.
*
* @property ERROR_DATANULL
* @type String
* @final
* @default "Null data"
*/
YAHOO.util.DataSource.ERROR_DATANULL = "Null data";
/////////////////////////////////////////////////////////////////////////////
//
// Private member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Internal class variable to index multiple DataSource instances.
*
* @property _nIndex
* @type Number
* @private
*/
YAHOO.util.DataSource._nIndex = 0;
/**
* Name of DataSource instance.
*
* @property _sName
* @type String
* @private
*/
YAHOO.util.DataSource.prototype._sName = null;
/**
* Local cache of data result objects indexed chronologically.
*
* @property _aCache
* @type Object[]
* @private
*/
YAHOO.util.DataSource.prototype._aCache = null;
/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
// Public member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Max size of the local cache. Set to 0 to turn off caching. Caching is
* useful to reduce the number of server connections. Recommended only for data
* sources that return comprehensive results for queries or when stale data is
* not an issue.
*
* @property maxCacheEntries
* @type Number
* @default 0
*/
YAHOO.util.DataSource.prototype.maxCacheEntries = 0;
/**
* Pointer to live database.
*
* @property liveData
* @type Object
*/
YAHOO.util.DataSource.prototype.liveData = null;
/**
* If data is accessed over XHR via Connection Manager, the connection timeout is
* configurable in milliseconds the XHR connection will wait for a server
* response. A a value of zero indicates the XHR connection will wait forever.
* Any value greater than zero will use the Connection utility's Auto-Abort
* feature.
*
* @property connTimeout
* @type Number
* @default 0
*/
YAHOO.util.DataSource.prototype.connTimeout = null;
/**
* Alias to YUI Connection Manager. Allows implementers to specify their own
* subclasses of the YUI Connection Manager utility.
*
* @property connMgr
* @type Object
* @default YAHOO.util.Connect
*/
YAHOO.util.DataSource.prototype.connMgr = YAHOO.util.Connect || null;
/**
* Where the live data is held.
*
* @property dataType
* @type Number
* @default YAHOO.util.DataSource.TYPE_UNKNOWN
*
*/
YAHOO.util.DataSource.prototype.dataType = YAHOO.util.DataSource.TYPE_UNKNOWN;
/**
* Format of response.
*
* @property responseType
* @type Number
* @default YAHOO.util.DataSource.TYPE_UNKNOWN
*/
YAHOO.util.DataSource.prototype.responseType = YAHOO.util.DataSource.TYPE_UNKNOWN;
/**
* Response schema object literal takes a combination of the following properties:
*
* <dl>
* <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
* <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
* <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
* <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
* <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
* such as: {key:"fieldname",converter:YAHOO.util.DataSource.convertDate}</dd>
* </dl>
*
* @property responseSchema
* @type Object
*/
YAHOO.util.DataSource.prototype.responseSchema = null;
/////////////////////////////////////////////////////////////////////////////
//
// Public static methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Converts data from String to Number objects.
*
* @method convertNumber
* @method sData {String} Number string.
* @return {Number} Number object.
* @static
*/
YAHOO.util.DataSource.convertNumber = function(sData) {
return sData * 1;
};
/**
* Converts data from String to Date objects.
*
* @method convertDate
* @method sData {String} Date string.
* @return {Date} Date object.
* @static
*/
YAHOO.util.DataSource.convertDate = function(sData) {
var mm = sMarkup.substring(0,sMarkup.indexOf("/"));
sMarkup = sMarkup.substring(sMarkup.indexOf("/")+1);
var dd = sMarkup.substring(0,sMarkup.indexOf("/"));
var yy = sMarkup.substring(sMarkup.indexOf("/")+1);
return new Date(yy, mm, dd);
};
/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Public accessor to the unique name of the DataSource instance.
*
* @method toString
* @return {String} Unique name of the DataSource instance.
*/
YAHOO.util.DataSource.prototype.toString = function() {
return "DataSource " + this._sName;
};
/**
* Overridable method passes request to cache and returns cached response if any,
* refreshing the hit in the cache as the newest item. Returns null if there is
* no cache hit.
*
* @method getCachedResponse
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response
* @param oCaller {Object} The Calling object that is making the request
* @return {Object} Cached response object or null.
*/
YAHOO.util.DataSource.prototype.getCachedResponse = function(oRequest, oCallback, oCaller) {
var aCache = this._aCache;
var nCacheLength = (aCache) ? aCache.length : 0;
var oResponse = null;
// If cache is enabled...
if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) {
this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
// Loop through each cached element
for(var i = nCacheLength-1; i >= 0; i--) {
var oCacheElem = aCache[i];
// Defer cache hit logic to a public overridable method
if(this.isCacheHit(oRequest,oCacheElem.request)) {
// Grab the cached response
oResponse = oCacheElem.response;
// The cache returned a hit!
// Remove element from its original location
aCache.splice(i,1);
// Add as newest
this.addToCache(oRequest, oResponse);
this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
break;
}
}
}
YAHOO.log("The cached response for \"" + oRequest + "\" is " + oResponse,"info",this.toString());
return oResponse;
};
/**
* Default overridable method matches given request to given cached request.
* Returns true if is a hit, returns false otherwise. Implementers should
* override this method to customize the cache-matching algorithm.
*
* @method isCacheHit
* @param oRequest {Object} Request object.
* @param oCachedRequest {Object} Cached request object.
* @return {Boolean} True if given request matches cached request, false otherwise.
*/
YAHOO.util.DataSource.prototype.isCacheHit = function(oRequest, oCachedRequest) {
return (oRequest === oCachedRequest);
};
/**
* Adds a new item to the cache. If cache is full, evicts the stalest item
* before adding the new item.
*
* @method addToCache
* @param oRequest {Object} Request object.
* @param oResponse {Object} Response object to cache.
*/
YAHOO.util.DataSource.prototype.addToCache = function(oRequest, oResponse) {
var aCache = this._aCache;
if(!aCache) {
return;
}
//TODO: check for duplicate entries
// If the cache is full, make room by removing stalest element (index=0)
while(aCache.length >= this.maxCacheEntries) {
aCache.shift();
}
// Add to cache in the newest position, at the end of the array
var oCacheElem = {request:oRequest,response:oResponse};
aCache.push(oCacheElem);
this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse});
YAHOO.log("Cached response for \"" + oRequest + "\"","info",this.toString());
};
/**
* Flushes cache.
*
* @method flushCache
*/
YAHOO.util.DataSource.prototype.flushCache = function() {
if(this._aCache) {
this._aCache = [];
this.fireEvent("cacheFlushEvent");
YAHOO.log("Flushed cache","info",this.toString());
}
};
/**
* First looks for cached response, then sends request to live data.
*
* @method sendRequest
* @param oRequest {Object} Request object
* @param oCallback {Function} Handler function to receive the response
* @param oCaller {Object} The Calling object that is making the request
*/
YAHOO.util.DataSource.prototype.sendRequest = function(oRequest, oCallback, oCaller) {
// First look in cache
var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
if(oCachedResponse) {
oCallback.call(oCaller, oRequest, oCachedResponse);
return;
}
// Not in cache, so forward request to live data
YAHOO.log("Making connection to live data for \"" + oRequest + "\"","info",this.toString());
this.makeConnection(oRequest, oCallback, oCaller);
};
/**
* Overridable method provides default functionality to make a connection to
* live data in order to send request. The response coming back is then
* forwarded to the handleResponse function. This method should be customized
* for more complex implementations.
*
* @method makeConnection
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response
* @param oCaller {Object} The Calling object that is making the request
*/
YAHOO.util.DataSource.prototype.makeConnection = function(oRequest, oCallback, oCaller) {
this.fireEvent("requestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
var oRawResponse = null;
// How to make the connection depends on the type of data
switch(this.dataType) {
// If the live data is a JavaScript Array
// simply forward the entire array to the handler
case YAHOO.util.DataSource.TYPE_JSARRAY:
case YAHOO.util.DataSource.TYPE_JSON:
oRawResponse = this.liveData;
this.handleResponse(oRequest, oRawResponse, oCallback, oCaller);
break;
// If the live data is a JavaScript Function
// pass the request in as a parameter and
// forward the return value to the handler
case YAHOO.util.DataSource.TYPE_JSFUNCTION:
oRawResponse = this.liveData(oRequest);
this.handleResponse(oRequest, oRawResponse, oCallback, oCaller);
break;
// If the live data is over Connection Manager
// set up the callback object and
// pass the request in as a URL query and
// forward the response to the handler
case YAHOO.util.DataSource.TYPE_XHR:
/**
* Connection Manager success handler
*
* @method _xhrSuccess
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrSuccess = function(oResponse) {
// If response ID does not match last made request ID,
// silently fail and wait for the next response
if(oResponse && (!this._oConn || (oResponse.tId != this._oConn.tId))) {
this.fireEvent("dataErrorEvent", {request:oRequest,callback:oCallback,caller:oCaller,message:YAHOO.util.DataSource.ERROR_DATAINVALID});
YAHOO.log(YAHOO.util.DataSource.ERROR_DATAINVALID, "error", this.toString());
return null;
}
// Error if no response
else if(!oResponse) {
this.fireEvent("dataErrorEvent", {request:oRequest,callback:oCallback,caller:oCaller,message:YAHOO.util.DataSource.ERROR_DATANULL});
YAHOO.log(YAHOO.util.DataSource.ERROR_DATANULL, "error", this.toString());
// Send error response back to the caller with the error flag on
oCallback.call(oCaller, oRequest, oResponse, true);
return null;
}
// Forward to handler
else {
this.handleResponse(oRequest, oResponse, oCallback, oCaller);
}
};
/**
* Connection Manager failure handler
*
* @method _xhrFailure
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrFailure = function(oResponse) {
this.fireEvent("dataErrorEvent", {request:oRequest,callback:oCallback,caller:oCaller,message:YAHOO.util.DataSource.ERROR_DATAINVALID});
YAHOO.log(YAHOO.util.DataSource.ERROR_DATAINVALID + ": " + oResponse.statusText, "error", this.toString());
// Send failure response back to the caller with the error flag on
oCallback.call(oCaller, oRequest, oResponse, true);
return null;
};
/**
* Connection Manager callback object
*
* @property _xhrCallback
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrCallback = {
success:_xhrSuccess,
failure:_xhrFailure,
scope: this
};
//TODO: connTimeout config
if(YAHOO.lang.isNumber(this.connTimeout) && (this.connTimeout > 0)) {
_xhrCallback.timeout = this.connTimeout;
}
//TODO: oConn config
if(this._oConn && this.connMgr) {
this.connMgr.abort(this._oConn);
}
var sUri = this.liveData+"?"+oRequest;
if(this.connMgr) {
//this._oConn = this.connMgr.asyncRequest("GET", sUri, _xhrCallback, null);
this._oConn = this.connMgr.asyncRequest(this.connMgr._method, sUri, _xhrCallback, null);
}
else {
YAHOO.log("Could not find a valid Connection Manager","error",this.toString());
// Send null response back to the caller with the error flag on
oCallback.call(oCaller, oRequest, null, true);
}
break;
default:
//TODO: any default?
break;
}
};
/**
* Handles raw data response from live data source.
*
* @method handleResponse
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database
* @param oCallback {Function} Handler function to receive the response
* @param oCaller {Object} The calling object that is making the request
*/
YAHOO.util.DataSource.prototype.handleResponse = function(oRequest, oRawResponse, oCallback, oCaller) {
this.fireEvent("responseEvent", {request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});
YAHOO.log("The live data response for \"" + oRequest + "\" is " + oRawResponse,"info",this.toString());
var xhr = (this.dataType == YAHOO.util.DataSource.TYPE_XHR) ? true : false;
var oParsedResponse = null;
//TODO: break out into overridable methods
switch(this.responseType) {
case YAHOO.util.DataSource.TYPE_JSARRAY:
if(xhr && oRawResponse.responseText) {
oRawResponse = oRawResponse.responseText;
}
oParsedResponse = this.parseArrayData(oRequest, oRawResponse);
break;
case YAHOO.util.DataSource.TYPE_JSON:
if(xhr && oRawResponse.responseText) {
oRawResponse = oRawResponse.responseText;
}
oParsedResponse = this.parseJSONData(oRequest, oRawResponse);
break;
case YAHOO.util.DataSource.TYPE_XML:
if(xhr && oRawResponse.responseXML) {
oRawResponse = oRawResponse.responseXML;
}
oParsedResponse = this.parseXMLData(oRequest, oRawResponse);
break;
case YAHOO.util.DataSource.TYPE_TEXT:
if(xhr && oRawResponse.responseText) {
oRawResponse = oRawResponse.responseText;
}
oParsedResponse = this.parseTextData(oRequest, oRawResponse);
break;
default:
//TODO: pass off to custom function
//var contentType = oRawResponse.getResponseHeader["Content-Type"];
YAHOO.log("Unknown response type","warn",this.toString());
break;
}
if(oParsedResponse) {
this.fireEvent("responseParseEvent", {request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});
// Cache the response
this.addToCache(oRequest, oParsedResponse);
// Send the response back to the caller
oCallback.call(oCaller, oRequest, oParsedResponse);
}
else {
this.fireEvent("dataErrorEvent", {request:oRequest,callback:oCallback,caller:oCaller,message:YAHOO.util.DataSource.ERROR_DATANULL});
YAHOO.log(YAHOO.util.DataSource.ERROR_DATANULL, "error", this.toString());
// Send null response back to the caller with the error flag on
oCallback.call(oCaller, oRequest, null, true);
}
};
/**
* Overridable method parses raw array data into a response object.
*
* @method parseArrayData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database
* @return {Object} Parsed response object
*/
YAHOO.util.DataSource.prototype.parseArrayData = function(oRequest, oRawResponse) {
if(YAHOO.lang.isArray(oRawResponse) && YAHOO.lang.isArray(this.responseSchema.fields)) {
var oParsedResponse = [];
var fields = this.responseSchema.fields;
for(var i=oRawResponse.length-1; i>-1; i--) {
var oResult = {};
for(var j=fields.length-1; j>-1; j--) {
var field = fields[j];
var key = field.key || field;
var data = oRawResponse[i][j] || oRawResponse[i][key];
if(field.converter) {
data = field.converter(data);
}
oResult[key] = data;
}
oParsedResponse.unshift(oResult);
}
YAHOO.log("Parsed array data = " + oParsedResponse,"info",this.toString());
return oParsedResponse;
}
else {
YAHOO.log("Array data could not be parsed" + oRawResponse,"error",this.toString());
return null;
}
};
/**
* Overridable method parses raw plain text data into a response object.
*
* @method parseTextData
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database
* @return {Object} Parsed response object
*/
YAHOO.util.DataSource.prototype.parseTextData = function(oRequest, oRawResponse) {
if(YAHOO.lang.isString(oRawResponse) &&
YAHOO.lang.isArray(this.responseSchema.fields) &&
YAHOO.lang.isString(this.responseSchema.recordDelim) &&
YAHOO.lang.isString(this.responseSchema.fieldDelim)) {
var oParsedResponse = [];
var recDelim = this.responseSchema.recordDelim;
var fieldDelim = this.responseSchema.fieldDelim;
var fields = this.responseSchema.fields;
if(oRawResponse.length > 0) {
// Delete the last line delimiter at the end of the data if it exists
var newLength = oRawResponse.length-recDelim.length;
if(oRawResponse.substr(newLength) == recDelim) {
oRawResponse = oRawResponse.substr(0, newLength);
}
// Split along record delimiter to get an array of strings
var recordsarray = oRawResponse.split(recDelim);
// Cycle through each record, except the first which contains header info
for(var i = recordsarray.length-1; i>-1; i--) {
var oResult = {};
for(var j=fields.length-1; j>-1; j--) {
// Split along field delimter to get each data value
var fielddataarray = recordsarray[i].split(fieldDelim);
// Remove quotation marks from edges, if applicable
var data = fielddataarray[j];
if(data.charAt(0) == "\"") {
data = data.substr(1);
}
if(data.charAt(data.length-1) == "\"") {
data = data.substr(0,data.length-1);
}
var field = fields[j];
var key = field.key || field;
if(field.converter) {
data = field.converter(data);
}
oResult[key] = data;
}
oParsedResponse.unshift(oResult);
}
}
YAHOO.log("Parsed text data = " + oParsedResponse,"info",this.toString());
return oParsedResponse;
}
else {
YAHOO.log("Text data could not be parsed" + oRawResponse,"error",this.toString());
return null;
}
};
/**
* Overridable method parses raw XML data into a response object.
*
* @method parseXMLData
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database
* @return {Object} Parsed response object
*/
YAHOO.util.DataSource.prototype.parseXMLData = function(oRequest, oRawResponse) {
var bError = false;
var oParsedResponse = [];
var xmlList = (this.responseSchema.resultNode) ?
oRawResponse.getElementsByTagName(this.responseSchema.resultNode) :
null;
if(!xmlList || !YAHOO.lang.isArray(this.responseSchema.fields)) {
bError = true;
}
// Loop through each result
else {
for(var k = xmlList.length-1; k >= 0 ; k--) {
var result = xmlList.item(k);
var oResult = {};
// Loop through each data field in each result using the schema
for(var m = this.responseSchema.fields.length-1; m >= 0 ; m--) {
var field = this.responseSchema.fields[m];
var key = field.key || field;
var data = null;
// Values may be held in an attribute...
var xmlAttr = result.attributes.getNamedItem(key);
if(xmlAttr) {
data = xmlAttr.value;
}
// ...or in a node
else {
var xmlNode = result.getElementsByTagName(key);
if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) {
data = xmlNode.item(0).firstChild.nodeValue;
}
else {
data = "";
}
}
if(field.converter) {
data = field.converter(data);
}
// Capture the schema-mapped data field values into an array
oResult[key] = data;
}
// Capture each array of values into an array of results
oParsedResponse.unshift(oResult);
}
}
if(bError) {
YAHOO.log("JSON data could not be parsed" + oRawResponse,"error",this.toString());
return null;
}
YAHOO.log("Parsed XML data = " + oParsedResponse,"info",this.toString());
return oParsedResponse;
};
/**
* Overridable method parses raw JSON data into a response object.
*
* @method parseJSONData
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database
* @return {Object} Parsed response object
*/
YAHOO.util.DataSource.prototype.parseJSONData = function(oRequest, oRawResponse) {
if(oRawResponse && YAHOO.lang.isArray(this.responseSchema.fields)) {
var fields = this.responseSchema.fields;
var bError = false;
var oParsedResponse = [];
var jsonObj,jsonList;
// Parse JSON object out if it's a string
if(YAHOO.lang.isString(oRawResponse)) {
// Check for latest JSON lib but divert KHTML clients
var isNotMac = (navigator.userAgent.toLowerCase().indexOf('khtml')== -1);
if(oRawResponse.parseJSON && isNotMac) {
// Use the new JSON utility if available
jsonObj = oRawResponse.parseJSON();
if(!jsonObj) {
bError = true;
}
}
// Check for older JSON lib but divert KHTML clients
else if(window.JSON && JSON.parse && isNotMac) {
// Use the JSON utility if available
jsonObj = JSON.parse(oRawResponse);
if(!jsonObj) {
bError = true;
}
}
// No JSON lib found so parse the string
else {
try {
// Trim leading spaces
while (oRawResponse.length > 0 &&
(oRawResponse.charAt(0) != "{") &&
(oRawResponse.charAt(0) != "[")) {
oRawResponse = oRawResponse.substring(1, oResponse.length);
}
if(oRawResponse.length > 0) {
// Strip extraneous stuff at the end
var objEnd = Math.max(oRawResponse.lastIndexOf("]"),oRawResponse.lastIndexOf("}"));
oRawResponse = oRawResponse.substring(0,objEnd+1);
// Turn the string into an object literal...
// ...eval is necessary here
jsonObj = eval("(" + oRawResponse + ")");
if(!jsonObj) {
bError = true;
}
}
}
catch(e) {
bError = true;
}
}
}
// Response must already be a JSON object
else if(oRawResponse.constructor == Object) {
jsonObj = oRawResponse;
}
// Not a string or an object
else {
bError = true;
}
// Now that we have a JSON object, parse a jsonList out of it
if(jsonObj && jsonObj.constructor == Object) {
try {
// eval is necessary here since schema can be of unknown depth
jsonList = eval("jsonObj." + this.responseSchema.resultsList);
}
catch(e) {
bError = true;
}
}
if(bError || !jsonList) {
YAHOO.log("JSON data could not be parsed" + oRawResponse,"error",this.toString());
return null;
}
else if(!YAHOO.lang.isArray(jsonList)) {
jsonList = [jsonList];
}
// Loop through the array of all responses...
for(var i = jsonList.length-1; i >= 0 ; i--) {
var oResult = {};
var jsonResult = jsonList[i];
// ...and loop through each data field value of each response
for(var j = fields.length-1; j >= 0 ; j--) {
var field = fields[j];
var key = field.key || field;
// ...and capture data into an array mapped according to the schema...
// eval is necessary here since schema can be of unknown depth
var data;
if(key.indexOf(".")>-1){
data = jsonResult[key];
} else {
data = eval("jsonResult." + key);
}
if((typeof data == "undefined") || (data === null)) {
data = "";
}
//YAHOO.log("data: " + i + " value:" +j+" = "+dataFieldValue,"debug",this.toString());
if(field.converter) {
data = field.converter(data);
}
oResult[key] = data;
}
// Capture the array of data field values in an array of results
oParsedResponse.unshift(oResult);
}
YAHOO.log("Parsed JSON data = " + oParsedResponse,"info",this.toString());
// totalRecords
this.totalRecords = parseInt(eval("jsonObj.totalRecords"));
if(isNaN(this.totalRecords)){
this.totalRecords = 0;
}
return oParsedResponse;
}
else {
YAHOO.log("JSON data could not be parsed" + oRawResponse,"error",this.toString());
return null;
}
};
YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.2.2", build: "204"});
| {
"content_hash": "3880fee68788a24b1d9819e4bbee84d0",
"timestamp": "",
"source": "github",
"line_count": 1040,
"max_line_length": 155,
"avg_line_length": 34.9625,
"alnum_prop": 0.5791644894254834,
"repo_name": "wangzijian777/contentManager",
"id": "6dac3ac41f03b3d53431e398b06b8c35e35e6bff",
"size": "36514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/webapp/widgets/yui/datasource/datasource-beta-debug.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "266"
},
{
"name": "Java",
"bytes": "549647"
},
{
"name": "JavaScript",
"bytes": "2593"
}
],
"symlink_target": ""
} |
export function capitalize (text: string): string {
if (text.length < 1) return text
return text[0].toUpperCase() + text.substr(1)
}
export function uncapitalize (text: string): string {
if (text.length < 1) return text
return text[0].toLowerCase() + text.substr(1)
}
| {
"content_hash": "82f1b7fc95cd8fdef51032e8cf0954d6",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 53,
"avg_line_length": 30.77777777777778,
"alnum_prop": 0.7003610108303249,
"repo_name": "joshforisha/merchant-quest",
"id": "b9133bd9177154a04da0fdb2a2bc68c227c963f8",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/Text.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1303"
},
{
"name": "HTML",
"bytes": "506"
},
{
"name": "JavaScript",
"bytes": "431"
},
{
"name": "TypeScript",
"bytes": "48177"
}
],
"symlink_target": ""
} |
package com.jy.controller.moblie.cms;
import com.jy.common.ajax.AjaxRes;
import com.jy.common.mybatis.Page;
import com.jy.common.utils.DateUtils;
import com.jy.common.utils.base.Const;
import com.jy.common.utils.echarts.series.Map;
import com.jy.common.utils.echarts.series.MarkPoint;
import com.jy.controller.base.BaseController;
import com.jy.entity.system.cms.SysNews;
import com.jy.service.system.cms.SysNewsService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
@Controller
@RequestMapping("/moblie/api/v1/news")
public class MSysNewsController extends BaseController<SysNews> {
@Autowired
private SysNewsService service;
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public AjaxRes findByPage() {
AjaxRes ar = getAjaxRes();
if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, "/backstage/SysNews/index"))) {
try {
Page<SysNews> page = new Page<SysNews>();
page.setPageNum(1);
page.setPageSize(100);
SysNews o = new SysNews();
o.setIsValid(1);
o.setCompany(getCompany());
Page<SysNews> news = service.findByPage(o, page);
ar.setSucceed(getTimeList(news.getResults()));
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg(Const.DATA_FAIL);
}
}
return ar;
}
private TreeMap<String, List<SysNews>> getTimeList(List<SysNews> list) {
TreeMap<String, List<SysNews>> result = new TreeMap<String, List<SysNews>>();
for (SysNews s : list) {
String time = DateUtils.formatDate(s.getAddtime(), "yyyy-MM-dd");
List<SysNews> sysNews = result.get(time);
if (CollectionUtils.isEmpty(sysNews)) {
sysNews = new ArrayList<SysNews>();
}
sysNews.add(s);
result.put(time, sysNews);
}
return result;
}
@RequestMapping(value = "find", method = RequestMethod.GET)
@ResponseBody
public AjaxRes find(String id) {
AjaxRes ar = getAjaxRes();
if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON))) {
try {
SysNews o = new SysNews();
o.setId(id);
o.setCompany(o.getCompany());
List<SysNews> list = service.find(o);
if (list != null && list.size() != 0) {
SysNews obj = list.get(0);
ar.setSucceed(obj);
} else {
ar.setFailMsg(Const.DATA_FAIL);
}
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg(Const.DATA_FAIL);
}
}
return ar;
}
} | {
"content_hash": "ce3c0b171eec9aec9980578a4d5883d7",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 103,
"avg_line_length": 35.97802197802198,
"alnum_prop": 0.6069028711056811,
"repo_name": "futureskywei/whale",
"id": "c25fd3039fc200e3886cb79ed2c4879f085f1b88",
"size": "3274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/jy/controller/moblie/cms/MSysNewsController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "784148"
},
{
"name": "ColdFusion",
"bytes": "2253"
},
{
"name": "HTML",
"bytes": "2208161"
},
{
"name": "Java",
"bytes": "1987736"
},
{
"name": "JavaScript",
"bytes": "5161683"
},
{
"name": "PHP",
"bytes": "38915"
}
],
"symlink_target": ""
} |
<div class="container" data-ng-controller="HeaderController">
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-ng-click="toggleCollapsibleMenu()">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/#!/" class="navbar-brand">app</a>
</div>
<nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation">
<ul class="nav navbar-nav" data-ng-if="menu.shouldRender(authentication.user);">
<li data-ng-repeat="item in menu.items | orderBy: 'position'" data-ng-if="item.shouldRender(authentication.user);" ng-switch="item.menuItemType" ui-route="{{item.uiRoute}}" class="{{item.menuItemClass}}" ng-class="{active: ($uiRoute)}" dropdown="item.menuItemType === 'dropdown'">
<a ng-switch-when="dropdown" class="dropdown-toggle">
<span data-ng-bind="item.title"></span>
<b class="caret"></b>
</a>
<ul ng-switch-when="dropdown" class="dropdown-menu">
<li data-ng-repeat="subitem in item.items | orderBy: 'position'" data-ng-if="subitem.shouldRender(authentication.user);" ui-route="{{subitem.uiRoute}}" ng-class="{active: $uiRoute}">
<a href="/#!/{{subitem.link}}" data-ng-bind="subitem.title"></a>
</li>
</ul>
<a ng-switch-default href="/#!/{{item.link}}" data-ng-bind="item.title"></a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-hide="authentication.user">
<li ui-route="/signup" ng-class="{active: $uiRoute}">
<a href="/#!/signup">Sign Up</a>
</li>
<li class="divider-vertical"></li>
<li ui-route="/signin" ng-class="{active: $uiRoute}">
<a href="/#!/signin">Sign In</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-show="authentication.user">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span data-ng-bind="authentication.user.displayName"></span> <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="/#!/settings/profile">Edit Profile</a>
</li>
<li>
<a href="/#!/settings/accounts">Manage Social Accounts</a>
</li>
<li data-ng-show="authentication.user.provider === 'local'">
<a href="/#!/settings/password">Change Password</a>
</li>
<li class="divider"></li>
<li>
<a href="/auth/signout">Signout</a>
</li>
</ul>
</li>
</ul>
</nav>
</div> | {
"content_hash": "7e332db70cbad4476bc72c0bfdc90130",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 283,
"avg_line_length": 42.672413793103445,
"alnum_prop": 0.6234343434343435,
"repo_name": "Batname/mean_tutorial",
"id": "b3c8d83f9344630db202204b5822d7525900ed40",
"size": "2475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/modules/core/views/header.client.view.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "500"
},
{
"name": "JavaScript",
"bytes": "68466"
},
{
"name": "Perl",
"bytes": "48"
},
{
"name": "Shell",
"bytes": "1083"
}
],
"symlink_target": ""
} |
package io.github.jeddict.jsonb.modeler.widget;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import io.github.jeddict.jsonb.modeler.widget.context.NodeContextModel;
import static io.github.jeddict.jsonb.modeler.properties.PropertiesHandler.getJsonbTypeAdapter;
import static io.github.jeddict.jsonb.modeler.properties.PropertiesHandler.getJsonbTypeDeserializer;
import static io.github.jeddict.jsonb.modeler.properties.PropertiesHandler.getJsonbTypeSerializer;
import io.github.jeddict.jsonb.modeler.spec.JSONBNode;
import io.github.jeddict.jsonb.modeler.initializer.JSONBModelerScene;
import io.github.jeddict.jpa.modeler.widget.FlowPinWidget;
import static io.github.jeddict.jpa.modeler.widget.JavaClassWidget.getFileObject;
import io.github.jeddict.jpa.modeler.widget.OpenSourceCodeAction;
import io.github.jeddict.jpa.spec.extend.Attribute;
import io.github.jeddict.jpa.modeler.initializer.JPAModelerScene;
import static io.github.jeddict.util.StringUtils.equalsIgnoreCase;
import static io.github.jeddict.util.StringUtils.isNotBlank;
import static io.github.jeddict.util.StringUtils.trim;
import org.netbeans.modeler.specification.model.document.property.ElementPropertySet;
import org.netbeans.modeler.widget.context.ContextPaletteModel;
import org.netbeans.modeler.widget.node.IPNodeWidget;
import org.netbeans.modeler.widget.pin.info.PinWidgetInfo;
import org.netbeans.modeler.widget.properties.handler.PropertyChangeListener;
import org.netbeans.modeler.widget.properties.handler.PropertyVisibilityHandler;
/**
*
* @author Gaurav Gupta
*/
public abstract class JSONNodeWidget<E extends JSONBNode> extends FlowPinWidget<E, JSONBModelerScene> {
private final List<ReferenceFlowWidget> referenceFlowWidget = new ArrayList<>();
public JSONNodeWidget(JSONBModelerScene scene, IPNodeWidget nodeWidget, PinWidgetInfo pinWidgetInfo) {
super(scene, nodeWidget, pinWidgetInfo);
}
@Override
public void createPropertySet(ElementPropertySet set) {
Attribute attribute = this.getBaseElementSpec().getAttribute();
//JsonbDateFormat and JsonbNumberFormat is also used at EntityMapping and JavaClass level so custom VisibilityHandler is required here
PropertyVisibilityHandler dateVisibilityHandler = () -> {
boolean result = !attribute.getJsonbTransient() && attribute.getJsonbDateFormat().isSupportedFormat(attribute.getDataTypeLabel());
if (result) {
attribute.setJsonbNumberFormat(null);
} else {
attribute.setJsonbDateFormat(null);
}
return result;
};
this.addPropertyVisibilityHandler("date_value", dateVisibilityHandler);
this.addPropertyVisibilityHandler("date_locale", dateVisibilityHandler);
PropertyVisibilityHandler numberVisibilityHandler = () -> {
boolean result = !attribute.getJsonbTransient() && attribute.getJsonbNumberFormat().isSupportedFormat(attribute.getDataTypeLabel());
if (result) {
attribute.setJsonbDateFormat(null);
} else {
attribute.setJsonbNumberFormat(null);
}
return result;
};
this.addPropertyVisibilityHandler("number_value", numberVisibilityHandler);
this.addPropertyVisibilityHandler("number_locale", numberVisibilityHandler);
this.addPropertyChangeListener("jsonbTransient", (PropertyChangeListener<Boolean>)(oldValue, newValue) -> {
this.getBaseElementSpec().getAttribute().setIncludeInUI(false);
setTransientLabel(newValue);
});
super.createPropertySet(set);
JPAModelerScene parentScene = (JPAModelerScene) this.getModelerScene().getModelerFile().getParentFile().getModelerScene();
set.put("JSONB_PROP", getJsonbTypeAdapter(attribute, this, parentScene));
set.put("JSONB_PROP", getJsonbTypeSerializer(attribute, this, parentScene));
set.put("JSONB_PROP", getJsonbTypeDeserializer(attribute, this, parentScene));
attribute.getAttributeConstraints().forEach((constraint) -> {
set.createPropertySet("ATTRIBUTE_CONSTRAINTS", "ATTRIBUTE_CONSTRAINTS", this, constraint);
});
attribute.getKeyConstraints().forEach((constraint) -> {
set.createPropertySet("KEY_CONSTRAINTS", "KEY_CONSTRAINTS", this, constraint);
});
attribute.getValueConstraints().forEach((constraint) -> {
set.createPropertySet("VALUE_CONSTRAINTS", "VALUE_CONSTRAINTS", this, constraint);
});
}
private void setTransientLabel(Boolean transientProperty){
Font font = getPinNameWidget().getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, transientProperty);
getPinNameWidget().setFont(new Font(attributes));
}
public void setDatatypeTooltip() {
this.setToolTipText(this.getBaseElementSpec().getAttribute().getDataTypeLabel());
}
@Override
public void setLabel(String label) {
if (isNotBlank(label)) {
this.setPinName(this.getModelerScene().transferPropertyName(label));
}
}
@Override
public void init() {
this.setImage(getIcon());
validateName(this.getName());
setDatatypeTooltip();
addOpenSourceCodeAction();
setTransientLabel(((JSONBNode)this.getBaseElementSpec()).getAttribute().getJsonbTransient());
}
protected void addOpenSourceCodeAction() {
this.getImageWidget().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.getImageWidget().getActions().addAction(
new OpenSourceCodeAction(
() -> getFileObject(
this.getBaseElementSpec().getAttribute().getJavaClass(),
this.getModelerScene().getModelerFile().getParentFile()
),
this.getBaseElementSpec().getAttribute(),
this.getModelerScene().getModelerFile().getParentFile()
)
);
}
@Override
public void destroy() {
}
public DocumentWidget getDocumentWidget() {
return (DocumentWidget) this.getPNodeWidget();
}
public boolean addReferenceFlowWidget(ReferenceFlowWidget flowWidget) {
return getReferenceFlowWidget().add(flowWidget);
}
public boolean removeReferenceFlowWidget(ReferenceFlowWidget flowWidget) {
return getReferenceFlowWidget().remove(flowWidget);
}
@Override
public ContextPaletteModel getContextPaletteModel() {
if (contextPaletteModel == null) {
contextPaletteModel = NodeContextModel.getContextPaletteModel(this);
}
return contextPaletteModel;
}
/**
* @return the referenceFlowWidget
*/
public List<ReferenceFlowWidget> getReferenceFlowWidget() {
return referenceFlowWidget;
}
@Override
public void setName(String name) {
if(equalsIgnoreCase(this.name, trim(name))) {
return;
}
if (isNotBlank(name)) {
this.name = name.replaceAll("\\s+", "");
if (this.getModelerScene().getModelerFile().isLoaded()) {
updateName(this.name);
}
} else {
setDefaultName();
}
validateName(this.name);
}
/**
* Called when developer delete value
*/
protected void setDefaultName() {
this.name = evaluateName();
if (this.getModelerScene().getModelerFile().isLoaded()) {
updateName(null);
}
setLabel(name);
}
protected void updateName(String newName) {
Attribute attribute = this.getBaseElementSpec().getAttribute();
attribute.setJsonbProperty(newName);
}
protected String evaluateName() {
Attribute attribute = this.getBaseElementSpec().getAttribute();
return attribute.getName();
}
@Override // to return attribute name instead of property display strategy label
public String getName() {
return evaluateName();
}
protected void validateName(String name) {
// JSONBDocument documentSpec = (JSONBDocument) this.getDocumentWidget().getBaseElementSpec();
// if (documentSpec.findColumns(name).size() > 1) {
// getSignalManager().fire(ERROR, AttributeValidator.NON_UNIQUE_COLUMN_NAME);
// } else {
// getSignalManager().clear(ERROR, AttributeValidator.NON_UNIQUE_COLUMN_NAME);
// }
}
}
| {
"content_hash": "6cd654830dd0cdc8f0a42188b088cc0f",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 144,
"avg_line_length": 41.082191780821915,
"alnum_prop": 0.6634433700122263,
"repo_name": "jGauravGupta/jpamodeler",
"id": "0e381248873ea47738691063097aab1c13972db7",
"size": "9681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsonb-modeler/src/main/java/io/github/jeddict/jsonb/modeler/widget/JSONNodeWidget.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2049"
},
{
"name": "Java",
"bytes": "3407069"
}
],
"symlink_target": ""
} |
import * as React from "react";
import {InputProps} from "./input"
export interface DropdownStringInputProps<T> extends InputProps{
options: {
value: string,
id: T
}[]
value?: T,
onChange: (value: T) => void,
}
let last_id = 0
export class DropdownStringInput<T extends React.Key> extends React.Component<DropdownStringInputProps<T>, {}> {
state: {value: string, expanded: boolean};
last: T = undefined
constructor(props: DropdownStringInputProps<T>) {
super(props);
this.state = {value: props.value?this.props.options.find( o => o.id==this.props.value).value:"", expanded: false};
window.addEventListener("click", (event) => {
this.setState({expanded: (event as any).dropdown == this});
})
}
componentWillReceiveProps(props: DropdownStringInputProps<T>) {
if (props.value == this.props.value) {
return;
}
this.setState({value: props.value?this.props.options.find( o => o.id==this.props.value).value:""})
}
checkStatus(value: string) {
let valid_options = this.props.options.filter(
(option) => option.value.toLowerCase().indexOf(value.toLowerCase()) >= 0
)
if (valid_options.length == 1) {
if (valid_options[0].id !== this.last) {
this.last = valid_options[0].id
this.props.onChange(valid_options[0].id);
}
} else if (this.last !== undefined){
this.last = undefined;
this.props.onChange(undefined);
}
}
render() {
let valid_options = this.props.options.filter(
(option) => option.value.toLowerCase().indexOf(this.state.value.toLowerCase()) >= 0
)
let dropdown = valid_options.map(
(option) => <div key={option.id} onClick={e => {
this.setState({value: option.value});
this.checkStatus(option.value);
}}>{option.value}</div>
)
let id = "";
if (!this.props.id) {
id = "dropdown_input" + last_id;
last_id+=1;
} else {
id = this.props.id
}
return <div style={{position: "relative"}} className={this.props.class+" float-label"} onFocus={_ => this.setState({expanded: true})}>
<input required className="dropdown-input" id={id} value={this.state.value} onChange={(e: any) =>{
this.setState({value: e.target.value})
this.checkStatus(e.target.value)
}} onClick={e => (e.nativeEvent as any).dropdown = this}/>
<label htmlFor={id} > {this.props.label} </label>
{ (() => {
if (this.state.expanded) {
return <div style={{position: "absolute", zIndex: 1}} className="dropdown">
{dropdown}
</div>
} else {
return <div/>
}
})()}
</div>
}
} | {
"content_hash": "7f4da739a325f441df87cddcfda85b8f",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 143,
"avg_line_length": 38.5609756097561,
"alnum_prop": 0.510752688172043,
"repo_name": "goodbye-island/S-Store-Front-End",
"id": "7fcb61b7336500de4fbf4fdb664a462dcd604166",
"size": "3162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/utilities/dropdown-string-input.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4314"
},
{
"name": "HTML",
"bytes": "538"
},
{
"name": "JavaScript",
"bytes": "1159"
},
{
"name": "TypeScript",
"bytes": "58634"
}
],
"symlink_target": ""
} |
package graphene.dao.titan;
import graphene.dao.UserDAO;
import graphene.model.idl.G_User;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import com.thinkaurelius.titan.core.TitanGraph;
public class SlowIngestTestFromTitanDAO {
private UserDAO dao;
private Logger logger = LoggerFactory
.getLogger(SlowIngestTestFromTitanDAO.class);
int numberOfNodes = 100;
int numberOfRandomUpdates = 500;
private TitanGraph service;
@Test
public void testComplexChange02() {
logger.debug("=========================testComplexChange02");
G_User u = new G_User();
u.setAvatar("bugatti.png");
for (int i = 0; i < numberOfNodes; i++) {
logger.debug("Adding user " + i);
u.setUsername("complexChange02-" + i);
G_User x = dao.save(u);
}
Random generator = new Random();
for (int j = 0; j < numberOfRandomUpdates; j++) {
int k = generator.nextInt(numberOfNodes - 1);
logger.debug("Modifying user " + k);
G_User y = dao.getByUsername("complexChange02-" + k);
}
}
}
| {
"content_hash": "bd77e481a5d54ee8cb1fec02abd1517c",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 63,
"avg_line_length": 21.93877551020408,
"alnum_prop": 0.6920930232558139,
"repo_name": "Sotera/graphene",
"id": "578c4a70be510812ed592684cb8f62e3111502cb",
"size": "1894",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "graphene-parent/graphene-dao-titan/src/test/java/graphene/dao/titan/SlowIngestTestFromTitanDAO.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "15982"
},
{
"name": "Batchfile",
"bytes": "2998"
},
{
"name": "CSS",
"bytes": "1638268"
},
{
"name": "HTML",
"bytes": "31729"
},
{
"name": "Java",
"bytes": "3415980"
},
{
"name": "JavaScript",
"bytes": "5029687"
},
{
"name": "Shell",
"bytes": "96"
}
],
"symlink_target": ""
} |
package server
import (
"context"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
betapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/dataplex/beta/dataplex_beta_go_proto"
emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/dataplex/beta"
)
// LakeServer implements the gRPC interface for Lake.
type LakeServer struct{}
// ProtoToLakeStateEnum converts a LakeStateEnum enum from its proto representation.
func ProtoToDataplexBetaLakeStateEnum(e betapb.DataplexBetaLakeStateEnum) *beta.LakeStateEnum {
if e == 0 {
return nil
}
if n, ok := betapb.DataplexBetaLakeStateEnum_name[int32(e)]; ok {
e := beta.LakeStateEnum(n[len("DataplexBetaLakeStateEnum"):])
return &e
}
return nil
}
// ProtoToLakeMetastoreStatusStateEnum converts a LakeMetastoreStatusStateEnum enum from its proto representation.
func ProtoToDataplexBetaLakeMetastoreStatusStateEnum(e betapb.DataplexBetaLakeMetastoreStatusStateEnum) *beta.LakeMetastoreStatusStateEnum {
if e == 0 {
return nil
}
if n, ok := betapb.DataplexBetaLakeMetastoreStatusStateEnum_name[int32(e)]; ok {
e := beta.LakeMetastoreStatusStateEnum(n[len("DataplexBetaLakeMetastoreStatusStateEnum"):])
return &e
}
return nil
}
// ProtoToLakeMetastore converts a LakeMetastore object from its proto representation.
func ProtoToDataplexBetaLakeMetastore(p *betapb.DataplexBetaLakeMetastore) *beta.LakeMetastore {
if p == nil {
return nil
}
obj := &beta.LakeMetastore{
Service: dcl.StringOrNil(p.GetService()),
}
return obj
}
// ProtoToLakeAssetStatus converts a LakeAssetStatus object from its proto representation.
func ProtoToDataplexBetaLakeAssetStatus(p *betapb.DataplexBetaLakeAssetStatus) *beta.LakeAssetStatus {
if p == nil {
return nil
}
obj := &beta.LakeAssetStatus{
UpdateTime: dcl.StringOrNil(p.GetUpdateTime()),
ActiveAssets: dcl.Int64OrNil(p.GetActiveAssets()),
SecurityPolicyApplyingAssets: dcl.Int64OrNil(p.GetSecurityPolicyApplyingAssets()),
}
return obj
}
// ProtoToLakeMetastoreStatus converts a LakeMetastoreStatus object from its proto representation.
func ProtoToDataplexBetaLakeMetastoreStatus(p *betapb.DataplexBetaLakeMetastoreStatus) *beta.LakeMetastoreStatus {
if p == nil {
return nil
}
obj := &beta.LakeMetastoreStatus{
State: ProtoToDataplexBetaLakeMetastoreStatusStateEnum(p.GetState()),
Message: dcl.StringOrNil(p.GetMessage()),
UpdateTime: dcl.StringOrNil(p.GetUpdateTime()),
Endpoint: dcl.StringOrNil(p.GetEndpoint()),
}
return obj
}
// ProtoToLake converts a Lake resource from its proto representation.
func ProtoToLake(p *betapb.DataplexBetaLake) *beta.Lake {
obj := &beta.Lake{
Name: dcl.StringOrNil(p.GetName()),
DisplayName: dcl.StringOrNil(p.GetDisplayName()),
Uid: dcl.StringOrNil(p.GetUid()),
CreateTime: dcl.StringOrNil(p.GetCreateTime()),
UpdateTime: dcl.StringOrNil(p.GetUpdateTime()),
Description: dcl.StringOrNil(p.GetDescription()),
State: ProtoToDataplexBetaLakeStateEnum(p.GetState()),
ServiceAccount: dcl.StringOrNil(p.GetServiceAccount()),
Metastore: ProtoToDataplexBetaLakeMetastore(p.GetMetastore()),
AssetStatus: ProtoToDataplexBetaLakeAssetStatus(p.GetAssetStatus()),
MetastoreStatus: ProtoToDataplexBetaLakeMetastoreStatus(p.GetMetastoreStatus()),
Project: dcl.StringOrNil(p.GetProject()),
Location: dcl.StringOrNil(p.GetLocation()),
}
return obj
}
// LakeStateEnumToProto converts a LakeStateEnum enum to its proto representation.
func DataplexBetaLakeStateEnumToProto(e *beta.LakeStateEnum) betapb.DataplexBetaLakeStateEnum {
if e == nil {
return betapb.DataplexBetaLakeStateEnum(0)
}
if v, ok := betapb.DataplexBetaLakeStateEnum_value["LakeStateEnum"+string(*e)]; ok {
return betapb.DataplexBetaLakeStateEnum(v)
}
return betapb.DataplexBetaLakeStateEnum(0)
}
// LakeMetastoreStatusStateEnumToProto converts a LakeMetastoreStatusStateEnum enum to its proto representation.
func DataplexBetaLakeMetastoreStatusStateEnumToProto(e *beta.LakeMetastoreStatusStateEnum) betapb.DataplexBetaLakeMetastoreStatusStateEnum {
if e == nil {
return betapb.DataplexBetaLakeMetastoreStatusStateEnum(0)
}
if v, ok := betapb.DataplexBetaLakeMetastoreStatusStateEnum_value["LakeMetastoreStatusStateEnum"+string(*e)]; ok {
return betapb.DataplexBetaLakeMetastoreStatusStateEnum(v)
}
return betapb.DataplexBetaLakeMetastoreStatusStateEnum(0)
}
// LakeMetastoreToProto converts a LakeMetastore object to its proto representation.
func DataplexBetaLakeMetastoreToProto(o *beta.LakeMetastore) *betapb.DataplexBetaLakeMetastore {
if o == nil {
return nil
}
p := &betapb.DataplexBetaLakeMetastore{}
p.SetService(dcl.ValueOrEmptyString(o.Service))
return p
}
// LakeAssetStatusToProto converts a LakeAssetStatus object to its proto representation.
func DataplexBetaLakeAssetStatusToProto(o *beta.LakeAssetStatus) *betapb.DataplexBetaLakeAssetStatus {
if o == nil {
return nil
}
p := &betapb.DataplexBetaLakeAssetStatus{}
p.SetUpdateTime(dcl.ValueOrEmptyString(o.UpdateTime))
p.SetActiveAssets(dcl.ValueOrEmptyInt64(o.ActiveAssets))
p.SetSecurityPolicyApplyingAssets(dcl.ValueOrEmptyInt64(o.SecurityPolicyApplyingAssets))
return p
}
// LakeMetastoreStatusToProto converts a LakeMetastoreStatus object to its proto representation.
func DataplexBetaLakeMetastoreStatusToProto(o *beta.LakeMetastoreStatus) *betapb.DataplexBetaLakeMetastoreStatus {
if o == nil {
return nil
}
p := &betapb.DataplexBetaLakeMetastoreStatus{}
p.SetState(DataplexBetaLakeMetastoreStatusStateEnumToProto(o.State))
p.SetMessage(dcl.ValueOrEmptyString(o.Message))
p.SetUpdateTime(dcl.ValueOrEmptyString(o.UpdateTime))
p.SetEndpoint(dcl.ValueOrEmptyString(o.Endpoint))
return p
}
// LakeToProto converts a Lake resource to its proto representation.
func LakeToProto(resource *beta.Lake) *betapb.DataplexBetaLake {
p := &betapb.DataplexBetaLake{}
p.SetName(dcl.ValueOrEmptyString(resource.Name))
p.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))
p.SetUid(dcl.ValueOrEmptyString(resource.Uid))
p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))
p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))
p.SetDescription(dcl.ValueOrEmptyString(resource.Description))
p.SetState(DataplexBetaLakeStateEnumToProto(resource.State))
p.SetServiceAccount(dcl.ValueOrEmptyString(resource.ServiceAccount))
p.SetMetastore(DataplexBetaLakeMetastoreToProto(resource.Metastore))
p.SetAssetStatus(DataplexBetaLakeAssetStatusToProto(resource.AssetStatus))
p.SetMetastoreStatus(DataplexBetaLakeMetastoreStatusToProto(resource.MetastoreStatus))
p.SetProject(dcl.ValueOrEmptyString(resource.Project))
p.SetLocation(dcl.ValueOrEmptyString(resource.Location))
mLabels := make(map[string]string, len(resource.Labels))
for k, r := range resource.Labels {
mLabels[k] = r
}
p.SetLabels(mLabels)
return p
}
// applyLake handles the gRPC request by passing it to the underlying Lake Apply() method.
func (s *LakeServer) applyLake(ctx context.Context, c *beta.Client, request *betapb.ApplyDataplexBetaLakeRequest) (*betapb.DataplexBetaLake, error) {
p := ProtoToLake(request.GetResource())
res, err := c.ApplyLake(ctx, p)
if err != nil {
return nil, err
}
r := LakeToProto(res)
return r, nil
}
// applyDataplexBetaLake handles the gRPC request by passing it to the underlying Lake Apply() method.
func (s *LakeServer) ApplyDataplexBetaLake(ctx context.Context, request *betapb.ApplyDataplexBetaLakeRequest) (*betapb.DataplexBetaLake, error) {
cl, err := createConfigLake(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return s.applyLake(ctx, cl, request)
}
// DeleteLake handles the gRPC request by passing it to the underlying Lake Delete() method.
func (s *LakeServer) DeleteDataplexBetaLake(ctx context.Context, request *betapb.DeleteDataplexBetaLakeRequest) (*emptypb.Empty, error) {
cl, err := createConfigLake(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return &emptypb.Empty{}, cl.DeleteLake(ctx, ProtoToLake(request.GetResource()))
}
// ListDataplexBetaLake handles the gRPC request by passing it to the underlying LakeList() method.
func (s *LakeServer) ListDataplexBetaLake(ctx context.Context, request *betapb.ListDataplexBetaLakeRequest) (*betapb.ListDataplexBetaLakeResponse, error) {
cl, err := createConfigLake(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
resources, err := cl.ListLake(ctx, request.GetProject(), request.GetLocation())
if err != nil {
return nil, err
}
var protos []*betapb.DataplexBetaLake
for _, r := range resources.Items {
rp := LakeToProto(r)
protos = append(protos, rp)
}
p := &betapb.ListDataplexBetaLakeResponse{}
p.SetItems(protos)
return p, nil
}
func createConfigLake(ctx context.Context, service_account_file string) (*beta.Client, error) {
conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
return beta.NewClient(conf), nil
}
| {
"content_hash": "7ad6c22f5a480ce43852d7cf1d396892",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 155,
"avg_line_length": 39.61538461538461,
"alnum_prop": 0.7834951456310679,
"repo_name": "GoogleCloudPlatform/declarative-resource-client-library",
"id": "4ea97358e381596d6d57b797ffff1e68cd118a64",
"size": "9882",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "python/services/dataplex/beta/lake_server.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2560"
},
{
"name": "C++",
"bytes": "3947"
},
{
"name": "Go",
"bytes": "116489733"
},
{
"name": "Python",
"bytes": "17240408"
},
{
"name": "Starlark",
"bytes": "319733"
}
],
"symlink_target": ""
} |
#ifndef STAN_MATH_PRIM_PROB_MULTINOMIAL_LOG_HPP
#define STAN_MATH_PRIM_PROB_MULTINOMIAL_LOG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/prob/multinomial_lpmf.hpp>
#include <vector>
namespace stan {
namespace math {
/** \ingroup multivar_dists
* @deprecated use <code>multinomial_lpmf</code>
*/
template <bool propto, typename T_prob>
return_type_t<T_prob> multinomial_log(const std::vector<int>& ns,
const T_prob& theta) {
return multinomial_lpmf<propto>(ns, theta);
}
/** \ingroup multivar_dists
* @deprecated use <code>multinomial_lpmf</code>
*/
template <typename T_prob>
return_type_t<T_prob> multinomial_log(const std::vector<int>& ns,
const T_prob& theta) {
return multinomial_lpmf<false>(ns, theta);
}
} // namespace math
} // namespace stan
#endif
| {
"content_hash": "98834c20a4b8f7e1420927e7262f26fe",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 65,
"avg_line_length": 28.34375,
"alnum_prop": 0.6659316427783903,
"repo_name": "stan-dev/math",
"id": "1a5c18c60f1fd74635888f9345fe27217a836f4a",
"size": "907",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "stan/math/prim/prob/multinomial_log.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89079"
},
{
"name": "Assembly",
"bytes": "566183"
},
{
"name": "Batchfile",
"bytes": "33076"
},
{
"name": "C",
"bytes": "7093229"
},
{
"name": "C#",
"bytes": "54013"
},
{
"name": "C++",
"bytes": "166268432"
},
{
"name": "CMake",
"bytes": "820167"
},
{
"name": "CSS",
"bytes": "11283"
},
{
"name": "Cuda",
"bytes": "342187"
},
{
"name": "DIGITAL Command Language",
"bytes": "32438"
},
{
"name": "Dockerfile",
"bytes": "118"
},
{
"name": "Fortran",
"bytes": "2299405"
},
{
"name": "HTML",
"bytes": "8320473"
},
{
"name": "JavaScript",
"bytes": "38507"
},
{
"name": "M4",
"bytes": "10525"
},
{
"name": "Makefile",
"bytes": "74538"
},
{
"name": "Meson",
"bytes": "4233"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NASL",
"bytes": "106079"
},
{
"name": "Objective-C",
"bytes": "420"
},
{
"name": "Objective-C++",
"bytes": "420"
},
{
"name": "Pascal",
"bytes": "75208"
},
{
"name": "Perl",
"bytes": "47080"
},
{
"name": "Python",
"bytes": "1958975"
},
{
"name": "QMake",
"bytes": "18714"
},
{
"name": "Roff",
"bytes": "30570"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "SWIG",
"bytes": "5501"
},
{
"name": "Shell",
"bytes": "187001"
},
{
"name": "Starlark",
"bytes": "29435"
},
{
"name": "XSLT",
"bytes": "567938"
},
{
"name": "Yacc",
"bytes": "22343"
}
],
"symlink_target": ""
} |
<?php
final class FundInitiativeEditController
extends FundController {
private $id;
public function willProcessRequest(array $data) {
$this->id = idx($data, 'id');
}
public function processRequest() {
$request = $this->getRequest();
$viewer = $request->getUser();
if ($this->id) {
$initiative = id(new FundInitiativeQuery())
->setViewer($viewer)
->withIDs(array($this->id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$initiative) {
return new Aphront404Response();
}
$is_new = false;
} else {
$initiative = FundInitiative::initializeNewInitiative($viewer);
$is_new = true;
}
if ($is_new) {
$title = pht('Create Initiative');
$button_text = pht('Create Initiative');
$cancel_uri = $this->getApplicationURI();
} else {
$title = pht(
'Edit %s %s',
$initiative->getMonogram(),
$initiative->getName());
$button_text = pht('Save Changes');
$cancel_uri = '/'.$initiative->getMonogram();
}
$e_name = true;
$v_name = $initiative->getName();
$e_merchant = null;
$v_merchant = $initiative->getMerchantPHID();
$v_desc = $initiative->getDescription();
$v_risk = $initiative->getRisks();
if ($is_new) {
$v_projects = array();
} else {
$v_projects = PhabricatorEdgeQuery::loadDestinationPHIDs(
$initiative->getPHID(),
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
$v_projects = array_reverse($v_projects);
}
$validation_exception = null;
if ($request->isFormPost()) {
$v_name = $request->getStr('name');
$v_desc = $request->getStr('description');
$v_risk = $request->getStr('risks');
$v_view = $request->getStr('viewPolicy');
$v_edit = $request->getStr('editPolicy');
$v_merchant = $request->getStr('merchantPHID');
$v_projects = $request->getArr('projects');
$type_name = FundInitiativeTransaction::TYPE_NAME;
$type_desc = FundInitiativeTransaction::TYPE_DESCRIPTION;
$type_risk = FundInitiativeTransaction::TYPE_RISKS;
$type_merchant = FundInitiativeTransaction::TYPE_MERCHANT;
$type_view = PhabricatorTransactions::TYPE_VIEW_POLICY;
$type_edit = PhabricatorTransactions::TYPE_EDIT_POLICY;
$xactions = array();
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_name)
->setNewValue($v_name);
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_desc)
->setNewValue($v_desc);
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_risk)
->setNewValue($v_risk);
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_merchant)
->setNewValue($v_merchant);
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_view)
->setNewValue($v_view);
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType($type_edit)
->setNewValue($v_edit);
$proj_edge_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST;
$xactions[] = id(new FundInitiativeTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue('edge:type', $proj_edge_type)
->setNewValue(array('=' => array_fuse($v_projects)));
$editor = id(new FundInitiativeEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true);
try {
$editor->applyTransactions($initiative, $xactions);
return id(new AphrontRedirectResponse())
->setURI('/'.$initiative->getMonogram());
} catch (PhabricatorApplicationTransactionValidationException $ex) {
$validation_exception = $ex;
$e_name = $ex->getShortMessage($type_name);
$e_merchant = $ex->getShortMessage($type_merchant);
$initiative->setViewPolicy($v_view);
$initiative->setEditPolicy($v_edit);
}
}
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($initiative)
->execute();
if ($v_projects) {
$project_handles = $this->loadViewerHandles($v_projects);
} else {
$project_handles = array();
}
$merchants = id(new PhortuneMerchantQuery())
->setViewer($viewer)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
$merchant_options = array();
foreach ($merchants as $merchant) {
$merchant_options[$merchant->getPHID()] = pht(
'Merchant %d %s',
$merchant->getID(),
$merchant->getName());
}
if ($v_merchant && empty($merchant_options[$v_merchant])) {
$merchant_options = array(
$v_merchant => pht('(Restricted Merchant)'),
) + $merchant_options;
}
if (!$merchant_options) {
return $this->newDialog()
->setTitle(pht('No Valid Phortune Merchant Accounts'))
->appendParagraph(
pht(
'You do not control any merchant accounts which can receive '.
'payments from this initiative. When you create an initiative, '.
'you need to specify a merchant account where funds will be paid '.
'to.'))
->appendParagraph(
pht(
'Create a merchant account in the Phortune application before '.
'creating an initiative in Fund.'))
->addCancelButton($this->getApplicationURI());
}
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild(
id(new AphrontFormTextControl())
->setName('name')
->setLabel(pht('Name'))
->setValue($v_name)
->setError($e_name))
->appendChild(
id(new AphrontFormSelectControl())
->setName('merchantPHID')
->setLabel(pht('Pay To Merchant'))
->setValue($v_merchant)
->setError($e_merchant)
->setOptions($merchant_options))
->appendChild(
id(new PhabricatorRemarkupControl())
->setName('description')
->setLabel(pht('Description'))
->setValue($v_desc))
->appendChild(
id(new PhabricatorRemarkupControl())
->setName('risks')
->setLabel(pht('Risks/Challenges'))
->setValue($v_risk))
->appendChild(
id(new AphrontFormTokenizerControl())
->setLabel(pht('Projects'))
->setName('projects')
->setValue($project_handles)
->setDatasource(new PhabricatorProjectDatasource()))
->appendChild(
id(new AphrontFormPolicyControl())
->setName('viewPolicy')
->setPolicyObject($initiative)
->setCapability(PhabricatorPolicyCapability::CAN_VIEW)
->setPolicies($policies))
->appendChild(
id(new AphrontFormPolicyControl())
->setName('editPolicy')
->setPolicyObject($initiative)
->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
->setPolicies($policies))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue($button_text)
->addCancelButton($cancel_uri));
$crumbs = $this->buildApplicationCrumbs();
if ($is_new) {
$crumbs->addTextCrumb(pht('Create Initiative'));
} else {
$crumbs->addTextCrumb(
$initiative->getMonogram(),
'/'.$initiative->getMonogram());
$crumbs->addTextCrumb(pht('Edit'));
}
$box = id(new PHUIObjectBoxView())
->setValidationException($validation_exception)
->setHeaderText($title)
->appendChild($form);
return $this->buildApplicationPage(
array(
$crumbs,
$box,
),
array(
'title' => $title,
));
}
}
| {
"content_hash": "70b489a44cb0e1ed400a392738b6821b",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 79,
"avg_line_length": 31.45945945945946,
"alnum_prop": 0.5937653411880216,
"repo_name": "huaban/phabricator",
"id": "b6b69945b6ea69e104cbe28ecf418c6e42ef4ccd",
"size": "8148",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/applications/fund/controller/FundInitiativeEditController.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "50788"
},
{
"name": "CSS",
"bytes": "284591"
},
{
"name": "JavaScript",
"bytes": "685398"
},
{
"name": "Makefile",
"bytes": "6426"
},
{
"name": "PHP",
"bytes": "10803685"
},
{
"name": "Python",
"bytes": "7385"
},
{
"name": "Shell",
"bytes": "8229"
}
],
"symlink_target": ""
} |
Public Class SettingsForm
Dim flag As Boolean = False
Private Sub SettingsForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, MyBase.Shown
NumericUpDown1.Value = decimalDigits
NumericUpDown2.Value = railLenght
End Sub
Private Sub decimalDigitsChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.Validated, NumericUpDown1.MouseCaptureChanged, NumericUpDown1.Leave, NumericUpDown1.Enter, NumericUpDown1.DoubleClick, NumericUpDown1.Click
decimalDigits = NumericUpDown1.Value
DataForm.writeData()
End Sub
Private Sub railLenghtChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown2.Validated, NumericUpDown2.MouseCaptureChanged, NumericUpDown2.Leave, NumericUpDown2.Enter, NumericUpDown2.DoubleClick, NumericUpDown2.Click
railLenght = NumericUpDown2.Value
For i = 1 To numberOfIntervals
DataForm.lenghtTexts(i).Maximum = railLenght
Next
DataForm.updateLenghts()
End Sub
End Class | {
"content_hash": "899c41a41e2c2f38ced0a57abf025a3b",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 259,
"avg_line_length": 38.10344827586207,
"alnum_prop": 0.7601809954751131,
"repo_name": "biosan/RaDAS",
"id": "c7f538cf7a5f20fab381f3224f6f0ec8cbec570b",
"size": "1107",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VB/RaDAS/SettingsForm.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "4558"
},
{
"name": "Visual Basic",
"bytes": "76194"
}
],
"symlink_target": ""
} |
id: security-architecture
title: Security Architecture
---
Hydra is built with tough security in mind.
<!-- toc -->
## OAuth 2.0 Security Overview
Hydra is an implementation of the security-first Fosite OAuth 2.0 SDK
([https://github.com/ory/fosite](https://github.com/ory/fosite)). Fosite
respects the
[OAuth 2.0 Threat Model and Security Considerations](https://tools.ietf.org/html/rfc6819#section-5.1.5.3)
by the IETF, specifically:
- No Cleartext Storage of Credentials
- Encryption of Credentials
- Use Short Expiration Time
- Limit Number of Usages or One-Time Usage
- Bind Token to Client id
- Automatic Revocation of Derived Tokens If Abuse Is Detected
- Binding of Refresh Token to "client_id"
- Refresh Token Rotation
- Revocation of Refresh Tokens
- Validate Pre-Registered "redirect_uri"
- Binding of Authorization "code" to "client_id"
- Binding of Authorization "code" to "redirect_uri"
- Opaque access tokens
- Opaque refresh tokens
- Ensure Confidentiality of Requests
- Use of Asymmetric Cryptography
- Enforcing random states: Without a random-looking state or OpenID Connect
nonce the request will fail.
Additionally these safeguards are implemented:
- Advanced Token Validation: Tokens are laid out as
<key>.<signature> where <signature> is created using
HMAC-SHA256 using a global secret.
### Advanced Token Validation (Datastore Security)
For a OAuth2 access token, refresh token or authorize code to be valid, one
requires both the key and the signature (formatted as
<key>.<signature>). Only the signature is stored in the datastore
(SQL), thus a compromised datastore will not allow an attacker to gain access to
any valid authorize codes, access tokens, or refresh tokens.
Because HMAC-SHA256 is used, the System Secret is required to create valid
key-signature pairs, rendering an attacker unable to inject new codes or tokens
into a compromised datastore.
## Cryptography
Hydra uses different cryptographic methods, this is an overview of all of them.
### AES-GCM
AES-GCM is used to encrypt JWKs at rest using a key size of 256 bit which
exceeds requirements by Lenstra, ECRYPT II, NIST, ANSSI, and BSI, see
[https://www.keylength.com/en/compare/](https://www.keylength.com/en/compare/).
GCM (Galois/Counter Mode) is an authenticated encryption algorithm designed to
provide both data authenticity (integrity) and confidentiality. GCM uses a nonce
(“IV”) that has an upper limit of 2^32 nonces. If more nonces are used, there is
risk of repeats. This means that you risk collisions when storing more than 2^32
documents authenticated with GCM. Because AES-GCM is only used to encrypt data
at rest, this is might only impose a problem if
1. more than 2^32 documents are stored using AES-GCM
2. an attacker gains access to the datastore where > 2^32 documents are
stored
3. the attacker is able to exploit repeats, for example by authenticating
malicious documents
### RS256
RSASSA-PKCS1-v1_5 using SHA-256 (RS256) is used to sign JWTs. Its use is
recommended by the JWA specification, see
[https://www.rfc-editor.org/rfc/rfc7518.txt](https://www.rfc-editor.org/rfc/rfc7518.txt)
The RSA Key size is 4096 bit long, exceeding the minimum requirement of 2048 bit
by
[https://www.rfc-editor.org/rfc/rfc7518.txt](https://www.rfc-editor.org/rfc/rfc7518.txt).
Recommendations from NIST, ANSSI, IAD-NSA, BSI, Lenstra and others vary between
1300 and 2048 bit key lengths for asymmetric cryptography based on discrete
logarithms (RSA). 4096 exceeds all recommendations for 2017 from all
authorities, see
[https://www.keylength.com/en/compare/](https://www.keylength.com/en/compare/).
### HMAC-SHA256
HMAC (FIPS 198) with SHA256 (FIPS 180-4) is used to sign access tokens,
authorize codes and refresh tokens. SHA-2 (with 256 bit) is encouraged by NIST,
see
[http://csrc.nist.gov/groups/ST/hash/policy.html](http://csrc.nist.gov/groups/ST/hash/policy.html)
### BCrypt
BCrypt is used to hash client credentials at rest. It is not officially
recommended by NIST as it is not based on hashing primitives such as SHA-2, but
rather on Blowfish. However, BCrypt is much stronger than any other (salted)
hashing method for passwords, has wide adoption and is an official golang/x
library.
I recommend reading this thread on Security Stack Exchange on BCrypt, SCrypt and
PBKDF2:
[https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage](https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage)
Be aware that BCrypt causes very high CPU loads, depending on the Workload
Factor. We strongly advise reducing the number of requests that use Basic
Authorization.
## How does Access Control work with Hydra?
See [OAuth 2.0 Token Introspection](guides/oauth2-token-introspection).
| {
"content_hash": "cfe289fcd67d5c2fafda75485134f95b",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 226,
"avg_line_length": 41.23728813559322,
"alnum_prop": 0.7792848335388409,
"repo_name": "ory-am/go-iam",
"id": "f2b742bb61323fc58e9f96dd0a68879e7211ec19",
"size": "4874",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/docs/security-architecture.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "240185"
},
{
"name": "Shell",
"bytes": "3143"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Entity;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\PreSerialize;
use JMS\Serializer\Annotation as Serialiser ;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class Project
*
* @package Entity
* @author Fondative <[email protected]>
* @copyright 2015-2016 Fondative
* @version 1.0.0
* @since Class available since Release 1.0.0
*
*/
/**
* Project
*
* @ExclusionPolicy("all")
* @ORM\Entity(repositoryClass="ProjectBundle\Repository\ProjetRepository")
* @ORM\Table(name="project")
* @ORM\Entity
*/
class Project
{
/**
* @Expose
* @var integer Id of the project
*
* @ORM\Column(name="idproject", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idproject;
/**
* @Expose
* @var string Name of the project
*
* @ORM\Column(name="name", type="string", length=45, nullable=true)
*/
private $name;
/**
* @Expose
* @var string Url of the project
*
* @ORM\Column(name="url", type="string", length=45, nullable=true)
*/
private $url;
/**
* @Expose
* @var string Status of the project
*
* @ORM\Column(name="status", type="string", length=45, nullable=true)
*/
private $status;
/**
* @Expose
* @var string Sttatus of the project
*
* @ORM\Column(name="description", type="string", length=45, nullable=true)
*/
private $description;
/**
* @var string Flag to delete a project
*
* @ORM\Column(name="is_deleted", type="string", length=45, nullable=true)
*/
private $isDeleted;
/**
* @Expose
* @var ArrayCollection $allFiles Project's Files
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\File", mappedBy="project", cascade = {"persist", "remove", "merge"})
* @Exclude
*/
private $allFiles;
/**
* @Expose
* @var ArrayCollection $allTestBooklet Projects 's TestBooklet
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\TestBooklet", mappedBy="project", cascade = {"persist"})
*
*
*/
private $allTestBooklet;
/**
* @Expose
* @var ArrayCollection $allBuilds Project'Builds
*
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Build", mappedBy="project", cascade = {"persist"})
* @ORM\OrderBy({"idbuild" = "DESC"})
* @Exclude
*/
private $allBuilds;
/**
*
* Set name
*
* @param string $name
*
* @return Project
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set url
*
* @param string $url
*
* @return Project
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set status
*
* @param string $status
*
* @return Project
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set description
*
* @param string $description
*
* @return Project
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set isDeleted
*
* @param string $isDeleted
*
* @return Project
*/
public function setIsDeleted($isDeleted)
{
$this->isDeleted = $isDeleted;
return $this;
}
/**
* Get isDeleted
*
* @return string
*/
public function getIsDeleted()
{
return $this->isDeleted;
}
/**
* Get idproject
*
* @return integer
*/
public function getIdproject()
{
return $this->idproject;
}
/**
* set idproject
*
* @param $id
* @return int
*/
public function setIdproject($id)
{
$this->idproject =$id;
return $this;
}
/**
* Add a file
* @param File $file
* @return $this
*/
public function addFile(File $file)
{
$this->allFiles[] = $file;
return $this;
}
/**
* Delete a file
* @param File $file
*/
public function removeFile(File $file)
{
$this->allFiles->removeElement($file);
}
/**
* Get files
* @return ArrayCollection
*/
public function getAllFiles()
{
return new ArrayCollection((array) $this->allFiles->toArray());
// return $this->allFiles;
}
/**
* Add s TestBooklet
*
* @param \AppBundle\Entity\TestBooklet $testBooklet
*
* @return Project
*/
public function addAllTestBooklet(\AppBundle\Entity\TestBooklet $testBooklet)
{
$this->allTestBooklet[] = $testBooklet;
return $this;
}
/**
* Remove a TestBooklet
*
* @param \AppBundle\Entity\TestBooklet $testBooklet
*/
public function removeAllTestBooklet(\AppBundle\Entity\TestBooklet $testBooklet)
{
$this->allTestBooklet->removeElement($testBooklet);
}
/**
* Get all testBooklet
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAllTestBooklet()
{
return $this->allTestBooklet;
}
/**
* Add a Build
*
* @param \AppBundle\Entity\Build $build
*
* @return Project
*/
public function addAllBuild(\AppBundle\Entity\Build $build)
{
$this->allBuilds[] = $build;
return $this;
}
/**
* Remove a Build
*
* @param \AppBundle\Entity\Build $build
*/
public function removeAllBuilds(\AppBundle\Entity\Build $build)
{
$this->allBuilds->removeElement($build);
}
/**
* Get all Builds
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAllBuild()
{
return $this->allBuilds;
}
/**
* Filter Builds
*
* @return \Doctrine\Common\Collections\Collection
*/
public function filterBuilds()
{
$builds= new ArrayCollection();
$builds= $this->allBuilds;
$this->allBuilds=new ArrayCollection();
foreach($builds as $build)
{
if($build->getIsDeleted()==0)
{
$this->allBuilds->add($build);
}
}
}
/**
* Project constructor.
*/
public function __construct()
{
$this->setIsDeleted("0");
$this->setStatus("open");
$this->allFiles = new ArrayCollection();
$this->allTestBooklet = new ArrayCollection();
$this->allBuilds= new ArrayCollection();
}
/**
* Set attributes before serialization
*
* @author Fondative <dev [email protected]>
* @PreSerialize
*/
public function beforeSerialization(){
$this->name=$this->getName();
$this->status= $this->getStatus();
$this->description=$this->getDescription();
$this->allTestBooklet=$this->getAllTestBooklet();
}
}
| {
"content_hash": "aa9089c417bc4912d2b288072be22a66",
"timestamp": "",
"source": "github",
"line_count": 404,
"max_line_length": 121,
"avg_line_length": 19.65841584158416,
"alnum_prop": 0.5498614958448753,
"repo_name": "abbeshamza/habtest",
"id": "9c43e497304ed626335cd54baf0c9aa814d35838",
"size": "8176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Entity/Project.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "470"
},
{
"name": "HTML",
"bytes": "2255396"
},
{
"name": "PHP",
"bytes": "843928"
},
{
"name": "Ruby",
"bytes": "928"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd
http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd">
<changeSet id="20161128-2344" author="gustavojotz">
<addColumn tableName="proprietario">
<column name="participa_sorteio" type="boolean" defaultValueBoolean="false">
<constraints nullable="false"/>
</column>
</addColumn>
</changeSet>
<changeSet id="20161130-2329" author="gustavojotz">
<addColumn tableName="proprietario">
<column name="dt_contemplacao" type="date" />
</addColumn>
</changeSet>
<changeSet id="20161201-1705" author="gustavojotz">
<preConditions onFail="MARK_RAN">
<columnExists tableName="proprietario" columnName="vaga_gerencial"/>
</preConditions>
<dropColumn tableName="proprietario" columnName="vaga_gerencial"/>
</changeSet>
<changeSet id="20161201-1708" author="gustavojotz">
<addColumn tableName="proprietario">
<column name="vaga_gerencial" type="boolean" defaultValueBoolean="false" />
</addColumn>
</changeSet>
<changeSet id="20161201-1710" author="gustavojotz">
<addColumn tableName="proprietario">
<column name="numero_vaga" type="varchar(32)" />
</addColumn>
</changeSet>
</databaseChangeLog> | {
"content_hash": "2325d614991443dc405a2f8784f0538e",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 133,
"avg_line_length": 43.275,
"alnum_prop": 0.659734257654535,
"repo_name": "gustajz/parking",
"id": "07b0eac8c8a6e7fd8d75ce48759d67e8590ccc8f",
"size": "1731",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/resources/db/1.1.0/changelog-01.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "13680"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Services;
using AdventureWorks.UILogic.Tests.Mocks;
using AdventureWorks.UILogic.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AdventureWorks.UILogic.Tests.ViewModels
{
[TestClass]
public class CheckoutHubPageViewModelFixture
{
[TestMethod]
public void ExecuteGoNextCommand_Validates3ViewModels()
{
bool shippingValidationExecuted = false;
bool billingValidationExecuted = false;
bool paymentValidationExecuted = false;
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => { shippingValidationExecuted = true; return false; }
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => { billingValidationExecuted = true; return false; }
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => { paymentValidationExecuted = true; return false; }
};
var target = new CheckoutHubPageViewModel(new MockNavigationService(), null, null, new MockShoppingCartRepository(),
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(shippingValidationExecuted);
Assert.IsTrue(billingValidationExecuted);
Assert.IsTrue(paymentValidationExecuted);
}
[TestMethod]
public void ExecuteGoNextCommand_ProcessesFormsAndNavigates_IfViewModelsAreValid()
{
bool shippingInfoProcessed = false;
bool billingInfoProcessed = false;
bool paymentInfoProcessed = false;
bool navigated = false;
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () =>
{
shippingInfoProcessed = true;
return Task.Delay(0);
}
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () =>
{
billingInfoProcessed = true;
return Task.Delay(0);
}
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () =>
{
paymentInfoProcessed = true;
await Task.Delay(0);
}
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo() { UserName = "test" }
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (a, b, c, d, e) => Task.FromResult(new Order() { Id = 1 })
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate = () => Task.FromResult(new ShoppingCart(null))
};
var navigationService = new MockNavigationService()
{
NavigateDelegate = (a, b) => navigated = true
};
var target = new CheckoutHubPageViewModel(navigationService, accountService, orderRepository, shoppingCartRepository,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(shippingInfoProcessed);
Assert.IsTrue(billingInfoProcessed);
Assert.IsTrue(paymentInfoProcessed);
Assert.IsTrue(navigated);
}
[TestMethod]
public void ExecuteGoNextCommand_DoNothing_IfViewModelsAreInvalid()
{
bool formProcessStarted = false;
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () =>
{
// The process starts with a call to retrieve the logged user
formProcessStarted = true;
return Task.FromResult(new UserInfo());
}
};
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel();
var billingAddressPageViewModel = new MockBillingAddressPageViewModel();
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel();
var target = new CheckoutHubPageViewModel(new MockNavigationService(), accountService, null, null,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
// ShippingAddress invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => false;
billingAddressPageViewModel.ValidateFormDelegate = () => true;
paymentMethodPageViewModel.ValidateFormDelegate = () => true;
target.GoNextCommand.Execute();
Assert.IsFalse(formProcessStarted);
// BillingAddress invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => true;
billingAddressPageViewModel.ValidateFormDelegate = () => false;
paymentMethodPageViewModel.ValidateFormDelegate = () => true;
Assert.IsFalse(formProcessStarted);
// PaymentMethod invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => true;
billingAddressPageViewModel.ValidateFormDelegate = () => true;
paymentMethodPageViewModel.ValidateFormDelegate = () => false;
Assert.IsFalse(formProcessStarted);
}
[TestMethod]
public void SettingUseShippingAddressToTrue_CopiesValuesFromShippingAddressToBilling()
{
var mockAddress = new Address()
{
FirstName = "TestFirstName",
MiddleInitial = "TestMiddleInitial",
LastName = "TestLastName",
StreetAddress = "TestStreetAddress",
OptionalAddress = "TestOptionalAddress",
City = "TestCity",
State = "TestState",
ZipCode = "123456",
Phone = "123456"
};
var compareAddressesFunc = new Func<Address, Address, bool>((Address a1, Address a2) =>
{
return a1.FirstName == a2.FirstName && a1.MiddleInitial == a2.MiddleInitial && a1.LastName == a2.LastName
&& a1.StreetAddress == a2.StreetAddress && a1.OptionalAddress == a2.OptionalAddress && a1.City == a2.City
&& a1.State == a2.State && a1.ZipCode == a2.ZipCode && a1.Phone == a2.Phone;
});
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = mockAddress
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true
};
billingAddressPageViewModel.ProcessFormAsyncDelegate = () =>
{
// The Address have to be updated before the form is processed
Assert.IsTrue(compareAddressesFunc(shippingAddressPageViewModel.Address, billingAddressPageViewModel.Address));
return Task.Delay(0);
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () => await Task.Delay(0),
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo()
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (userId, shoppingCart, shippingAddress, billingAddress, paymentMethod) =>
{
// The Address information stored in the order must be the same
Assert.IsTrue(compareAddressesFunc(shippingAddress, billingAddress));
return Task.FromResult<Order>(new Order());
}
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate = () => Task.FromResult(new ShoppingCart(null))
};
var navigationService = new MockNavigationService()
{
NavigateDelegate = (a, b) => true
};
var target = new CheckoutHubPageViewModel(navigationService, accountService, orderRepository, shoppingCartRepository,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.UseSameAddressAsShipping = true;
target.GoNextCommand.Execute();
}
[TestMethod]
public void ProcessFormAsync_WithServerValidationError_ShowsMessage()
{
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = new Address()
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = new Address()
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () => await Task.Delay(0),
PaymentMethod = new PaymentMethod()
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo()
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate =
() => Task.FromResult(new ShoppingCart(null))
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (s, cart, arg3, arg4, arg5) =>
{
var result = new ModelValidationResult();
result.ModelState.Add("order.ShippingAddress.ZipCode", new List<string>{"Validation Message"});
throw new ModelValidationException(result);
}
};
var target = new CheckoutHubPageViewModel(new MockNavigationService(), accountService, orderRepository, shoppingCartRepository, shippingAddressPageViewModel,
billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(target.IsShippingAddressInvalid);
}
}
}
| {
"content_hash": "ee60405aa16ae22aa87d4d2b0a26d969",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 169,
"avg_line_length": 49.56666666666667,
"alnum_prop": 0.5332885003362475,
"repo_name": "PrismLibrary/Prism-Samples-Windows",
"id": "f3fd23c863732388a761ac8483b1cd176255b017",
"size": "13383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AdventureWorks.Shopper/AdventureWorks.UILogic.Tests/ViewModels/CheckoutHubPageViewModelFixture.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "117"
},
{
"name": "C#",
"bytes": "820673"
}
],
"symlink_target": ""
} |
/**
* Status of different components
* Tells us which which components are loaded so we can start the server
*/
// Wowwie, I've been scared of OOP for all my life (more like 5 years .. thats a lot :'( ) and now I realize how cool and powerful it is
//? AmIDoingThisRite?
//? Why am I trying to use javadoc'ish block comments so incorrectly (above, not below)? And ... im not even doing it right. How should I comment instead?
// Arguments: items - Array of items to populate this.items
//? Bad argument naming? Two "items"
module.exports = function statusItem(items) {
this.items = {};
this.onlineItems = 0; // Number of online components
this.totalItems = 0; // Total number of components
this.allOnline = false;
if (typeof items == 'object') {
for (var key in items) {
this.items[items[key]] = false;
}
}
this.update();
}
// Returns status
module.exports.prototype.update = function(item, status) {
// Add new item if defined
if (typeof item !== 'undefined' && typeof status !== 'undefined') {
if (!(item in this.items)) {
throw new Error('Component "' + component + '" doesn\'t exist');
} else {
this.items[item] = status; //? Hey, should we typecast this into Boolean or do we trust that we don't mess things up by accidentally (0.01% chance) putting in a number or something else? Maybe for our purposes, it isn't important but for a public api, it would?
}
}
this.totalItems = Object.size(this.items); //? Is there any way to be able to call Object
// Update online count
this.onlineItems = 0;
for (var key in this.items) {
if (this.items[key] == true)
this.onlineItems += 1;
}
if (this.onlineItems == this.totalItems)
this.allOnline = true;
// Return status report
if (status == true) {
var report = 'ready';
} else {
var report = 'offline';
}
return '"' + item + '" is now ' + report + '. [' + this.onlineItems + '/' + this.totalItems + ']';
} | {
"content_hash": "bfff49d5ac875e1399a13c45ad3920c1",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 267,
"avg_line_length": 33.91379310344828,
"alnum_prop": 0.6517539400101677,
"repo_name": "irisli/crowd-prediction-pool",
"id": "ea29244d77cdcd059402ed0a70b8e04f75ac476c",
"size": "1967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/statusitem.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2929"
},
{
"name": "JavaScript",
"bytes": "37640"
}
],
"symlink_target": ""
} |
package com.newsblur.fragment;
import android.os.Bundle;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.newsblur.R;
import com.newsblur.database.BlurDatabaseHelper;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefConstants;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class SettingsFragment extends PreferenceFragmentCompat {
@Inject
BlurDatabaseHelper dbHelper;
private Preference deleteOfflineStoriesPref;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(PrefConstants.PREFERENCES);
setPreferencesFromResource(R.xml.activity_settings, rootKey);
deleteOfflineStoriesPref = findPreference(getString(R.string.menu_delete_offline_stories_key));
if (deleteOfflineStoriesPref != null) {
deleteOfflineStoriesPref.setOnPreferenceClickListener(preference -> {
deleteOfflineStories();
return true;
});
}
}
private void deleteOfflineStories() {
if (deleteOfflineStoriesPref != null) {
deleteOfflineStoriesPref.setOnPreferenceClickListener(null);
deleteOfflineStoriesPref.setSummary("");
deleteOfflineStoriesPref.setTitle(R.string.menu_delete_offline_stories_confirmation);
dbHelper.deleteStories();
NBSyncService.forceFeedsFolders();
FeedUtils.triggerSync(requireContext());
}
}
} | {
"content_hash": "e193cd121a7958f86b0a1fcc3077592e",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 103,
"avg_line_length": 33.35849056603774,
"alnum_prop": 0.7369909502262444,
"repo_name": "samuelclay/NewsBlur",
"id": "2e21d3bba0cea95ccb37d93f7c0ac42d828f2ee3",
"size": "1768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clients/android/NewsBlur/src/com/newsblur/fragment/SettingsFragment.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "454"
},
{
"name": "CSS",
"bytes": "776813"
},
{
"name": "CoffeeScript",
"bytes": "13093"
},
{
"name": "Dockerfile",
"bytes": "3704"
},
{
"name": "HCL",
"bytes": "29303"
},
{
"name": "HTML",
"bytes": "1921563"
},
{
"name": "Java",
"bytes": "853216"
},
{
"name": "JavaScript",
"bytes": "1803770"
},
{
"name": "Jinja",
"bytes": "89121"
},
{
"name": "Kotlin",
"bytes": "298281"
},
{
"name": "Makefile",
"bytes": "8909"
},
{
"name": "Objective-C",
"bytes": "2565934"
},
{
"name": "Perl",
"bytes": "55606"
},
{
"name": "Python",
"bytes": "2067295"
},
{
"name": "R",
"bytes": "527"
},
{
"name": "Ruby",
"bytes": "2094"
},
{
"name": "SCSS",
"bytes": "47069"
},
{
"name": "Shell",
"bytes": "51526"
},
{
"name": "Swift",
"bytes": "136021"
}
],
"symlink_target": ""
} |
host_pattern=^.*\..*$
protocol_pattern=\/\/
ssh_pattern=^.*@.*\..*:.*$
# Check for git
git --version > /dev/null 2>&1
GIT_INSTALLED=$?
[[ $GIT_INSTALLED -ne 0 ]] && { echo "Install git before executing this script."; exit 0; }
test_init=false
while getopts ":t" opt; do
case $opt in
t) test_init=true;;
\?) echo "Invalid option: -$OPTARG" >&2; exit 1;;
esac
done
# Get input for Git
if [[ $test_init == false ]]; then
repo_url=""
while [[ $repo_url == false ]] || [[ ! $repo_url =~ $ssh_pattern ]]; do
if [[ $repo_url != "" ]]; then
echo "Invalid Git SSH URL"
fi
read -p "Enter Git SSH URL: " repo_url
done
fi
# Get input for configs
dev_api_host=""
while [[ ! $dev_api_host =~ $host_pattern ]] || [[ $dev_api_host =~ $protocol_pattern ]]; do
read -p "Enter Dev API Host [api.project.vm]: " dev_api_host
done
qa_api_host=""
while [[ ! $qa_api_host =~ $host_pattern ]] || [[ $qa_api_host =~ $protocol_pattern ]]; do
read -p "Enter QA API Host [api-project-com.example.com]: " qa_api_host
done
production_api_host=""
while [[ ! $production_api_host =~ $host_pattern ]] || [[ $production_api_host =~ $protocol_pattern ]]; do
read -p "Enter Production API Host [api.project.com]: " production_api_host
done
# Confirm settings are correct
echo -e "\n"
if [[ $test_init == false ]]; then
echo -e "Git URL\t\t\t$repo_url"
fi
echo -e "Dev API Host\t\t$dev_api_host"
echo -e "QA API Host\t\t$qa_api_host"
echo -e "Production API Host\t$production_api_host"
echo -e "\n"
read -p "Are these settings correct? " confirm
if [[ $confirm =~ ^[yY] ]]; then
if [[ $test_init == false ]]; then
# Intialize new git repo
set -e
rm -rf .git
git init
git remote add origin $repo_url
git checkout -b master
fi
echo "Updating config files"
sed -i "" s/%DEV_API_HOST%/$dev_api_host/g "./application/config/config.development.js"
sed -i "" s/%QA_API_HOST%/$qa_api_host/g "./application/config/config.qa.js"
sed -i "" s/%PRODUCTION_API_HOST%/$production_api_host/g "./application/config/config.production.js"
if [[ $test_init == false ]]; then
rm initialize.sh
fi
else
echo "Initialization cancelled"
fi
| {
"content_hash": "9c3c15e87551871bd7ac2f79f1c75b43",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 106,
"avg_line_length": 27.2625,
"alnum_prop": 0.6226501604768455,
"repo_name": "dcpages/dcLibrary-Template",
"id": "1a19795d6923b5d98965286073252744d73c0472",
"size": "2193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "initialize.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50587"
},
{
"name": "JavaScript",
"bytes": "33715"
},
{
"name": "Shell",
"bytes": "2193"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d6704dbdb0ac24b6d85318df6b66f496",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "05a3c63dbd7fa09d5695d5b131ce68d06129e974",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium pervagiforme/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using Codeer.Friendly;
using Friendly.XamControls.Inside;
using System;
using System.Collections.Generic;
using Codeer.TestAssistant.GeneratorToolKit;
namespace Friendly.XamControls
{
[ControlDriver(TypeFullName = "Infragistics.Controls.Editors.XamCalendar")]
public class XamCalendarDriver : XamControlBase
{
public DateTime? ActiveDate { get { return This.ActiveDate; } }
public DateTime[] SelectedDates { get { return Static.GetSelectedDates(this); } }
public XamCalendarDriver(AppVar src) : base(src) { }
public void EmulateChangeDate(DateTime? date)
{
Static.EmulateChangeDate(this, date);
}
public void EmulateChangeDate(DateTime? date, Async async)
{
Static.EmulateChangeDate(this, date, async);
}
static void EmulateChangeDate(dynamic calendar, DateTime? date)
{
calendar.Focus();
calendar.SelectedDate = date;
calendar.ActiveDate = date;
}
public void EmulateAddDate(DateTime date)
{
Static.EmulateAddDate(this, date);
}
public void EmulateAddDate(DateTime date, Async async)
{
Static.EmulateAddDate(this, date, async);
}
public void EmulateRemoveDate(DateTime date)
{
Static.EmulateRemoveDate(this, date);
}
public void EmulateRemoveDate(DateTime date, Async async)
{
Static.EmulateRemoveDate(this, date, async);
}
static void EmulateAddDate(dynamic calendar, DateTime date)
{
calendar.Focus();
calendar.BringDateIntoView(date);
calendar.SelectedDates.Add(date);
calendar.ActiveDate = date;
}
static void EmulateRemoveDate(dynamic calendar, DateTime date)
{
calendar.Focus();
calendar.BringDateIntoView(date);
calendar.SelectedDates.Remove(date);
}
static DateTime[] GetSelectedDates(dynamic calendar)
{
var list = new List<DateTime>();
foreach (var e in calendar.SelectedDates)
{
list.Add(e);
}
return list.ToArray();
}
}
}
| {
"content_hash": "e2472c604ac3d01c917e12b973295f34",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 89,
"avg_line_length": 28.725,
"alnum_prop": 0.5970409051348999,
"repo_name": "Codeer-Software/Friendly.XamControls",
"id": "bb4aad0fa5fb8d9da6acb796cead2157dafc7c28",
"size": "2300",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Project/Friendly.XamControls/XamCalendarDriver.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "129567"
},
{
"name": "Smalltalk",
"bytes": "24870"
}
],
"symlink_target": ""
} |
<div class="odo-carousel">
<div class="odo-carousel__wrapper">
<div class="odo-carousel__element">
<div class="odo-carousel__slide"></div>
<div class="odo-carousel__slide"></div>
<div class="odo-carousel__slide"></div>
<div class="odo-carousel__slide"></div>
</div>
</div>
</div>
| {
"content_hash": "59e4c2cb0717e894302eab618b9eb8b3",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 45,
"avg_line_length": 31.6,
"alnum_prop": 0.5949367088607594,
"repo_name": "odopod/code-library",
"id": "03d957fc629ad26ca82f5b4ff9b0ec4e9a5fc30f",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/odo-carousel/test/fixtures/looped-4-slides.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "124575"
},
{
"name": "HTML",
"bytes": "426878"
},
{
"name": "JavaScript",
"bytes": "861836"
}
],
"symlink_target": ""
} |
const base = require('./karma.conf.js');
const webpack = base.webpackConfig;
const files = base.files.concat(base.helperGlobs).concat(base.unitGlobs).concat(
base.integrationGlobs
);
const wp = ['webpack'];
const preprocessors = files.concat(base.srcGlobs).reduce((acc, key) => {
acc[key] = wp;
return acc;
}, {});
module.exports = function(config) {
base(config);
config.set({files, preprocessors, webpack});
};
| {
"content_hash": "e5dcc2f01778458f4afb2b43ce4a56fd",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 80,
"avg_line_length": 28.266666666666666,
"alnum_prop": 0.6981132075471698,
"repo_name": "mdittmer/smw",
"id": "11630fbb652e2c50f948a3a768db450249a41f48",
"size": "424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/karma.all.conf.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1807"
},
{
"name": "JavaScript",
"bytes": "110050"
},
{
"name": "Shell",
"bytes": "382"
}
],
"symlink_target": ""
} |
package com.github.wz2cool.dynamic.mybatis.mapper;
import com.github.wz2cool.dynamic.GroupedQuery;
import com.github.wz2cool.dynamic.helper.CommonsHelper;
import com.github.wz2cool.dynamic.lambda.*;
import com.github.wz2cool.dynamic.mybatis.QueryHelper;
import com.github.wz2cool.dynamic.mybatis.TypeHelper;
import com.github.wz2cool.dynamic.mybatis.mapper.constant.MapperConstants;
import com.github.wz2cool.dynamic.mybatis.mapper.provider.GroupedQueryProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.session.RowBounds;
import tk.mybatis.mapper.annotation.RegisterMapper;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
/**
* @author Frank
**/
@RegisterMapper
@SuppressWarnings("java:S119")
public interface SelectMaxByGroupedQueryMapper<T> {
QueryHelper QUERY_HELPER = new QueryHelper();
/**
* Select max value of column by dynamic query.
*
* @param column the column need get max value
* @param groupedQuery grouped query
* @return max value of column.
*/
@SelectProvider(type = GroupedQueryProvider.class, method = "dynamicSQL")
<TSelect extends Comparable> List<Object> selectMaxByGroupedQuery(
@Param(MapperConstants.COLUMN) String column,
@Param(MapperConstants.GROUPED_QUERY) GroupedQuery<T, TSelect> groupedQuery);
/**
* Select max value of column by dynamic query.
*
* @param column the column need get max value
* @param groupedQuery grouped query
* @return max value of column.
*/
@SelectProvider(type = GroupedQueryProvider.class, method = "dynamicSQL")
<TSelect extends Comparable> List<Object> selectMaxRowBoundsByGroupedQuery(
@Param(MapperConstants.COLUMN) String column,
@Param(MapperConstants.GROUPED_QUERY) GroupedQuery<T, TSelect> groupedQuery,
RowBounds rowBounds);
default <TSelect extends Comparable> List<Object> selectMaxByGroupedQueryInternal(
GetPropertyFunction<T, TSelect> getPropertyFunction, GroupedQuery<T, TSelect> groupedQuery) {
String propertyName = CommonsHelper.getPropertyName(getPropertyFunction);
Class<T> queryClass = groupedQuery.getQueryClass();
String queryColumn = QUERY_HELPER.getQueryColumnByProperty(queryClass, propertyName);
return selectMaxByGroupedQuery(queryColumn, groupedQuery);
}
default <TSelect extends Comparable> List<Object> selectMaxByGroupedQueryInternal(
GetPropertyFunction<T, TSelect> getPropertyFunction, GroupedQuery<T, TSelect> groupedQuery,
RowBounds rowBounds) {
String propertyName = CommonsHelper.getPropertyName(getPropertyFunction);
Class<T> queryClass = groupedQuery.getQueryClass();
String queryColumn = QUERY_HELPER.getQueryColumnByProperty(queryClass, propertyName);
return selectMaxRowBoundsByGroupedQuery(queryColumn, groupedQuery, rowBounds);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bounds
* @return max value of property.
*/
default List<BigDecimal> selectMaxByGroupedQuery(
GetBigDecimalPropertyFunction<T> getPropertyFunction,
GroupedQuery<T, BigDecimal> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<BigDecimal> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getBigDecimal(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Byte> selectMaxByGroupedQuery(
GetBytePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Byte> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Byte> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getByte(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Byte> selectMaxByGroupedQuery(
GetBytePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Byte> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bounds
* @return max value of property.
*/
default List<Date> selectMaxByGroupedQuery(
GetDatePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Date> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Date> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getDate(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Date> selectMaxByGroupedQuery(
GetDatePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Date> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bounds
* @return max value of property.
*/
default List<Double> selectMaxByGroupedQuery(
GetDoublePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Double> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Double> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getDouble(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Double> selectMaxByGroupedQuery(
GetDoublePropertyFunction<T> getPropertyFunction, GroupedQuery<T, Double> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bounds
* @return max value of property.
*/
default List<Float> selectMaxByGroupedQuery(
GetFloatPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Float> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Float> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getFloat(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Float> selectMaxByGroupedQuery(
GetFloatPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Float> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Integer> selectMaxByGroupedQuery(
GetIntegerPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Integer> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Integer> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getInteger(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Integer> selectMaxByGroupedQuery(
GetIntegerPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Integer> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Long> selectMaxByGroupedQuery(
GetLongPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Long> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Long> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getLong(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Long> selectMaxByGroupedQuery(
GetLongPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Long> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bonds
* @return max value of property.
*/
default List<Short> selectMaxByGroupedQuery(
GetShortPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Short> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<Short> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getShort(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<Short> selectMaxByGroupedQuery(
GetShortPropertyFunction<T> getPropertyFunction, GroupedQuery<T, Short> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @param rowBounds row bounds
* @return max value of property.
*/
default List<String> selectMaxByGroupedQuery(
GetStringPropertyFunction<T> getPropertyFunction, GroupedQuery<T, String> groupedQuery,
RowBounds rowBounds) {
List<Object> objects = rowBounds == null ?
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery) :
selectMaxByGroupedQueryInternal(getPropertyFunction, groupedQuery, rowBounds);
List<String> result = new ArrayList<>();
if (objects.isEmpty()) {
return result;
}
for (Object object : objects) {
Optional.ofNullable(TypeHelper.getString(object))
.ifPresent(result::add);
}
return result;
}
/**
* Select max value of property by dynamic query.
*
* @param getPropertyFunction the property need get max value
* @param groupedQuery grouped query.
* @return max value of property.
*/
default List<String> selectMaxByGroupedQuery(
GetStringPropertyFunction<T> getPropertyFunction, GroupedQuery<T, String> groupedQuery) {
return selectMaxByGroupedQuery(getPropertyFunction, groupedQuery, null);
}
}
| {
"content_hash": "31a4c87d8ab613ae1684a1c004e5b4b6",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 105,
"avg_line_length": 39.92602040816327,
"alnum_prop": 0.6560603156347837,
"repo_name": "wz2cool/mybatis-dynamic-query",
"id": "8f5a558a3027c5c8ab5c52a792a9ad897f942021",
"size": "15651",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/wz2cool/dynamic/mybatis/mapper/SelectMaxByGroupedQueryMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "495567"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b8c7fdb15fbf1c5e1f84fec5a3ca2259",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "ec2b14b6ef5b702687745c614fc2d91b98c283ad",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Arabis/Arabis alpina/ Syn. Arabis cuneifolia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import React, { useRef } from 'react';
import { Text } from 'native-base';
import { View, Image, NativeSyntheticEvent, ScrollViewProps } from 'react-native';
import { HeaderComponent } from '../main/header_component';
import { colors, textStyles, themedStyles } from '../../application/styles';
import { BackButtonComponent } from '../header_button/back_button_component';
import { mbStartBackground, mbStartLogoSquare } from '../../application/images';
import { Trans } from '@lingui/react';
import { Link } from '../link/link_component';
import { ScrollView } from 'react-native-gesture-handler';
import { OffsetHook, useOffset } from '../use_offset';
import { useScrollViewToOffset } from '../use_scroll_view_to_offset';
import { useTheme } from '../main/context_component';
export const MBStartComponent = (): JSX.Element => {
const scrollViewRef = useRef<ScrollView>();
const { setOffset, offsetFromRouteLocation }: OffsetHook = useOffset();
// tslint:disable-next-line: no-expression-statement
useScrollViewToOffset(scrollViewRef, offsetFromRouteLocation);
const theme = useTheme();
const scrollViewThrottle = 8;
const aspectRatio = 360 / 180;
const mbStartUrl = 'https://manitobastart.com/';
return (
<View style={{ flex: 1 }}>
<HeaderComponent
backgroundColor={colors.lightGrey}
statusBarColour={colors.lightGrey}
leftButton={<BackButtonComponent textColor={colors.black} />}
rightButtons={[]}
/>
<ScrollView
ref={scrollViewRef}
onScroll={(e: NativeSyntheticEvent<ScrollViewProps>): void => setOffset(e.nativeEvent.contentOffset.y)}
scrollEventThrottle={scrollViewThrottle}
>
<Image
source={mbStartBackground}
resizeMode='contain'
style={{height: undefined, width: '100%', aspectRatio}}
/>
<View style={{ top: -60, marginHorizontal: 24 }}>
<Image
source={mbStartLogoSquare}
style={{height: 120, width: 120, borderColor: colors.lightGrey, borderRadius: 8, borderWidth: 4}}
/>
<Text style={[textStyles.headlineH1StyleBlackLeft, { paddingTop: 24 }]}>Manitoba Start</Text>
<Text style={[textStyles.paragraphStyle, { paddingTop: 16 }]}>
<Trans>Manitoba Start provides central registration and needs assessment for all newcomers arriving to Winnipeg/Manitoba.
It is an important step to register through Manitoba Start then you will be connected to language services and other
settlement agencies in your area.Manitoba Start can help internationally educated and skilled newcomers
with credential recognition and employment preparation/opportunities.</Trans>
</Text>
<Link href={mbStartUrl} style={[themedStyles(theme).link, { paddingTop: 16 }]}>manitobastart.com</Link>
</View>
</ScrollView>
</View>
);
};
| {
"content_hash": "c7ae1fdb91f910dc213d395461ecf527",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 145,
"avg_line_length": 53.983333333333334,
"alnum_prop": 0.6122259956776783,
"repo_name": "pg-irc/pathways-frontend",
"id": "5ea9333003d0589019f970dc45aa423a3ac990aa",
"size": "3239",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/components/mb_start/mb_start_component.tsx",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "6657"
},
{
"name": "Python",
"bytes": "1572"
},
{
"name": "Shell",
"bytes": "20183"
},
{
"name": "TypeScript",
"bytes": "1198904"
}
],
"symlink_target": ""
} |
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([REAppDelegate class]));
}
}
| {
"content_hash": "659653fe52fcbd0e7fc1e2b7621dca20",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 92,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.6625,
"repo_name": "rafaecheve/REGooglePlacesAPI",
"id": "1ce08dc5c22f7b2eb1470ba452726646ac8398c0",
"size": "356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "REGooglePlacesAPI/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "53248"
},
{
"name": "C++",
"bytes": "7459"
},
{
"name": "Objective-C",
"bytes": "844120"
},
{
"name": "Ruby",
"bytes": "147"
},
{
"name": "Shell",
"bytes": "3552"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bull. trimest. Soc. mycol. Fr. 54(1): 134 (1938)
#### Original name
Russula insignis Quél., 1888
### Remarks
null | {
"content_hash": "9208e4ccb20c94b6a51b1092dc0c867a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 48,
"avg_line_length": 13.615384615384615,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "a8c2aecf9893908664d9cabb61efefc38fe26a35",
"size": "230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Russulaceae/Russula/Russula burlinghamiae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
CREATE OR REPLACE FUNCTION @extschema@._CDB_GetConfAnalysisQuotaFactor()
RETURNS float8 AS
$$
BEGIN
RETURN @[email protected]_Conf_GetConf('analysis_quota_factor')::text::float8;
END;
$$ LANGUAGE 'plpgsql'
STABLE
PARALLEL SAFE
SECURITY DEFINER
SET search_path = pg_temp;
-- Get the factor (fraction of the quota) for Camshaft cached analysis tables
CREATE OR REPLACE FUNCTION @extschema@._CDB_AnalysisQuotaFactor()
RETURNS float8 AS
$$
DECLARE
factor float8;
BEGIN
-- We use a floating point cdb_conf parameter
factor := @extschema@._CDB_GetConfAnalysisQuotaFactor();
-- With a default value
IF factor IS NULL THEN
factor := 2;
END IF;
RETURN factor;
END;
$$
LANGUAGE 'plpgsql' STABLE PARALLEL SAFE;
-- This checks the space used up by Camshaft cached analysis tables.
-- An exception will be raised if the limits are exceeded.
-- The name of an analysis table is passed; this, in addition to the
-- db role that executes this function is used to determined which
-- analysis tables will be considered.
CREATE OR REPLACE FUNCTION @[email protected]_CheckAnalysisQuota(table_name TEXT)
RETURNS void AS
$$
DECLARE
schema_name TEXT;
user_name TEXT;
nominal_quota int8;
cache_size float8;
BEGIN
-- We rely on the search_path to determine the user's schema and
-- check for all analysis tables in that schema.
-- An alternative would be to use cdb_analysis_catalog to
-- select analysis tables (cache_tables) from the same user, analysis or node.
-- For example:
-- SELECT unnest(cache_tables) FROM cdb_analysis_catalog
-- WHERE username IN (SELECT username FROM cdb_analysis_catalog
-- WHERE table_name::regclass = ANY (cache_tables));
-- At the moment we're not using the provided table_name.
SELECT current_schema() INTO schema_name;
EXECUTE FORMAT('SELECT %I._CDB_UserQuotaInBytes();', schema_name) INTO nominal_quota;
IF nominal_quota * @extschema@._CDB_AnalysisQuotaFactor() < @extschema@._CDB_AnalysisDataSize(schema_name) THEN
-- The limit is defined by a factor applied to the total space quota for the user
RAISE EXCEPTION 'Analysis cache space limits exceeded';
END IF;
END;
$$ LANGUAGE PLPGSQL VOLATILE PARALLEL UNSAFE;
| {
"content_hash": "e574c269cc08fe04f64a14231ee53227",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 113,
"avg_line_length": 35.17460317460318,
"alnum_prop": 0.7369133574007221,
"repo_name": "CartoDB/cartodb-postgresql",
"id": "9800f7d8a5450047d896f9f13bd756b5a23353bb",
"size": "2350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts-available/CDB_AnalysisCheck.sql",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "5238"
},
{
"name": "PLpgSQL",
"bytes": "324059"
},
{
"name": "Ruby",
"bytes": "1398"
},
{
"name": "Shell",
"bytes": "52968"
}
],
"symlink_target": ""
} |
require 'spec_helper'
require 'wordalator/wdlt'
module Wordalator
describe WDLT do
describe 'parse' do
let(:w) { WDLT.new(query) }
context 'when only one sentence exists' do
let(:query) { ['What is 10 divided by 2?'] }
it 'should return the correct result' do
expect(w.parse).to eq 5
end
end
context 'when there are multiple operators in one sentence' do
let(:query) { ['What is 4 plus 10 divided by 2?'] }
it 'should return the correct results' do
expect(w.parse).to eq 7
end
end
context 'when there are multiple sentences' do
let(:query) { ['What is 10 divided by 2?','What is 4 plus 10 divided by 2?',' What is 4 to the 2nd power?'] }
it 'should return the correct results' do
expect(w.parse).to eq [5, 7, 16]
end
end
context 'when the solution is a decimal number' do
let(:query) { ['What is 4 plus 10 plus 5 divided by 2?'] }
it 'should return the correct results' do
expect(w.parse).to eq 9.5
end
end
context 'when the solution is a decimal number' do
let(:query) { ['What is 4 plus 10 plus 5 divided by 2?'] }
it 'should return the correct results' do
expect(w.parse).to eq 9.5
end
end
context 'when there are too few numbers' do
let(:query) { ['What is 5 minus?'] }
it 'should raise an error' do
lambda {w.parse}.should raise_error(ArgumentError)
end
end
context 'when there are too few operators' do
let(:query) { ['What is 5 2?'] }
it 'should raise an error' do
lambda {w.parse}.should raise_error(ArgumentError)
end
end
end
end
end | {
"content_hash": "c95f0a4f7d3564a1a186f3f97699f0c9",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 117,
"avg_line_length": 27.227272727272727,
"alnum_prop": 0.577072899276572,
"repo_name": "okoyea/wordalator",
"id": "89d79f73fd3f23cfd5cc2466b0445884e69d5ffc",
"size": "1797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/lib/wdlt_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7996"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCoreDemoApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvcCore()
.AddCors()
.AddJsonFormatters();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app
.UseDefaultFiles()
.UseStaticFiles()
.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
)
.UseMvcWithDefaultRoute();
if (env.IsProduction())
{
Console.WriteLine("https");
var options = new RewriteOptions()
.AddRedirectToHttpsPermanent();
app.UseRewriter(options);
}
}
}
} | {
"content_hash": "def3b49d2be28f765f59f5a9b0e31562",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 27.452380952380953,
"alnum_prop": 0.5160450997398092,
"repo_name": "jincod/AspNet5DemoApp",
"id": "0a90944debf9af1eb8c809cea2fffdf9d60529eb",
"size": "1153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AspNetCoreDemoApp/Startup.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1657"
},
{
"name": "CSS",
"bytes": "27"
},
{
"name": "HTML",
"bytes": "580"
},
{
"name": "JavaScript",
"bytes": "986"
},
{
"name": "Shell",
"bytes": "79"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center">
<ProgressBar android:id="@android:id/text1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout><!-- From: file:/Users/fjunya/AndroidStudioProjects/Antena/Application/src/main/res/layout/listview_footer.xml --> | {
"content_hash": "1ce2932e9dfc2b91c2e5898760d2b450",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 129,
"avg_line_length": 52.61538461538461,
"alnum_prop": 0.7470760233918129,
"repo_name": "fjunya/Antena_Android",
"id": "0a8db4a73a387da426b6cd615b06f7e7df7460b5",
"size": "684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Application/build/intermediates/res/debug/layout/listview_footer.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "66330"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Depositante">
<item
android:id="@+id/action_settings"
android:title="@string/desconectar"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
| {
"content_hash": "6f19727e59f985d9321dd35f401cb448",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 33.3,
"alnum_prop": 0.6606606606606606,
"repo_name": "danibasauri/persistencia-practica-1",
"id": "37631edf667a5d70fc1ba55bc210e46b2c565763",
"size": "333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EcoParque/src/main/res/menu/depositante.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AssemblyInfoParams - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>AssemblyInfoParams</h1>
<div class="xmldoc">
</div>
<h3>Record Fields</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Record Field</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '997', 997)" onmouseover="showTip(event, '997', 997)">
AssemblyCompany
</code>
<div class="tip" id="997">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L27-27" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '998', 998)" onmouseover="showTip(event, '998', 998)">
AssemblyConfiguration
</code>
<div class="tip" id="998">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L26-26" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '999', 999)" onmouseover="showTip(event, '999', 999)">
AssemblyCopyright
</code>
<div class="tip" id="999">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L29-29" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1000', 1000)" onmouseover="showTip(event, '1000', 1000)">
AssemblyCulture
</code>
<div class="tip" id="1000">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L31-31" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1001', 1001)" onmouseover="showTip(event, '1001', 1001)">
AssemblyDelaySign
</code>
<div class="tip" id="1001">
<strong>Signature:</strong> bool option<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L37-37" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1002', 1002)" onmouseover="showTip(event, '1002', 1002)">
AssemblyDescription
</code>
<div class="tip" id="1002">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L25-25" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1003', 1003)" onmouseover="showTip(event, '1003', 1003)">
AssemblyFileVersion
</code>
<div class="tip" id="1003">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L33-33" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1004', 1004)" onmouseover="showTip(event, '1004', 1004)">
AssemblyInformationalVersion
</code>
<div class="tip" id="1004">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L34-34" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1005', 1005)" onmouseover="showTip(event, '1005', 1005)">
AssemblyKeyFile
</code>
<div class="tip" id="1005">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L35-35" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1006', 1006)" onmouseover="showTip(event, '1006', 1006)">
AssemblyKeyName
</code>
<div class="tip" id="1006">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L36-36" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1007', 1007)" onmouseover="showTip(event, '1007', 1007)">
AssemblyProduct
</code>
<div class="tip" id="1007">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L28-28" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1008', 1008)" onmouseover="showTip(event, '1008', 1008)">
AssemblyTitle
</code>
<div class="tip" id="1008">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L24-24" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1009', 1009)" onmouseover="showTip(event, '1009', 1009)">
AssemblyTrademark
</code>
<div class="tip" id="1009">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L30-30" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1010', 1010)" onmouseover="showTip(event, '1010', 1010)">
AssemblyVersion
</code>
<div class="tip" id="1010">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L32-32" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1011', 1011)" onmouseover="showTip(event, '1011', 1011)">
CLSCompliant
</code>
<div class="tip" id="1011">
<strong>Signature:</strong> bool option<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L21-21" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1012', 1012)" onmouseover="showTip(event, '1012', 1012)">
CodeLanguage
</code>
<div class="tip" id="1012">
<strong>Signature:</strong> CodeLanguage<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L23-23" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1013', 1013)" onmouseover="showTip(event, '1013', 1013)">
ComVisible
</code>
<div class="tip" id="1013">
<strong>Signature:</strong> bool option<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L20-20" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1014', 1014)" onmouseover="showTip(event, '1014', 1014)">
GenerateClass
</code>
<div class="tip" id="1014">
<strong>Signature:</strong> bool<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L38-38" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1015', 1015)" onmouseover="showTip(event, '1015', 1015)">
Guid
</code>
<div class="tip" id="1015">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L22-22" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1016', 1016)" onmouseover="showTip(event, '1016', 1016)">
OutputFileName
</code>
<div class="tip" id="1016">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L19-19" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="http://fsharp.github.io/FAKE/index.html">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">FAKE - F# Make</li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Tutorials</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li>
<li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li>
<li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li>
<li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li class="nav-header">Reference</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
| {
"content_hash": "b92bcbb797815d23664827efc9e27a75",
"timestamp": "",
"source": "github",
"line_count": 464,
"max_line_length": 209,
"avg_line_length": 42.633620689655174,
"alnum_prop": 0.5185522191891618,
"repo_name": "rodrigoelp/wpfgesturerecognizer",
"id": "3e1dab55e08cc2654304562a17d50eb2842c6b88",
"size": "19782",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dependencies/FAKE.Core/docs/apidocs/fake-assemblyinfohelper-assemblyinfoparams.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "29858"
},
{
"name": "F#",
"bytes": "3064"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v10/resources/customizer_attribute.proto
namespace Google\Ads\GoogleAds\V10\Resources;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* A customizer attribute.
* Use CustomerCustomizer, CampaignCustomizer, AdGroupCustomizer, or
* AdGroupCriterionCustomizer to associate a customizer attribute and
* set its value at the customer, campaign, ad group, or ad group criterion
* level, respectively.
*
* Generated from protobuf message <code>google.ads.googleads.v10.resources.CustomizerAttribute</code>
*/
class CustomizerAttribute extends \Google\Protobuf\Internal\Message
{
/**
* Immutable. The resource name of the customizer attribute.
* Customizer Attribute resource names have the form:
* `customers/{customer_id}/customizerAttributes/{customizer_attribute_id}`
*
* Generated from protobuf field <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = {</code>
*/
protected $resource_name = '';
/**
* Output only. The ID of the customizer attribute.
*
* Generated from protobuf field <code>int64 id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
protected $id = 0;
/**
* Required. Immutable. Name of the customizer attribute. Required. It must have a minimum length
* of 1 and maximum length of 40. Name of an enabled customizer attribute must
* be unique (case insensitive).
*
* Generated from protobuf field <code>string name = 3 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
*/
protected $name = '';
/**
* Immutable. The type of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeTypeEnum.CustomizerAttributeType type = 4 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
protected $type = 0;
/**
* Output only. The status of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeStatusEnum.CustomizerAttributeStatus status = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
protected $status = 0;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $resource_name
* Immutable. The resource name of the customizer attribute.
* Customizer Attribute resource names have the form:
* `customers/{customer_id}/customizerAttributes/{customizer_attribute_id}`
* @type int|string $id
* Output only. The ID of the customizer attribute.
* @type string $name
* Required. Immutable. Name of the customizer attribute. Required. It must have a minimum length
* of 1 and maximum length of 40. Name of an enabled customizer attribute must
* be unique (case insensitive).
* @type int $type
* Immutable. The type of the customizer attribute.
* @type int $status
* Output only. The status of the customizer attribute.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Ads\GoogleAds\V10\Resources\CustomizerAttribute::initOnce();
parent::__construct($data);
}
/**
* Immutable. The resource name of the customizer attribute.
* Customizer Attribute resource names have the form:
* `customers/{customer_id}/customizerAttributes/{customizer_attribute_id}`
*
* Generated from protobuf field <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = {</code>
* @return string
*/
public function getResourceName()
{
return $this->resource_name;
}
/**
* Immutable. The resource name of the customizer attribute.
* Customizer Attribute resource names have the form:
* `customers/{customer_id}/customizerAttributes/{customizer_attribute_id}`
*
* Generated from protobuf field <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = {</code>
* @param string $var
* @return $this
*/
public function setResourceName($var)
{
GPBUtil::checkString($var, True);
$this->resource_name = $var;
return $this;
}
/**
* Output only. The ID of the customizer attribute.
*
* Generated from protobuf field <code>int64 id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return int|string
*/
public function getId()
{
return $this->id;
}
/**
* Output only. The ID of the customizer attribute.
*
* Generated from protobuf field <code>int64 id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param int|string $var
* @return $this
*/
public function setId($var)
{
GPBUtil::checkInt64($var);
$this->id = $var;
return $this;
}
/**
* Required. Immutable. Name of the customizer attribute. Required. It must have a minimum length
* of 1 and maximum length of 40. Name of an enabled customizer attribute must
* be unique (case insensitive).
*
* Generated from protobuf field <code>string name = 3 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Required. Immutable. Name of the customizer attribute. Required. It must have a minimum length
* of 1 and maximum length of 40. Name of an enabled customizer attribute must
* be unique (case insensitive).
*
* Generated from protobuf field <code>string name = 3 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param string $var
* @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
return $this;
}
/**
* Immutable. The type of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeTypeEnum.CustomizerAttributeType type = 4 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return int
*/
public function getType()
{
return $this->type;
}
/**
* Immutable. The type of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeTypeEnum.CustomizerAttributeType type = 4 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @param int $var
* @return $this
*/
public function setType($var)
{
GPBUtil::checkEnum($var, \Google\Ads\GoogleAds\V10\Enums\CustomizerAttributeTypeEnum\CustomizerAttributeType::class);
$this->type = $var;
return $this;
}
/**
* Output only. The status of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeStatusEnum.CustomizerAttributeStatus status = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Output only. The status of the customizer attribute.
*
* Generated from protobuf field <code>.google.ads.googleads.v10.enums.CustomizerAttributeStatusEnum.CustomizerAttributeStatus status = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param int $var
* @return $this
*/
public function setStatus($var)
{
GPBUtil::checkEnum($var, \Google\Ads\GoogleAds\V10\Enums\CustomizerAttributeStatusEnum\CustomizerAttributeStatus::class);
$this->status = $var;
return $this;
}
}
| {
"content_hash": "a558525adb8a914cdae5bfb42c861717",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 194,
"avg_line_length": 36.72645739910314,
"alnum_prop": 0.6500610500610501,
"repo_name": "googleads/google-ads-php",
"id": "2ca0346bd07a72ef4cfb66fa2e825a70e57c880a",
"size": "8190",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Google/Ads/GoogleAds/V10/Resources/CustomizerAttribute.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "899"
},
{
"name": "PHP",
"bytes": "9952711"
},
{
"name": "Shell",
"bytes": "338"
}
],
"symlink_target": ""
} |
echo [INFO] Create Menu Files.
cd ..
export I18N_LOCALE=en_US
xtab -menu
| {
"content_hash": "919f98d010fa645b7fc47f75560900d6",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 30,
"avg_line_length": 14.8,
"alnum_prop": 0.7162162162162162,
"repo_name": "goyy/goyy",
"id": "4ce08d970c69f0d6670f1e46e71ae2c7dcba1b8d",
"size": "85",
"binary": false,
"copies": "1",
"ref": "refs/heads/v0",
"path": "app/schema/bin/exp-menu.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2537"
},
{
"name": "CSS",
"bytes": "55656"
},
{
"name": "Go",
"bytes": "1466751"
},
{
"name": "HTML",
"bytes": "95260"
},
{
"name": "JavaScript",
"bytes": "78403"
},
{
"name": "Shell",
"bytes": "4893"
}
],
"symlink_target": ""
} |
<!-- Javascript -->
<script type="text/javascript" src="{{site.baseurl}}/assets/plugins/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="{{site.baseurl}}/assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!-- custom js -->
<script type="text/javascript" src="{{site.baseurl}}/assets/js/main.js"></script> | {
"content_hash": "a708ce9cbd36a5cdd585348910481be6",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 116,
"avg_line_length": 72.8,
"alnum_prop": 0.6318681318681318,
"repo_name": "vipulshah2010/vipulshah2010.github.io",
"id": "393995f8d1d7b31aa1b89beee8f645fabeef6c81",
"size": "364",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_includes/scripts.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "406610"
},
{
"name": "HTML",
"bytes": "27579"
},
{
"name": "JavaScript",
"bytes": "69712"
}
],
"symlink_target": ""
} |
{# requires jQuery #}
{% load static %}
<script>
var csrftoken = getCookie("csrftoken");
jQuery.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var markSeen = (function () {
var marked = false;
return function (actionIDs, callback) {
if (!marked) {
jQuery.post("{% url 'mark_seen' %}",
{ids: actionIDs}
).success(function () {
marked = true;
}).always(function (data, textStatus, errorThrown) {
if (typeof callback != "undefined") {
callback(data, textStatus, errorThrown);
}
});
}
}
})();
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
</script>
| {
"content_hash": "bea531b426caabd07bbb776a6a677f41",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 88,
"avg_line_length": 35.93617021276596,
"alnum_prop": 0.4624037892243931,
"repo_name": "github-account-because-they-want-it/django-activity-stream",
"id": "8d59cf0be5d06f8ce8b45d6d2c6a6920d66cac52",
"size": "1689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "actstream/templates/actstream/mark_seen.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "4808"
},
{
"name": "Makefile",
"bytes": "464"
},
{
"name": "Python",
"bytes": "159555"
}
],
"symlink_target": ""
} |
package liulx.masterdetailexample;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
/**
* An activity representing a single BlogPost detail screen. This
* activity is only used on handset devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {@link BlogPostListActivity}.
* <p>
* This activity is mostly just a 'shell' activity containing nothing
* more than a {@link BlogPostDetailFragment}.
*/
public class BlogPostDetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpost_detail);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(BlogPostDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(BlogPostDetailFragment.ARG_ITEM_ID));
BlogPostDetailFragment fragment = new BlogPostDetailFragment();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.add(R.id.blogpost_detail_container, fragment)
.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, BlogPostListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
| {
"content_hash": "d751f110bcd9ce75560aead5e845fc59",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 86,
"avg_line_length": 40.98529411764706,
"alnum_prop": 0.6580552565482598,
"repo_name": "liulixiang1988/android_demo",
"id": "60d4cbc572ee1153926b4f8cfcca7d9271e3724d",
"size": "2787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MasterDetailExample/src/liulx/masterdetailexample/BlogPostDetailActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "340"
},
{
"name": "HTML",
"bytes": "77336"
},
{
"name": "Java",
"bytes": "1973589"
}
],
"symlink_target": ""
} |
package nl.tudelft.ewi.dea.security;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import nl.tudelft.ewi.dea.di.SecurityModule;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.junit.Test;
public class TestCredentialsMatcher {
/**
* This test verifies that the AbstractHash and Salt are functioning
* correctly.
*/
@Test
public void whenPasswordIsGeneratedTheCredentialsShouldMatch() {
final CredentialsMatcher matcher = new SecurityModule(null).matcher();
final String salt = "abc";
final String plainPassword = "password";
final String hashedPassword = new UserFactory().hashPassword(plainPassword, salt);
final AuthenticationInfo info = new SimpleAccount("admin", hashedPassword, SaltTool.getFullSalt(salt), "testrealm");
final AuthenticationToken token = new UsernamePasswordToken("admin", plainPassword);
assertThat(matcher.doCredentialsMatch(token, info), is(true));
}
}
| {
"content_hash": "48d6869aca3b4e063786a3cfb86c8fcf",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 118,
"avg_line_length": 38.766666666666666,
"alnum_prop": 0.7970765262252795,
"repo_name": "devhub-tud/devhub-prototype",
"id": "5ff7705b5b39b3bbaf7f715199d5c58bbf57410d",
"size": "1163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "devhub-server/web/src/test/java/nl/tudelft/ewi/dea/security/TestCredentialsMatcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "149663"
},
{
"name": "Java",
"bytes": "300574"
},
{
"name": "JavaScript",
"bytes": "97359"
},
{
"name": "Shell",
"bytes": "3549"
}
],
"symlink_target": ""
} |
XProtectCheck(){
osvers_major=$(/usr/bin/sw_vers -productVersion | awk -F. '{print $1}')
osvers_minor=$(/usr/bin/sw_vers -productVersion | awk -F. '{print $2}')
if [[ ${osvers_major} -eq 10 ]] && [[ ${osvers_minor} -lt 6 ]]; then
# This section of the function will display a message that XProtect is not
# available for the relevant version of Mac OS X. This will apply to Macs
# running Mac OS X 10.5.8 and earlier.
result="XProtect not available for `/usr/bin/sw_vers -productVersion`"
elif [[ ${osvers_major} -eq 10 ]] && [[ ${osvers_minor} -ge 6 ]] && [[ ${osvers_minor} -lt 9 ]]; then
# This section of the function will check the last-modified time of XProtect's
# XProtect.meta.plist file and report the date when the file was last modified
# in a human-readable date format. This will apply to Macs running Mac OS X 10.6.x
# through OS X 10.8.5.
last_xprotect_update_epoch_time=`/bin/date -jf "%s" $(/usr/bin/stat -s /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/XProtect.meta.plist | tr ' ' '\n' | awk -F= '/st_mtime/{print $NF}') +%s`
last_xprotect_update_human_readable_time=`/bin/date -r "$last_xprotect_update_epoch_time" '+%m-%d-%Y %H:%M:%S'`
result="$last_xprotect_update_human_readable_time"
elif [[ ${osvers_major} -eq 10 ]] && [[ ${osvers_minor} -ge 9 ]]; then
# This section of the function will check the installer package receipts for
# XProtect update installer packages for the relevant version of Mac OS X and
# display the installation date of the most recent update in a human-readable
# date format. This will apply to Macs running OS X 10.9.0 and later.
last_xprotect_update_epoch_time=$(printf "%s\n" `for i in $(pkgutil --pkgs=".*XProtect.*"); do pkgutil --pkg-info $i | awk '/install-time/ {print $2}'; done` | sort -n | tail -1)
last_xprotect_update_human_readable_time=`/bin/date -r "$last_xprotect_update_epoch_time" '+%m-%d-%Y %H:%M:%S'`
result="$last_xprotect_update_human_readable_time"
fi
}
XProtectCheck
echo "$result" | {
"content_hash": "a1f679c802203f3527f13f6bd65338df",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 211,
"avg_line_length": 48.76190476190476,
"alnum_prop": 0.67626953125,
"repo_name": "kevinstrick/rtrouton_scripts",
"id": "31bc25556ac0a2d320d641cea08b4beb90cba5bf",
"size": "2061",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rtrouton_scripts/report_latest_xprotect_update/report latest_xprotect_update.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8809"
},
{
"name": "Shell",
"bytes": "578716"
}
],
"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 (1.8.0_151) on Wed Jan 16 10:54:26 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.netflix.ribbon.secured.client (BOM: * : All 2.3.0.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.wildfly.swarm.netflix.ribbon.secured.client (BOM: * : All 2.3.0.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/netflix/ribbon/secured/client/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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="Uses of Package org.wildfly.swarm.netflix.ribbon.secured.client" class="title">Uses of Package<br>org.wildfly.swarm.netflix.ribbon.secured.client</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/netflix/ribbon/secured/client/package-summary.html">org.wildfly.swarm.netflix.ribbon.secured.client</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.netflix.ribbon.secured.client">org.wildfly.swarm.netflix.ribbon.secured.client</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.netflix.ribbon.secured.client">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../org/wildfly/swarm/netflix/ribbon/secured/client/package-summary.html">org.wildfly.swarm.netflix.ribbon.secured.client</a> used by <a href="../../../../../../../org/wildfly/swarm/netflix/ribbon/secured/client/package-summary.html">org.wildfly.swarm.netflix.ribbon.secured.client</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../../org/wildfly/swarm/netflix/ribbon/secured/client/class-use/SecuredRibbonResourceFactory.html#org.wildfly.swarm.netflix.ribbon.secured.client">SecuredRibbonResourceFactory</a> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.0.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/netflix/ribbon/secured/client/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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 © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "d11a1d6fa85c8bc1b031707000d6b04f",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 388,
"avg_line_length": 39.65217391304348,
"alnum_prop": 0.6320488721804511,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "6a3ab44b1890c259bab3482437369a25b188b4f0",
"size": "6384",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.3.0.Final-SNAPSHOT/apidocs/org/wildfly/swarm/netflix/ribbon/secured/client/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<div class="df-component-navbar">
<ul class="nav nav-pills pull-left visible-md visible-lg">
<li data-ng-repeat="link in options.links" data-ng-class="activeLink === link.name ? 'active' : ''">
<a href="#{{link.path}}" ng-click="reloadRoute(link.path)">{{link.label}}</a>
</li>
</ul>
<div class="hidden-md hidden-lg pull-right">
<button type="button" class="btn btn-default btn-sm" data-ng-click="openMenu()"><i class="fa fa-fw fa-bars"></i></button>
</div>
<!-- Flyout menu -->
<div id="component-nav-flyout-menu" class="df-flyout-menu df-flyout-menu-right hidden-lg hidden-md">
<div class="panel panel-default" id="component-nav-flyout-panel">
<div class="panel-heading">
<button class="btn btn-default btn-xs" data-ng-click="closeMenu()">Cancel</button>
</div>
<ul class="list-group">
<li data-ng-repeat="link in options.links" class="list-group-item" data-ng-class="activeLink === link.name ? 'active' : ''">
<a href="#{{link.path}}" ng-click="reloadRoute(link.path)" >{{link.label}}</a>
</li>
</ul>
</div>
</div>
<div id="component-nav-flyout-mask" class="mask"></div>
</div>
| {
"content_hash": "3d044ad9f7d0b1dedce0d0136201d050",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 140,
"avg_line_length": 37.970588235294116,
"alnum_prop": 0.5662277304415182,
"repo_name": "dreamfactorysoftware/df-admin-app",
"id": "6f6fc5c9d612c3683343016e4385dc793b6c4cdf",
"size": "1291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/admin_components/adf-utility/views/df-component-nav.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "704788"
},
{
"name": "HTML",
"bytes": "369047"
},
{
"name": "JavaScript",
"bytes": "1063636"
},
{
"name": "PHP",
"bytes": "1490"
},
{
"name": "Python",
"bytes": "2824"
},
{
"name": "Ruby",
"bytes": "887"
},
{
"name": "SCSS",
"bytes": "676208"
},
{
"name": "Shell",
"bytes": "36"
}
],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from '../store';
import { type } from '../util';
export const LayoutActionTypes = {
/*
layout-modal action types
*/
OPEN_LAYOUT_MODAL: type('[LayoutModal] open layout modal'),
CLOSE_LAYOUT_MODAL: type('[LayoutModal] close layout modal'),
}
@Injectable()
export class LayoutActions {
constructor(
private ngRedux: NgRedux<IAppState>
) { }
/*
layout-modal actions
*/
public openLayoutModalAction(data: any) {
return {
type: LayoutActionTypes.OPEN_LAYOUT_MODAL,
payload: data
};
}
public closeLayoutModalAction() {
return {
type: LayoutActionTypes.CLOSE_LAYOUT_MODAL
};
}
} | {
"content_hash": "510a89b2a60ae005eb3bb365bbd1b7e0",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 63,
"avg_line_length": 21.083333333333332,
"alnum_prop": 0.6587615283267457,
"repo_name": "FlorinskiyDI/coremanage",
"id": "ab28d0e524ce018254cd1fdcbd3b4385104dace1",
"size": "759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coremanage/coremanage.Dashboard.Web/src/app/redux/actions/layout.actions.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "165344"
},
{
"name": "CSS",
"bytes": "10949"
},
{
"name": "HTML",
"bytes": "29654"
},
{
"name": "JavaScript",
"bytes": "6714"
},
{
"name": "TypeScript",
"bytes": "119110"
}
],
"symlink_target": ""
} |
<?php
require_once "../config.php";
require_once "utils.php";
require_once "users.php";
require_once "goods.php";
require_once "authorization.php";
require_once 'sms.php';
require_once "orders.php";
require_once "message.php";
require_once "./dzApi.php";
header('Content-type: application/json');
// TODO: intval($goods_id)
session_start();
if(!isset($_GET['action'])) die(generate_error_report("No action! Please check document for usage"));
$action = $_GET["action"];
$student_id = "";
if($student_id = get_student_id_from_session_key(session_id())){ // 已登录
if($action == "logout"){
user_logout(session_id());
die(json_encode(array(
"status" => "success"
)));
}elseif($action == "update_self_info"){
if(isset($_POST['info'])){
$info = fetch_info_from_user($student_id);
$data = json_decode(urldecode($_POST['info']),true);
if(isset($data['nickname'])){
$info['nickname'] = $data['nickname'];
}
if(isset($data['dormitory'])){
if(isset($data['dormitory']['access'])) $info['dormitory']['access'] = $data['dormitory']['access'];
if(isset($data['dormitory']['dormitory_id'])){
if(isset($data['dormitory']['dormitory_id']['access'])) $info['dormitory']['dormitory_id']['access'] = $data['dormitory']['dormitory_id']['access'];
if(isset($data['dormitory']['dormitory_id']['value'])) $info['dormitory']['dormitory_id']['value'] = $data['dormitory']['dormitory_id']['value'] ;
}
if(isset($data['dormitory']['room_no'])){
if(isset($data['dormitory']['room_no']['access'])) $info['dormitory']['room_no']['access'] = $data['dormitory']['room_no']['access'];
if(isset($data['dormitory']['room_no']['value'])) $info['dormitory']['room_no']['value'] = $data['dormitory']['room_no']['value'] ;
}
if(isset($data['phone_number'])){
if(isset($data['phone_number']['access'])) $info['phone_number']['access'] = $data['phone_number']['access'];
if(isset($data['phone_number']['value'])) $info['phone_number']['value'] = $data['phone_number']['value'];
}
}
if(isset($data['class_info']) and isset($data['class_info']['department'])){
if(isset($data['class_info']['department']['access'])) $info['class_info']['department']['access'] = $data['class_info']['department']['access'];
if(isset($data['class_info']['department']['value'])) $info['class_info']['department']['value'] = $data['class_info']['department']['value'];
if(isset($data['class_info']['enrollment']) and isset($data['class_info']['enrollment']['access'])) $info['class_info']['enrollment']['access'] = $data['class_info']['enrollment']['access'];
if(isset($data['class_info']['class_no']) and isset($data['class_info']['class_no']['access'])) $info['class_info']['class_no']['access'] = $data['class_info']['class_no']['access'];
}
if(isset($data['student_id']) and isset($data['student_id']['access'])) $info['student_id']['access'] = $data['student_id']['access'];
if(isset($data['name']) and isset($data['name']['access'])) $info['name']['access'] = $data['name']['access'];
if(isset($data['gender']) and isset($data['gender']['access'])) $info['gender']['access'] = $data['gender']['access'];
if(isset($data['birthday']) and isset($data['birthday']['access'])) $info['birthday']['access'] = $data['birthday']['access'];
if(isset($data['header'])) $info['header'] = urlencode($data['header']);
// 合法性检测
$info_hash = update_user_info(json_encode($info),$student_id);
die(json_encode(array(
"status" => "success",
"info_hash" => $info_hash
)));
}else{
die(generate_error_report("Please check doc for usage"));
}
}elseif($action == "cancel_order"){
if(!isset($_GET['order_id']))
die(generate_error_report("Please check doc for usage"));
die(cancel_order_from_user($student_id, $_GET['order_id']));
}elseif($action == "login") {
die(json_encode(array(
"status" => "success",
"session" => session_id()
)));
}elseif($action == "change_password"){
if(isset($_POST['original_pass']) && isset($_POST['new_pass'])){
$original_pass = filter_password($_POST['original_pass']);
$new_pass = filter_password($_POST['new_pass']);
if(check_pass($student_id,$original_pass)){
if(change_password($student_id,$new_pass)){
die(json_encode(array(
"status" => "success"
)));
// todos: remove all session connected to this account
}else{
die("Error occured?");
}
}else{
die("Wrong password");
}
}else{
die(generate_error_report("Please use GET to specify original_pass and new_pass"));
}
}elseif($action == "submit_goods"){ // Todo: 输入检查注意
$json_data = $_POST['goods_info'];
die(submit_goods_from_id($json_data, $student_id));
}elseif($action == "new_order"){
if(!isset(
$_GET['goods_id'],
$_GET['order_type'],
$_GET['delivery_fee'],
$_GET['purchase_amount'],
$_GET['single_cost'],
$_GET['offer']
)){die(generate_error_report("Please check code for usage"));}
$goods_id = $_GET['goods_id'];
$order_type = $_GET['order_type'];
if($order_type == 'rent'){
if(!isset($_GET['rent_duration'])) die(generate_error_report("No duration specified!"));
$rent_duration = intval($_GET['rent_duration']);
}else{
$rent_duration = 0;
}
$delivery_fee = floatval($_GET['delivery_fee']);
$purchase_amount = intval($_GET['purchase_amount']);
$single_cost = floatval($_GET['single_cost']);
$offer = floatval($_GET['offer']);
$order_id = create_order_from_user($student_id, $order_type, $rent_duration, $goods_id, $delivery_fee, $purchase_amount, $single_cost, $offer);
if($order_id){
// $sms = new OrderSms; $sms_status = $sms->create_order($order_id);
die(json_encode(array(
"status" => "success",
"order_id" => $order_id,
)));
}else{
die(json_encode(array(
"status" => "failed"
)));
}
}elseif($action == "accept_order"){
if(!isset($_GET['order_id'])){
die(generate_error_report("Please check doc for usage"));
}
accept_order_from_user($student_id, intval($_GET['order_id']));
}elseif($action == "complete_order"){
if(!isset($_GET['order_id'])){
die(generate_error_report("Please check doc for usage"));
}
die(complete_order_from_user($student_id, intval($_GET['order_id'])));
}elseif($action == "finish_order"){
if(!isset($_GET['order_id'])){
die(generate_error_report("Please check doc for usage"));
}
die(finish_order_from_user($student_id, intval($_GET['order_id'])));
}elseif($action == "list_orders"){
$filter = array();
$limit = 10;
$page = 1;
if(isset($_GET['order_status']))
$filter['order_status'] = urlencode($_GET['order_status']); // Todo: 输入检查注意
if(isset($_GET['limit']))
$limit = intval($_GET['limit']);
if(isset($_GET['page']))
$page = intval($_GET['page']);
if(isset($_GET['order_submitter'])){
if ($_GET['order_submitter'] == 'self'){
$filter['order_submitter'] = $student_id;
}else if($_GET['order_submitter'] == 'other'){
$filter['goods_owner'] = $student_id;
}else if($_GET['order_submitter'] == 'both'){
$filter['goods_owner'] = "$student_id' or goods_owner='$student_id";
}else{
die(generate_error_report("Please specify order submitter [self or other]"));
}
}else{
die(generate_error_report("Please specify order submitter [self or other]"));
}
$results = list_orders_from_user($student_id, $filter, $page, $limit);
$count = count($results);
die(json_encode(array(
"status" => "success",
"orders" => $results,
"count" => $count,
'total' => fetch_orders_total_pages($student_id, $filter,$limit),
)));
}elseif($action == "fetch_self_info"){
$return_var = fetch_info_from_user($student_id);
if($return_var){
die(json_encode(array(
"status" => "success",
"self_info" => $return_var
)));
}else{
die(generate_error_report("Access denied or no such user"));
}
}elseif($action == "fetch_user_info"){
if(!isset($_GET['user_id']))
die(generate_error_report("Please specify user id as user_id=xxx in url"));
$return_var = fetch_info_from_user($_GET['user_id']);
$return_var = recursion_remove_sensitive_info($return_var,"protected");
if($return_var){
die(json_encode(array(
"status" => "success",
"user_info" => $return_var
)));
}else{
die(generate_error_report("Unknown error in fetch user info"));
}
}elseif($action == "revoke_goods"){
if(!isset($_GET['goods_id'])){
die(generate_error_report("Please specify goods_id"));
}
if(revoke_goods(intval($_GET['goods_id']),$student_id)){
die(json_encode(array(
"status" => "success"
)));
}
}elseif($action == "edit_goods"){
}elseif($action == "fetch_user_goods") {
$user_id = $student_id; $page = 1; $amount=8; $goods = null;
if (isset($_GET['page'])) $page = $_GET['page'];
if (isset($_GET['user_id'])) {
$user_id = $_GET['user_id'];
$goods = fetch_goods_for_sale_from_user($user_id,$page,$amount);
}else{
$goods = fetch_all_goods_from_user($user_id,$page,$amount);
}
die(json_encode(array(
'status' => 'success',
'goods' => $goods,
'total' => fetch_total_pages($student_id,$amount),
)));
}elseif($action == "update_goods_info"){
if(isset($_POST['goods_info'])){
die(update_goods_info($_POST['goods_info'],$student_id));
}
}elseif($action == "msg_send"){
if(isset($_GET["msg_content"]) && isset($_GET["peer_id"])){
$peer_id = filter_student_id($_GET['peer_id']);
$content = base64_encode($_GET['msg_content']);
new_msg($student_id, $peer_id, $content); // 只在成功时返回
die(json_encode(array(
"status" => "success"
)));
}else{
die(generate_error_report("No enough params, please read doc for further information"));
}
}elseif($action == "fetch_msg"){
if(isset($_GET["peer_id"])){
$peer_id = filter_student_id($_GET['peer_id']);
$result = fetch_msg($peer_id, $student_id);
die(json_encode($result));
}else{
die(generate_error_report("No enough params, please read doc for further information"));
}
}elseif($action == "msg_count"){
$result = msg_count($student_id);
die(json_encode($result));
}elseif ($action == 'check') {
die(json_encode(array(
'status' => 'failed',
'error' => 'you have logged in',
)));
}
}else{ // 未登录
if($action == "login"){ // 登陆操作
$session_key = false;
if(isset($_POST['username']) and isset($_POST['password']))
$session_key = user_login($_POST['username'],$_POST['password']);
else
$session_key = user_login($_GET['username'],$_GET['password']);
if($session_key){
session_unset();
session_destroy();
session_id($session_key);
session_start();
die(json_encode(array(
"status" => "success",
"session" => $session_key
)));
}else{
die(generate_error_report("Wrong username or password"));
}
}elseif($action == "check"){ // 检查用户是否为学生 TODO:检验
if(isset($_POST["student_id"]) and isset($_POST["password"])){
$info = confirm_student($_POST["student_id"],$_POST["password"]);
// $info = confirm_ibeike($_POST["student_id"],$_POST["password"]);
if ($info == false) {
die(json_encode(array(
'status' => 'failed',
'error' => 'Wrong username or password',
)));
}else{
die(json_encode(array(
'status' => 'success',
'student_info' => $info,
)));
}
}else die(generate_error_report("Please specify student id and password"));
}elseif($action == "signup"){
if(isset($_POST['student_id']) and isset($_POST['password']) and isset($_POST['student_info']) and isset($_POST['new_password'])){
$session_key = user_bind($_POST['student_id'],$_POST['password']);
if($session_key){
session_unset();
session_destroy();
session_id($session_key);
session_start();
$info_hash = update_user_info(json_encode($_POST['student_info']),$_POST['student_id']);
$change_result = change_password($_POST['student_id'],$_POST['new_password']);
if ($change_result == true) {
die(json_encode(array(
"status" => "success",
"session" => $session_key,
'info_hash'=>$info_hash,
)));
}else {
die(json_encode(array(
"status" => "failed",
'error' => 'failed to reset password',
"session" => $session_key,
'info_hash'=>$info_hash,
)));
}
}else{
die(generate_error_report("Wrong username or password"));
}
}else{
die(generate_error_report("Please specify id and password"));
}
}elseif($action == "reset"){
if(isset($_POST['id']) and isset($_POST['password'])){
if(confirm_student(strval($_GET['id']),strval($_POST['password']))){
if(change_password(strval($_GET['id']),strval($_POST['password']))){
die(json_encode(array(
"status" => "success"
)));
}
}
}
}elseif($action == 'fetch_phone_captcha'){
if (isset($_GET['phone_number'])) {
$sms = new Captcha;
die(json_encode($sms->phone_captcha($_GET['phone_number'])));
}else {
die(json_encode(array(
'status' => 'failed',
'error' => 'no phone_number',
)));
}
}elseif ($action == 'forget_password') {
if(isset($_POST['student_id']) and isset($_POST['password']) and isset($_POST['new_password'])){
if(confirm_student(strval($_POST['student_id']),strval($_POST['password']))){
if(change_password(strval($_POST['student_id']),strval($_POST['new_password']))){
die(json_encode(array(
"status" => "success",
)));
}
}
}
}
}
// 这个名字是不是有点太随意了?
if($action == "fetch_user_total_info"){
$current_id = get_student_id_from_session_key(session_id());
$user_id = 0;
if(!isset($_GET['user_id'])){
if(!$current_id)
die(generate_error_report("No user id specified!"));
else
$user_id = $current_id;
}else{
$user_id = intval($_GET['user_id']);
}
$goods = fetch_goods_for_sale_from_user($user_id);
$filter = array(
'order_submitter' => $user_id
);
$orders = list_orders_from_user($user_id);
$info = fetch_user_info_from_id($user_id);
$flag = "public";
if($current_id){
if($current_id == $user_id)
$flag = "private";
else
$flag = "protected";
}else{
$flag = "public";
}
$info = recursion_remove_sensitive_info($info,$flag);
die(json_encode(array(
"target_id" => $user_id,
"status" => "success",
"goods" => $goods,
"orders" => $orders,
"info" => $info
)));
}elseif ($action == 'search_goods_by_title') {
if (isset($_GET['goods_title'])) {
$page = 1; $amount = 12;
if (isset($_GET['page'])) $page = $_GET['page'];
die(search_goods_by_title($_GET['goods_title'],$page,$amount));
}
}elseif ($action == 'search_goods_by_category') {
if (isset($_GET['category'],$_GET['level'])) {
$page = 1; $amount = 12;
if (isset($_GET['page'])) $page = $_GET['page'];
die(search_goods_by_category($_GET['category'],$_GET['level'],$page,$amount));
}
}
die(generate_error_report( "No such method, please read sources and try again"));
?>
| {
"content_hash": "e1a95cbe0a6d68995472d85a1e05275d",
"timestamp": "",
"source": "github",
"line_count": 407,
"max_line_length": 206,
"avg_line_length": 44.61179361179361,
"alnum_prop": 0.4907749077490775,
"repo_name": "Trickness/iBeiKe-SaltedFish",
"id": "a2cf3ff92c36adef6682150887a4e8ec9d84c466",
"size": "18275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "salted-shell/core/api-v1.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "109130"
},
{
"name": "HTML",
"bytes": "90339"
},
{
"name": "JavaScript",
"bytes": "1840807"
},
{
"name": "PHP",
"bytes": "507481"
},
{
"name": "Shell",
"bytes": "17194"
}
],
"symlink_target": ""
} |
'use babel';
/* @flow*/
import type { TextEditor } from 'atom';
import { Observable } from 'rxjs';
import { UPDATE_EDITOR, errorAction, testAction } from '../actions';
import { observableFromSubscribeFunction } from './../../helpers';
import { handleGutter } from '../../decorate-manager';
import type { TesterAction } from '../../types';
export default function updateEditor(action$: Observable<TesterAction>): Observable<TesterAction> {
return action$.ofType(UPDATE_EDITOR)
.switchMap((action: TesterAction) => {
if (action.payload && action.payload.editor) {
const textEditor: TextEditor = action.payload.editor;
let subscription = Observable.fromPromise(handleGutter(textEditor)).switchMap(() => Observable.empty());
if (atom.config.get('tester.testOnSave') && textEditor) {
subscription = observableFromSubscribeFunction(callback => textEditor.onDidSave(callback)).mapTo(testAction());
}
if (atom.config.get('tester.testOnOpen')) {
subscription = Observable.concat(
Observable.of(testAction()),
subscription,
);
}
return subscription;
}
return Observable.empty();
})
.catch(err => Observable.of(errorAction(err)));
}
| {
"content_hash": "8ac5da365f0d25f2946e83ee9aecb698",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 121,
"avg_line_length": 40.74193548387097,
"alnum_prop": 0.6571654790182107,
"repo_name": "yacut/tester",
"id": "cfb4ffcaf2194e5a44f82ae4252e5b1e8638a226",
"size": "1263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/redux/epics/updateEditor.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6529"
},
{
"name": "JavaScript",
"bytes": "141746"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.groovy.template;
import com.intellij.codeInsight.template.EverywhereContextType;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.openapi.util.Condition;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionData;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
/**
* @author peter
*/
public abstract class GroovyTemplateContextType extends TemplateContextType {
protected GroovyTemplateContextType(@NotNull @NonNls String id,
@NotNull String presentableName,
@Nullable Class<? extends TemplateContextType> baseContextType) {
super(id, presentableName, baseContextType);
}
public boolean isInContext(@NotNull final PsiFile file, final int offset) {
if (PsiUtilBase.getLanguageAtOffset(file, offset).isKindOf(GroovyFileType.GROOVY_LANGUAGE)) {
PsiElement element = file.findElementAt(offset);
if (element instanceof PsiWhiteSpace) {
return false;
}
return element != null && isInContext(element);
}
return false;
}
protected abstract boolean isInContext(@NotNull PsiElement element);
public static class Generic extends GroovyTemplateContextType {
public Generic() {
super("GROOVY", "Groovy", EverywhereContextType.class);
}
@Override
protected boolean isInContext(@NotNull PsiElement element) {
return true;
}
}
public static class Statement extends GroovyTemplateContextType {
public Statement() {
super("GROOVY_STATEMENT", "Statement", Generic.class);
}
@Override
protected boolean isInContext(@NotNull PsiElement element) {
PsiElement stmt = PsiTreeUtil.findFirstParent(element, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element11) {
return PsiUtil.isExpressionStatement(element11);
}
});
return !isAfterExpression(element) && stmt != null && stmt.getTextRange().getStartOffset() == element.getTextRange().getStartOffset();
}
}
public static class Expression extends GroovyTemplateContextType {
public Expression() {
super("GROOVY_EXPRESSION", "Expression", Generic.class);
}
@Override
protected boolean isInContext(@NotNull PsiElement element) {
return isExpressionContext(element);
}
private static boolean isExpressionContext(PsiElement element) {
final PsiElement parent = element.getParent();
if (!(parent instanceof GrReferenceExpression)) {
return false;
}
if (((GrReferenceExpression)parent).isQualified()) {
return false;
}
if (parent.getParent() instanceof GrCall) {
return false;
}
return !isAfterExpression(element);
}
}
private static boolean isAfterExpression(PsiElement element) {
ProcessingContext context = new ProcessingContext();
if (PlatformPatterns.psiElement().afterLeaf(
PlatformPatterns.psiElement().inside(PlatformPatterns.psiElement(GrExpression.class).save("prevExpr"))).accepts(element, context)) {
PsiElement prevExpr = (PsiElement)context.get("prevExpr");
if (prevExpr.getTextRange().getEndOffset() <= element.getTextRange().getStartOffset()) {
return true;
}
}
return false;
}
public static class Declaration extends GroovyTemplateContextType {
public Declaration() {
super("GROOVY_DECLARATION", "Declaration", Generic.class);
}
@Override
protected boolean isInContext(@NotNull PsiElement element) {
if (PsiTreeUtil.getParentOfType(element, GrCodeBlock.class, false, GrTypeDefinition.class) != null) {
return false;
}
if (element instanceof PsiComment) {
return false;
}
return GroovyCompletionData.suggestClassInterfaceEnum(element) || GroovyCompletionData.suggestFinalDef(element);
}
}
}
| {
"content_hash": "fbecec1caa659d1e472a969fbec6ca59",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 140,
"avg_line_length": 35.07194244604317,
"alnum_prop": 0.7288205128205129,
"repo_name": "liveqmock/platform-tools-idea",
"id": "9799547748345ff460d402c8ae3b6732ac867d59",
"size": "5475",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/groovy/src/org/jetbrains/plugins/groovy/template/GroovyTemplateContextType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "C",
"bytes": "174455"
},
{
"name": "C#",
"bytes": "326"
},
{
"name": "C++",
"bytes": "76245"
},
{
"name": "CSS",
"bytes": "10373"
},
{
"name": "Cucumber",
"bytes": "14485"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groff",
"bytes": "35084"
},
{
"name": "Groovy",
"bytes": "1838147"
},
{
"name": "HTML",
"bytes": "1209876"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "116762135"
},
{
"name": "JavaScript",
"bytes": "112"
},
{
"name": "Objective-C",
"bytes": "18984"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6570"
},
{
"name": "Python",
"bytes": "2787996"
},
{
"name": "Shell",
"bytes": "68627"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
My personal toolbox to speed up basic frontend tasks.
Current status: in production.
Version: 0.0.8.
| {
"content_hash": "f190bf962b98ce2d2883b0b449956fcc",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 20.6,
"alnum_prop": 0.7669902912621359,
"repo_name": "ArturJanik/OmniBlocks",
"id": "294b008fbd6312e86de7cfe1488848bb84a2bad7",
"size": "116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "123270"
},
{
"name": "HTML",
"bytes": "51113"
},
{
"name": "JavaScript",
"bytes": "17964"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Controls
{
/// <summary>
/// Renders a template supplied by a resource binding or from a runtime.
/// </summary>
[ControlMarkupOptions(AllowContent = false)]
public class TemplateHost : DotvvmControl
{
/// <summary>
/// Gets or sets the template that will be rendered inside this control.
/// </summary>
[MarkupOptions(AllowBinding = false, MappingMode = MappingMode.Attribute, Required = true)]
public ITemplate? Template
{
get { return (ITemplate?)GetValue(TemplateProperty); }
set { SetValue(TemplateProperty, value); }
}
public static readonly DotvvmProperty TemplateProperty
= DotvvmProperty.Register<ITemplate, TemplateHost>(c => c.Template, null);
public TemplateHost() { }
public TemplateHost(ITemplate template)
{
Template = template;
}
protected internal override void OnLoad(IDotvvmRequestContext context)
{
var placeHolder = new PlaceHolder();
Template.NotNull("TemplateHost.Template is required").BuildContent(context, placeHolder);
// validate data context of the passed template
var myDataContext = this.GetDataContextType()!;
if (!CheckChildrenDataContextStackEquality(myDataContext, placeHolder.Children))
{
throw new DotvvmControlException(this, "Passing templates into markup controls or to controls which change the binding context, is not supported!");
}
Children.Add(placeHolder);
base.OnLoad(context);
}
private bool CheckChildrenDataContextStackEquality(DataContextStack desiredDataContext, DotvvmControlCollection children)
{
return children.Select(c => c.GetDataContextType())
.Where(t => t != null)
.All(t => Equals(t, desiredDataContext));
}
}
}
| {
"content_hash": "7dbe9e9496b6403c9f731d91e8353653",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 164,
"avg_line_length": 35.82539682539682,
"alnum_prop": 0.6530793088170137,
"repo_name": "riganti/dotvvm",
"id": "b0b587c69d441930dcf92d256562a04426fd934b",
"size": "2259",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Framework/Framework/Controls/TemplateHost.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "247"
},
{
"name": "C#",
"bytes": "6123311"
},
{
"name": "CSS",
"bytes": "7424"
},
{
"name": "HTML",
"bytes": "73696"
},
{
"name": "JavaScript",
"bytes": "580314"
},
{
"name": "Liquid",
"bytes": "416"
},
{
"name": "PowerShell",
"bytes": "22339"
},
{
"name": "Svelte",
"bytes": "6616"
},
{
"name": "TypeScript",
"bytes": "548456"
}
],
"symlink_target": ""
} |
var should = require("should"),
redisClient = require("redis").createClient(),
lock = require("../index")(redisClient);
describe("redis-lock", function() {
it("should aquire a lock and call the callback", function(done) {
lock("testLock", function(completed) {
redisClient.get("lock.testLock", function(err, timeStamp) {
if(err) throw err;
parseFloat(timeStamp).should.be.above(Date.now());
completed(function() {
redisClient.get("lock.testLock", function(err, lockValue) {
should.not.exist(lockValue);
done();
});
});
});
});
});
it("should defer second operation if first has lock", function(done) {
var savedValue, taskCount = 0;
lock("testLock", function(completed) {
setTimeout(function() {
savedValue = 1;
taskCount++;
completed();
proceed();
}, 500); // Longer, started first
});
lock("testLock", function(completed) {
setTimeout(function() {
savedValue = 2;
taskCount++;
completed();
proceed();
}, 200); // Shorter, started later
});
function proceed() {
if(taskCount === 2) {
savedValue.should.equal(2);
done();
}
}
});
it("shouldn't create a deadlock if the first operation doesn't release the lock within <timeout>", function(done) {
var start = new Date();
lock("testLock", 300, function(completed) {
// Not signalling completion
});
lock("testLock", function(completed) {
// This should be called after 300 ms
(new Date() - start).should.be.above(300);
completed();
done();
});
});
});
| {
"content_hash": "4c3cc9debc6c1048ead7ab3cbebbc006",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 116,
"avg_line_length": 24.375,
"alnum_prop": 0.6224358974358974,
"repo_name": "DuoSoftware/ARDS",
"id": "53e99f8fe72d553a89538ef26c0a1353a3eb72af",
"size": "1560",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ArdsCommon/ArdsCommon/node_modules/redis-lock/test/test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "31369"
},
{
"name": "Go",
"bytes": "54721"
},
{
"name": "JavaScript",
"bytes": "229220"
}
],
"symlink_target": ""
} |
#pragma once
#include "envoy/common/pure.h"
namespace Buffer {
/**
* A raw memory data slice including location and length.
*/
struct RawSlice {
void* mem_;
uint64_t len_;
};
/**
* A basic buffer abstraction.
*/
class Instance {
public:
virtual ~Instance() {}
/**
* Copy data into the buffer.
* @param data supplies the data address.
* @param size supplies the data size.
*/
virtual void add(const void* data, uint64_t size) PURE;
/**
* Copy a string into the buffer.
* @param data supplies the string to copy.
*/
virtual void add(const std::string& data) PURE;
/**
* Copy another buffer into this buffer.
* @param data supplies the buffer to copy.
*/
virtual void add(const Instance& data) PURE;
/**
* Commit a set of slices originally obtained from reserve(). The number of slices can be
* different from the number obtained from reserve(). The size of each slice can also be altered.
* @param iovecs supplies the array of slices to commit.
* @param num_iovecs supplies the size of the slices array.
*/
virtual void commit(RawSlice* iovecs, uint64_t num_iovecs) PURE;
/**
* Drain data from the buffer.
* @param size supplies the length of data to drain.
*/
virtual void drain(uint64_t size) PURE;
/**
* Fetch the raw buffer slices. This routine is optimized for performance.
* @param out supplies an array of RawSlice objects to fill.
* @param out_size supplies the size of out.
* @return the actual number of slices needed, which may be greater than out_size. Passing
* nullptr for out and 0 for out_size will just return the size of the array needed
* to capture all of the slice data.
* TODO(mattklein123): WARNING: The underlying implementation of this function currently uses
* libevent's evbuffer. It has the infuriating property where calling getRawSlices(nullptr, 0)
* will return the slices that include all of the buffer data, but not any empty slices at the
* end. However, calling getRawSlices(iovec, SOME_CONST), WILL return potentially empty slices
* beyond the end of the buffer. Code that is trying to avoid stack overflow by limiting the
* number of returned slices needs to deal with this. When we get rid of evbuffer we can rework
* all of this.
*/
virtual uint64_t getRawSlices(RawSlice* out, uint64_t out_size) const PURE;
/**
* @return uint64_t the total length of the buffer (not necessarily contiguous in memory).
*/
virtual uint64_t length() const PURE;
/**
* @return a pointer to the first byte of data that has been linearized out to size bytes.
*/
virtual void* linearize(uint32_t size) PURE;
/**
* Move a buffer into this buffer. As little copying is done as possible.
* @param rhs supplies the buffer to move.
*/
virtual void move(Instance& rhs) PURE;
/**
* Move a portion of a buffer into this buffer. As little copying is done as possible.
* @param rhs supplies the buffer to move.
* @param length supplies the amount of data to move.
*/
virtual void move(Instance& rhs, uint64_t length) PURE;
/**
* Read from a file descriptor directly into the buffer.
* @param fd supplies the descriptor to read from.
* @param max_length supplies the maximum length to read.
* @return the number of bytes read or -1 if there was an error.
*/
virtual int read(int fd, uint64_t max_length) PURE;
/**
* Reserve space in the buffer.
* @param length supplies the amount of space to reserve.
* @param iovecs supplies the slices to fill with reserved memory.
* @param num_iovecs supplies the size of the slices array.
* @return the number of iovecs used to reserve the space.
*/
virtual uint64_t reserve(uint64_t length, RawSlice* iovecs, uint64_t num_iovecs) PURE;
/**
* Search for an occurence of a buffer within the larger buffer.
* @param data supplies the data to search for.
* @param size supplies the length of the data to search for.
* @param start supplies the starting index to search from.
* @return the index where the match starts or -1 if there is no match.
*/
virtual ssize_t search(const void* data, uint64_t size, size_t start) const PURE;
/**
* Write the buffer out to a file descriptor.
* @param fd supplies the descriptor to write to.
* @return the number of bytes written or -1 if there was an error.
*/
virtual int write(int fd) PURE;
};
typedef std::unique_ptr<Instance> InstancePtr;
} // Buffer
| {
"content_hash": "e42b58142a7acf4a5260207cd5b56522",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 99,
"avg_line_length": 34.54961832061068,
"alnum_prop": 0.6953159522757402,
"repo_name": "timperrett/envoy",
"id": "a874168b1d930b75985d522ebe98344c946c5e6f",
"size": "4526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/envoy/buffer/buffer.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "226"
},
{
"name": "C++",
"bytes": "2662234"
},
{
"name": "CMake",
"bytes": "20781"
},
{
"name": "Makefile",
"bytes": "3887"
},
{
"name": "Protocol Buffer",
"bytes": "6293"
},
{
"name": "Python",
"bytes": "187935"
},
{
"name": "Shell",
"bytes": "30686"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Larret est
un village
localisé dans le département de Haute-Saône en Franche-Comté. On dénombrait 53 habitants en 2008.</p>
<p>Le nombre d'habitations, à Larret, se décomposait en 2011 en zero appartements et 41 maisons soit
un marché plutôt équilibré.</p>
<p>À proximité de Larret sont positionnées géographiquement les communes de
<a href="{{VLROOT}}/immobilier/framont_70252/">Framont</a> localisée à 6 km, 190 habitants,
<a href="{{VLROOT}}/immobilier/delain_70201/">Delain</a> localisée à 5 km, 184 habitants,
<a href="{{VLROOT}}/immobilier/courtesoult-et-gatey_70183/">Courtesoult-et-Gatey</a> à 1 km, 63 habitants,
<a href="{{VLROOT}}/immobilier/roche-et-raucourt_70448/">Roche-et-Raucourt</a> située à 5 km, 150 habitants,
<a href="{{VLROOT}}/immobilier/pierrecourt_70409/">Pierrecourt</a> à 3 km, 132 habitants,
<a href="{{VLROOT}}/immobilier/argillieres_70027/">Argillières</a> située à 4 km, 69 habitants,
entre autres. De plus, Larret est située à seulement 20 km de <a href="{{VLROOT}}/immobilier/gray_70279/">Gray</a>.</p>
<p>Si vous envisagez de venir habiter à Larret, vous pourrez aisément trouver une maison à vendre. </p>
</div>
| {
"content_hash": "dc2836dd6a7159a379d635c075699b80",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 125,
"avg_line_length": 73,
"alnum_prop": 0.7348912167606769,
"repo_name": "donaldinou/frontend",
"id": "1cdca52ba2a9cce65cf8d159c38cc227cb64af84",
"size": "1272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/70297.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
import optparse
import os
import sys
import m5
from m5.defines import buildEnv
from m5.objects import *
from m5.util import addToPath, fatal
if not buildEnv['FULL_SYSTEM']:
fatal("This script requires full-system mode (*_FS).")
addToPath('../common')
from FSConfig import *
from SysPaths import *
from Benchmarks import *
import Simulation
import CacheConfig
from Caches import *
# Get paths we might need. It's expected this file is in m5/configs/example.
config_path = os.path.dirname(os.path.abspath(__file__))
config_root = os.path.dirname(config_path)
parser = optparse.OptionParser()
# Simulation options
parser.add_option("--timesync", action="store_true",
help="Prevent simulated time from getting ahead of real time")
# System options
parser.add_option("--kernel", action="store", type="string")
parser.add_option("--script", action="store", type="string")
if buildEnv['TARGET_ISA'] == "arm":
parser.add_option("--bare-metal", action="store_true",
help="Provide the raw system without the linux specific bits")
parser.add_option("--machine-type", action="store", type="choice",
choices=ArmMachineType.map.keys(), default="RealView_PBX")
# Benchmark options
parser.add_option("--dual", action="store_true",
help="Simulate two systems attached with an ethernet link")
parser.add_option("-b", "--benchmark", action="store", type="string",
dest="benchmark",
help="Specify the benchmark to run. Available benchmarks: %s"\
% DefinedBenchmarks)
# Metafile options
parser.add_option("--etherdump", action="store", type="string", dest="etherdump",
help="Specify the filename to dump a pcap capture of the" \
"ethernet traffic")
#fault injection option
parser.add_option("--where", action="store", type="string", dest="where",
help="in which core to insert faults")
parser.add_option("--firun", action="store", type="int", dest="firun",
help="number of fi campaign run: Used to enable a fault")
parser.add_option("--regnum", action="store", type="int", dest="regnum",
help="reg number to inject")
parser.add_option("--regtype", action="store", type="string", dest="regtype",
help="reg number to inject")
parser.add_option("--whatval", action="store", type="int", dest="whatval",
help="what value to use from the array")
parser.add_option("--timeval", action="store", type="int", dest="timeval",
help="what value to use from the array")
parser.add_option("--ftype", action="store", type="string", dest="ftype",
help="what value to use from the array")
parser.add_option("--threadId", action="store", type="string", dest="thread_Id",
help="which thread will be injected with this fault")
execfile(os.path.join(config_root, "common", "Options.py"))
(options, args) = parser.parse_args()
if args:
print "Error: script doesn't take any positional arguments"
sys.exit(1)
# driver system CPU is always simple... note this is an assignment of
# a class, not an instance.
DriveCPUClass = AtomicSimpleCPU
drive_mem_mode = 'atomic'
# system under test can be any CPU
(TestCPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
TestCPUClass.clock = '2GHz'
DriveCPUClass.clock = '2GHz'
if options.benchmark:
try:
bm = Benchmarks[options.benchmark]
except KeyError:
print "Error benchmark %s has not been defined." % options.benchmark
print "Valid benchmarks are: %s" % DefinedBenchmarks
sys.exit(1)
else:
if options.dual:
bm = [SysConfig(), SysConfig()]
else:
bm = [SysConfig()]
np = options.num_cpus
if buildEnv['TARGET_ISA'] == "alpha":
test_sys = makeLinuxAlphaSystem(test_mem_mode, bm[0])
elif buildEnv['TARGET_ISA'] == "mips":
test_sys = makeLinuxMipsSystem(test_mem_mode, bm[0])
elif buildEnv['TARGET_ISA'] == "sparc":
test_sys = makeSparcSystem(test_mem_mode, bm[0])
elif buildEnv['TARGET_ISA'] == "x86":
test_sys = makeLinuxX86System(test_mem_mode, options.num_cpus, bm[0])
setWorkCountOptions(test_sys, options)
elif buildEnv['TARGET_ISA'] == "arm":
test_sys = makeArmSystem(test_mem_mode,
options.machine_type, bm[0],
bare_metal=options.bare_metal)
else:
fatal("incapable of building non-alpha or non-sparc full system!")
if options.kernel is not None:
test_sys.kernel = binary(options.kernel)
if options.script is not None:
test_sys.readfile = options.script
test_sys.cpu = [TestCPUClass(cpu_id=i) for i in xrange(np)]
CacheConfig.config_cache(options, test_sys)
if options.caches or options.l2cache:
if bm[0]:
mem_size = bm[0].mem()
else:
mem_size = SysConfig().mem()
# For x86, we need to poke a hole for interrupt messages to get back to the
# CPU. These use a portion of the physical address space which has a
# non-zero prefix in the top nibble. Normal memory accesses have a 0
# prefix.
if buildEnv['TARGET_ISA'] == 'x86':
test_sys.bridge.filter_ranges_a=[AddrRange(0, Addr.max >> 4)]
else:
test_sys.bridge.filter_ranges_a=[AddrRange(0, Addr.max)]
test_sys.bridge.filter_ranges_b=[AddrRange(mem_size)]
test_sys.iocache = IOCache(addr_range=mem_size)
test_sys.iocache.cpu_side = test_sys.iobus.port
test_sys.iocache.mem_side = test_sys.membus.port
for i in xrange(np):
if options.fastmem:
test_sys.cpu[i].physmem_port = test_sys.physmem.port
if buildEnv['TARGET_ISA'] == 'mips':
setMipsOptions(TestCPUClass)
if len(bm) == 2:
if buildEnv['TARGET_ISA'] == 'alpha':
drive_sys = makeLinuxAlphaSystem(drive_mem_mode, bm[1])
elif buildEnv['TARGET_ISA'] == 'mips':
drive_sys = makeLinuxMipsSystem(drive_mem_mode, bm[1])
elif buildEnv['TARGET_ISA'] == 'sparc':
drive_sys = makeSparcSystem(drive_mem_mode, bm[1])
elif buildEnv['TARGET_ISA'] == 'x86':
drive_sys = makeX86System(drive_mem_mode, np, bm[1])
elif buildEnv['TARGET_ISA'] == 'arm':
drive_sys = makeArmSystem(drive_mem_mode,
machine_options.machine_type, bm[1])
drive_sys.cpu = DriveCPUClass(cpu_id=0)
drive_sys.cpu.connectAllPorts(drive_sys.membus)
if options.fastmem:
drive_sys.cpu.physmem_port = drive_sys.physmem.port
if options.kernel is not None:
drive_sys.kernel = binary(options.kernel)
root = makeDualRoot(test_sys, drive_sys, options.etherdump)
elif len(bm) == 1:
root = Root(system=test_sys)
else:
print "Error I don't know how to create more than 2 systems."
sys.exit(1)
if options.timesync:
root.time_sync_enable = True
what_val_num = options.whatval
if (what_val_num == 65):
what_type = "All0"
elif (what_val_num == 64):
what_type = "All1"
else:
what_type = "Flip"
time_type = "Inst"
time_val = options.timeval;
where_str = options.where
thread = options.thread_Id
if options.ftype == "register" :
print "####################################eisai malakas eisai malakas eisai malakas###################################################################"
reg_type = options.regtype
reg_num = options.regnum
test_sys.f = RegisterInjectedFault( RegType = reg_type, Register = reg_num, where = where_str, when = ''.join([time_type, ":", str(time_val)]), what = ''.join([what_type, ":", str(what_val_num)]), relative = True, occurrence = 1,threadId=thread,cores=np)
elif options.ftype == "pc" :
test_sys.f = PCInjectedFault( where = where_str, when = ''.join([time_type, ":", str(time_val)]), what = ''.join([what_type, ":", str(what_val_num)]), relative = True, occurrence = 1,threadId=thread,cores=np)
elif options.ftype == "execute" :
test_sys.f = IEWStageInjectedFault( where = where_str, when = ''.join([time_type, ":", str(time_val)]), what = ''.join([what_type, ":", str(what_val_num)]), relative = True, occurrence = 1,threadId=thread,cores=np)
elif options.ftype == "fetch" :
test_sys.f = GeneralFetchInjectedFault( where = where_str, when = ''.join([time_type, ":", str(time_val)]), what = ''.join([what_type, ":", str(what_val_num)]), relative = True, occurrence = 1,threadId=thread,cores=np)
else :
print "echo"
#if options.firun == 1 :
# test_sys.f1 = f
#if options.firun == 1 :
# test_sys.f1 = f
Simulation.run(options, root, test_sys, FutureClass)
| {
"content_hash": "49272f737ab4a70e9c627cac7a193ce7",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 258,
"avg_line_length": 37.60176991150443,
"alnum_prop": 0.6488585549541068,
"repo_name": "koparasy/faultinjection-gem5",
"id": "9c97b3270152a6dd10de2ceb8fcebf4c1a5d92bf",
"size": "10684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "configs/example/fi.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "231590"
},
{
"name": "C",
"bytes": "812127"
},
{
"name": "C++",
"bytes": "8479504"
},
{
"name": "Emacs Lisp",
"bytes": "1969"
},
{
"name": "JavaScript",
"bytes": "34804"
},
{
"name": "Nu",
"bytes": "6911"
},
{
"name": "Perl",
"bytes": "608447"
},
{
"name": "Python",
"bytes": "3061829"
},
{
"name": "Racket",
"bytes": "46205"
},
{
"name": "Ruby",
"bytes": "122028"
},
{
"name": "Scala",
"bytes": "2992"
},
{
"name": "Shell",
"bytes": "30749"
},
{
"name": "Visual Basic",
"bytes": "2884"
}
],
"symlink_target": ""
} |
package org.apache.ignite.internal.processors.cache.binary.datastreaming;
import java.io.Serializable;
import java.util.Map;
import java.util.Random;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.binary.BinaryReader;
import org.apache.ignite.binary.BinaryWriter;
import org.apache.ignite.binary.Binarylizable;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.processors.cache.IgniteCacheProxy;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Tests for {@code IgniteDataStreamerImpl}.
*/
public class GridDataStreamerImplSelfTest extends GridCommonAbstractTest {
/** IP finder. */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** Number of keys to load via data streamer. */
private static final int KEYS_COUNT = 1000;
/** Flag indicating should be cache configured with binary or not. */
private static boolean binaries;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
discoSpi.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(discoSpi);
if (binaries) {
BinaryMarshaller marsh = new BinaryMarshaller();
cfg.setMarshaller(marsh);
}
cfg.setCacheConfiguration(cacheConfiguration());
return cfg;
}
/**
* Gets cache configuration.
*
* @return Cache configuration.
*/
private CacheConfiguration cacheConfiguration() {
CacheConfiguration cacheCfg = defaultCacheConfiguration();
cacheCfg.setCacheMode(PARTITIONED);
cacheCfg.setNearConfiguration(null);
cacheCfg.setBackups(0);
cacheCfg.setWriteSynchronizationMode(FULL_SYNC);
return cacheCfg;
}
/**
* Data streamer should correctly load entries from HashMap in case of grids with more than one node
* and with GridOptimizedMarshaller that requires serializable.
*
* @throws Exception If failed.
*/
public void testAddDataFromMap() throws Exception {
try {
binaries = false;
startGrids(2);
awaitPartitionMapExchange();
Ignite g0 = grid(0);
IgniteDataStreamer<Integer, String> dataLdr = g0.dataStreamer(null);
Map<Integer, String> map = U.newHashMap(KEYS_COUNT);
for (int i = 0; i < KEYS_COUNT; i ++)
map.put(i, String.valueOf(i));
dataLdr.addData(map);
dataLdr.close();
checkDistribution(grid(0));
checkDistribution(grid(1));
// Check several random keys in cache.
Random rnd = new Random();
IgniteCache<Integer, String> c0 = g0.cache(null);
for (int i = 0; i < 100; i ++) {
Integer k = rnd.nextInt(KEYS_COUNT);
String v = c0.get(k);
assertEquals(k.toString(), v);
}
}
finally {
G.stopAll(true);
}
}
/**
* Data streamer should add binary object that weren't registered explicitly.
*
* @throws Exception If failed.
*/
public void testAddMissingBinary() throws Exception {
try {
binaries = true;
startGrids(2);
awaitPartitionMapExchange();
Ignite g0 = grid(0);
IgniteDataStreamer<Integer, TestObject2> dataLdr = g0.dataStreamer(null);
dataLdr.perNodeBufferSize(1);
dataLdr.autoFlushFrequency(1L);
Map<Integer, TestObject2> map = U.newHashMap(KEYS_COUNT);
for (int i = 0; i < KEYS_COUNT; i ++)
map.put(i, new TestObject2(i));
dataLdr.addData(map).get();
dataLdr.close();
}
finally {
G.stopAll(true);
}
}
/**
* Data streamer should correctly load binary entries from HashMap in case of grids with more than one node
* and with GridOptimizedMarshaller that requires serializable.
*
* @throws Exception If failed.
*/
public void testAddBinaryDataFromMap() throws Exception {
try {
binaries = true;
startGrids(2);
awaitPartitionMapExchange();
Ignite g0 = grid(0);
IgniteDataStreamer<Integer, TestObject> dataLdr = g0.dataStreamer(null);
Map<Integer, TestObject> map = U.newHashMap(KEYS_COUNT);
for (int i = 0; i < KEYS_COUNT; i ++)
map.put(i, new TestObject(i));
dataLdr.addData(map);
dataLdr.close(false);
checkDistribution(grid(0));
checkDistribution(grid(1));
// Read random keys. Take values as TestObject.
Random rnd = new Random();
IgniteCache<Integer, TestObject> c = g0.cache(null);
for (int i = 0; i < 100; i ++) {
Integer k = rnd.nextInt(KEYS_COUNT);
TestObject v = c.get(k);
assertEquals(k, v.val());
}
// Read random keys. Take values as BinaryObject.
IgniteCache<Integer, BinaryObject> c2 = ((IgniteCacheProxy)c).keepBinary();
for (int i = 0; i < 100; i ++) {
Integer k = rnd.nextInt(KEYS_COUNT);
BinaryObject v = c2.get(k);
assertEquals(k, v.field("val"));
}
}
finally {
G.stopAll(true);
}
}
/**
* Tries to propagate cache with binary objects created using the builder.
*
* @throws Exception If failed.
*/
public void testAddBinaryCreatedWithBuilder() throws Exception {
try {
binaries = true;
startGrids(2);
awaitPartitionMapExchange();
Ignite g0 = grid(0);
IgniteDataStreamer<Integer, BinaryObject> dataLdr = g0.dataStreamer(null);
for (int i = 0; i < 500; i++) {
BinaryObjectBuilder obj = g0.binary().builder("NoExistedClass");
obj.setField("id", i);
obj.setField("name", String.valueOf("name = " + i));
dataLdr.addData(i, obj.build());
}
dataLdr.close(false);
assertEquals(500, g0.cache(null).size(CachePeekMode.ALL));
assertEquals(500, grid(1).cache(null).size(CachePeekMode.ALL));
}
finally {
G.stopAll(true);
}
}
/**
* Check that keys correctly destributed by nodes after data streamer.
*
* @param g Grid to check.
*/
private void checkDistribution(Ignite g) {
ClusterNode n = g.cluster().localNode();
IgniteCache c = g.cache(null);
// Check that data streamer correctly split data by nodes.
for (int i = 0; i < KEYS_COUNT; i ++) {
if (g.affinity(null).isPrimary(n, i))
assertNotNull(c.localPeek(i, CachePeekMode.ONHEAP));
else
assertNull(c.localPeek(i, CachePeekMode.ONHEAP));
}
}
/**
*/
private static class TestObject implements Binarylizable, Serializable {
/** */
private int val;
/**
*
*/
private TestObject() {
// No-op.
}
/**
* @param val Value.
*/
private TestObject(int val) {
this.val = val;
}
public Integer val() {
return val;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return val;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {
return obj instanceof TestObject && ((TestObject)obj).val == val;
}
/** {@inheritDoc} */
@Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
writer.writeInt("val", val);
}
/** {@inheritDoc} */
@Override public void readBinary(BinaryReader reader) throws BinaryObjectException {
val = reader.readInt("val");
}
}
/**
*/
private static class TestObject2 implements Binarylizable, Serializable {
/** */
private int val;
/**
*/
private TestObject2() {
// No-op.
}
/**
* @param val Value.
*/
private TestObject2(int val) {
this.val = val;
}
public Integer val() {
return val;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return val;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {
return obj instanceof TestObject2 && ((TestObject2)obj).val == val;
}
/** {@inheritDoc} */
@Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
writer.writeInt("val", val);
}
/** {@inheritDoc} */
@Override public void readBinary(BinaryReader reader) throws BinaryObjectException {
val = reader.readInt("val");
}
}
}
| {
"content_hash": "cd6ee2d0e9bc47fa2bcac70c3272f601",
"timestamp": "",
"source": "github",
"line_count": 367,
"max_line_length": 111,
"avg_line_length": 28.22343324250681,
"alnum_prop": 0.5864066422089207,
"repo_name": "nivanov/ignite",
"id": "c8a64b41fce6022c57a5441d61fc636901c60821",
"size": "11160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/datastreaming/GridDataStreamerImplSelfTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "37548"
},
{
"name": "C",
"bytes": "5286"
},
{
"name": "C#",
"bytes": "4772806"
},
{
"name": "C++",
"bytes": "2506272"
},
{
"name": "CSS",
"bytes": "134061"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "515192"
},
{
"name": "Java",
"bytes": "27293772"
},
{
"name": "JavaScript",
"bytes": "1116197"
},
{
"name": "M4",
"bytes": "5568"
},
{
"name": "Makefile",
"bytes": "104025"
},
{
"name": "Nginx",
"bytes": "3468"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "13480"
},
{
"name": "Scala",
"bytes": "683756"
},
{
"name": "Shell",
"bytes": "586711"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
<?php
/**
* NOTICE:
*
* If you need to make modifications to the default configuration, copy
* this file to your app/config folder, and make them in there.
*
* This will allow you to upgrade fuel without losing your custom config.
*/
return array(
/**
* base_url - The base URL of the application.
* MUST contain a trailing slash (/)
*
* You can set this to a full or relative URL:
*
* 'base_url' => '/foo/',
* 'base_url' => 'http://foo.com/'
*
* Set this to null to have it automatically detected.
*/
'base_url' => null,
/**
* url_suffix - Any suffix that needs to be added to
* URL's generated by Fuel. If the suffix is an extension,
* make sure to include the dot
*
* 'url_suffix' => '.html',
*
* Set this to an empty string if no suffix is used
*/
'url_suffix' => '',
/**
* index_file - The name of the main bootstrap file.
*
* Set this to 'index.php if you don't use URL rewriting
*/
'index_file' => false,
'profiling' => false,
/**
* profiling_paths - The paths to show in profiler.
*
* If you do not wish to see path set to 'NULL'
* You can also add other paths that you wish not to see
*/
'profiling_paths' => array(
'APPPATH' => APPPATH,
'COREPATH' => COREPATH,
'PKGPATH' => PKGPATH,
),
/**
* Default location for the file cache
*/
'cache_dir' => APPPATH.'cache/',
/**
* Settings for the file finder cache (the Cache class has it's own config!)
*/
'caching' => false,
'cache_lifetime' => 3600, // In Seconds
/**
* Callback to use with ob_start(), set this to 'ob_gzhandler' for gzip encoding of output
*/
'ob_callback' => null,
'errors' => array(
// Which errors should we show, but continue execution? You can add the following:
// E_NOTICE, E_WARNING, E_DEPRECATED, E_STRICT to mimic PHP's default behaviour
// (which is to continue on non-fatal errors). We consider this bad practice.
'continue_on' => array(),
// How many errors should we show before we stop showing them? (prevents out-of-memory errors)
'throttle' => 10,
// Should notices from Error::notice() be shown?
'notices' => true,
// Render previous contents or show it as HTML?
'render_prior' => false,
),
/**
* Localization & internationalization settings
*/
'language' => 'en', // Default language
'language_fallback' => 'en', // Fallback language when file isn't available for default language
'locale' => 'en_US', // PHP set_locale() setting, null to not set
/**
* Internal string encoding charset
*/
'encoding' => 'UTF-8',
/**
* DateTime settings
*
* server_gmt_offset in seconds the server offset from gmt timestamp when time() is used
* default_timezone optional, if you want to change the server's default timezone
*/
'server_gmt_offset' => 0,
'default_timezone' => null,
/**
* Logging Threshold. Can be set to any of the following:
*
* Fuel::L_NONE
* Fuel::L_ERROR
* Fuel::L_WARNING
* Fuel::L_DEBUG
* Fuel::L_INFO
* Fuel::L_ALL
*/
'log_threshold' => Fuel::L_WARNING,
'log_path' => APPPATH.'logs/',
'log_date_format' => 'Y-m-d H:i:s',
/**
* Security settings
*/
'security' => array(
/**
* If true, every HTTP request of the type speficied in autoload_methods
* will be checked for a CSRF token. If not present or not valid, a
* security exception will be thrown.
*/
'csrf_autoload' => false,
'csrf_autoload_methods' => array('post', 'put', 'delete'),
/**
* Name of the form field that holds the CSRF token.
*/
'csrf_token_key' => 'fuel_csrf_token',
/**
* Expiry of the token in seconds. If zero, the token remains the same
* for the entire user session.
*/
'csrf_expiration' => 0,
/**
* A salt to make sure the generated security tokens are not predictable
*/
'token_salt' => 'put your salt value here to make the token more secure',
/**
* Allow the Input class to use X headers when present
*
* Examples of these are HTTP_X_FORWARDED_FOR and HTTP_X_FORWARDED_PROTO, which
* can be faked which could have security implications
*/
'allow_x_headers' => false,
/**
* This input filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*
* Note: MUST BE DEFINED IN THE APP CONFIG FILE!
*/
//'uri_filter' => array(),
/**
* This input filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*
* Note: MUST BE DEFINED IN THE APP CONFIG FILE!
*/
//'input_filter' => array(),
/**
* This output filter can be any normal PHP function as well as 'xss_clean'
*
* WARNING: Using xss_clean will cause a performance hit.
* How much is dependant on how much input data there is.
*
* Note: MUST BE DEFINED IN THE APP CONFIG FILE!
*/
//'output_filter' => array(),
/**
* Encoding mechanism to use on htmlentities()
*/
'htmlentities_flags' => ENT_QUOTES,
/**
* Wether to encode HTML entities as well
*/
'htmlentities_double_encode' => false,
/**
* Whether to automatically filter view data
*/
'auto_filter_output' => true,
/**
* With output encoding switched on all objects passed will be converted to strings or
* throw exceptions unless they are instances of the classes in this array.
*/
'whitelisted_classes' => array(),
),
/**
* Cookie settings
*/
'cookie' => array(
// Number of seconds before the cookie expires
'expiration' => 0,
// Restrict the path that the cookie is available to
'path' => '/',
// Restrict the domain that the cookie is available to
'domain' => null,
// Only transmit cookies over secure connections
'secure' => false,
// Only transmit cookies over HTTP, disabling Javascript access
'http_only' => false,
),
/**
* Validation settings
*/
'validation' => array(
/**
* Wether to fallback to global when a value is not found in the input array.
*/
'global_input_fallback' => true,
),
/**
* Controller class prefix
*/
'controller_prefix' => 'Controller_',
/**
* Routing settings
*/
'routing' => array(
/**
* Whether URI routing is case sensitive or not
*/
'case_sensitive' => true,
/**
* Wether to strip the extension
*/
'strip_extension' => true,
),
/**
* Response settings
*/
'response' => array(
/**
* Wether to support URI wildcards when redirecting
*/
'redirect_with_wildcards' => true,
),
/**
* Config settings
*/
'config' => array(
/*
* Name of the table used by the Config_Db driver
*/
'table_name' => 'config',
),
/**
* Lang settings
*/
'lang' => array(
/*
* Name of the table used by the Lang_Db driver
*/
'table_name' => 'lang',
),
/**
* To enable you to split up your application into modules which can be
* routed by the first uri segment you have to define their basepaths
* here. By default empty, but to use them you can add something
* like this:
* array(APPPATH.'modules'.DS)
*
* Paths MUST end with a directory separator (the DS constant)!
*/
'module_paths' => array(
//APPPATH.'modules'.DS
),
/**
* To enable you to split up your additions to the framework, packages are
* used. You can define the basepaths for your packages here. By default
* empty, but to use them you can add something like this:
* array(APPPATH.'modules'.DS)
*
* Paths MUST end with a directory separator (the DS constant)!
*/
'package_paths' => array(
//PKGPATH
),
/**************************************************************************/
/* Always Load */
/**************************************************************************/
'always_load' => array(
/**
* These packages are loaded on Fuel's startup.
* You can specify them in the following manner:
*
* array('auth'); // This will assume the packages are in PKGPATH
*
* // Use this format to specify the path to the package explicitly
* array(
* array('auth' => PKGPATH.'auth/')
* );
*/
'packages' => array(
//'orm',
),
/**
* These modules are always loaded on Fuel's startup. You can specify them
* in the following manner:
*
* array('module_name');
*
* A path must be set in module_paths for this to work.
*/
'modules' => array(),
/**
* Classes to autoload & initialize even when not used
*/
'classes' => array(),
/**
* Configs to autoload
*
* Examples: if you want to load 'session' config into a group 'session' you only have to
* add 'session'. If you want to add it to another group (example: 'auth') you have to
* add it like 'session' => 'auth'.
* If you don't want the config in a group use null as groupname.
*/
'config' => array(),
/**
* Language files to autoload
*
* Examples: if you want to load 'validation' lang into a group 'validation' you only have to
* add 'validation'. If you want to add it to another group (example: 'forms') you have to
* add it like 'validation' => 'forms'.
* If you don't want the lang in a group use null as groupname.
*/
'language' => array(),
),
);
| {
"content_hash": "f6bb4aab5496501e3e37e8e758ed95c8",
"timestamp": "",
"source": "github",
"line_count": 371,
"max_line_length": 98,
"avg_line_length": 26.681940700808624,
"alnum_prop": 0.5833922618446308,
"repo_name": "wizardry/gitadora_skill_sim",
"id": "386e95f2559f88a5ccc6f777fa5b52da43c5993b",
"size": "10135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fuel/core/config/config.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1697"
},
{
"name": "CSS",
"bytes": "17842"
},
{
"name": "HTML",
"bytes": "8589"
},
{
"name": "JavaScript",
"bytes": "154968"
},
{
"name": "PHP",
"bytes": "2010034"
}
],
"symlink_target": ""
} |
namespace network {
namespace test {
// Parses the given Trust Tokens signed redemption record
// https://docs.google.com/document/d/1TNnya6B8pyomDK2F1R9CL3dY10OAmqWlnCxsWyOBDVQ/edit#bookmark=id.omg78vbnmjid,
// extracts the signature and body, and uses the given verification key to
// verify the signature.
//
// On success, if |srr_body_out| is non-null, sets |srr_body_out| to the
// obtained SRR body.
enum class SrrVerificationStatus {
kParseError,
kSignatureVerificationError,
kSuccess
};
SrrVerificationStatus VerifyTrustTokenSignedRedemptionRecord(
base::StringPiece record,
base::StringPiece verification_key,
std::string* srr_body_out = nullptr);
// Reconstructs a request's canonical request data, extracts the signature from
// its Sec-Signature header, checks that the Sec-Signature header's contained
// signature verifies.
//
// Optionally:
// - if |verification_key_out| is non-null, on success, returns the verification
// key so that the caller can verify further state concerning the key (like
// confirming that the key was bound to a previous redemption).
// - if |error_out| is non-null, on failure, sets it to a human-readable
// description of the reason the verification failed.
// - if |verifier| is non-null, uses the given verifier to verify the
// signature instead of Ed25519
bool ReconstructSigningDataAndVerifySignature(
const GURL& destination,
const net::HttpRequestHeaders& headers,
base::OnceCallback<bool(base::span<const uint8_t> data,
base::span<const uint8_t> signature,
base::span<const uint8_t> verification_key)>
verifier = {}, // defaults to Ed25519
std::string* error_out = nullptr,
std::string* verification_key_out = nullptr);
// Returns true if |srr_body| a valid CBOR encoding of an "SRR body" struct, as
// defined in the design doc. Otherwise, returns false and, if |error_out| is
// non-null, sets |error_out| to a helpful error message.
bool ConfirmSrrBodyIntegrity(base::StringPiece srr_body,
std::string* error_out = nullptr);
} // namespace test
} // namespace network
#endif // SERVICES_NETWORK_TRUST_TOKENS_TEST_SIGNED_REQUEST_VERIFICATION_UTIL_H_
| {
"content_hash": "6df2c3763e5a56ccd30d76ce1e612828",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 113,
"avg_line_length": 43.21153846153846,
"alnum_prop": 0.7222963951935915,
"repo_name": "endlessm/chromium-browser",
"id": "3f0a9fb4677ba19fa822032d94cac571527bfecd",
"size": "2784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services/network/trust_tokens/test/signed_request_verification_util.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
echo "<input class='top-search' type='text' name='top-search' placeholder='Поиск'>"; | {
"content_hash": "a4c8ad5cf09e4001065f0d33dab045bc",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 84,
"avg_line_length": 45,
"alnum_prop": 0.7,
"repo_name": "peskovsb/itdeptMain",
"id": "bd4fb11265e8e0a1fc322dacc46e242680ccee6e",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/widgets/views/searchwidget.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "275"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "171894"
},
{
"name": "HTML",
"bytes": "2316"
},
{
"name": "JavaScript",
"bytes": "973311"
},
{
"name": "PHP",
"bytes": "76091"
}
],
"symlink_target": ""
} |
"use strict";
// Wait for things to happen before continuing.
var Promise = require("bluebird");
var _ = require("lodash");
var _require = require("../redux"),
emitter = _require.emitter;
var waiters = [];
emitter.on("BOOTSTRAP_STAGE", function (action) {
var stage = action.payload.stage;
// Remove this stage from the waiters
waiters = waiters.map(function (w) {
var newWaiter = {
resolve: w.resolve,
events: _.difference(w.events, [stage])
};
if (newWaiter.events.length === 0) {
// Call resolve function then remove by returning undefined.
newWaiter.resolve();
return undefined;
} else {
return newWaiter;
}
}
// Cleanup null entries
);waiters = _.filter(waiters);
});
module.exports = function (_ref) {
var events = _ref.events;
return new Promise(function (resolve) {
waiters.push({
resolve: resolve,
events: events
});
});
};
//# sourceMappingURL=checkpoints-promise.js.map | {
"content_hash": "5c8c30141852dfdcb00317d704fcca66",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 66,
"avg_line_length": 23.428571428571427,
"alnum_prop": 0.633130081300813,
"repo_name": "juhov/travis-test",
"id": "6574418e7398ee5dbb96fa0e33f293d18f36b345",
"size": "984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/gatsby/dist/utils/checkpoints-promise.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11269"
},
{
"name": "JavaScript",
"bytes": "3414"
}
],
"symlink_target": ""
} |
title: "RHEL/CentOS"
description: "User documentation for installing and operating Sensu on Red Hat
Enterprise Linux and CentOS Linux systems."
weight: 6
version: "0.29"
product: "Sensu Core"
platformContent: true
menu:
sensu-core-0.29:
parent: platforms
---
# Sensu on RHEL/CentOS
## Reference documentation
- [Installing Sensu Core](#sensu-core)
- [Install Sensu using YUM](#install-sensu-core-repository)
- [Installing Sensu Enterprise](#sensu-enterprise)
- [Install the Sensu Enterprise repository](#install-sensu-enterprise-repository)
- [Install the Sensu Enterprise Dashboard repository](#install-sensu-enterprise-dashboard-repository)
- [Install Sensu Enterprise (server & API)](#install-sensu-enterprise)
- [Configure Sensu](#configure-sensu)
- [Create the Sensu configuration directory](#create-the-sensu-configuration-directory)
- [Example client configuration](#example-client-configuration)
- [Example transport configuration](#example-transport-configuration)
- [Example data store configuration](#example-data-store-configuration)
- [Example API configurations](#example-api-configurations)
- [Standalone configuration](#api-standalone-configuration)
- [Distributed configuration](#api-distributed-configuration)
- [Example Sensu Enterprise Dashboard configurations](#example-sensu-enterprise-dashboard-configurations)
- [Standalone configuration](#dashboard-standalone-configuration)
- [Distributed configuration](#dashboard-distributed-configuration)
- [Enable the Sensu services to start on boot](#enable-the-sensu-services-to-start-on-boot)
- [Disable the Sensu services on boot](#disable-the-sensu-services-on-boot)
- [Operating Sensu](#operating-sensu)
- [Managing the Sensu services/processes](#service-management)
## Install Sensu Core {#sensu-core}
Sensu Core is installed on RHEL and CentOS systems via a native system installer package (i.e. a .rpm file), which is available for [download][1] and from YUM package management repositories.
The Sensu Core package installs several processes including `sensu-server`, `sensu-api`, and `sensu-client`.
### Install Sensu using YUM (recommended) {#install-sensu-core-repository}
Sensu packages for Red Hat target currently supported versions of Red Hat
Enterprise Linux and their Centos equivalents. These packages are generally
expected to be compatible with Red Hat derivatives like SuSE, Amazon or
Scientific Linux, but packages are not tested on these platforms.
The following instructions describe configuring package repository definitions
using [Yum variables][14] as components of the baseurl. On Red Hat derivative
platforms the value of the `$releasever` variable will not typically align with
the RHEL release versions (e.g. `6` or `7`) advertised in the Sensu Yum
repository. Please use `6` or `7` in lieu of `$releasever` on RHEL derivatives,
depending on whether they use sysv init or systemd, respectively.
_NOTE: As of Sensu version 0.27, the yum repository URL has changed to
include the `$releasever` variable. To install or upgrade to the
latest version of Sensu, please ensure you have updated existing
repository configurations._
1. Create the YUM repository configuration file for the Sensu Core repository at
`/etc/yum.repos.d/sensu.repo`:
{{< code shell >}}
echo '[sensu]
name=sensu
baseurl=https://eol-repositories.sensuapp.org/yum/$releasever/$basearch/
gpgkey=https://eol-repositories.sensuapp.org/yum/pubkey.gpg
gpgcheck=1
enabled=1' | sudo tee /etc/yum.repos.d/sensu.repo{{< /code >}}
2. Install Sensu:
{{< code shell >}}
sudo yum install sensu{{< /code >}}
_NOTE: as mentioned above, the `sensu` package installs all of the Sensu Core
processes, including `sensu-client`, `sensu-server`, and `sensu-api`._
3. Configure Sensu. **No "default" configuration is provided with Sensu**, so
none of the Sensu processes will run without the corresponding configuration.
Please refer to the ["Configure Sensu" section][10] (below), for more
information on configuring Sensu. **At minimum, all of the Sensu processes
will need a working [transport definition][11]**. The Sensu client will need
a [client definition][12], and both the `sensu-server` and `sensu-api` will
need a [data-store (Redis) definition][13] — all of which are explained
below.
## Install Sensu Enterprise {#sensu-enterprise}
[Sensu Enterprise][2] is installed on RHEL and CentOS systems via a native
system installer package (i.e. a .rpm file). The Sensu Enterprise installer
package is made available via the Sensu Enterprise YUM repository, which
requires access credentials to access. The Sensu Enterprise packages install two
processes: `sensu-enterprise` (which provides the Sensu server and API from a
single process), and `sensu-enterprise-dashboard` (which provides the dashboard
API and web application).
_NOTE: Some versions of RHEL and CentOS may require the
[EPEL package repository][epel] to provide the required OpenJDK runtime._
_WARNING: Sensu Enterprise is designed to be a drop-in replacement for the Sensu
Core server and API, **only**. Sensu Enterprise uses the same `sensu-client`
process provided by the Sensu Core installer packages (above). As a result,
**Sensu Enterprise does not need to be installed on every system** being
monitored by Sensu._
### Install the Sensu Enterprise repository {#install-sensu-enterprise-repository}
1. Set access credentials as environment variables
{{< code shell >}}
SE_USER=1234567890
SE_PASS=PASSWORD{{< /code >}}
_NOTE: please replace `1234567890` and `PASSWORD` with the access credentials
provided with your Sensu Enterprise subscription. These access
credentials can be found by logging into the [Sensu Account Manager portal][15]._
Confirm that you have correctly set your access credentials as environment
variables
{{< code shell >}}
$ echo $SE_USER:$SE_PASS
1234567890:PASSWORD{{< /code >}}
2. Create a YUM repository configuration file for the Sensu Enterprise
repository at `/etc/yum.repos.d/sensu-enterprise.repo`:
{{< code shell >}}
echo "[sensu-enterprise]
name=sensu-enterprise
baseurl=https://$SE_USER:[email protected]/yum/noarch/
gpgkey=https://eol-repositories.sensuapp.org/yum/pubkey.gpg
gpgcheck=1
enabled=1" | sudo tee /etc/yum.repos.d/sensu-enterprise.repo{{< /code >}}
3. Install Sensu Enterprise
{{< code shell >}}
sudo yum install sensu-enterprise{{< /code >}}
4. Configure Sensu Enterprise. **No "default" configuration is provided with
Sensu Enterprise**, so Sensu Enterprise will run without the corresponding
configuration. Please refer to the ["Configure Sensu" section][11] (below)
for more information on configuring Sensu Enterprise.
### Install the Sensu Enterprise Dashboard repository {#install-sensu-enterprise-dashboard-repository}
1. Set access credentials as environment variables
{{< code shell >}}
SE_USER=1234567890
SE_PASS=PASSWORD{{< /code >}}
_NOTE: please replace `1234567890` and `PASSWORD` with the access credentials
provided with your Sensu Enterprise subscription. These access
credentials can be found by logging into the [Sensu Account Manager portal][15]._
Confirm that you have correctly set your access credentials as environment
variables
{{< code shell >}}
$ echo $SE_USER:$SE_PASS
1234567890:PASSWORD{{< /code >}}
2. Create a YUM repository configuration file for the Sensu Enterprise Dashboard
repository at `/etc/yum.repos.d/sensu-enterprise-dashboard.repo`:
{{< code shell >}}
echo "[sensu-enterprise-dashboard]
name=sensu-enterprise-dashboard
baseurl=https://$SE_USER:[email protected]/yum/\$basearch/
gpgkey=https://eol-repositories.sensuapp.org/yum/pubkey.gpg
gpgcheck=1
enabled=1" | sudo tee /etc/yum.repos.d/sensu-enterprise-dashboard.repo{{< /code >}}
4. Install Sensu Enterprise Dashboard
{{< code shell >}}
sudo yum install sensu-enterprise-dashboard{{< /code >}}
5. Configure Sensu Enterprise Dashboard. **The default configuration
will not work without modification** Please refer to the
["Example Sensu Enterprise Dashboard configurations" section][16] (below) for more information on
configuring Sensu Enterprise Dashboard.
## Configure Sensu
By default, all of the Sensu services on RHEL and CentOS systems will load
configuration from the following locations:
- `/etc/sensu/config.json`
- `/etc/sensu/conf.d/`
_NOTE: Additional or alternative configuration file and directory locations may
be used by modifying Sensu's service scripts and/or by starting the Sensu
services with the corresponding CLI arguments. For more information, please
consult the [Sensu Configuration][3] reference documentation._
### Create the Sensu configuration directory
In some cases, the default Sensu configuration directory (i.e.
`/etc/sensu/conf.d/`) is not created by the Sensu installer, in which case it is
necessary to create this directory manually.
{{< code shell >}}
mkdir /etc/sensu/conf.d{{< /code >}}
### Example client configuration
1. Copy the following contents to a configuration file located at
`/etc/sensu/conf.d/client.json`:
{{< code json >}}
{
"client": {
"name": "rhel-client",
"address": "127.0.0.1",
"environment": "development",
"subscriptions": [
"dev",
"rhel-hosts"
],
"socket": {
"bind": "127.0.0.1",
"port": 3030
}
}
}{{< /code >}}
### Example transport configuration
At minimum, all of the Sensu processes require configuration to tell them how to
connect to the configured [Sensu Transport][4].
1. Copy the following contents to a configuration file located at
`/etc/sensu/conf.d/transport.json`:
{{< code json >}}
{
"transport": {
"name": "rabbitmq",
"reconnect_on_error": true
}
}{{< /code >}}
_NOTE: if you are using Redis as your transport, please use `"name": "redis"`
for your transport configuration. For more information, please visit the
[transport definition specification][11]._
2. If the transport being used is running on a different host, additional configuration is required to tell the sensu client how to connect to the transport.
Please see [Redis][5] or [RabbitMQ][6] reference documentation for examples.
### Example data store configuration
The Sensu Core server and API processes, and the Sensu Enterprise process all
require configuration to tell them how to connect to Redis (the Sensu data
store). Please refer to the [Redis reference documentation][5] for configuration
file examples.
### Example API configurations
#### Standalone configuration {#api-standalone-configuration}
1. Copy the following contents to a configuration file located at
`/etc/sensu/conf.d/api.json`:
{{< code json >}}
{
"api": {
"host": "localhost",
"bind": "0.0.0.0",
"port": 4567
}
}{{< /code >}}
#### Distributed configuration {#api-distributed-configuration}
1. Obtain the IP address of the system where the Sensu API is installed. For the
purpose of this guide, we will use `10.0.1.7` as our example IP address.
1. Create a configuration file with the following contents at
`/etc/sensu/conf.d/api.json` on the Sensu server and API system(s):
{{< code json >}}
{
"api": {
"host": "10.0.1.7",
"bind": "10.0.1.7",
"port": 4567
}
}{{< /code >}}
### Example Sensu Enterprise Dashboard configurations
#### Standalone configuration {#dashboard-standalone-configuration}
1. Copy the following contents to a configuration file located at
`/etc/sensu/dashboard.json`:
{{< code json >}}
{
"sensu": [
{
"name": "Datacenter 1",
"host": "localhost",
"port": 4567
}
],
"dashboard": {
"host": "0.0.0.0",
"port": 3000
}
}{{< /code >}}
#### Distributed configuration {#dashboard-distributed-configuration}
1. Obtain the IP address of the system where Sensu Enterprise is installed. For
the purpose of this guide, we will use `10.0.1.7` as our example IP address.
2. Copy the following contents to a configuration file located at
`/etc/sensu/dashboard.json`:
{{< code json >}}
{
"sensu": [
{
"name": "Datacenter 1",
"host": "10.0.1.7",
"port": 4567
}
],
"dashboard": {
"host": "0.0.0.0",
"port": 3000
}
}{{< /code >}}
_NOTE: Multiple Sensu Enterprise Dashboard instances can be installed. When
load balancing across multiple Dashboard instances, your load balancer should
support "sticky sessions"._
3. The Sensu Enterprise Dashboard process requires configuration to tell it how
to connect to Redis (the Sensu data store). Please refer to the [Redis
installation instructions][5] for configuration file examples.
### Enable the Sensu services to start on boot
By default, the Sensu services are not configured to start automatically on
system boot (we recommend managing the Sensu services with a process supervisor
such as [runit][7]). To enable Sensu services on system boot, use the
[`chkconfig` utility][8].
- Enable the Sensu client on system boot
{{< code shell >}}
sudo chkconfig sensu-client on{{< /code >}}
- Enable the Sensu server and API to start on system boot
- For Sensu Core users (i.e. `sensu-server` and `sensu-api`)
{{< code shell >}}
sudo chkconfig sensu-server on
sudo chkconfig sensu-api on{{< /code >}}
- For Sensu Enterprise users
{{< code shell >}}
sudo chkconfig sensu-enterprise on{{< /code >}}
_WARNING: the `sensu-enterprise` process is intended to be a drop-in
replacement for the Sensu Core `sensu-server` and `sensu-api` processes.
Please [ensure that the Sensu Core processes are not configured to start on
system][8] boot before enabling Sensu Enterprise to start on system boot._
- Enable Sensu Enterprise Dashboard on system boot
{{< code shell >}}
sudo chkconfig sensu-enterprise-dashboard defaults{{< /code >}}
_WARNING: the `sensu-enterprise-dashboard` process is intended to be a drop-in
replacement for the Uchiwa dashboard. Please ensure that the Uchiwa processes
are not configured to start on system boot before enabling the Sensu
Enterprise Dashboard to start on system boot._
### Disable the Sensu services on boot
If you have enabled Sensu services on boot and now need to disable them, this
can also be accomplished using the [`chkconfig` utility][9].
- Disable the Sensu client on system boot
{{< code shell >}}
sudo chkconfig sensu-client off{{< /code >}}
- Disable the Sensu Core server on system boot
{{< code shell >}}
sudo chkconfig sensu-server off{{< /code >}}
- Disable the Sensu Core API on system boot
{{< code shell >}}
sudo chkconfig sensu-api off{{< /code >}}
- Disable Sensu Enterprise on system boot
{{< code shell >}}
sudo chkconfig sensu-enterprise off{{< /code >}}
- Disable Sensu Enterprise Dashboard on system boot
{{< code shell >}}
sudo chkconfig sensu-enterprise-dashboard remove{{< /code >}}
## Operating Sensu
### Managing the Sensu services/processes {#service-management}
To manually start and stop the Sensu services, use the following commands:
_NOTE: The `service` command will not work on CentOS 5, the sysvinit
script must be used, e.g. `sudo /etc/init.d/sensu-client start`_
- Start or stop the Sensu client
{{< code shell >}}
sudo service sensu-client start
sudo service sensu-client stop{{< /code >}}
- Start or stop the Sensu Core server
{{< code shell >}}
sudo service sensu-server start
sudo service sensu-server stop{{< /code >}}
- Start or stop the Sensu Core API
{{< code shell >}}
sudo service sensu-api start
sudo service sensu-api stop{{< /code >}}
- Start or stop Sensu Enterprise
{{< code shell >}}
sudo service sensu-enterprise start
sudo service sensu-enterprise stop{{< /code >}}
- Start or stop the Sensu Enterprise Dashboard
{{< code shell >}}
sudo service sensu-enterprise-dashboard start
sudo service sensu-enterprise-dashboard stop{{< /code >}}
Verify the Sensu Enterprise Dashboard is running by visiting view the
dashboard at http://localhost:3000 (replace `localhost` with the hostname or
IP address where the Sensu Enterprise Dashboard is running).
[1]: https://eol-repositories.sensuapp.org/yum/
[2]: https://sensu.io/products/enterprise
[3]: ../../reference/configuration/
[4]: ../../reference/transport/
[5]: ../../reference/redis/#configure-sensu
[6]: ../../reference/rabbitmq/#sensu-rabbitmq-configuration
[7]: http://smarden.org/runit/
[8]: #disable-the-sensu-services-on-boot
[9]: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s2-services-chkconfig.html
[10]: #configure-sensu
[11]: #example-transport-configuration
[12]: #example-client-configuration
[13]: #example-data-store-configuration
[14]: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/sec-Using_Yum_Variables.html
[15]: https://account.sensu.io
[16]: #example-sensu-enterprise-dashboard-configurations
[epel]: https://www.fedoraproject.org/wiki/EPEL
| {
"content_hash": "152d80df52caed9de531147191c504f2",
"timestamp": "",
"source": "github",
"line_count": 457,
"max_line_length": 191,
"avg_line_length": 37.288840262582056,
"alnum_prop": 0.7335837098761809,
"repo_name": "sensu/sensu-docs",
"id": "60e6fb71e962f7543da1097e1ae52bc791c2b161",
"size": "17045",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "archived/sensu-core/0.29/platforms/sensu-on-rhel-centos.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "123020"
},
{
"name": "JavaScript",
"bytes": "61971"
},
{
"name": "Procfile",
"bytes": "14"
},
{
"name": "Python",
"bytes": "3764"
},
{
"name": "Ruby",
"bytes": "4422"
},
{
"name": "SCSS",
"bytes": "32403"
},
{
"name": "Shell",
"bytes": "30924"
}
],
"symlink_target": ""
} |
module Graph
module Queries
module Tags
Show = GraphQL::Field.define do |field|
field.type -> { Types::Tag }
field.description 'Get a tag'
field.argument :id, types.ID
field.argument :name, types.String
field.resolve Graph::Handler.new ->(_obj, args, context) do
case
when args[:id]
::Tag.find_by!(key: args[:id].match(/\ATag::(.+)\z/).try(:[], 1))
when args[:name]
::Tag.find_by!(content: Tag.normalize(args[:name]))
end.tap do |tag|
Pundit.authorize(context[:access_token], tag, :show?) if tag
end
end
end
end
end
end
| {
"content_hash": "794f2eee092bd5ba4b2ad20050c32613",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 77,
"avg_line_length": 28.333333333333332,
"alnum_prop": 0.5352941176470588,
"repo_name": "rutan/potmum",
"id": "d5523d185c1e99002e52acf21648444bedd47e87",
"size": "711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/apis/graph/queries/tags/show.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27441"
},
{
"name": "HTML",
"bytes": "46455"
},
{
"name": "JavaScript",
"bytes": "20263"
},
{
"name": "Ruby",
"bytes": "164551"
}
],
"symlink_target": ""
} |
cookbook_path [
'/vagrant/cookbooks',
]
Chef::Config['/vagrant/cookbooks']
| {
"content_hash": "546fe8b22f025bb4d6101f733855abb5",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 36,
"avg_line_length": 21,
"alnum_prop": 0.5142857142857142,
"repo_name": "Gum-Joe/Web-OS-docker",
"id": "028aa31263d5cfd80a89f7456f08a3c1b83ab93b",
"size": "105",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "solo.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12566"
},
{
"name": "Shell",
"bytes": "320"
}
],
"symlink_target": ""
} |
@javax.xml.bind.annotation.XmlSchema(namespace = "http://rest.immobilienscout24.de/schema/customer/1.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package de.immobilienscout24.rest.schema.customer._1;
| {
"content_hash": "7de14e28b203a2ea40e857dbe154d650",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 172,
"avg_line_length": 77,
"alnum_prop": 0.8051948051948052,
"repo_name": "ImmobilienScout24/restapi-java-sdk",
"id": "2b6faecc98b7dcd5a974bb00e626744a58265c2a",
"size": "575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/generated-sources/de/immobilienscout24/rest/schema/customer/_1/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1551100"
},
{
"name": "Shell",
"bytes": "199"
},
{
"name": "XSLT",
"bytes": "617"
}
],
"symlink_target": ""
} |
var inject = require('../../../lib/inject.js');
var DOM = require('jsx-dom-factory');
var _ = require('underscore');
var $ = require('jquery');
function renderQuickText(id, selections) {
return (
<div class="form-group">
<div class="row">
<label class="col-md-4 col-lg-3 control-label">
<img style="width:16px;vertical-align:top;margin-right:5px"
src={chrome.extension.getURL("icons/lh-black.png")} />
Quick Text
</label>
<div class="col-md-8 col-lg-9">
<select class="form-control" id={id} style="width:100%">
{
_.map(selections, function(selection) {
return <option>{selection}</option>;
})
}
</select>
</div>
</div>
</div>
);
}
// Quick Text - Job - Finalise
$('#finaliseJobModal .modal-body .form-group:nth-child(1)').after(
renderQuickText("FinaliseQuickTextBox", [
"",
"All paperwork and documentation completed",
"NFA",
"Job completed"
])
);
// Quick Text - Job - Complete
// this is nth-child(1) even though there are more elements because
// at the time this code _usually_ runs knockout hasn't been initialised
// yet so there are less elements than after it has rendered.
// TODO: make this more intelligent by searching for the appropriate
// label and inserting before/after that.
$('#completeRescueModal .modal-body .form-group:nth-child(1)').after(
renderQuickText("CompleteQuickTextBox", [
"",
"All paperwork and documentation completed",
"NFA",
"NFA SES. Referred to council",
"Job completed"
])
);
// Quick Actions - Job - Team Complete
var options = [
["Storm/Tree Ops", "stormtree", "tag-task"],
["Storm/Property Protect", "stormproperty", "tag-task"],
["Storm/Public Safety", "stormsafety", "tag-task"],
["Storm/Road Access", "stormaccess", "tag-task"],
["Storm/Recon", "stormrecon", "tag-task"],
["RCR/Calloff", "rcrcalloff", "tag-rescue"],
["RCR/Extricate", "rcrcallextricate", "tag-rescue"]
];
var html = (
<div class="form-group">
<div class="row">
<label class="col-md-4 col-lg-3 control-label">
<img style="width:16px;vertical-align:top;margin-right:5px"
src={chrome.extension.getURL("icons/lh-black.png")} />
Quick Tasks
</label>
<div class="col-md-8 col-lg-9">
{
_.map(options, function(option) {
return (
<span id={option[1]} class={'label tag tag-disabled '+option[2]}>
<span class="tag-text">{option[0]}</span>
</span>
);
})
}
</div>
</div>
</div>
);
// Quick Text - Job - Team Complete
var html2 = renderQuickText("CompleteTeamQuickTextBox", [
"",
"NSW SES volunteers attended scene and resident no longer required assistance.",
])
$('#completeTeamModal .modal-body .form-group:nth-child(12)').after([html, html2]);
// Insert element into DOM - Will populate with AJAX results via checkAddressHistory()
job_view_history = (
<fieldset id="job_view_history_groups" class="col-md-12">
<legend class="main"><img style="width:16px;vertical-align:inherit;margin-right:5px"
src={chrome.extension.getURL("icons/lh-black.png")} />Job History <span>12 Months search by Address</span></legend>
<div id="job_view_history_container">
<div style="text-align:center">
<img src="/Content/images/loading_30.gif" />
</div>
</div>
</fieldset>
);
$('fieldset.col-md-12 legend').each(function(k,v){
var $v = $(v);
var $p = $v.closest('fieldset');
var section_title = $v.text().trim();
if( section_title.indexOf( 'Notes' ) === 0 || section_title.indexOf( 'Messages' ) === 0 ){
$p.before(job_view_history);
return false; // break out of $.each()
}
});
// inject the coded needed to fix visual problems
// needs to be injected so that it runs after the DOMs are created
// We run this last because we want to ensure the elements created above have
// been loaded into the DOM before the injected script runs
inject('jobs/view.js');
| {
"content_hash": "889e6c35a063578a4729f003b3a14ad9",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 132,
"avg_line_length": 31.96212121212121,
"alnum_prop": 0.6018013747333492,
"repo_name": "sjcliffe/Lighthouse",
"id": "3e8082ca03860173fb5b4c63b95c950f16ca7ceb",
"size": "4219",
"binary": false,
"copies": "1",
"ref": "refs/heads/nitcstats",
"path": "src/contentscripts/jobs/view.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10167"
},
{
"name": "HTML",
"bytes": "11490"
},
{
"name": "JavaScript",
"bytes": "140284"
}
],
"symlink_target": ""
} |
package io.joern.jimple2cpg.querying
import io.joern.jimple2cpg.testfixtures.JimpleCode2CpgFixture
import io.shiftleft.codepropertygraph.generated.EvaluationStrategies
import io.shiftleft.semanticcpg.language._
class MethodParameterTests extends JimpleCode2CpgFixture {
val cpg = code("""package a;
|class Foo {
| int foo(int param1, Object param2) {
| return 0;
| }
|}
""".stripMargin)
"should return exactly three parameters with correct fields" in {
cpg.parameter.filter(_.method.name == "foo").name.toSetMutable shouldBe Set("this", "param1", "param2")
val List(t) = cpg.parameter.filter(_.method.name == "foo").name("this").l
t.code shouldBe "this"
t.typeFullName shouldBe "a.Foo"
t.lineNumber shouldBe Some(3)
t.columnNumber shouldBe None
t.order shouldBe 0
t.evaluationStrategy shouldBe EvaluationStrategies.BY_SHARING
val List(x) = cpg.parameter.filter(_.method.name == "foo").name("param1").l
x.code shouldBe "int param1"
x.typeFullName shouldBe "int"
x.lineNumber shouldBe Some(3)
x.columnNumber shouldBe None
x.order shouldBe 1
x.evaluationStrategy shouldBe EvaluationStrategies.BY_VALUE
val List(y) = cpg.parameter.filter(_.method.name == "foo").name("param2").l
y.code shouldBe "java.lang.Object param2"
y.typeFullName shouldBe "java.lang.Object"
y.lineNumber shouldBe Some(3)
y.columnNumber shouldBe None
y.order shouldBe 2
y.evaluationStrategy shouldBe EvaluationStrategies.BY_REFERENCE
}
"should allow traversing from parameter to method" in {
cpg.parameter.name("param1").method.filter(_.isExternal == false).name.l shouldBe List("foo")
}
}
| {
"content_hash": "ee6b9eccaa7279d59d02fc2a92c5e5bd",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 107,
"avg_line_length": 34.816326530612244,
"alnum_prop": 0.7121922626025792,
"repo_name": "joernio/joern",
"id": "bda965d2603b0dabe3ef96e6d3ec63a6a79569fa",
"size": "1706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "joern-cli/frontends/jimple2cpg/src/test/scala/io/joern/jimple2cpg/querying/MethodParameterTests.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "392"
},
{
"name": "Assembly",
"bytes": "2863"
},
{
"name": "Batchfile",
"bytes": "4007"
},
{
"name": "C",
"bytes": "6454"
},
{
"name": "C++",
"bytes": "1470"
},
{
"name": "Dockerfile",
"bytes": "1293"
},
{
"name": "HCL",
"bytes": "22"
},
{
"name": "Java",
"bytes": "2081117"
},
{
"name": "JavaScript",
"bytes": "544"
},
{
"name": "Kotlin",
"bytes": "3465"
},
{
"name": "PHP",
"bytes": "58140"
},
{
"name": "Python",
"bytes": "69"
},
{
"name": "Scala",
"bytes": "4031151"
},
{
"name": "Shell",
"bytes": "60108"
},
{
"name": "SuperCollider",
"bytes": "6313"
}
],
"symlink_target": ""
} |
/**
* Test for map type parser from proto IDL
*
* @author xiemalin
* @since 2.0.0.0
*/
package com.baidu.bjf.remoting.protobuf.idlproxy.map; | {
"content_hash": "222cd2c03f23bb59fdf825e1cfc3f91c",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 53,
"avg_line_length": 19.25,
"alnum_prop": 0.6493506493506493,
"repo_name": "jhunters/jprotobuf",
"id": "fb564574b7e50c5f673a0cd3aac410a875ec64e3",
"size": "154",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/com/baidu/bjf/remoting/protobuf/idlproxy/map/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2074579"
},
{
"name": "Smarty",
"bytes": "3474"
}
],
"symlink_target": ""
} |
package srcscan
import (
"github.com/kr/pretty"
"go/build"
"os"
"reflect"
"sort"
"strings"
"testing"
)
func TestScan(t *testing.T) {
Default.PathIndependent = true
Default.Base = "testdata"
type scanTest struct {
config *Config
dir string
units []Unit
}
tests := []scanTest{
{
dir: "testdata",
units: []Unit{
&BowerComponent{
Dir: "bower",
BowerJSON: []byte(`{"name":"foo","dependencies":{"baz":"1.0.0"}}`),
},
&GoPackage{
Package: build.Package{
Dir: "go",
Name: "mypkg",
ImportPath: "github.com/sourcegraph/srcscan/testdata/go",
GoFiles: []string{"a.go", "b.go"},
Imports: []string{},
ImportPos: nil,
TestGoFiles: []string{"a_test.go"},
TestImports: []string{},
TestImportPos: nil,
XTestGoFiles: []string{"b_test.go"},
XTestImports: []string{},
XTestImportPos: nil,
},
},
&GoPackage{
Package: build.Package{
Dir: "go/cmd/mycmd",
Name: "main",
ImportPath: "github.com/sourcegraph/srcscan/testdata/go/cmd/mycmd",
GoFiles: []string{"mycmd.go"},
Imports: []string{},
ImportPos: nil,
TestGoFiles: nil,
TestImports: []string{},
TestImportPos: nil,
XTestGoFiles: nil,
XTestImports: []string{},
XTestImportPos: nil,
},
},
&GoPackage{
Package: build.Package{
Dir: "go/qux",
Name: "qux",
ImportPath: "github.com/sourcegraph/srcscan/testdata/go/qux",
GoFiles: []string{"qux.go"},
Imports: []string{},
ImportPos: nil,
TestGoFiles: nil,
TestImports: []string{},
TestImportPos: nil,
XTestGoFiles: nil,
XTestImports: []string{},
XTestImportPos: nil,
},
},
&JavaProject{
Dir: "java-maven",
ProjectClasspath: "target/classes",
SrcFiles: []string{"src/main/java/foo/Foo.java"},
TestFiles: []string{"src/test/java/bar/Bar.java"},
},
&NPMPackage{
Dir: "npm",
PackageJSON: []byte(`{"name":"mypkg"}`),
LibFiles: []string{"a.js", "lib/a.js"},
TestFiles: []string{"a_test.js", "test/b.js", "test/c_test.js"},
VendorFiles: []string{"example/bower_components/foo/foo.js", "vendor/a.js"},
GeneratedFiles: []string{"a.min.js", "dist/a.js"},
},
&NPMPackage{
Dir: "npm/subpkg",
PackageJSON: []byte(`{"name":"subpkg"}`),
LibFiles: []string{"a.js"},
},
&PythonModule{"python/myscript.py"},
&PythonPackage{"python/mypkg"},
&RubyApp{
Dir: "ruby/sample_app",
SrcFiles: []string{"app/app.rb"},
TestFiles: nil,
},
&RubyGem{
Dir: "ruby/sample_gem",
Name: "sample_ruby_gem",
GemSpecFile: "sample_ruby_gem.gemspec",
SrcFiles: []string{"lib/sample_ruby_gem.rb"},
TestFiles: []string{"spec/my_spec.rb", "test/qux.rb", "test/test_foo.rb"},
},
},
},
{
config: &Config{
PathIndependent: true,
Base: "testdata",
Profiles: []Profile{
{
Name: "Python package",
TopLevelOnly: false,
Dir: FileInDir{"__init__.py"},
File: FileHasSuffix{".py"},
Unit: func(abspath, relpath string, config Config, info os.FileInfo) Unit {
if info.IsDir() {
return &PythonPackage{relpath}
} else {
return &PythonModule{relpath}
}
},
},
},
},
dir: "testdata/python",
units: []Unit{
&PythonModule{"python/mypkg/__init__.py"},
&PythonModule{"python/mypkg/a.py"},
&PythonModule{"python/mypkg/qux/__init__.py"},
&PythonModule{"python/myscript.py"},
&PythonPackage{"python/mypkg"},
&PythonPackage{"python/mypkg/qux"},
},
},
}
for _, test := range tests {
// Use default config if config is nil.
var config Config
if test.config != nil {
config = *test.config
} else {
config = Default
}
units, err := config.Scan(test.dir)
if err != nil {
t.Errorf("got error %q", err)
continue
}
sort.Sort(Units(units))
sort.Sort(Units(test.units))
if !reflect.DeepEqual(test.units, units) {
t.Errorf("units:\n%v", pretty.Diff(test.units, units))
if len(test.units) == len(units) {
for i := range test.units {
if !reflect.DeepEqual(test.units[i], units[i]) {
t.Errorf("units[%d]:\n%v", i, strings.Join(pretty.Diff(test.units[i], units[i]), "\n"))
}
}
}
}
}
}
| {
"content_hash": "6da1901c0731455591d0e0e6009f365f",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 93,
"avg_line_length": 27.269005847953217,
"alnum_prop": 0.5359210808492387,
"repo_name": "sourcegraph/srcscan",
"id": "9ca677eeb31cb8eaebcaebb3d8b0bed85a74b114",
"size": "4663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "srcscan_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "27395"
},
{
"name": "Java",
"bytes": "72"
},
{
"name": "JavaScript",
"bytes": "0"
},
{
"name": "Python",
"bytes": "0"
},
{
"name": "Ruby",
"bytes": "0"
}
],
"symlink_target": ""
} |
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "m.macro.test", kind = State, state_key_type = String)]
pub struct MacroTestContent {
pub url: String,
}
fn main() {}
| {
"content_hash": "57f545a01f70cf388cd6732665f23d33",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 75,
"avg_line_length": 27.4,
"alnum_prop": 0.708029197080292,
"repo_name": "ruma/ruma",
"id": "c502c443a80e99c2664a2bc8ad9c980587972ab6",
"size": "274",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "crates/ruma-common/tests/events/ui/01-content-sanity-check.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "2765243"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Facebook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Facebook")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| {
"content_hash": "a6c372df0887002ccb66efd73995672e",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 84,
"avg_line_length": 37.14705882352941,
"alnum_prop": 0.7545526524148852,
"repo_name": "Hitcents/monodroid-bindings",
"id": "e2a6edf277bc2659eb39874b662052b3048c56c7",
"size": "1266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Facebook/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "31148"
},
{
"name": "Java",
"bytes": "26442"
}
],
"symlink_target": ""
} |
package org.sourcecodemetrics.report.generators;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openide.util.Exceptions;
import org.sourcecodemetrics.measurer.api.IClass;
import org.sourcecodemetrics.measurer.api.IMethod;
import org.sourcecodemetrics.measurer.api.IPackage;
import org.sourcecodemetrics.measurer.api.IProject;
import org.sourcecodemetrics.measurer.api.ISourceFile;
/**
*
* @author Krystian Warzocha
*/
public class RawDataGenerator {
public static void generateRawData(IProject project, HSSFWorkbook workbook) {
try {
generatePackages(project, workbook);
generateClasses(project, workbook);
generateMethods(project, workbook);
} catch (NoSuchMethodException ex) {
Exceptions.printStackTrace(ex);
} catch (IllegalAccessException ex) {
Exceptions.printStackTrace(ex);
} catch (IllegalArgumentException ex) {
Exceptions.printStackTrace(ex);
} catch (InvocationTargetException ex) {
Exceptions.printStackTrace(ex);
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
}
}
private static void generatePackages(IProject project, HSSFWorkbook workbook) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
HSSFSheet worksheet = workbook.createSheet("Raw package metrics");
// generation of header row
HSSFRow headerRow = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
for (int i = 0; i < packageMetrics.size(); i++) {
String title = packageMetrics.get(i);
HSSFCell cell = headerRow.createCell(i);
cell.setCellValue(title);
}
// generation of package metrics
for (IPackage pkg : project.getPackages()) {
if (!pkg.isTests() && !pkg.getSourceFiles().isEmpty()) {
HSSFRow row = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
// writing out the name of the package
HSSFCell nameCell = row.createCell(0);
nameCell.setCellValue(pkg.getName());
for (int i = 1; i < packageMetrics.size(); i++) {
String propertyName = packageMetrics.get(i);
Method getter = pkg.getClass().getMethod("get" + propertyName);
Object metricValue = getter.invoke(pkg);
HSSFCell cell = row.createCell(i);
if (metricValue instanceof Integer) {
cell.setCellValue((Integer) metricValue);
} else if (metricValue instanceof Double) {
cell.setCellValue((Double) metricValue);
} else if (metricValue instanceof String) {
cell.setCellValue((String) metricValue);
}
}
}
}
// autosizing the main column
worksheet.autoSizeColumn(0);
}
private static void generateClasses(IProject project, HSSFWorkbook workbook) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
HSSFSheet worksheet = workbook.createSheet("Raw class metrics");
// generation of header row
HSSFRow headerRow = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
for (int i = 0; i < classMetrics.size(); i++) {
String title = classMetrics.get(i);
HSSFCell cell = headerRow.createCell(i);
cell.setCellValue(title);
}
// generation of class metrics
for (IPackage pkg : project.getPackages()) {
if (!pkg.isTests() && !pkg.getSourceFiles().isEmpty()) {
for (ISourceFile sf : pkg.getSourceFiles()) {
for (IClass c : sf.getClasses()) {
HSSFRow row = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
// writing out the name of the package
HSSFCell packageCell = row.createCell(0);
packageCell.setCellValue(pkg.getName());
// writing out the name of the class
HSSFCell classCell = row.createCell(1);
classCell.setCellValue(c.getName());
// writing values of the metrics
for (int i = 2; i < classMetrics.size(); i++) {
String propertyName = classMetrics.get(i);
Method getter = c.getClass().getMethod("get" + propertyName);
Object metricValue = getter.invoke(c);
HSSFCell cell = row.createCell(i);
if (metricValue instanceof Integer) {
cell.setCellValue((Integer) metricValue);
} else if (metricValue instanceof Double) {
cell.setCellValue((Double) metricValue);
} else if (metricValue instanceof String) {
cell.setCellValue((String) metricValue);
} else if (metricValue instanceof Boolean) {
Boolean value = (Boolean) metricValue;
cell.setCellValue(value ? 1 : 0);
}
}
}
}
}
}
// autosizing the main columns
for (int i = 0; i < 2; i++) {
worksheet.autoSizeColumn(i);
}
}
private static void generateMethods(IProject project, HSSFWorkbook workbook) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
HSSFSheet worksheet = workbook.createSheet("Raw method metrics");
// generation of header row
HSSFRow headerRow = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
for (int i = 0; i < methodMetrics.size(); i++) {
String title = methodMetrics.get(i);
HSSFCell cell = headerRow.createCell(i);
cell.setCellValue(title);
}
// generation of method metrics
for (IPackage pkg : project.getPackages()) {
if (!pkg.isTests() && !pkg.getSourceFiles().isEmpty()) {
if (!pkg.isTests() && !pkg.getSourceFiles().isEmpty()) {
for (ISourceFile sf : pkg.getSourceFiles()) {
for (IClass c : sf.getClasses()) {
for (IMethod m : c.getMethods()) {
HSSFRow row = worksheet.createRow(worksheet.getPhysicalNumberOfRows());
// writing out the name of the package
HSSFCell packageCell = row.createCell(0);
packageCell.setCellValue(pkg.getName());
// writing out the name of the class
HSSFCell classCell = row.createCell(1);
classCell.setCellValue(c.getName());
// writing out the name of the method
HSSFCell methodCell = row.createCell(2);
methodCell.setCellValue(m.getName());
for (int i = 3; i < methodMetrics.size(); i++) {
String propertyName = methodMetrics.get(i);
Method getter = m.getClass().getMethod("get" + propertyName);
Object metricValue = getter.invoke(m);
HSSFCell cell = row.createCell(i);
if (metricValue instanceof Integer) {
cell.setCellValue((Integer) metricValue);
} else if (metricValue instanceof Double) {
cell.setCellValue((Double) metricValue);
} else if (metricValue instanceof String) {
cell.setCellValue((String) metricValue);
}
}
}
}
}
}
}
}
// autosizing the main columns
for (int i = 0; i < 3; i++) {
worksheet.autoSizeColumn(i);
}
}
public static final List<String> packageMetrics = new ArrayList<String>(Arrays.asList(
"Package",
"A",
"AC",
"C",
"D",
"EC",
"I",
"NCP",
"NIP",
"LOC",
"LOCm"));
public static final List<String> classMetrics = new ArrayList<String>(Arrays.asList(
"Package",
"Class",
"C",
"LCC",
"LCOM1",
"LCOM2",
"LCOM3",
"LCOM4",
"LCOM5",
"NAK",
"NOC",
"NOF",
"NOM",
"NOSF",
"NOSM",
"NTM",
"TCC",
"WMC",
"LOC",
"LOCm"));
public static final List<String> methodMetrics = new ArrayList<String>(Arrays.asList(
"Package",
"Class",
"Method",
"NBD",
"NOP",
"VG",
"LOC",
"LOCm"));
}
| {
"content_hash": "5cb6ea40856b710e2062ca3f395aa92b",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 213,
"avg_line_length": 40.955465587044536,
"alnum_prop": 0.5199683669434559,
"repo_name": "javatlacati/source-code-metrics",
"id": "2e3cb903cced46de4b1d66fc6d699d4d67d8104a",
"size": "10887",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/org/sourcecodemetrics/report/generators/RawDataGenerator.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "507129"
}
],
"symlink_target": ""
} |
package org.springframework.data.jpa.domain.sample;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Oliver Gierke
*/
@Entity
public class Customer {
@Id Long id;
}
| {
"content_hash": "2c8e205e8213e2f6b57b394b0d7c0669",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 51,
"avg_line_length": 14.214285714285714,
"alnum_prop": 0.7386934673366834,
"repo_name": "sdw2330976/Research-spring-data-jpa",
"id": "a6819e3af54bbb1f02f563fe06eb65f75cf30d4d",
"size": "814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-data-jpa-1.7.1.RELEASE/src/test/java/org/springframework/data/jpa/domain/sample/Customer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "866967"
}
],
"symlink_target": ""
} |
package amino_test
import (
"fmt"
amino "github.com/tendermint/go-amino"
)
func Example() {
defer func() {
if e := recover(); e != nil {
fmt.Println("Recovered:", e)
}
}()
type Message interface{}
type bcMessage struct {
Message string
Height int
}
type bcResponse struct {
Status int
Message string
}
type bcStatus struct {
Peers int
}
var cdc = amino.NewCodec()
cdc.RegisterInterface((*Message)(nil), nil)
cdc.RegisterConcrete(&bcMessage{}, "bcMessage", nil)
cdc.RegisterConcrete(&bcResponse{}, "bcResponse", nil)
cdc.RegisterConcrete(&bcStatus{}, "bcStatus", nil)
var bm = &bcMessage{Message: "ABC", Height: 100}
var msg = bm
var bz []byte // the marshalled bytes.
var err error
bz, err = cdc.MarshalBinaryLengthPrefixed(msg)
fmt.Printf("Encoded: %X (err: %v)\n", bz, err)
var msg2 Message
err = cdc.UnmarshalBinaryLengthPrefixed(bz, &msg2)
fmt.Printf("Decoded: %v (err: %v)\n", msg2, err)
var bm2 = msg2.(*bcMessage)
fmt.Printf("Decoded successfully: %v\n", *bm == *bm2)
// Output:
// Encoded: 0B740613650A034142431064 (err: <nil>)
// Decoded: &{ABC 100} (err: <nil>)
// Decoded successfully: true
}
| {
"content_hash": "f55ebce316e41b106b4b1a2ba8316f98",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 55,
"avg_line_length": 20.473684210526315,
"alnum_prop": 0.6666666666666666,
"repo_name": "tendermint/go-wire",
"id": "6459c24ee2e8f33cbf4b0f47559be56e53a5bb00",
"size": "1778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "142543"
},
{
"name": "Makefile",
"bytes": "2872"
}
],
"symlink_target": ""
} |
For detailed instructions on using this sample, refer to [Extend an Android app to Google Assistant with App Actions (Level 2)](https://codelabs.developers.google.com/codelabs/appactions-2).
This sample Android app manages items on to-do lists. Users can add items to to-do lists, search for items by category, and view information about completed tasks.
Note: This sample application is a fork of the [Android to-do sample](https://github.com/android/architecture-samples).
This is the starting code for the [Extend an Android app to Google Assistant with App Actions](https://codelabs.developers.google.com/codelabs/appactions) codelab.
To see the completed project, go to `master` branch.
## Contribution guidelines
If you want to contribute to this project, be sure to review the
[contribution guidelines](CONTRIBUTING.md).
We use [GitHub issues](https://github.com/actions-on-google/appactions-common-biis-kotlin/issues) for
tracking requests and bugs, please get support by posting your technical questions to
[Stack Overflow](https://stackoverflow.com/questions/tagged/app-actions).
Report [general issues with App Actions features](https://issuetracker.google.com/issues/new?component=617864&template=1257475)
or [make suggestions for additional built-in intents](https://issuetracker.google.com/issues/new?component=617864&template=1261453)
through our public issue tracker.
## References
* [App Actions Overview](https://developers.google.com/assistant/app/overview)
* [Built-in Intents reference](https://developers.google.com/assistant/app/reference/built-in-intents/bii-index)
* [App Actions Test Tool](https://developers.google.com/assistant/app/test-tool)
* [Codelab](https://developers.google.com/assistant/app/codelabs)
* [Other samples](https://developers.google.com/assistant/app/samples)
| {
"content_hash": "25f4bd3ee4765760dd9839ecbb621aeb",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 190,
"avg_line_length": 58.67741935483871,
"alnum_prop": 0.794392523364486,
"repo_name": "actions-on-google/appactions-common-biis-kotlin",
"id": "0fc0fdc6569f2e9c26b137122c387b39d35daf85",
"size": "1898",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Kotlin",
"bytes": "216316"
}
],
"symlink_target": ""
} |
package com.android.ex.variablespeed;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import java.io.IOException;
import javax.annotation.concurrent.Immutable;
/**
* Encapsulates the data source for a media player.
* <p>
* Is used to make the setting of the data source for a
* {@link android.media.MediaPlayer} easier, or the calling of the correct
* {@link VariableSpeedNative} method done correctly. You should not use this class
* directly, it is for the benefit of the {@link VariableSpeed} implementation.
*/
@Immutable
/*package*/ class MediaPlayerDataSource {
private final Context mContext;
private final Uri mUri;
private final String mPath;
public MediaPlayerDataSource(Context context, Uri intentUri) {
mContext = context;
mUri = intentUri;
mPath = null;
}
public MediaPlayerDataSource(String path) {
mContext = null;
mUri = null;
mPath = path;
}
public void setAsSourceFor(MediaPlayer mediaPlayer) throws IOException {
if (mContext != null) {
mediaPlayer.setDataSource(mContext, mUri);
} else {
mediaPlayer.setDataSource(mPath);
}
}
public void playNative() throws IOException {
if (mContext != null) {
VariableSpeedNative.playFromContext(mContext, mUri);
} else {
VariableSpeedNative.playUri(mPath);
}
}
}
| {
"content_hash": "17ff1a3f4e8010d5fa00c017ff39cd21",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 83,
"avg_line_length": 27.166666666666668,
"alnum_prop": 0.6687116564417178,
"repo_name": "JuudeDemos/android-sdk-20",
"id": "1c6a8cb5ea12c3fd518644664db591605800f90f",
"size": "2086",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/com/android/ex/variablespeed/MediaPlayerDataSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "93628991"
}
],
"symlink_target": ""
} |
<?php
namespace pgb_liv\php_ms\Utility\Fragment;
use pgb_liv\php_ms\Constant\ChemicalConstants;
/**
* Generates the C ions from a peptide
*
* @author Andrew Collins
*/
class CFragment extends AbstractFragment implements FragmentInterface
{
/**
*
* {@inheritdoc}
*/
protected function getAdditiveMass()
{
return ChemicalConstants::HYDROGEN_MASS + ChemicalConstants::NITROGEN_MASS + ChemicalConstants::HYDROGEN_MASS + ChemicalConstants::HYDROGEN_MASS;
}
/**
*
* {@inheritdoc}
*/
protected function getEnd()
{
return parent::getEnd() - 1;
}
}
| {
"content_hash": "a21e64c56433529c5a0dfcaf3e2d202f",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 153,
"avg_line_length": 19.59375,
"alnum_prop": 0.645933014354067,
"repo_name": "PGB-LIV/php-ms",
"id": "406d51d7bea4321fe445f395255e2bf83a12370d",
"size": "1230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Utility/Fragment/CFragment.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "626715"
}
],
"symlink_target": ""
} |
#pragma warning disable 612, 618
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Wivuu.DataSeed;
namespace System.Data.Entity.Migrations
{
public static class SeedManagerExtensions
{
/// <summary>
/// Executes input DataSeed migrations in a transaction
/// </summary>
public static void Execute<T>(
this DbMigrationsConfiguration<T> config, T context,
params Seed<T>[] migrations)
where T : DbContext
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
foreach (var migration in migrations)
{
if (migration.ShouldRun(context))
migration.Apply(context);
}
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// Executes all DataSeed migrations in a transaction
/// </summary>
[Obsolete("Use new BaseMigration class for your migrations")]
public static void Execute<T>(this DbMigrationsConfiguration<T> config, T context)
where T : DbContext
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
var builder = new ContainerBuilder();
var configType = config.GetType();
builder.RegisterAssemblyTypes(configType.Assembly)
.Where(t => t.BaseType == typeof(DataMigration<T>))
.As<DataMigration<T>>().PropertiesAutowired();
builder.RegisterAssemblyTypes(configType.Assembly)
.Where(t => t.BaseType == typeof(DbMigrationsConfiguration<T>))
.As<DbMigrationsConfiguration<T>>();
using (var container = builder.Build())
{
var migrations = from migration in container.Resolve<IEnumerable<DataMigration<T>>>()
orderby migration.Order
select migration;
foreach (var migration in migrations)
{
if (migration.AlreadyApplied(context) == false || migration.AlwaysRun)
migration.ApplyInternal(context);
}
}
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
}
} | {
"content_hash": "976b48d525bb546986527015785150c8",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 109,
"avg_line_length": 34.367816091954026,
"alnum_prop": 0.46120401337792644,
"repo_name": "onionhammer/dataseed",
"id": "2ed559c21dff553d61ba748abda1fda26bf0ba41",
"size": "2992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Wivuu.DataSeed/SeedManagerExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "68297"
}
],
"symlink_target": ""
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {FilesAlertDialog} from './files_alert_dialog.js';
import {ListContainer} from './list_container.js';
/** @interface */
export class ActionModelUI {
constructor() {
/** @type {!FilesAlertDialog} */
this.alertDialog;
/** @type {!ListContainer} */
this.listContainer;
}
}
| {
"content_hash": "9c82cdedee4a8290fba6431b3229760e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 73,
"avg_line_length": 27.352941176470587,
"alnum_prop": 0.6881720430107527,
"repo_name": "scheib/chromium",
"id": "41e10c5c5f35f563226fe3b8ef92e5dc24d9cdd0",
"size": "465",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "ui/file_manager/file_manager/foreground/js/ui/action_model_ui.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2016 yuriel<[email protected]>
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
~ SOFTWARE.
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view" android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout> | {
"content_hash": "3e61d305eb64f102854ae25bec722e9c",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 82,
"avg_line_length": 47.43333333333333,
"alnum_prop": 0.7378777231201686,
"repo_name": "kiruto/kotlin-android-mahjong",
"id": "ab76de7f802c3c5f915e6048510eb81160d90383",
"size": "1423",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10198"
},
{
"name": "HTML",
"bytes": "26543"
},
{
"name": "Java",
"bytes": "13016"
},
{
"name": "Kotlin",
"bytes": "500032"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4347b095079d2dd3c1417fa83bce714f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "88718aebfdef7084f3e1cdbebd297bf986beac69",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Grevillea/Grevillea myosodes/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
class BrEASTFeedController extends Controller
{
public $layout="/layouts/breastfeed";
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow',
"users"=>array('@'),
'ips'=>array('192.168.32.*','127.0.0.1'),
'expression'=>'$user->profile=="IT"',
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
public function actionIndex()
{
$this->render("index");
}
public function actionNewFeed()
{
$this->render("newfeed");
}
public function actionAddNewFeed()
{
if (isset($_POST["newfeed"]) && !empty($_POST["newfeed"]))
{
$newsFeed=new NewsFeed;
$newsFeed->HTMLTEXT=$_POST["newfeed"];
$newsFeed->TIMESTAMP=new CDbExpression("SYSDATE");
if ($newsFeed->save())
echo "ok";
else
echo "nok";
}
else
echo "nok";
}
public function actionDisplayAllFeed()
{
$cdbCriteria = new CDbCriteria();
$cdbCriteria->order="ID DESC";
$duration=60*60*24*7;
$dependency = new CDbCacheDependency("SELECT MAX(TIMESTAMP) FROM BREAST.NEWSFEED");
$model = NewsFeed::model()->cache($duration, $dependency)->findAll($cdbCriteria);
Yii::log("dependency:".$dependency->getDependentData());
$this->render("listAllFeed",array("model"=>$model));
}
} | {
"content_hash": "795ea230ce9324090d70077e3bd6f9a8",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 91,
"avg_line_length": 26.589041095890412,
"alnum_prop": 0.5059247810407007,
"repo_name": "proxi24be/yii-sandbox",
"id": "a6e03db1698af55d30b257d96dd3c045bb244a4d",
"size": "1941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protected/modules/administration/controllers/BrEASTFeedController.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1794044"
},
{
"name": "PHP",
"bytes": "4293251"
},
{
"name": "Perl",
"bytes": "240"
},
{
"name": "Racket",
"bytes": "1620"
},
{
"name": "Shell",
"bytes": "5607"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.