text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
class Item < ActiveRecord::Base
has_and_belongs_to_many :genres, -> { uniq }
has_and_belongs_to_many :languages, -> { uniq }
validates :title, :episodes, :discs, presence: true
validates :title, uniqueness: { case_sensitive: false }
validates :discs, numericality: { only_integer: true, greater_than: 0 }
dragonfly_accessor :front do
after_assign do |img|
img.convert!(%q[
-strip -filter Triangle -define filter:support=2
-thumbnail 'x1081' -gravity east -crop '764x1081+0+0' -unsharp 0.25x0.25+8+0.065
-dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off
-define png:compression-filter=5 -define png:compression-level=9
-define png:compression-strategy=1 -define png:exclude-chunk=all
-interlace none -colorspace sRGB -units PixelsPerInch -density 72
], 'format' => 'jpg') unless img.width == 764 &&
img.height == 1081 &&
img.format == 'jpeg'
end
end
dragonfly_accessor :back do
after_assign do |img|
img.convert!(%q[
-strip -filter Triangle -define filter:support=2
-thumbnail 'x1081' -crop '764x1081+0+0' -unsharp 0.25x0.25+8+0.065
-dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off
-define png:compression-filter=5 -define png:compression-level=9
-define png:compression-strategy=1 -define png:exclude-chunk=all
-interlace none -colorspace sRGB -units PixelsPerInch -density 72
], 'format' => 'jpg') unless img.width == 764 &&
img.height == 1081 &&
img.format == 'jpeg'
end
end
normalize_attribute :title, :episodes, :discs, with: [ :squish, :blank ]
end
| {'content_hash': '1fd6df163532229bb9412a86dada868f', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 103, 'avg_line_length': 51.975, 'alnum_prop': 0.5348725348725348, 'repo_name': 'akariSoft/discs', 'id': '18e865f6a3e8428d0a9bec725a59aa1999352f56', 'size': '2079', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/item.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1829'}, {'name': 'HTML', 'bytes': '7745'}, {'name': 'JavaScript', 'bytes': '1106'}, {'name': 'Ruby', 'bytes': '29852'}]} |
package ar.com.larreta.stepper.impl;
import java.io.Serializable;
import org.slf4j.Logger;
import ar.com.larreta.annotations.Log;
import ar.com.larreta.mystic.exceptions.PersistenceException;
import ar.com.larreta.stepper.Step;
import ar.com.larreta.stepper.exceptions.BusinessException;
@Deprecated
//FIXME: Revisar necesidad de esta clase
public abstract class CallAnotherBusinessListener extends StepImpl {
public static final Long NOT_EXECUTE = new Long(-1);
private static final String ERROR_MESSAGE = "Ocurrio un error invocando a servicio desde listener";
private static @Log Logger LOG;
private Step business;
public Step getBusiness() {
return business;
}
public void setBusiness(Step business) {
this.business = business;
}
@Override
public Serializable execute(Serializable source, Serializable target, Object... args) throws BusinessException, PersistenceException{
try {
if (isExecuteAvaiable(source, target, args)){
return business.execute(getParam(source, target, args), null, null);
}
return NOT_EXECUTE;
} catch (Exception e) {
LOG.error(ERROR_MESSAGE, e);
throw new BusinessException(ERROR_MESSAGE, e);
}
}
public Boolean isExecuteAvaiable(Serializable source, Serializable target, Object... args){
return Boolean.TRUE;
}
public abstract Serializable getParam(Serializable source, Serializable target, Object... args);
}
| {'content_hash': 'cf206070941aa1f3acd24e1053d6a182', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 134, 'avg_line_length': 27.49019607843137, 'alnum_prop': 0.7646219686162625, 'repo_name': 'llarreta/larretasources', 'id': 'afc5d775943345b975732b2941102a778484c590', 'size': '1402', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Stepper/src/main/java/ar/com/larreta/stepper/impl/CallAnotherBusinessListener.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1112452'}, {'name': 'CoffeeScript', 'bytes': '16948'}, {'name': 'HTML', 'bytes': '776138'}, {'name': 'Java', 'bytes': '1214844'}, {'name': 'JavaScript', 'bytes': '306947'}, {'name': 'PLSQL', 'bytes': '70597'}, {'name': 'Ruby', 'bytes': '2898'}, {'name': 'TypeScript', 'bytes': '454785'}]} |
Copyright (c) 2014 Neil Sveri
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.
| {'content_hash': 'd29b8b84ff6747042f7aa7d6f2865ae3', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 70, 'avg_line_length': 52.7, 'alnum_prop': 0.8055028462998103, 'repo_name': 'Nonameghost/atom-placeholder-text', 'id': '4f2540f2df589a3eae2e4acbebb135c07bfb2957', 'size': '1054', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LICENSE.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '249'}, {'name': 'CoffeeScript', 'bytes': '3118'}]} |
'use strict';
const childProcess = require('child_process');
const CONFIG = require('../config');
module.exports = function(ci) {
if (ci) {
// Tell apm not to dedupe its own dependencies during its
// postinstall script. (Deduping during `npm ci` runs is broken.)
process.env.NO_APM_DEDUPE = 'true';
}
console.log('Installing apm');
childProcess.execFileSync(
CONFIG.getNpmBinPath(),
['--global-style', '--loglevel=error', ci ? 'ci' : 'install'],
{ env: process.env, cwd: CONFIG.apmRootPath }
);
};
| {'content_hash': 'e37cdd3dd653bcf263e1923d7149da34', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 69, 'avg_line_length': 28.210526315789473, 'alnum_prop': 0.6492537313432836, 'repo_name': 'brettle/atom', 'id': 'a0c20162c8ab4ebbd0e5ef2199837ce2397970be', 'size': '536', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'script/lib/install-apm.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1863'}, {'name': 'CSS', 'bytes': '36767'}, {'name': 'CoffeeScript', 'bytes': '242385'}, {'name': 'HTML', 'bytes': '336'}, {'name': 'JavaScript', 'bytes': '3550134'}, {'name': 'Shell', 'bytes': '5891'}]} |
<?php
namespace Test\Integration\Version2x8;
include_once(__DIR__. '/../Version2x6/ListsCommandsTest.php');
use RedisClient\Client\Version\RedisClient2x8;
use Test\Integration\Version2x6\ListsCommandsTest as ListsCommandsTestVersion2x6;
/**
* @see \RedisClient\Command\Traits\Version2x6\ListsCommandsTrait
*/
class ListsCommandsTest extends ListsCommandsTestVersion2x6 {
const TEST_REDIS_SERVER_1 = TEST_REDIS_SERVER_2x8_1;
/**
* @inheritdoc
*/
public static function setUpBeforeClass() {
static::$Redis = new RedisClient2x8([
'server' => static::TEST_REDIS_SERVER_1,
'timeout' => 10,
]);
}
}
| {'content_hash': 'ed094f8ebde22c7a20d318206e3df087', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 81, 'avg_line_length': 25.692307692307693, 'alnum_prop': 0.6856287425149701, 'repo_name': 'evnix/cas', 'id': 'f1fbc0968ae0967ef3ecd286a6bb2519a5bc1fe6', 'size': '947', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'v1/php-redis-client/tests/Integration/Version2x8/ListsCommandsTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '742'}, {'name': 'CSS', 'bytes': '83476'}, {'name': 'HTML', 'bytes': '22358'}, {'name': 'JavaScript', 'bytes': '31930'}, {'name': 'PHP', 'bytes': '1009284'}, {'name': 'Shell', 'bytes': '4440'}]} |
Fun-Facts
=========
Android app that is a fact telling app. Simple stuff.
![screen](http://i.imgur.com/xAKfsrv.png "screenshot")
| {'content_hash': 'bbfb56d842708829100646878c79077e', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 54, 'avg_line_length': 22.0, 'alnum_prop': 0.6742424242424242, 'repo_name': 'fadelakin/Fun-Facts', 'id': '2d23a4a8a627ead0f821a680275329754ad7ca31', 'size': '132', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Groovy', 'bytes': '989'}, {'name': 'Java', 'bytes': '3858'}, {'name': 'Prolog', 'bytes': '667'}]} |
using UnityEngine;
using System;
using UnityEditor;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
public enum PrecisionType
{
Float = 0,
Half,
Fixed
}
public enum AvailableShaderTypes
{
SurfaceShader
}
[Serializable]
public class MasterNode : OutputNode
{
private const string IndentationHelper = "\t\t{0}\n";
private const string ShaderLODFormat = "\t\tLOD {0}\n";
public delegate void OnMaterialUpdated( MasterNode masterNode );
public event OnMaterialUpdated OnMaterialUpdatedEvent;
public event OnMaterialUpdated OnShaderUpdatedEvent;
protected readonly string[] ShaderModelTypeArr = { "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "4.6", "5.0" };
private const string ShaderKeywordsStr = "Shader Keywords";
[SerializeField]
protected int m_shaderLOD = 0;
[SerializeField]
protected int m_shaderModelIdx = 2;
[SerializeField]
protected Shader m_currentShader;
[SerializeField]
protected Material m_currentMaterial;
//[SerializeField]
//private bool m_isMainMasterNode = false;
[SerializeField]
private Rect m_masterNodeIconCoords;
[SerializeField]
protected string m_shaderName = "MyNewShader";
[SerializeField]
protected string m_customInspectorName = Constants.DefaultCustomInspector;
[SerializeField]
protected AvailableShaderTypes m_currentShaderType = AvailableShaderTypes.SurfaceShader;
private Texture2D m_masterNodeOnTex;
private Texture2D m_masterNodeOffTex;
private Texture2D m_gpuInstanceOnTex;
private Texture2D m_gpuInstanceOffTex;
// Shader Keywords
[SerializeField]
private List<string> m_shaderKeywords = new List<string>();
[SerializeField]
private bool m_shaderKeywordsFoldout = true;
private GUIStyle m_addShaderKeywordStyle;
private GUIStyle m_removeShaderKeywordStyle;
private GUIStyle m_smallAddShaderKeywordItemStyle;
private GUIStyle m_smallRemoveShaderKeywordStyle;
private const float ShaderKeywordButtonLayoutWidth = 15;
public MasterNode() : base() { CommonInit(); }
public MasterNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { CommonInit(); }
protected GUIContent m_shaderTypeLabel = new GUIContent( "Shader Type ", "Specify the type of shader you want to be working on" );
void CommonInit()
{
m_currentMaterial = null;
m_masterNodeIconCoords = new Rect( 0, 0, 64, 64 );
m_isMainOutputNode = false;
m_connStatus = NodeConnectionStatus.Connected;
m_activeType = GetType();
m_currentPrecisionType = PrecisionType.Float;
AddMasterPorts();
}
public virtual void AddMasterPorts() { }
public virtual void ForcePortType() { }
public virtual void UpdateMasterNodeMaterial( Material material ) { }
public virtual void SetName( string name ) { }
public void DrawShaderKeywords()
{
if ( m_addShaderKeywordStyle == null )
m_addShaderKeywordStyle = UIUtils.PlusStyle;
if ( m_removeShaderKeywordStyle == null )
m_removeShaderKeywordStyle = UIUtils.MinusStyle;
if ( m_smallAddShaderKeywordItemStyle == null )
m_smallAddShaderKeywordItemStyle = UIUtils.PlusStyle;
if ( m_smallRemoveShaderKeywordStyle == null )
m_smallRemoveShaderKeywordStyle = UIUtils.MinusStyle;
EditorGUILayout.BeginHorizontal();
{
m_shaderKeywordsFoldout = EditorGUILayout.Foldout( m_shaderKeywordsFoldout, ShaderKeywordsStr );
// Add keyword
if ( GUILayout.Button( string.Empty, m_addShaderKeywordStyle ) )
{
m_shaderKeywords.Insert( 0, "" );
}
//Remove keyword
if ( GUILayout.Button( string.Empty, m_removeShaderKeywordStyle ) )
{
m_shaderKeywords.RemoveAt( m_shaderKeywords.Count - 1 );
}
}
EditorGUILayout.EndHorizontal();
if ( m_shaderKeywordsFoldout )
{
EditorGUI.indentLevel += 1;
int itemCount = m_shaderKeywords.Count;
int markedToDelete = -1;
for ( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label( " " );
// Add new port
if ( GUILayoutButton( string.Empty, m_smallAddShaderKeywordItemStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_shaderKeywords.Insert( i, "" );
}
//Remove port
if ( GUILayoutButton( string.Empty, m_smallRemoveShaderKeywordStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
}
if ( markedToDelete > -1 )
{
m_shaderKeywords.RemoveAt( markedToDelete );
}
EditorGUI.indentLevel -= 1;
}
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isMainOutputNode )
{
if ( m_masterNodeOnTex == null )
{
m_masterNodeOnTex = UIUtils.MasterNodeOnTexture;
}
if ( m_masterNodeOffTex == null )
{
m_masterNodeOffTex = UIUtils.MasterNodeOffTexture;
}
if ( m_gpuInstanceOnTex == null )
{
m_gpuInstanceOnTex = UIUtils.GPUInstancedOnTexture;
}
if ( m_gpuInstanceOffTex == null )
{
m_gpuInstanceOffTex = UIUtils.GPUInstancedOffTexture;
}
m_masterNodeIconCoords = m_globalPosition;
m_masterNodeIconCoords.x += m_globalPosition.width - m_masterNodeOffTex.width * drawInfo.InvertedZoom;
m_masterNodeIconCoords.y += m_globalPosition.height - m_masterNodeOffTex.height * drawInfo.InvertedZoom;
m_masterNodeIconCoords.width = m_masterNodeOffTex.width * drawInfo.InvertedZoom;
m_masterNodeIconCoords.height = m_masterNodeOffTex.height * drawInfo.InvertedZoom;
GUI.DrawTexture( m_masterNodeIconCoords, m_masterNodeOffTex );
if ( m_gpuInstanceOnTex == null )
{
m_gpuInstanceOnTex = UIUtils.GPUInstancedOnTexture;
}
if ( UIUtils.IsInstancedShader() )
{
m_masterNodeIconCoords = m_globalPosition;
m_masterNodeIconCoords.x += m_globalPosition.width - 5 - m_gpuInstanceOffTex.width * drawInfo.InvertedZoom;
m_masterNodeIconCoords.y += m_headerPosition.height;
m_masterNodeIconCoords.width = m_gpuInstanceOffTex.width * drawInfo.InvertedZoom;
m_masterNodeIconCoords.height = m_gpuInstanceOffTex.height * drawInfo.InvertedZoom;
GUI.DrawTexture( m_masterNodeIconCoords, m_gpuInstanceOffTex );
}
}
}
//public override void DrawProperties()
//{
// base.DrawProperties();
// //EditorGUILayout.LabelField( _shaderTypeLabel );
//}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
//IOUtils.AddFieldValueToString( ref nodeInfo, m_isMainMasterNode );
IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderModelIdx );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentPrecisionType );
IOUtils.AddFieldValueToString( ref nodeInfo, m_customInspectorName );
IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderLOD );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
if ( UIUtils.CurrentShaderVersion() > 21 )
{
m_shaderModelIdx = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_currentPrecisionType = ( PrecisionType ) Enum.Parse( typeof( PrecisionType ), GetCurrentParam( ref nodeParams ) );
}
if ( UIUtils.CurrentShaderVersion() > 2404 )
{
m_customInspectorName = GetCurrentParam( ref nodeParams );
}
if ( UIUtils.CurrentShaderVersion() > 6101 )
{
m_shaderLOD = Convert.ToInt32( GetCurrentParam( ref nodeParams ));
}
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
if ( activateNode )
{
InputPort port = GetInputPortByUniqueId( portId );
port.GetOutputNode().ActivateNode( UniqueId, portId, m_activeType );
}
}
public void FireMaterialChangedEvt()
{
if ( OnMaterialUpdatedEvent != null )
{
OnMaterialUpdatedEvent( this );
}
}
public void FireShaderChangedEvt()
{
if ( OnShaderUpdatedEvent != null )
OnShaderUpdatedEvent( this );
}
// What operation this node does
public virtual void Execute( Shader selectedShader )
{
Execute( AssetDatabase.GetAssetPath( selectedShader ), false );
}
public virtual Shader Execute( string pathname, bool isFullPath )
{
ContainerGraph.ResetNodesLocalVariables();
return null;
}
public virtual void UpdateFromShader( Shader newShader ) { }
public void ClearUpdateEvents()
{
OnShaderUpdatedEvent = null;
OnMaterialUpdatedEvent = null;
}
public Material CurrentMaterial { get { return m_currentMaterial; } }
public Shader CurrentShader
{
set
{
if ( value != null )
{
SetName( value.name );
}
m_currentShader = value;
FireShaderChangedEvt();
}
get { return m_currentShader; }
}
public override void Destroy()
{
base.Destroy();
OnMaterialUpdatedEvent = null;
OnShaderUpdatedEvent = null;
m_masterNodeOnTex = null;
m_masterNodeOffTex = null;
m_gpuInstanceOnTex = null;
m_gpuInstanceOffTex = null;
m_addShaderKeywordStyle = null;
m_removeShaderKeywordStyle = null;
m_smallAddShaderKeywordItemStyle = null;
m_smallRemoveShaderKeywordStyle = null;
m_shaderKeywords.Clear();
m_shaderKeywords = null;
}
public static void OpenShaderBody( ref string result, string name )
{
result += string.Format( "Shader \"{0}\"\n", name ) + "{\n";
}
public static void CloseShaderBody( ref string result )
{
result += "}\n";
}
public static void OpenSubShaderBody( ref string result )
{
result += "\n\tSubShader\n\t{\n";
}
public static void CloseSubShaderBody( ref string result )
{
result += "\t}\n";
}
public static void AddShaderProperty( ref string result, string name, string value )
{
result += string.Format( "\t{0} \"{1}\"\n", name, value );
}
public static void AddShaderPragma( ref string result, string value )
{
result += string.Format( "\t\t#pragma {0}\n", value );
}
public static void AddRenderState( ref string result, string state, string stateParams )
{
result += string.Format( "\t\t{0} {1}\n", state, stateParams );
}
public static void AddRenderTags( ref string result, string tags )
{
result += string.Format( IndentationHelper, tags ); ;
}
public static void AddShaderLOD( ref string result, int shaderLOD )
{
if ( shaderLOD > 0 )
{
result += string.Format( ShaderLODFormat, shaderLOD );
}
}
public static void AddMultilineBody( ref string result, string[] lines )
{
for ( int i = 0; i < lines.Length; i++ )
{
result += string.Format( IndentationHelper, lines[ i ] );
}
}
public static void OpenCGInclude( ref string result )
{
result += "\t\tCGINCLUDE\n";
}
public static void OpenCGProgram( ref string result )
{
result += "\t\tCGPROGRAM\n";
}
public static void CloseCGProgram( ref string result )
{
result += "\n\t\tENDCG\n";
}
public string ShaderName
{
//get { return ( ( _isHidden ? "Hidden/" : string.Empty ) + ( String.IsNullOrEmpty( _shaderCategory ) ? "" : ( _shaderCategory + "/" ) ) + _shaderName ); }
get { return m_shaderName; }
set
{
m_shaderName = value;
m_content.text = value;
m_sizeIsDirty = true;
}
}
}
}
| {'content_hash': 'e9c3d2a529b07bd076c841b75558573f', 'timestamp': '', 'source': 'github', 'line_count': 415, 'max_line_length': 158, 'avg_line_length': 27.342168674698794, 'alnum_prop': 0.6936635233982551, 'repo_name': 'kompyang/UnityGamePlayPocketLab', 'id': '6c43d3cc340c0e00fac498f4a288c131a14ae862', 'size': '11460', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'FPS/Assets/3rd/AmplifyShaderEditor/Plugins/Editor/Nodes/Master/MasterNode.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118649'}, {'name': 'C#', 'bytes': '5545847'}, {'name': 'GLSL', 'bytes': '74457'}, {'name': 'HLSL', 'bytes': '206896'}, {'name': 'ShaderLab', 'bytes': '901389'}, {'name': 'Smalltalk', 'bytes': '5308'}]} |
package j_snapshot
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
"koding/remoteapi/models"
)
// PostRemoteAPIJSnapshotOneReader is a Reader for the PostRemoteAPIJSnapshotOne structure.
type PostRemoteAPIJSnapshotOneReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PostRemoteAPIJSnapshotOneReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewPostRemoteAPIJSnapshotOneOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 401:
result := NewPostRemoteAPIJSnapshotOneUnauthorized()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewPostRemoteAPIJSnapshotOneOK creates a PostRemoteAPIJSnapshotOneOK with default headers values
func NewPostRemoteAPIJSnapshotOneOK() *PostRemoteAPIJSnapshotOneOK {
return &PostRemoteAPIJSnapshotOneOK{}
}
/*PostRemoteAPIJSnapshotOneOK handles this case with default header values.
Request processed successfully
*/
type PostRemoteAPIJSnapshotOneOK struct {
Payload *models.DefaultResponse
}
func (o *PostRemoteAPIJSnapshotOneOK) Error() string {
return fmt.Sprintf("[POST /remote.api/JSnapshot.one][%d] postRemoteApiJSnapshotOneOK %+v", 200, o.Payload)
}
func (o *PostRemoteAPIJSnapshotOneOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.DefaultResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPostRemoteAPIJSnapshotOneUnauthorized creates a PostRemoteAPIJSnapshotOneUnauthorized with default headers values
func NewPostRemoteAPIJSnapshotOneUnauthorized() *PostRemoteAPIJSnapshotOneUnauthorized {
return &PostRemoteAPIJSnapshotOneUnauthorized{}
}
/*PostRemoteAPIJSnapshotOneUnauthorized handles this case with default header values.
Unauthorized request
*/
type PostRemoteAPIJSnapshotOneUnauthorized struct {
Payload *models.UnauthorizedRequest
}
func (o *PostRemoteAPIJSnapshotOneUnauthorized) Error() string {
return fmt.Sprintf("[POST /remote.api/JSnapshot.one][%d] postRemoteApiJSnapshotOneUnauthorized %+v", 401, o.Payload)
}
func (o *PostRemoteAPIJSnapshotOneUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.UnauthorizedRequest)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| {'content_hash': '0f1e6bcbeea8e43543c42aa98badc0cc', 'timestamp': '', 'source': 'github', 'line_count': 101, 'max_line_length': 153, 'avg_line_length': 29.88118811881188, 'alnum_prop': 0.7826375082836315, 'repo_name': 'drewsetski/koding', 'id': '0b451059e5f8b8811335e842e520a467c7f811dc', 'size': '3018', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'go/src/koding/remoteapi/client/j_snapshot/post_remote_api_j_snapshot_one_responses.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '590155'}, {'name': 'CoffeeScript', 'bytes': '3965874'}, {'name': 'Go', 'bytes': '9096098'}, {'name': 'HTML', 'bytes': '30375'}, {'name': 'JavaScript', 'bytes': '2209340'}, {'name': 'Makefile', 'bytes': '6065'}, {'name': 'PHP', 'bytes': '1570'}, {'name': 'PLSQL', 'bytes': '370'}, {'name': 'PLpgSQL', 'bytes': '16704'}, {'name': 'Perl', 'bytes': '1612'}, {'name': 'Python', 'bytes': '27895'}, {'name': 'Ruby', 'bytes': '1763'}, {'name': 'SQLPL', 'bytes': '6868'}, {'name': 'Shell', 'bytes': '109550'}]} |
#import "PFFile.h"
#import "PFFile_Private.h"
#import <Bolts/BFCancellationTokenSource.h>
#import "BFTask+Private.h"
#import "PFAssert.h"
#import "PFAsyncTaskQueue.h"
#import "PFCommandResult.h"
#import "PFCoreManager.h"
#import "PFErrorUtilities.h"
#import "PFFileController.h"
#import "PFFileManager.h"
#import "PFFileStagingController.h"
#import "PFInternalUtils.h"
#import "PFMacros.h"
#import "PFMutableFileState.h"
#import "PFRESTFileCommand.h"
#import "PFThreadsafety.h"
#import "PFUserPrivate.h"
#import "Parse_Private.h"
static const unsigned long long PFFileMaxFileSize = 10 * 1024 * 1024; // 10 MB
@interface PFFile () {
dispatch_queue_t _synchronizationQueue;
}
@property (nonatomic, strong, readwrite) PFFileState *state;
@property (nonatomic, copy, readonly) NSString *stagedFilePath;
//
// Private
@property (nonatomic, strong) PFAsyncTaskQueue *taskQueue;
@property (nonatomic, strong) BFCancellationTokenSource *cancellationTokenSource;
@end
@implementation PFFile
@synthesize stagedFilePath = _stagedFilePath;
///--------------------------------------
#pragma mark - Public
///--------------------------------------
#pragma mark Init
+ (instancetype)fileWithData:(NSData *)data {
return [self fileWithName:nil data:data contentType:nil];
}
+ (instancetype)fileWithName:(NSString *)name data:(NSData *)data {
return [self fileWithName:name data:data contentType:nil];
}
+ (instancetype)fileWithName:(NSString *)name contentsAtPath:(NSString *)path {
NSError *error = nil;
PFFile *file = [self fileWithName:name contentsAtPath:path error:&error];
PFParameterAssert(!error, @"Could not access file at %@: %@", path, error);
return file;
}
+ (instancetype)fileWithName:(NSString *)name contentsAtPath:(NSString *)path error:(NSError **)error {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL directory = NO;
if (![fileManager fileExistsAtPath:path isDirectory:&directory] || directory) {
NSString *message = [NSString stringWithFormat:@"Failed to create PFFile at path '%@': file does not exist.", path];
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileNoSuchFileError
userInfo:@{ NSLocalizedDescriptionKey : message }];
}
return nil;
}
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:nil];
unsigned long long length = [attributes[NSFileSize] unsignedLongValue];
if (length > PFFileMaxFileSize) {
NSString *message = [NSString stringWithFormat:@"Failed to create PFFile at path '%@': file is larger than %lluMB.",
path, (PFFileMaxFileSize >> 20)];
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileReadTooLargeError
userInfo:@{ NSLocalizedDescriptionKey : message }];
}
return nil;
}
PFFile *file = [self fileWithName:name url:nil];
if (![file _stageWithPath:path error:error]) {
return nil;
}
return file;
}
+ (instancetype)fileWithName:(NSString *)name
data:(NSData *)data
contentType:(NSString *)contentType {
NSError *error = nil;
PFFile *file = [self fileWithName:name data:data contentType:contentType error:&error];
PFConsistencyAssert(!error, @"Could not save file data for %@ : %@", name, error);
return file;
}
+ (instancetype)fileWithName:(NSString *)name
data:(NSData *)data
contentType:(NSString *)contentType
error:(NSError **)error {
if (!data) {
NSString *message = @"Cannot create a PFFile with nil data.";
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileNoSuchFileError
userInfo:@{ NSLocalizedDescriptionKey : message }];
}
return nil;
}
if (data.length > PFFileMaxFileSize) {
NSString *message = [NSString stringWithFormat:@"Failed to create PFFile with data: data is larger than %lluMB.",
(PFFileMaxFileSize >> 20)];
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileReadTooLargeError
userInfo:@{ NSLocalizedDescriptionKey : message }];
}
return nil;
}
PFFile *file = [[self alloc] initWithName:name urlString:nil mimeType:contentType];
if (![file _stageWithData:data error:error]) {
return nil;
}
return file;
}
+ (instancetype)fileWithData:(NSData *)data contentType:(NSString *)contentType {
return [self fileWithName:nil data:data contentType:contentType];
}
#pragma mark Uploading
- (BFTask *)saveInBackground {
return [self _uploadAsyncWithProgressBlock:nil];
}
- (BFTask *)saveInBackgroundWithProgressBlock:(PFProgressBlock)progressBlock {
return [self _uploadAsyncWithProgressBlock:progressBlock];
}
- (void)saveInBackgroundWithBlock:(PFBooleanResultBlock)block {
[[self saveInBackground] thenCallBackOnMainThreadWithBoolValueAsync:block];
}
- (void)saveInBackgroundWithBlock:(PFBooleanResultBlock)block
progressBlock:(PFProgressBlock)progressBlock {
[[self _uploadAsyncWithProgressBlock:progressBlock] thenCallBackOnMainThreadWithBoolValueAsync:block];
}
#pragma mark Downloading
- (BFTask *)getDataInBackground {
return [self _getDataAsyncWithProgressBlock:nil];
}
- (BFTask *)getDataInBackgroundWithProgressBlock:(PFProgressBlock)progressBlock {
return [self _getDataAsyncWithProgressBlock:progressBlock];
}
- (BFTask *)getDataStreamInBackground {
return [self _getDataStreamAsyncWithProgressBlock:nil];
}
- (BFTask *)getDataStreamInBackgroundWithProgressBlock:(PFProgressBlock)progressBlock {
return [self _getDataStreamAsyncWithProgressBlock:progressBlock];
}
- (BFTask *)getDataDownloadStreamInBackground {
return [self getDataDownloadStreamInBackgroundWithProgressBlock:nil];
}
- (BFTask *)getDataDownloadStreamInBackgroundWithProgressBlock:(PFProgressBlock)progressBlock {
return [self _downloadStreamAsyncWithProgressBlock:progressBlock];
}
- (void)getDataInBackgroundWithBlock:(PFDataResultBlock)block {
[self getDataInBackgroundWithBlock:block progressBlock:nil];
}
- (void)getDataStreamInBackgroundWithBlock:(PFDataStreamResultBlock)block {
[self getDataStreamInBackgroundWithBlock:block progressBlock:nil];
}
- (void)getDataInBackgroundWithBlock:(PFDataResultBlock)resultBlock
progressBlock:(PFProgressBlock)progressBlock {
[[self _getDataAsyncWithProgressBlock:progressBlock] thenCallBackOnMainThreadAsync:resultBlock];
}
- (void)getDataStreamInBackgroundWithBlock:(PFDataStreamResultBlock)resultBlock
progressBlock:(PFProgressBlock)progressBlock {
[[self _getDataStreamAsyncWithProgressBlock:progressBlock] thenCallBackOnMainThreadAsync:resultBlock];
}
- (BFTask PF_GENERIC(NSString *)*)getFilePathInBackground {
return [self getFilePathInBackgroundWithProgressBlock:nil];
}
- (BFTask PF_GENERIC(NSString *)*)getFilePathInBackgroundWithProgressBlock:(PFProgressBlock)progressBlock {
return [[self _downloadAsyncWithProgressBlock:progressBlock] continueWithSuccessBlock:^id(BFTask *task) {
if (self.dirty) {
return self.stagedFilePath;
}
return [[[self class] fileController] cachedFilePathForFileState:self.state];
}];
}
- (void)getFilePathInBackgroundWithBlock:(nullable PFFilePathResultBlock)block {
[[self getFilePathInBackground] thenCallBackOnMainThreadAsync:block];
}
- (void)getFilePathInBackgroundWithBlock:(nullable PFFilePathResultBlock)block
progressBlock:(nullable PFProgressBlock)progressBlock {
[[self getFilePathInBackgroundWithProgressBlock:progressBlock] thenCallBackOnMainThreadAsync:block];
}
#pragma mark Interrupting
- (void)cancel {
[self _performDataAccessBlock:^{
[self.cancellationTokenSource cancel];
self.cancellationTokenSource = nil;
}];
}
///--------------------------------------
#pragma mark - Private
///--------------------------------------
#pragma mark Init
- (instancetype)initWithName:(NSString *)name urlString:(NSString *)url mimeType:(NSString *)mimeType {
self = [super init];
if (!self) return nil;
_taskQueue = [[PFAsyncTaskQueue alloc] init];
_synchronizationQueue = PFThreadsafetyCreateQueueForObject(self);
_state = [[PFFileState alloc] initWithName:name urlString:url mimeType:mimeType];
return self;
}
+ (instancetype)fileWithName:(NSString *)name url:(NSString *)url {
return [[self alloc] initWithName:name urlString:url mimeType:nil];
}
#pragma mark Upload
- (BFTask *)_uploadAsyncWithProgressBlock:(PFProgressBlock)progressBlock {
@weakify(self);
return [BFTask taskFromExecutor:[BFExecutor defaultPriorityBackgroundExecutor] withBlock:^id {
@strongify(self);
__block BFCancellationToken *cancellationToken = nil;
[self _performDataAccessBlock:^{
if (!self.cancellationTokenSource || self.cancellationTokenSource.cancellationRequested) {
self.cancellationTokenSource = [BFCancellationTokenSource cancellationTokenSource];
}
cancellationToken = self.cancellationTokenSource.token;
}];
return [[[PFUser _getCurrentUserSessionTokenAsync] continueWithBlock:^id(BFTask *task) {
NSString *sessionToken = task.result;
return [self.taskQueue enqueue:^id(BFTask *task) {
if (!self.dirty) {
[self _performProgressBlockAsync:progressBlock withProgress:100];
return nil;
}
return [self _uploadFileAsyncWithSessionToken:sessionToken
cancellationToken:cancellationToken
progressBlock:progressBlock];
}];
}] continueWithSuccessResult:@YES];
}];
}
- (BFTask *)_uploadFileAsyncWithSessionToken:(NSString *)sessionToken
cancellationToken:(BFCancellationToken *)cancellationToken
progressBlock:(PFProgressBlock)progressBlock {
if (cancellationToken.cancellationRequested) {
return [BFTask cancelledTask];
}
PFFileController *controller = [[self class] fileController];
@weakify(self);
return [[[controller uploadFileAsyncWithState:[self _fileState]
sourceFilePath:self.stagedFilePath
sessionToken:sessionToken
cancellationToken:cancellationToken
progressBlock:progressBlock] continueWithSuccessBlock:^id(BFTask *task) {
@strongify(self);
[self _performDataAccessBlock:^{
self.state = [task.result copy];
}];
return nil;
} cancellationToken:cancellationToken] continueWithBlock:^id(BFTask *task) {
@strongify(self);
[self _performDataAccessBlock:^{
self.cancellationTokenSource = nil;
}];
return task;
}];
}
#pragma mark Download
- (BFTask *)_getDataAsyncWithProgressBlock:(PFProgressBlock)progressBlock {
return [[self _downloadAsyncWithProgressBlock:progressBlock] continueWithSuccessBlock:^id(BFTask *task) {
return [self _cachedData];
}];
}
- (BFTask *)_getDataStreamAsyncWithProgressBlock:(PFProgressBlock)progressBlock {
return [[self _downloadAsyncWithProgressBlock:progressBlock] continueWithSuccessBlock:^id(BFTask *task) {
return [self _cachedDataStream];
}];
}
- (BFTask *)_downloadAsyncWithProgressBlock:(PFProgressBlock)progressBlock {
__block BFCancellationToken *cancellationToken = nil;
[self _performDataAccessBlock:^{
if (!self.cancellationTokenSource || self.cancellationTokenSource.cancellationRequested) {
self.cancellationTokenSource = [BFCancellationTokenSource cancellationTokenSource];
}
cancellationToken = self.cancellationTokenSource.token;
}];
@weakify(self);
return [self.taskQueue enqueue:^id(BFTask *task) {
@strongify(self);
if (self.dataAvailable) {
[self _performProgressBlockAsync:progressBlock withProgress:100];
return nil;
}
PFFileController *controller = [[self class] fileController];
return [[controller downloadFileAsyncWithState:[self _fileState]
cancellationToken:cancellationToken
progressBlock:progressBlock] continueWithBlock:^id(BFTask *task) {
[self _performDataAccessBlock:^{
self.cancellationTokenSource = nil;
}];
return task;
}];
}];
}
- (BFTask *)_downloadStreamAsyncWithProgressBlock:(PFProgressBlock)progressBlock {
__block BFCancellationToken *cancellationToken = nil;
[self _performDataAccessBlock:^{
if (!self.cancellationTokenSource || self.cancellationTokenSource.cancellationRequested) {
self.cancellationTokenSource = [BFCancellationTokenSource cancellationTokenSource];
}
cancellationToken = self.cancellationTokenSource.token;
}];
@weakify(self);
return [self.taskQueue enqueue:^id(BFTask *task) {
@strongify(self);
if (self.dataAvailable) {
[self _performProgressBlockAsync:progressBlock withProgress:100];
return [self _cachedDataStream];
}
PFFileController *controller = [[self class] fileController];
return [[controller downloadFileStreamAsyncWithState:[self _fileState]
cancellationToken:cancellationToken
progressBlock:progressBlock] continueWithBlock:^id(BFTask *task) {
[self _performDataAccessBlock:^{
self.cancellationTokenSource = nil;
}];
return task;
}];
}];
}
#pragma mark Caching
- (NSString *)_cachedFilePath {
return [[[self class] fileController] cachedFilePathForFileState:self.state];
}
- (NSData *)_cachedData {
NSString *filePath = (self.dirty ? self.stagedFilePath : [self _cachedFilePath]);
if (!filePath) {
return nil;
}
return [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:NULL];
}
- (NSInputStream *)_cachedDataStream {
NSString *filePath = (self.dirty ? self.stagedFilePath : [[[self class] fileController] cachedFilePathForFileState:self.state]);
if (!filePath) {
return nil;
}
return [NSInputStream inputStreamWithFileAtPath:filePath];
}
///--------------------------------------
#pragma mark - Staging
///--------------------------------------
- (BOOL)_stageWithData:(NSData *)data error:(NSError **)error {
__block BOOL result = NO;
[self _performDataAccessBlock:^{
_stagedFilePath = [[[[self class] fileController].fileStagingController stageFileAsyncWithData:data
name:self.state.name
uniqueId:(uintptr_t)self]
waitForResult:error withMainThreadWarning:NO];
result = (_stagedFilePath != nil);
}];
return result;
}
- (BOOL)_stageWithPath:(NSString *)path error:(NSError **)error {
__block BOOL result = NO;
[self _performDataAccessBlock:^{
_stagedFilePath = [[[[self class] fileController].fileStagingController stageFileAsyncAtPath:path
name:self.state.name
uniqueId:(uintptr_t)self]
waitForResult:error withMainThreadWarning:NO];
result = (_stagedFilePath != nil);
}];
return result;
}
#pragma mark Data Access
- (NSString *)name {
__block NSString *name = nil;
[self _performDataAccessBlock:^{
name = self.state.name;
}];
return name;
}
- (NSString *)url {
__block NSString *url = nil;
[self _performDataAccessBlock:^{
url = self.state.secureURLString;
}];
return url;
}
- (BOOL)isDirty {
return !self.url;
}
- (BOOL)isDataAvailable {
__block BOOL available = NO;
[self _performDataAccessBlock:^{
available = ((self.dirty && self.stagedFilePath) ||
(self.url && [[NSFileManager defaultManager] fileExistsAtPath:[self _cachedFilePath]]));
}];
return available;
}
- (void)_performDataAccessBlock:(dispatch_block_t)block {
PFThreadsafetySafeDispatchSync(_synchronizationQueue, block);
}
- (PFFileState *)_fileState {
__block PFFileState *state = nil;
[self _performDataAccessBlock:^{
state = self.state;
}];
return state;
}
#pragma mark Progress
- (void)_performProgressBlockAsync:(PFProgressBlock)block withProgress:(int)progress {
if (!block) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
block(progress);
});
}
///--------------------------------------
#pragma mark - FileController
///--------------------------------------
+ (PFFileController *)fileController {
return [Parse _currentManager].coreManager.fileController;
}
@end
///--------------------------------------
#pragma mark - Synchronous
///--------------------------------------
@implementation PFFile (Synchronous)
#pragma mark Storing Data with Parse
- (BOOL)save {
return [self save:nil];
}
- (BOOL)save:(NSError **)error {
return [[[self saveInBackground] waitForResult:error] boolValue];
}
#pragma mark Getting Data from Parse
- (NSData *)getData {
return [self getData:nil];
}
- (NSData *)getData:(NSError **)error {
BOOL enableWarning = !self.isDataAvailable;
return [[self getDataInBackground] waitForResult:error withMainThreadWarning:enableWarning];
}
- (NSInputStream *)getDataStream {
return [self getDataStream:nil];
}
- (NSInputStream *)getDataStream:(NSError **)error {
BOOL enableWarning = !self.isDataAvailable;
return [[self getDataStreamInBackground] waitForResult:error withMainThreadWarning:enableWarning];
}
@end
///--------------------------------------
#pragma mark - Deprecated
///--------------------------------------
@implementation PFFile (Deprecated)
- (void)saveInBackgroundWithTarget:(nullable id)target selector:(nullable SEL)selector {
[self saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[PFInternalUtils safePerformSelector:selector withTarget:target object:@(succeeded) object:error];
}];
}
- (void)getDataInBackgroundWithTarget:(nullable id)target selector:(nullable SEL)selector {
[self getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
[PFInternalUtils safePerformSelector:selector withTarget:target object:data object:error];
}];
}
@end
| {'content_hash': 'd96527c3de8e805256101ca3ad0f789e', 'timestamp': '', 'source': 'github', 'line_count': 565, 'max_line_length': 132, 'avg_line_length': 34.5504424778761, 'alnum_prop': 0.642897392551611, 'repo_name': 'natanrolnik/Parse-SDK-iOS-OSX', 'id': 'e93087b0e28b248ac0435fd9652dd62c59c560d8', 'size': '19826', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Parse/PFFile.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Objective-C', 'bytes': '2443728'}, {'name': 'Ruby', 'bytes': '22383'}, {'name': 'Swift', 'bytes': '24375'}]} |
*__Note:__ Observers are often over-used by new Ember developers. Observers are used
heavily within the Ember framework itself, but for most problems Ember app
developers face, computed properties are the appropriate solution.*
Ember supports observing any property, including computed properties.
Observers should contain behavior that reacts to changes in another property.
Observers are especially useful when you need to perform some behavior after a
binding has finished synchronizing.
You can set up an observer on an object by using `Ember.observer`:
```javascript
Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
}),
fullNameChanged: Ember.observer('fullName', function() {
// deal with the change
console.log(`fullName changed to: ${this.get('fullName')}`);
})
});
let person = Person.create({
firstName: 'Yehuda',
lastName: 'Katz'
});
// observer won't fire until `fullName` is consumed first
person.get('fullName'); // "Yehuda Katz"
person.set('firstName', 'Brohuda'); // fullName changed to: Brohuda Katz
```
Because the `fullName` computed property depends on `firstName`,
updating `firstName` will fire observers on `fullName` as well.
### Observers and asynchrony
Observers in Ember are currently synchronous. This means that they will fire
as soon as one of the properties they observe changes. Because of this, it
is easy to introduce bugs where properties are not yet synchronized:
```javascript
Person.reopen({
lastNameChanged: Ember.observer('lastName', function() {
// The observer depends on lastName and so does fullName. Because observers
// are synchronous, when this function is called the value of fullName is
// not updated yet so this will log the old value of fullName
console.log(this.get('fullName'));
})
});
```
This synchronous behavior can also lead to observers being fired multiple
times when observing multiple properties:
```javascript
Person.reopen({
partOfNameChanged: Ember.observer('firstName', 'lastName', function() {
// Because both firstName and lastName were set, this observer will fire twice.
})
});
person.set('firstName', 'John');
person.set('lastName', 'Smith');
```
To get around these problems, you should make use of [`Ember.run.once()`](http://emberjs.com/api/classes/Ember.run.html#method_once).
This will ensure that any processing you need to do only happens once, and
happens in the next run loop once all bindings are synchronized:
```javascript
Person.reopen({
partOfNameChanged: Ember.observer('firstName', 'lastName', function() {
Ember.run.once(this, 'processFullName');
}),
processFullName() {
// This will only fire once if you set two properties at the same time, and
// will also happen in the next run loop once all properties are synchronized
console.log(this.get('fullName'));
}
});
person.set('firstName', 'John');
person.set('lastName', 'Smith');
```
### Observers and object initialization
Observers never fire until after the initialization of an object is complete.
If you need an observer to fire as part of the initialization process, you
cannot rely on the side effect of `set`. Instead, specify that the observer
should also run after `init` by using [`Ember.on()`](http://emberjs.com/api/classes/Ember.html#method_on):
```javascript
Person = Ember.Object.extend({
init() {
this.set('salutation', 'Mr/Ms');
},
salutationDidChange: Ember.on('init', Ember.observer('salutation', function() {
// some side effect of salutation changing
}))
});
```
### Unconsumed Computed Properties Do Not Trigger Observers
If you never `get()` a computed property, its observers will not fire even if
its dependent keys change. You can think of the value changing from one unknown
value to another.
This doesn't usually affect application code because computed properties are
almost always observed at the same time as they are fetched. For example, you get
the value of a computed property, put it in DOM (or draw it with D3), and then
observe it so you can update the DOM once the property changes.
If you need to observe a computed property but aren't currently retrieving it,
get it in your `init()` method.
### Outside of class definitions
You can also add observers to an object outside of a class definition
using [`addObserver()`](http://emberjs.com/api/classes/Ember.Object.html#method_addObserver):
```javascript
person.addObserver('fullName', function() {
// deal with the change
});
```
| {'content_hash': '6c9b2068d7725311714a4a0f4aa4c3f7', 'timestamp': '', 'source': 'github', 'line_count': 140, 'max_line_length': 133, 'avg_line_length': 33.371428571428574, 'alnum_prop': 0.7365154109589042, 'repo_name': 'nicobot/guides', 'id': '6c4ead64e44f9c3ff495c600396ae0b80b38ce3b', 'size': '4672', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'source/localizable/object-model/observers.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '39354'}, {'name': 'HTML', 'bytes': '6403'}, {'name': 'JavaScript', 'bytes': '1727'}, {'name': 'Ruby', 'bytes': '33274'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'f362c6f5616ac6f58fe4f3484438b501', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '50279951f299fd4f017b43dc48bc87884c9f8898', 'size': '174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Pieris/Pieris duclouxii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using UnityEngine;
using System.Collections;
public class PlayFootsteps : MonoBehaviour {
private float AudioTimer = 0.0f;
public AudioClip[] footstep;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// Create an Audio Timer, so that we aren't calling too many footsteps to the scene.
if (AudioTimer > 0) {
AudioTimer -= Time.deltaTime;
}
if (AudioTimer < 0) {
AudioTimer = 0;
}
}
void OnTriggerEnter (Collider col) {
if (AudioTimer == 0) {
int clip_num = Random.Range(0, footstep.Length); // Choose a random footstep sound.
audio.clip = footstep[Random.Range(0, clip_num)]; // Load audio
audio.Play(); // Play audio
//Debug.Log("Footstep " + clip_num + " Played"); // Log for debug
AudioSource.PlayClipAtPoint(footstep[clip_num], transform.position);
AudioTimer = 0.1f; // Reset Audio timer
}
}
}
| {'content_hash': '3249243774e5b0334c1a540cb1d39ecb', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 86, 'avg_line_length': 24.289473684210527, 'alnum_prop': 0.6598049837486457, 'repo_name': 'ludimation/Winter', 'id': 'df9a67be0a182f94725dcc84acba2f5744e9e951', 'size': '925', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Winter/Assets/PlayFootsteps.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '47009'}, {'name': 'C#', 'bytes': '34482'}, {'name': 'JavaScript', 'bytes': '49681'}]} |
package seedu.manager.ui;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import seedu.manager.MainApp;
import seedu.manager.commons.core.ComponentManager;
import seedu.manager.commons.core.Config;
import seedu.manager.commons.core.LogsCenter;
import seedu.manager.commons.events.storage.DataSavingExceptionEvent;
import seedu.manager.commons.events.ui.ActivityListPanelUpdateEvent;
import seedu.manager.commons.events.ui.ShowHelpRequestEvent;
import seedu.manager.commons.util.StringUtil;
import seedu.manager.logic.Logic;
import seedu.manager.model.UserPrefs;
import java.util.logging.Logger;
/**
* The manager of the UI component.
*/
public class UiManager extends ComponentManager implements Ui {
private static final Logger logger = LogsCenter.getLogger(UiManager.class);
private static final String ICON_APPLICATION = "/images/logo.png";
private Logic logic;
private Config config;
private UserPrefs prefs;
private MainWindow mainWindow;
public UiManager(Logic logic, Config config, UserPrefs prefs) {
super();
this.logic = logic;
this.config = config;
this.prefs = prefs;
}
//@@author A0144704L
@Override
public void start(Stage primaryStage) {
logger.info("Starting UI...");
primaryStage.setTitle(config.getAppTitle());
//Set the application icon.
primaryStage.getIcons().add(getImage(ICON_APPLICATION));
try {
mainWindow = MainWindow.load(primaryStage, config, prefs, logic);
mainWindow.show(); //This should be called before creating other UI parts
mainWindow.fillInnerParts();
} catch (Throwable e) {
logger.severe(StringUtil.getDetails(e));
showFatalErrorDialogAndShutdown("Fatal error during initializing", e);
}
}
@Override
public void stop() {
prefs.updateLastUsedGuiSetting(mainWindow.getCurrentGuiSetting());
mainWindow.hide();
}
private void showFileOperationAlertAndWait(String description, String details, Throwable cause) {
final String content = details + ":\n" + cause.toString();
showAlertDialogAndWait(AlertType.ERROR, "File Op Error", description, content);
}
private Image getImage(String imagePath) {
return new Image(MainApp.class.getResourceAsStream(imagePath));
}
private void showAlertDialogAndWait(Alert.AlertType type, String title, String headerText, String contentText) {
showAlertDialogAndWait(mainWindow.getPrimaryStage(), type, title, headerText, contentText);
}
private static void showAlertDialogAndWait(Stage owner, AlertType type, String title, String headerText,
String contentText) {
final Alert alert = new Alert(type);
alert.getDialogPane().getStylesheets().add("view/DarkTheme.css");
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(contentText);
alert.showAndWait();
}
private void showFatalErrorDialogAndShutdown(String title, Throwable e) {
logger.severe(title + " " + e.getMessage() + StringUtil.getDetails(e));
showAlertDialogAndWait(Alert.AlertType.ERROR, title, e.getMessage(), e.toString());
Platform.exit();
System.exit(1);
}
//==================== Event Handling Code =================================================================
@Subscribe
private void handleDataSavingExceptionEvent(DataSavingExceptionEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
showFileOperationAlertAndWait("Could not save data", "Could not save data to file", event.exception);
}
@Subscribe
private void handleShowHelpEvent(ShowHelpRequestEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
mainWindow.handleHelp();
}
@Subscribe
//@@author A0139797E
private void handleActivityListPanelUpdateEvent(ActivityListPanelUpdateEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
mainWindow.getFloatingActivityListPanel().updateActivityListPanel(logic.getFilteredFloatingActivityList(), logic.getFilteredDeadlineAndEventList().size(), event.getTargetIndex());
mainWindow.getActivityListPanel().updateActivityListPanel(logic.getFilteredDeadlineAndEventList(), 0, event.getTargetIndex());
}
}
| {'content_hash': 'c6d316c55ba30982fa752a24e31de80e', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 184, 'avg_line_length': 38.56198347107438, 'alnum_prop': 0.7023146163737677, 'repo_name': 'CS2103AUG2016-W14-C1/main', 'id': '0375d177cc9ad87bcb220babc01a50ad85b508f4', 'size': '4666', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/seedu/manager/ui/UiManager.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6842'}, {'name': 'Java', 'bytes': '332966'}, {'name': 'XSLT', 'bytes': '6290'}]} |
@protocol AddProcessViewDelegate <NSObject>
- (void)addProcrssViewDidSavedWithString:(NSString *)string Date:(NSDate *)date Index:(NSInteger)index;
- (void)addProcrssViewDidCancel;
@end
@interface AddProcessView : UIView <UITextFieldDelegate>
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, strong) NSString *string;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, weak) id <AddProcessViewDelegate> delegate;
@end
| {'content_hash': 'e273090341d84be9699b58eb5b5f33ce', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 103, 'avg_line_length': 38.75, 'alnum_prop': 0.7784946236559139, 'repo_name': 'wongkoo/Jobs', 'id': 'e1734174f25e49f1b5c04e6e592d1088a018cb43', 'size': '624', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Jobs/View/FirstDetailPage/AddProcessView.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4555'}, {'name': 'Objective-C', 'bytes': '445697'}, {'name': 'Ruby', 'bytes': '242'}]} |
// Copyright 2016 Michael Mairegger
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Mairegger.Printing.PrintProcessor
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Printing;
using JetBrains.Annotations;
public class PrintProcessorCollection : Collection<PrintProcessor>, IPrintProcessorPrinter
{
private string _fileName = string.Empty;
public PrintProcessorCollection([NotNull] PrintProcessor printProcessor)
: this(new List<PrintProcessor> { printProcessor })
{
if (printProcessor == null)
{
throw new ArgumentNullException(nameof(printProcessor));
}
_fileName = printProcessor.FileName;
}
public PrintProcessorCollection([NotNull] IEnumerable<PrintProcessor> coll, string fileName = "")
: this(new List<PrintProcessor>(coll), fileName)
{
}
public PrintProcessorCollection([NotNull] IList<PrintProcessor> coll, string fileName = "")
{
if (coll == null)
{
throw new ArgumentNullException(nameof(coll));
}
FileName = fileName;
foreach (var printProcessor in coll)
{
if (printProcessor != null)
{
Add(printProcessor);
}
}
}
public string FileName
{
get => _fileName;
set => _fileName = PrintProcessor.ReplaceInvalidCharsFromFilename(value);
}
/// <summary>
/// Sets whether for each <see cref="PrintProcessor" /> in <see cref="Collection{T}.Items" /> the page
/// numbers begins with 0. The default value is true.
/// </summary>
public bool IndividualPageNumbers { get; set; } = true;
/// <summary>
/// Gets or sets whether each <see cref="PrintProcessor" /> uses its own <see cref="PrintProcessor.PageOrientation" />.
/// If false the first <see cref="PrintProcessor.PageOrientation" /> of the first <see cref="PrintProcessor" /> is
/// used. The default value is true.
/// </summary>
public bool IndividualPageOrientation { get; set; } = true;
public virtual void OnPageBreak()
{
}
/// <summary>
/// Creates the document in order to provide a preview of the document
/// </summary>
public void PreviewDocument(IWindowProvider windowsProvider = null)
{
PrintProcessor.PreviewDocument(this, windowsProvider);
}
/// <summary>
/// Prints the document.
/// </summary>
/// <returns> True if succeeds, false otherwise, or if the use cancels the print process. </returns>
public bool PrintDocument()
{
if (Count == 0)
{
return false;
}
var p = this.First();
IPrintDialog pd = p.PrintDialog;
if (pd.ShowDialog().Equals(false))
{
return false;
}
return PrintProcessor.PrintDocument(pd, this);
}
/// <summary>
/// Prints the document to the given <see cref="PrintServer" /> and the given <see cref="PrintQueue.Name" />
/// </summary>
/// <param name="printQueueName"> The name of the print queue. </param>
/// <param name="printServer"> The print server to host the print queue. </param>
/// ///
/// <returns> True if succeeds, false otherwise, or if the use cancels the print process. </returns>
public bool PrintDocument(string printQueueName, PrintServer printServer)
{
if (Count == 0)
{
return false;
}
var p = this.First();
IPrintDialog pd = p.PrintDialog;
pd.PrintQueue = new PrintQueue(printServer, printQueueName);
return PrintProcessor.PrintDocument(pd, this);
}
/// <summary>
/// Prints the document to a <see cref="LocalPrintServer" /> and the given <see cref="PrintQueue.Name" /> of the print
/// queue.
/// </summary>
/// <param name="printQueueName"> The Print-server to print on. </param>
/// <returns> True if succeeds, false otherwise, or if the use cancels the print process. </returns>
public bool PrintDocument(string printQueueName)
{
using (var printServer = new LocalPrintServer())
{
return PrintDocument(printQueueName, printServer);
}
}
}
} | {'content_hash': 'f981b08e27f441e65228b54a2ac96b21', 'timestamp': '', 'source': 'github', 'line_count': 149, 'max_line_length': 131, 'avg_line_length': 35.604026845637584, 'alnum_prop': 0.5792648444863336, 'repo_name': 'xxMUROxx/Mairegger.Printing', 'id': '0af83eef5607de728a7d9b1554d2b4a46a7b63a1', 'size': '5307', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Mairegger.Printing/PrintProcessor/PrintProcessorCollection.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '212292'}]} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
namespace IoTHubPartitionMap.Interfaces
{
public interface IIoTHubPartitionMap : IActor
{
Task<string> LeaseTHubPartitionAsync();
Task<string> RenewIoTHubPartitionLeaseAsync(string partition);
}
} | {'content_hash': 'dff061dc70221f8c7c36598d73917a16', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 84, 'avg_line_length': 31.5, 'alnum_prop': 0.7619047619047619, 'repo_name': 'Azure-Samples/MyDriving', 'id': '5043ced249cac4d0ff97424138ca20be3e24a4d6', 'size': '443', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Extensions/ServiceFabric/VINLookUpApplication/IoTHubPartitionMap.Interfaces/IIoTHubPartitionMap.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '570654'}, {'name': 'JavaScript', 'bytes': '138268'}, {'name': 'PowerShell', 'bytes': '41241'}, {'name': 'Shell', 'bytes': '10549'}, {'name': 'TSQL', 'bytes': '31117'}]} |
'use strict';
module.exports = {
skip: {
type: 'integer',
format: 'int32',
minimum: 0,
maximum: 500,
default: 0,
description: 'The number of results to skip before returning matches. Use this to support paging. Maximum of 500'
},
limit: {
type: 'integer',
format: 'int32',
minimum: 1,
maximum: 200,
default: 20,
description: 'Limit the number of results returned. Defaults to 20. Maximum of 200'
}
};
| {'content_hash': 'f792eac5ae280f7ac5b6e6cb518a9233', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 117, 'avg_line_length': 22.9, 'alnum_prop': 0.6222707423580786, 'repo_name': 'dennoa/cruddy-express-api', 'id': '7874012334afcf02a1bef0757a08a6379fab5709', 'size': '458', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/swagger/search-control-properties.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '50397'}]} |
//
// XQQUserInfoTool.h
// XQQChatProj
//
// Created by XQQ on 2016/11/21.
// Copyright © 2016年 UIP. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void(^completeBlock) (NSArray * array,NSError * error);
/*bmob网络数据库管理类*/
@interface XQQUserInfoTool : NSObject
+ (instancetype)sharedManager;
/*添加一个用户*/
- (void)addUser:(NSString*)user;
/*修改用户个人头像*/
- (void)changeUserIcon:(NSString*)iconURl;
/*修改个人昵称*/
- (void)changeNickName:(NSString*)nickName;
/*block方式获取所有好友的个人信息*/
- (void)getFriendPersionInfo:(NSArray*)list
complete:(void(^)(NSArray *array, NSError *error))complete;
/*根据昵称查询用户信息*/
- (void)getUserInfoWithNickName:(NSString*)nickName
complete:(void(^)(NSArray *array, NSError *error))complete;
/*获取好友的个人信息*/
- (void)getfriendPersionInfo:(NSArray*)list;
/*获取某个好友的信息*/
- (void)getFriendInfo:(NSString*)userName;
/*block方式查询好友信息*/
- (void)getOneFriendInfo:(NSString*)userName
complete:(void(^)(NSArray *array, NSError *error))complete;
/*获取当前登录用户的个人信息*/
- (void)getMyInfo;
/*block方式获取当前登录用户的个人信息*/
- (void)getMyInfoComplete:(void(^)(NSArray *array, NSError *error))complete;
/*改变当前的状态是否在线*/
- (void)changeMyStates:(BOOL)isOnline;
@end
| {'content_hash': '3e4c36c3d482009c5e3146708d42d0d8', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 82, 'avg_line_length': 29.11904761904762, 'alnum_prop': 0.7007358953393296, 'repo_name': 'xiaogehenjimo/XQQDemo', 'id': '87b637ba7351f4e56e356bb5fdbb3404608d332d', 'size': '1458', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'XQQChatProj/XQQChatProj/Classes/Tool/XQQUserInfoTool.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '8410'}, {'name': 'C++', 'bytes': '1206'}, {'name': 'Objective-C', 'bytes': '5415494'}, {'name': 'Objective-C++', 'bytes': '40580'}, {'name': 'Ruby', 'bytes': '458'}, {'name': 'Shell', 'bytes': '9546'}]} |
void zbx_set_common_signal_handlers();
void zbx_set_child_signal_handler();
| {'content_hash': '21877007cd72c907d8609670a8c1631a', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 38, 'avg_line_length': 19.5, 'alnum_prop': 0.7435897435897436, 'repo_name': 'canghai908/zabbix', 'id': '032d64d96617cca69fd096868667498aab55f18f', 'size': '853', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'include/sighandler.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '326'}, {'name': 'C', 'bytes': '4952390'}, {'name': 'C++', 'bytes': '32000'}, {'name': 'CSS', 'bytes': '113294'}, {'name': 'Java', 'bytes': '43280'}, {'name': 'JavaScript', 'bytes': '369508'}, {'name': 'Makefile', 'bytes': '467'}, {'name': 'Objective-C', 'bytes': '6959'}, {'name': 'PHP', 'bytes': '5072896'}, {'name': 'PLSQL', 'bytes': '295581'}, {'name': 'PLpgSQL', 'bytes': '1001591'}, {'name': 'Perl', 'bytes': '3610'}, {'name': 'SQLPL', 'bytes': '268653'}, {'name': 'Shell', 'bytes': '92791'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>ImageMagick: MagickCore, C API for ImageMagick: Compare an Image to a Reconstructed Image</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="application-name" content="ImageMagick">
<meta name="description" content="ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, JPEG-2000, GIF, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.">
<meta name="application-url" content="http://www.imagemagick.org">
<meta name="generator" content="PHP">
<meta name="keywords" content="magickcore, c, api, for, imagemagick:, compare, an, image, to, a, reconstructed, image, ImageMagick, PerlMagick, image processing, image, photo, software, Magick++, OpenMP, convert">
<meta name="rating" content="GENERAL">
<meta name="robots" content="INDEX, FOLLOW">
<meta name="generator" content="ImageMagick Studio LLC">
<meta name="author" content="ImageMagick Studio LLC">
<meta name="revisit-after" content="2 DAYS">
<meta name="resource-type" content="document">
<meta name="copyright" content="Copyright (c) 1999-2015 ImageMagick Studio LLC">
<meta name="distribution" content="Global">
<meta name="magick-serial" content="P131-S030410-R485315270133-P82224-A6668-G1245-1">
<link rel="icon" href="../images/wand.png">
<link rel="shortcut icon" href="../images/wand.ico">
<link rel="stylesheet" href="../css/magick.html">
</head>
<body>
<div class="main">
<div class="magick-masthead">
<div class="container">
<script async="async" src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3129977114552745" data-ad-slot="6345125851" data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<nav class="magick-nav">
<a class="magick-nav-item " href="../index.html">Home</a>
<a class="magick-nav-item " href="../binary-releases.html">Download</a>
<a class="magick-nav-item " href="../command-line-tools.html">Tools</a>
<a class="magick-nav-item " href="../command-line-options.html">Options</a>
<a class="magick-nav-item " href="../resources.html">Resources</a>
<a class="magick-nav-item " href="api.html">Develop</a>
<a class="magick-nav-item " href="http://www.imagemagick.org/script/search.php">Search</a>
<a class="magick-nav-item pull-right" href="http://www.imagemagick.org/discourse-server/">Community</a>
</nav>
</div>
</div>
<div class="container">
<div class="magick-header">
<p class="text-center"><a href="compare.html#CompareImageChannels">CompareImageChannels</a> • <a href="compare.html#GetImageChannelDistortion">GetImageChannelDistortion</a> • <a href="compare.html#GetImageChannelDistortions">GetImageChannelDistortions</a> • <a href="compare.html#IsImagesEqual">IsImagesEqual</a> • <a href="compare.html#SimilarityImage">SimilarityImage</a></p>
<h2><a href="http://www.imagemagick.org/api/MagickCore/compare_8c.html" id="CompareImageChannels">CompareImageChannels</a></h2>
<p>CompareImageChannels() compares one or more image channels of an image to a reconstructed image and returns the difference image.</p>
<p>The format of the CompareImageChannels method is:</p>
<pre class="text">
Image *CompareImageChannels(const Image *image,
const Image *reconstruct_image,const ChannelType channel,
const MetricType metric,double *distortion,ExceptionInfo *exception)
</pre>
<p>A description of each parameter follows:</p>
<dd>
</dd>
<dd> </dd>
<dl class="dl-horizontal">
<dt>image</dt>
<dd>the image. </dd>
<dd> </dd>
<dt>reconstruct_image</dt>
<dd>the reconstruct image. </dd>
<dd> </dd>
<dt>channel</dt>
<dd>the channel. </dd>
<dd> </dd>
<dt>metric</dt>
<dd>the metric. </dd>
<dd> </dd>
<dt>distortion</dt>
<dd>the computed distortion between the images. </dd>
<dd> </dd>
<dt>exception</dt>
<dd>return any errors or warnings in this structure. </dd>
<dd> </dd>
</dl>
<h2><a href="http://www.imagemagick.org/api/MagickCore/compare_8c.html" id="GetImageChannelDistortion">GetImageChannelDistortion</a></h2>
<p>GetImageChannelDistortion() compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.</p>
<p>The format of the GetImageChannelDistortion method is:</p>
<pre class="text">
MagickBooleanType GetImageChannelDistortion(const Image *image,
const Image *reconstruct_image,const ChannelType channel,
const MetricType metric,double *distortion,ExceptionInfo *exception)
</pre>
<p>A description of each parameter follows:</p>
<dd>
</dd>
<dd> </dd>
<dl class="dl-horizontal">
<dt>image</dt>
<dd>the image. </dd>
<dd> </dd>
<dt>reconstruct_image</dt>
<dd>the reconstruct image. </dd>
<dd> </dd>
<dt>channel</dt>
<dd>the channel. </dd>
<dd> </dd>
<dt>metric</dt>
<dd>the metric. </dd>
<dd> </dd>
<dt>distortion</dt>
<dd>the computed distortion between the images. </dd>
<dd> </dd>
<dt>exception</dt>
<dd>return any errors or warnings in this structure. </dd>
<dd> </dd>
</dl>
<h2><a href="http://www.imagemagick.org/api/MagickCore/compare_8c.html" id="GetImageChannelDistortions">GetImageChannelDistortions</a></h2>
<p>GetImageChannelDistortions() compares the image channels of an image to a reconstructed image and returns the specified distortion metric for each channel.</p>
<p>The format of the GetImageChannelDistortions method is:</p>
<pre class="text">
double *GetImageChannelDistortions(const Image *image,
const Image *reconstruct_image,const MetricType metric,
ExceptionInfo *exception)
</pre>
<p>A description of each parameter follows:</p>
<dd>
</dd>
<dd> </dd>
<dl class="dl-horizontal">
<dt>image</dt>
<dd>the image. </dd>
<dd> </dd>
<dt>reconstruct_image</dt>
<dd>the reconstruct image. </dd>
<dd> </dd>
<dt>metric</dt>
<dd>the metric. </dd>
<dd> </dd>
<dt>exception</dt>
<dd>return any errors or warnings in this structure. </dd>
<dd> </dd>
</dl>
<h2><a href="http://www.imagemagick.org/api/MagickCore/compare_8c.html" id="IsImagesEqual">IsImagesEqual</a></h2>
<p>IsImagesEqual() measures the difference between colors at each pixel location of two images. A value other than 0 means the colors match exactly. Otherwise an error measure is computed by summing over all pixels in an image the distance squared in RGB space between each image pixel and its corresponding pixel in the reconstruct image. The error measure is assigned to these image members:</p>
<pre class="text">
o mean_error_per_pixel: The mean error for any single pixel in
the image.
</pre>
<dt>normalized_mean_error</dt>
<p>The normalized mean quantization error for any single pixel in the image. This distance measure is normalized to a range between 0 and 1. It is independent of the range of red, green, and blue values in the image.</p>
<dt>normalized_maximum_error</dt>
<p>The normalized maximum quantization error for any single pixel in the image. This distance measure is normalized to a range between 0 and 1. It is independent of the range of red, green, and blue values in your image.</p>
<p>A small normalized mean square error, accessed as image->normalized_mean_error, suggests the images are very similar in spatial layout and color.</p>
<p>The format of the IsImagesEqual method is:</p>
<pre class="text">
MagickBooleanType IsImagesEqual(Image *image,
const Image *reconstruct_image)
</pre>
<p>A description of each parameter follows.</p>
<dt>image</dt>
<p>the image.</p>
<dt>reconstruct_image</dt>
<p>the reconstruct image.</p>
<h2><a href="http://www.imagemagick.org/api/MagickCore/compare_8c.html" id="SimilarityImage">SimilarityImage</a></h2>
<p>SimilarityImage() compares the reference image of the image and returns the best match offset. In addition, it returns a similarity image such that an exact match location is completely white and if none of the pixels match, black, otherwise some gray level in-between.</p>
<p>The format of the SimilarityImageImage method is:</p>
<pre class="text">
Image *SimilarityImage(const Image *image,const Image *reference,
RectangleInfo *offset,double *similarity,ExceptionInfo *exception)
</pre>
<p>A description of each parameter follows:</p>
<dd>
</dd>
<dd> </dd>
<dl class="dl-horizontal">
<dt>image</dt>
<dd>the image. </dd>
<dd> </dd>
<dt>reference</dt>
<dd>find an area of the image that closely resembles this image. </dd>
<dd> o the best match offset of the reference image within the image. </dd>
<dd> </dd>
<dt>similarity</dt>
<dd>the computed similarity between the images. </dd>
<dd> </dd>
<dt>exception</dt>
<dd>return any errors or warnings in this structure. </dd>
<dd> </dd>
</dl>
</div>
<footer class="magick-footer">
<p><a href="../support.html">Donate</a> •
<a href="../sitemap.html">Sitemap</a> •
<a href="../links.html">Related</a> •
<a href="../architecture.html">Architecture</a>
</p>
<p><a href="compare.html#">Back to top</a> •
<a href="http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x89AB63D48277377A">Public Key</a> •
<a href="http://www.imagemagick.org/script/contact.php">Contact Us</a></p>
<p><small>© 1999-2015 ImageMagick Studio LLC</small></p>
</footer>
</div><!-- /.container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../js/magick.html"></script>
</div>
</body>
</html>
| {'content_hash': '9a55a7671b83a2a55560b521709b6db6', 'timestamp': '', 'source': 'github', 'line_count': 263, 'max_line_length': 452, 'avg_line_length': 37.64638783269962, 'alnum_prop': 0.7135642864357136, 'repo_name': 'slothly/Expose-master', 'id': 'aa52f19a49fdda9dcd87987e7cbce933ef633b7f', 'size': '9922', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'share/doc/ImageMagick-6/www/api/compare.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '487663'}, {'name': 'C++', 'bytes': '317497'}, {'name': 'CSS', 'bytes': '47982'}, {'name': 'Groff', 'bytes': '98150'}, {'name': 'HTML', 'bytes': '3949868'}, {'name': 'JavaScript', 'bytes': '27209'}, {'name': 'Perl', 'bytes': '46341'}, {'name': 'Shell', 'bytes': '35521'}]} |
<?php
namespace Auth\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\Authentication\Adapter\DbTable,
Zend\Session\Container as SessionContainer,
Zend\View\Model\ViewModel,
Auth\Model\User,
Auth\Form\Login,
Auth\Auth\Adapter\Twitter as AuthTwitter;
class LoginController extends AbstractActionController {
public function loginAction() {
$authService = $this->serviceLocator->get('auth_service');
if ($authService->hasIdentity()) {
// if not log in, redirect to login page
return $this->redirect()->toUrl('/zf/main');
}
$form = new Login;
$loginMsg = array();
if ($this->getRequest()->isPost()) {
$form->setData($this->getRequest()->getPost());
if (!$form->isValid()) {
// not valid form
return new ViewModel(array(
'title' => 'Log In',
'form' => $form
));
}
$loginData = $form->getData();
$dbAdapter = $this->serviceLocator->get('Zend\Db\Adapter\Adapter');
$authAdapter = new DbTable($dbAdapter, 'user', 'username', 'password', 'MD5(?)');
$authAdapter->setIdentity($loginData['username'])
->setCredential(($loginData['password']));
$authService = $this->serviceLocator->get('auth_service');
$authService->setAdapter($authAdapter);
$result = $authService->authenticate();
if ($result->isValid()) {
// set id as identifier in session
$userId = $authAdapter->getResultRowObject('id')->id;
$authService->getStorage()
->write($userId);
return $this->redirect()->toUrl('/main');
} else {
$loginMsg = $result->getMessages();
}
}
return new ViewModel(array('title' => 'Log In',
'form' => $form,
'loginMsg' => $loginMsg
));
}
public function logoutAction() {
$authService = $this->serviceLocator->get('auth_service');
if (!$authService->hasIdentity()) {
// if not log in, redirect to login page
return $this->redirect()->toUrl('/login');
}
$authService->clearIdentity();
$form = new Login();
$viewModel = new ViewModel(array('loginMsg' => array('You have been logged out'),
'form' => $form,
'title' => 'Log out'
));
$viewModel->setTemplate('auth/login/login.phtml');
return $viewModel;
}
public function twitterAction() {
$consumer = $this->serviceLocator->get('twitter_oauth');
$token = $consumer->getRequestToken();
$session = new SessionContainer('twitter_oauth');
$session->requestToken = serialize($token);
$consumer->redirect();
}
public function twitterCallbackAction() {
$session = new SessionContainer('twitter_oauth');
$consumer = $this->serviceLocator->get('twitter_oauth');
try {
// get access token
$token = $consumer->getAccessToken($this->params()->fromQuery(), unserialize($session->requestToken));
$userTable = $this->getUserTable();
try {
// get user by twitter username
$user = $userTable->getUserByTwitter($token->getParam('screen_name'));
$userId = $user->id;
} catch (\Exception $e) {
// create new user with empty username & password
$data = array('username' => '',
'password' => '',
'twitter' => $token->getParam('screen_name')
);
$user = new User();
$user->exchangeArray($data);
$userTable->saveUser($user);
$userId = $userTable->getLastInsertUserId();
}
$authService = $this->serviceLocator->get('auth_service');
// get session storage
$storage = $authService->getStorage();
// write to session storage
$storage->write($userId);
return $this->redirect()->toUrl('/main');
} catch (\ZendOauth\Exception\InvalidArgumentException $e) {
// if there is error when get access token
$form = new Login();
$viewModel = new ViewModel(array('loginMsg' => array($e->getMessage()),
'form' => $form,
'title' => 'Twitter Sign In'
));
$viewModel->setTemplate('auth/login/login.phtml');
return $viewModel;
}
}
public function getUserTable() {
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('Auth\Model\UserTable');
}
return $this->userTable;
}
}
| {'content_hash': '94f1bb9f7d125d21847ca894c906caa9', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 114, 'avg_line_length': 35.62758620689655, 'alnum_prop': 0.5040650406504065, 'repo_name': 'indpurvesh/zf2-cms-application', 'id': '4268b1aaefa748c35a8bdb2639a069479cb196ac', 'size': '5488', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/Auth/src/Auth/Controller/LoginController.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '45764'}]} |
class Backend::NavigationItemTranslationForm < Backend::TranslationForm
attribute :label, String
attribute :path, String
def self.model_name
NavigationItem.model_name
end
end
| {'content_hash': 'fa642b4c41b3080a07287326280d5d60', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 71, 'avg_line_length': 23.5, 'alnum_prop': 0.7819148936170213, 'repo_name': 'udongo/udongo', 'id': 'e9fe5e202210496fe4066883ddd8d0895e54b2cd', 'size': '188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'app/forms/backend/navigation_item_translation_form.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4482'}, {'name': 'HTML', 'bytes': '106664'}, {'name': 'JavaScript', 'bytes': '23651'}, {'name': 'Ruby', 'bytes': '461668'}]} |
var SeeDCombatTrackerNamespace = SeeDCombatTrackerNamespace || {};
SeeDCombatTrackerNamespace.Commands = SeeDCombatTrackerNamespace.Commands || {};
//Calling initiative adds all active tokens to the tracker
//ToDo: Have a "speed" parameter on the tokens for quick addition to the battle.
SeeDCombatTrackerNamespace.Commands.initiative = function(message) {
if (message.content.indexOf("help") != -1) {
sendChat('SeeDCombatTracker API', '/w '+ message.who.split(" ")[0] + " Use !init to give everyone 30 delay, as that is how battles in SeeD start.");
return;
}
//Clear the init tracker
Campaign().set("turnorder",JSON.stringify(""));
var characters = findObjs({_type: 'graphic', _subtype: 'token'});
var turnOrder = [];
characters.forEach(function(element) {
//toss out things like dragged dice and whatnot
if (element.name == "") return;
var initEntry = {id:"-1",pr:0,custom:""};
initEntry.id = element.id;
initEntry.pr = 30;
initEntry.custom = element.name;
turnOrder.push(initEntry);
});
log(turnOrder);
Campaign().set("turnorder",JSON.stringify(turnOrder));
}
| {'content_hash': 'aa1801ff87006aaea7f9dc875eb75cdc', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 152, 'avg_line_length': 39.37931034482759, 'alnum_prop': 0.6856392294220666, 'repo_name': 'rdaquilante/SeeDCombatTracker', 'id': '1178a3e57fcc2acef54f6f09f9f6c80e4ee2fda1', 'size': '1317', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Commands/InitCommand.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '8894'}]} |
package ucar.nc2.iosp.bufr.writer;
import ucar.nc2.iosp.bufr.*;
import ucar.unidata.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.util.Formatter;
/**
* Read BUFR files and split them.
* Currently only files.
*
* @author caron
* @since 8/26/13
*/
public class BufrSplitter2 {
File dirOut;
MessageDispatchDDS dispatcher;
Formatter out;
int total_msgs;
public BufrSplitter2(String dirName, Formatter out) throws IOException {
this.out = out;
dirOut = new File(dirName);
if (dirOut.exists() && !dirOut.isDirectory()) {
throw new IllegalArgumentException(dirOut + " must be a directory");
} else if (!dirOut.exists()) {
if (!dirOut.mkdirs())
throw new IllegalArgumentException(dirOut + " filed to create");
}
dispatcher = new MessageDispatchDDS(null, dirOut);
}
// LOOK - needs to be a directory, or maybe an MFILE collection
public void execute(String filename) throws IOException {
try (RandomAccessFile mraf = new RandomAccessFile(filename, "r")) {
MessageScanner scanner = new MessageScanner(mraf);
while (scanner.hasNext()) {
Message m = scanner.next();
if (m == null)
continue;
total_msgs++;
if (m.getNumberDatasets() == 0)
continue;
// LOOK check on tables complete etc ??
m.setRawBytes(scanner.getMessageBytes(m));
// decide what to do with the message
dispatcher.dispatch(m);
}
dispatcher.resetBufrTableMessages();
}
}
public void exit() {
dispatcher.exit(out);
}
}
| {'content_hash': '3e6c6ebee57591b73f257e1c01c8473f', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 74, 'avg_line_length': 24.784615384615385, 'alnum_prop': 0.6505276225946617, 'repo_name': 'Unidata/netcdf-java', 'id': 'c276659d96d792dc00be291a92f38f1a54894026', 'size': '1740', 'binary': False, 'copies': '1', 'ref': 'refs/heads/maint-5.x', 'path': 'bufr/src/main/java/ucar/nc2/iosp/bufr/writer/BufrSplitter2.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AGS Script', 'bytes': '708007'}, {'name': 'C', 'bytes': '404428'}, {'name': 'C++', 'bytes': '10772'}, {'name': 'CSS', 'bytes': '13861'}, {'name': 'Groovy', 'bytes': '95588'}, {'name': 'HTML', 'bytes': '3774351'}, {'name': 'Java', 'bytes': '21758821'}, {'name': 'Makefile', 'bytes': '2434'}, {'name': 'Objective-J', 'bytes': '28890'}, {'name': 'Perl', 'bytes': '7860'}, {'name': 'PowerShell', 'bytes': '678'}, {'name': 'Python', 'bytes': '20750'}, {'name': 'Roff', 'bytes': '34262'}, {'name': 'Shell', 'bytes': '18859'}, {'name': 'Tcl', 'bytes': '5307'}, {'name': 'Vim Script', 'bytes': '88'}, {'name': 'Visual Basic 6.0', 'bytes': '1269'}, {'name': 'Yacc', 'bytes': '25086'}]} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AwfulRedux.BackgroundNotify")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AwfulRedux.BackgroundNotify")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | {'content_hash': '4af4acb296e998659f50f9abf0ff83ba', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 84, 'avg_line_length': 36.93103448275862, 'alnum_prop': 0.7469654528478058, 'repo_name': 'drasticactions/AwfulRedux', 'id': '2bdf43a3fbd28070326f63d006d09d4e76f87fd4', 'size': '1074', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AwfulRedux.BackgroundNotify/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '442'}, {'name': 'C#', 'bytes': '863879'}, {'name': 'CSS', 'bytes': '360433'}, {'name': 'HTML', 'bytes': '26843'}, {'name': 'JavaScript', 'bytes': '75558'}]} |
package com.atlassian.plugin.web.descriptors;
import java.io.InputStream;
import java.net.URL;
import junit.framework.TestCase;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.impl.AbstractPlugin;
public class TestDefaultWebItemModuleDescriptor extends TestCase
{
private WebItemModuleDescriptor descriptor;
private final Plugin plugin = new MockPlugin(this.getClass().getName());
@Override
protected void setUp() throws Exception
{
descriptor = new DefaultWebItemModuleDescriptor(new MockWebInterfaceManager());
}
public void testGetStyleClass() throws DocumentException, PluginParseException
{
final String className = "testClass";
final String styleClass = "<styleClass>" + className + "</styleClass>";
final Element element = createElement(styleClass);
descriptor.init(plugin, element);
assertEquals(className, descriptor.getStyleClass());
}
public void testGetStyleClassTrimmed() throws DocumentException, PluginParseException
{
final String className = "testClass";
final String styleClass = "<styleClass> " + className + " </styleClass>";
final Element element = createElement(styleClass);
descriptor.init(plugin, element);
assertEquals(className, descriptor.getStyleClass());
}
public void testGetStyleClassSpaceSeparated() throws DocumentException, PluginParseException
{
final String className = "testClass testClass2";
final String styleClass = "<styleClass>" + className + "</styleClass>";
final Element element = createElement(styleClass);
descriptor.init(plugin, element);
assertEquals(className, descriptor.getStyleClass());
}
public void testGetStyleClassEmpty() throws DocumentException, PluginParseException
{
final String styleClass = "<styleClass></styleClass>";
final Element element = createElement(styleClass);
descriptor.init(plugin, element);
assertEquals("", descriptor.getStyleClass());
}
public void testGetStyleClassNone() throws DocumentException, PluginParseException
{
final String styleClass = "";
final Element element = createElement(styleClass);
descriptor.init(plugin, element);
assertNotNull(descriptor.getStyleClass());
assertEquals("", descriptor.getStyleClass());
}
private Element createElement(final String childElement) throws DocumentException
{
final String rootElement = "<root key=\"key\">" + childElement + "</root>";
final Document document = DocumentHelper.parseText(rootElement);
final Element element = document.getRootElement();
return element;
}
private class MockPlugin extends AbstractPlugin
{
MockPlugin(final String key)
{
setKey(key);
setName(key);
}
public boolean isUninstallable()
{
return false;
}
public boolean isDeleteable()
{
return false;
}
public boolean isDynamicallyLoaded()
{
return false;
}
public <T> Class<T> loadClass(final String clazz, final Class<?> callingClass) throws ClassNotFoundException
{
return null;
}
public ClassLoader getClassLoader()
{
return this.getClass().getClassLoader();
}
public URL getResource(final String path)
{
return null;
}
public InputStream getResourceAsStream(final String name)
{
return null;
}
}
}
| {'content_hash': '43495eb58b47dd078cea20110c8380ba', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 116, 'avg_line_length': 29.112781954887218, 'alnum_prop': 0.6619318181818182, 'repo_name': 'mrdon/PLUG', 'id': '5ef5295186e77aedcfb95051dacbfc9e18c0bed8', 'size': '3872', 'binary': False, 'copies': '1', 'ref': 'refs/heads/trunk', 'path': 'atlassian-plugins-webfragment/src/test/java/com/atlassian/plugin/web/descriptors/TestDefaultWebItemModuleDescriptor.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '2614284'}]} |
<bill session="115" type="h" number="128" updated="2017-06-19T20:30:32Z">
<state datetime="2017-01-03">REFERRED</state>
<status>
<introduced datetime="2017-01-03"/>
</status>
<introduced datetime="2017-01-03"/>
<titles>
<title type="short" as="introduced">Semipostal Stamp Clarification Act of 2017</title>
<title type="short" as="introduced">Semipostal Stamp Clarification Act of 2017</title>
<title type="official" as="introduced">To amend section 416 of title 39, United States Code, to remove the authority of the United States Postal Service to issue semipostals except as provided for by an Act of Congress, and for other purposes.</title>
<title type="display">Semipostal Stamp Clarification Act of 2017</title>
</titles>
<sponsor bioguide_id="B001248"/>
<cosponsors/>
<actions>
<action datetime="2017-01-03">
<text>Introduced in House</text>
</action>
<action datetime="2017-01-03" state="REFERRED">
<text>Referred to the House Committee on Oversight and Government Reform.</text>
</action>
</actions>
<committees>
<committee subcommittee="" code="HSGO" name="House Oversight and Government Reform" activity="Referral"/>
</committees>
<relatedbills/>
<subjects>
<term name="Government operations and politics"/>
<term name="Postal service"/>
<term name="Social work, volunteer service, charitable organizations"/>
</subjects>
<amendments/>
<summary date="2017-01-03T05:00:00Z" status="Introduced in House">Semipostal Stamp Clarification Act of 2017
This bill removes the authority of the U.S. Postal Service (USPS) to issue semipostal stamps (stamps sold at a premium to raise funds for causes of national public interest) except as provided by an Act of Congress. (Currently, the USPS issues semipostals using its own discretion to determine the causes it considers to be in the national public interest.)
The bill also makes entities (currently, only agencies) eligible to receive amounts that become available from the sale of semipostals. Congress must determine the appropriate agencies or entities that receive such amounts.</summary>
<committee-reports/>
</bill>
| {'content_hash': '70184e7cbfbae59ba1643712ce8221ea', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 357, 'avg_line_length': 55.8974358974359, 'alnum_prop': 0.7371559633027523, 'repo_name': 'peter765/power-polls', 'id': '7047510ae5e12b172b8e1ed1a43cb572195ae1f0', 'size': '2180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/bills/hr/hr128/data.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '58567'}, {'name': 'JavaScript', 'bytes': '7370'}, {'name': 'Python', 'bytes': '22988'}]} |
package io.quarkus.grpc.client.deadline;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.Duration;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.grpc.Deadline;
import io.grpc.examples.helloworld.Greeter;
import io.grpc.examples.helloworld.GreeterClient;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.quarkus.grpc.GrpcClient;
import io.quarkus.grpc.GrpcClientUtils;
import io.quarkus.test.QuarkusUnitTest;
public class ClientDeadlineTest {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addPackage(GreeterGrpc.class.getPackage()).addClasses(MyConsumer.class,
HelloService.class))
.withConfigurationResource("hello-config-deadline.properties");
@Inject
MyConsumer consumer;
@Test
public void testCallOptions() {
GreeterClient client = (GreeterClient) GrpcClientUtils.getProxiedObject(consumer.service);
Deadline deadline = client.getStub().getCallOptions().getDeadline();
assertNotNull(deadline);
HelloReply reply = client.sayHello(HelloRequest.newBuilder().setName("Scaladar").build()).onFailure()
.recoverWithItem(HelloReply.newBuilder().setMessage("ERROR!").build()).await().atMost(Duration.ofSeconds(5));
assertEquals("ERROR!", reply.getMessage());
}
@Singleton
static class MyConsumer {
@GrpcClient("hello-service")
Greeter service;
}
}
| {'content_hash': '0d8e064da4f4b0c987c0502f1725283f', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 125, 'avg_line_length': 35.30909090909091, 'alnum_prop': 0.7378990731204943, 'repo_name': 'quarkusio/quarkus', 'id': '63ea795c5689fadb80ec1be90233a0efd99d4200', 'size': '1942', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/deadline/ClientDeadlineTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '23342'}, {'name': 'Batchfile', 'bytes': '13096'}, {'name': 'CSS', 'bytes': '6685'}, {'name': 'Dockerfile', 'bytes': '459'}, {'name': 'FreeMarker', 'bytes': '8106'}, {'name': 'Groovy', 'bytes': '16133'}, {'name': 'HTML', 'bytes': '1418749'}, {'name': 'Java', 'bytes': '38584810'}, {'name': 'JavaScript', 'bytes': '90960'}, {'name': 'Kotlin', 'bytes': '704351'}, {'name': 'Mustache', 'bytes': '13191'}, {'name': 'Scala', 'bytes': '9756'}, {'name': 'Shell', 'bytes': '71729'}]} |
package com.facebook.buck.jvm.java;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.util.MockClassLoader;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Files;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
public class Jsr199JavacIntegrationTest {
private static final SourcePathResolver PATH_RESOLVER =
new SourcePathResolver(
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()));
public static final ImmutableSortedSet<Path> SOURCE_PATHS =
ImmutableSortedSet.of(Paths.get("Example.java"));
@Rule
public DebuggableTemporaryFolder tmp = new DebuggableTemporaryFolder();
private Path pathToSrcsList;
@Before
public void setUp() {
pathToSrcsList = Paths.get(tmp.getRoot().getPath(), "srcs_list");
}
@Test
public void testGetDescription() throws IOException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
String pathToOutputDir = new File(tmp.getRoot(), "out").getAbsolutePath();
assertEquals(
String.format("javac -source %s -target %s -g " +
"-d %s " +
"-classpath '' " +
"@" + pathToSrcsList.toString(),
JavaBuckConfig.TARGETED_JAVA_VERSION,
JavaBuckConfig.TARGETED_JAVA_VERSION,
pathToOutputDir),
javac.getDescription(
ImmutableList.of(
"-source", JavaBuckConfig.TARGETED_JAVA_VERSION,
"-target", JavaBuckConfig.TARGETED_JAVA_VERSION,
"-g",
"-d", pathToOutputDir,
"-classpath", "''"),
SOURCE_PATHS,
pathToSrcsList));
}
@Test
public void testGetShortName() throws IOException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
assertEquals("javac", javac.getShortName());
}
@Test
public void testClassesFile() throws IOException, InterruptedException {
Jsr199Javac javac = createJavac(/* withSyntaxError */ false);
ExecutionContext executionContext = TestExecutionContext.newInstance();
int exitCode = javac.buildWithClasspath(
executionContext,
createProjectFilesystem(),
PATH_RESOLVER,
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.<String>of(),
ImmutableSet.<String>of(),
SOURCE_PATHS,
pathToSrcsList,
Optional.<Path>absent(),
NoOpClassUsageFileWriter.instance(),
Optional.<StandardJavaFileManagerFactory>absent());
assertEquals("javac should exit with code 0.", exitCode, 0);
File srcsListFile = pathToSrcsList.toFile();
assertTrue(srcsListFile.exists());
assertTrue(srcsListFile.isFile());
assertEquals("Example.java", Files.toString(srcsListFile, Charsets.UTF_8).trim());
}
/**
* There was a bug where `BuildTargetSourcePath` sources were written to the classes file using
* their string representation, rather than their resolved path.
*/
@Test
public void shouldWriteResolvedBuildTargetSourcePathsToClassesFile()
throws IOException, InterruptedException {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
BuildRule rule = new FakeBuildRule("//:fake", pathResolver);
resolver.addToIndex(rule);
Jsr199Javac javac = createJavac(
/* withSyntaxError */ false);
ExecutionContext executionContext = TestExecutionContext.newInstance();
int exitCode = javac.buildWithClasspath(
executionContext,
createProjectFilesystem(),
PATH_RESOLVER,
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.<String>of(),
ImmutableSet.<String>of(),
SOURCE_PATHS,
pathToSrcsList,
Optional.<Path>absent(),
NoOpClassUsageFileWriter.instance(),
Optional.<StandardJavaFileManagerFactory>absent());
assertEquals("javac should exit with code 0.", exitCode, 0);
File srcsListFile = pathToSrcsList.toFile();
assertTrue(srcsListFile.exists());
assertTrue(srcsListFile.isFile());
assertEquals("Example.java", Files.toString(srcsListFile, Charsets.UTF_8).trim());
}
public static final class MockJavac implements JavaCompiler {
public MockJavac() {
}
@Override
public Set<SourceVersion> getSourceVersions() {
return ImmutableSet.of(SourceVersion.RELEASE_7);
}
@Override
public int run(
InputStream in,
OutputStream out,
OutputStream err,
String... arguments) {
throw new UnsupportedOperationException("abcdef");
}
@Override
public int isSupportedOption(String option) {
return -1;
}
@Override
public StandardJavaFileManager
getStandardFileManager(
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale,
Charset charset) {
throw new UnsupportedOperationException("abcdef");
}
@Override
public CompilationTask getTask(
Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits) {
throw new UnsupportedOperationException("abcdef");
}
}
@Test
public void shouldUseSpecifiedJavacJar() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
BuildRule rule = new FakeBuildRule("//:fake", pathResolver);
resolver.addToIndex(rule);
Path fakeJavacJar = Paths.get("ae036e57-77a7-4356-a79c-0f85b1a3290d", "fakeJavac.jar");
ExecutionContext executionContext = TestExecutionContext.newInstance();
MockClassLoader mockClassLoader = new MockClassLoader(
ClassLoader.getSystemClassLoader(),
ImmutableMap.<String, Class<?>>of(
"com.sun.tools.javac.api.JavacTool",
MockJavac.class));
executionContext.getClassLoaderCache().injectClassLoader(
ClassLoader.getSystemClassLoader(),
ImmutableList.of(fakeJavacJar.toUri().toURL()),
mockClassLoader);
Jsr199Javac javac = createJavac(
/* withSyntaxError */ false,
Optional.of(fakeJavacJar));
boolean caught = false;
try {
javac.buildWithClasspath(
executionContext,
createProjectFilesystem(),
PATH_RESOLVER,
BuildTargetFactory.newInstance("//some:example"),
ImmutableList.<String>of(),
ImmutableSet.<String>of(),
SOURCE_PATHS,
pathToSrcsList,
Optional.<Path>absent(),
NoOpClassUsageFileWriter.instance(),
Optional.<StandardJavaFileManagerFactory>absent());
fail("Did not expect compilation to succeed");
} catch (UnsupportedOperationException ex) {
if (ex.toString().contains("abcdef")) {
caught = true;
}
}
assertTrue("mock Java compiler should throw", caught);
}
private Jsr199Javac createJavac(
boolean withSyntaxError,
Optional<Path> javacJar) throws IOException {
File exampleJava = tmp.newFile("Example.java");
Files.write(Joiner.on('\n').join(
"package com.example;",
"",
"public class Example {" +
(withSyntaxError ? "" : "}")
),
exampleJava,
Charsets.UTF_8);
Path pathToOutputDirectory = Paths.get("out");
tmp.newFolder(pathToOutputDirectory.toString());
Optional<SourcePath> jar = javacJar.transform(
SourcePaths.toSourcePath(new FakeProjectFilesystem()));
if (jar.isPresent()) {
return new JarBackedJavac("com.sun.tools.javac.api.JavacTool", ImmutableSet.of(jar.get()));
}
return new JdkProvidedInMemoryJavac();
}
private Jsr199Javac createJavac(boolean withSyntaxError) throws IOException {
return createJavac(withSyntaxError, Optional.<Path>absent());
}
private ProjectFilesystem createProjectFilesystem() {
return new ProjectFilesystem(tmp.getRootPath());
}
}
| {'content_hash': '7cb46cd0ed487964a086fab4c1f67f61', 'timestamp': '', 'source': 'github', 'line_count': 289, 'max_line_length': 99, 'avg_line_length': 34.3356401384083, 'alnum_prop': 0.7041217373778091, 'repo_name': 'Dominator008/buck', 'id': '80578de61bcd64f3b388acb0927a8a56aafc2036', 'size': '10528', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/com/facebook/buck/jvm/java/Jsr199JavacIntegrationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '579'}, {'name': 'Batchfile', 'bytes': '726'}, {'name': 'C', 'bytes': '248433'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '6074'}, {'name': 'CSS', 'bytes': '54863'}, {'name': 'D', 'bytes': '1017'}, {'name': 'Go', 'bytes': '14733'}, {'name': 'Groff', 'bytes': '440'}, {'name': 'Groovy', 'bytes': '3362'}, {'name': 'HTML', 'bytes': '5353'}, {'name': 'Haskell', 'bytes': '590'}, {'name': 'IDL', 'bytes': '128'}, {'name': 'Java', 'bytes': '14177476'}, {'name': 'JavaScript', 'bytes': '931960'}, {'name': 'Lex', 'bytes': '2442'}, {'name': 'Makefile', 'bytes': '1791'}, {'name': 'Matlab', 'bytes': '47'}, {'name': 'OCaml', 'bytes': '3060'}, {'name': 'Objective-C', 'bytes': '124101'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '244'}, {'name': 'Python', 'bytes': '379114'}, {'name': 'Rust', 'bytes': '938'}, {'name': 'Scala', 'bytes': '898'}, {'name': 'Shell', 'bytes': '35303'}, {'name': 'Smalltalk', 'bytes': '897'}, {'name': 'Standard ML', 'bytes': '15'}, {'name': 'Swift', 'bytes': '3735'}, {'name': 'Thrift', 'bytes': '2452'}, {'name': 'Yacc', 'bytes': '323'}]} |
package smartMeterExample;
import smartMeterExample.helper.ActorFactory;
import topology.ActorTopology;
/**
*
* This is the topology for the simulation
*
* @author bytschkow
*
*/
public class Topology {
private static String simulationName = "Simulation";
public static ActorTopology createTopology(){
ActorTopology top = new ActorTopology(simulationName);
/*
* Actor Topology
*/
top.addActor("Server", ActorFactory.createAggregator());
String path;
for (int i = 1; i <= 100; i++) {
path = "Server/SmartMeter"+i;
top.addActorAsChild(path, ActorFactory.createSmartMeter());
}
return top;
}
}
| {'content_hash': 'd2fbdbf0d1b17faec6a593b53a11cc6a', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 62, 'avg_line_length': 17.675675675675677, 'alnum_prop': 0.6850152905198776, 'repo_name': 'SES-fortiss/SmartGridCoSimulation', 'id': '48ac8654c51fa9dd1e94a86034260aa973380cbf', 'size': '941', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'examples/extendedExamples/src/main/java/smartMeterExample/Topology.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '494'}, {'name': 'C++', 'bytes': '68972'}, {'name': 'CSS', 'bytes': '10495'}, {'name': 'HTML', 'bytes': '27854'}, {'name': 'Java', 'bytes': '23777284'}, {'name': 'JavaScript', 'bytes': '144441'}, {'name': 'Processing', 'bytes': '16761'}, {'name': 'Shell', 'bytes': '1069'}, {'name': 'Solidity', 'bytes': '18269'}]} |
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
/// <summary>
/// Represents a response to a Move or Copy operation.
/// </summary>
public sealed class MoveCopyItemResponse : ServiceResponse
{
private Item item;
/// <summary>
/// Initializes a new instance of the <see cref="MoveCopyItemResponse"/> class.
/// </summary>
internal MoveCopyItemResponse()
: base()
{
}
/// <summary>
/// Gets Item instance.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Item.</returns>
private Item GetObjectInstance(ExchangeService service, string xmlElementName)
{
return EwsUtilities.CreateEwsObjectFromXmlElementName<Item>(service, xmlElementName);
}
/// <summary>
/// Reads response elements from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadElementsFromXml(EwsServiceXmlReader reader)
{
base.ReadElementsFromXml(reader);
List<Item> items = reader.ReadServiceObjectsCollectionFromXml<Item>(
XmlElementNames.Items,
this.GetObjectInstance,
false, /* clearPropertyBag */
null, /* requestedPropertySet */
false); /* summaryPropertiesOnly */
// We only receive the copied or moved items if the copy or move operation was within
// a single mailbox. No item is returned if the operation is cross-mailbox, from a
// mailbox to a public folder or from a public folder to a mailbox.
if (items.Count > 0)
{
this.item = items[0];
}
}
/// <summary>
/// Gets the copied or moved item. Item is null if the copy or move operation was between
/// two mailboxes or between a mailbox and a public folder.
/// </summary>
public Item Item
{
get { return this.item; }
}
}
} | {'content_hash': 'b43d8c4e200b23e9fb6f73f935b2f92c', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 97, 'avg_line_length': 34.2463768115942, 'alnum_prop': 0.5590351248413035, 'repo_name': 'WGroenestein/ews-managed-api', 'id': '6cddd4a3f2a5fc8604f7bee219b0cfc4db799629', 'size': '3582', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'Core/Responses/MoveCopyItemResponse.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '5075742'}]} |
package gov.nasa.jpf.vm;
import java.io.OutputStream;
/**
* debug extensions of StateSerializer interface
*/
public interface DebugStateSerializer extends StateSerializer {
void setOutputStream(OutputStream os);
}
| {'content_hash': 'b30fc7ab6a0a749937d000652b1b899d', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 63, 'avg_line_length': 18.5, 'alnum_prop': 0.7837837837837838, 'repo_name': 'parasoft-pl/jpf-core', 'id': '90ebfa0b4fa587bd4d1fde36f123c470b2c41b3c', 'size': '1007', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'main/src/main/java/gov/nasa/jpf/vm/DebugStateSerializer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '611'}, {'name': 'Java', 'bytes': '5168949'}, {'name': 'Shell', 'bytes': '625'}]} |
from unittest import TestCase, main
from os import remove, mkdir
from os.path import join, exists
from shutil import rmtree
from datetime import datetime
from qiita_core.util import qiita_test_checker
import qiita_db as qdb
@qiita_test_checker()
class JobTest(TestCase):
"""Tests that the job object works as expected"""
def setUp(self):
self.job = qdb.job.Job(1)
self.options = {"option1": False, "option2": 25, "option3": "NEW"}
self._delete_path = []
self._delete_dir = []
_, self._job_folder = qdb.util.get_mountpoint("job")[0]
self.job_id = 4
def tearDown(self):
# needs to be this way because map does not play well with remove and
# rmtree for python3
for item in self._delete_path:
remove(item)
for item in self._delete_dir:
rmtree(item)
def test_exists(self):
"""tests that existing job returns true"""
# need to insert matching sample data into analysis 2
self.conn_handler.execute(
"DELETE FROM qiita.analysis_sample WHERE analysis_id = 2")
sql = """INSERT INTO qiita.analysis_sample
(analysis_id, artifact_id, sample_id)
VALUES (2, 4, '1.SKB8.640193'), (2, 4, '1.SKD8.640184'),
(2, 4, '1.SKB7.640196'), (2, 4, '1.SKM9.640192'),
(2, 4, '1.SKM4.640180')"""
self.conn_handler.execute(sql)
self.assertTrue(qdb.job.Job.exists(
"18S", "Beta Diversity", {"--otu_table_fp": 1, "--mapping_fp": 1},
qdb.analysis.Analysis(1), qdb.reference.Reference(2),
qdb.software.Command(3)))
def test_exists_return_jobid(self):
"""tests that existing job returns true"""
# need to insert matching sample data into analysis 2
self.conn_handler.execute(
"DELETE FROM qiita.analysis_sample WHERE analysis_id = 2")
sql = """INSERT INTO qiita.analysis_sample
(analysis_id, artifact_id, sample_id)
VALUES (2, 4, '1.SKB8.640193'), (2, 4, '1.SKD8.640184'),
(2, 4, '1.SKB7.640196'), (2, 4, '1.SKM9.640192'),
(2, 4, '1.SKM4.640180')"""
self.conn_handler.execute(sql)
exists, jid = qdb.job.Job.exists(
"18S", "Beta Diversity", {"--otu_table_fp": 1, "--mapping_fp": 1},
qdb.analysis.Analysis(1), qdb.reference.Reference(2),
qdb.software.Command(3), return_existing=True)
self.assertTrue(exists)
self.assertEqual(jid, qdb.job.Job(2))
def test_exists_noexist_options(self):
"""tests that non-existant job with bad options returns false"""
# need to insert matching sample data into analysis 2
# makes sure failure is because options and not samples
self.conn_handler.execute(
"DELETE FROM qiita.analysis_sample WHERE analysis_id = 2")
sql = """INSERT INTO qiita.analysis_sample
(analysis_id, artifact_id, sample_id)
VALUES (2, 4, '1.SKB8.640193'), (2, 4, '1.SKD8.640184'),
(2, 4, '1.SKB7.640196'), (2, 4, '1.SKM9.640192'),
(2, 4, '1.SKM4.640180')"""
self.conn_handler.execute(sql)
self.assertFalse(qdb.job.Job.exists(
"18S", "Beta Diversity", {"--otu_table_fp": 1, "--mapping_fp": 27},
qdb.analysis.Analysis(1), qdb.reference.Reference(2),
qdb.software.Command(3)))
def test_exists_noexist_return_jobid(self):
"""tests that non-existant job with bad samples returns false"""
exists, jid = qdb.job.Job.exists(
"16S", "Beta Diversity", {"--otu_table_fp": 1, "--mapping_fp": 27},
qdb.analysis.Analysis(1), qdb.reference.Reference(2),
qdb.software.Command(3), return_existing=True)
self.assertFalse(exists)
self.assertEqual(jid, None)
def test_get_commands(self):
exp = [
qdb.job.Command('Summarize Taxa',
'summarize_taxa_through_plots.py',
'{"--otu_table_fp":null}', '{}',
'{"--mapping_category":null, "--mapping_fp":null,'
'"--sort":null}', '{"--output_dir":null}'),
qdb.job.Command('Beta Diversity',
'beta_diversity_through_plots.py',
'{"--otu_table_fp":null,"--mapping_fp":null}',
'{}',
'{"--tree_fp":null,"--color_by_all_fields":null,'
'"--seqs_per_sample":null}',
'{"--output_dir":null}'),
qdb.job.Command('Alpha Rarefaction', 'alpha_rarefaction.py',
'{"--otu_table_fp":null,"--mapping_fp":null}',
'{}',
'{"--tree_fp":null,"--num_steps":null,'
'"--min_rare_depth":null,"--max_rare_depth":null,'
'"--retain_intermediate_files":false}',
'{"--output_dir":null}')
]
self.assertEqual(qdb.job.Job.get_commands(), exp)
def test_delete_files(self):
try:
qdb.job.Job.delete(1)
with self.assertRaises(qdb.exceptions.QiitaDBUnknownIDError):
qdb.job.Job(1)
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.filepath WHERE filepath_id = 13")
self.assertEqual(obs, [])
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.job_results_filepath WHERE job_id = 1")
self.assertEqual(obs, [])
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.analysis_job WHERE job_id = 1")
self.assertEqual(obs, [])
self.assertFalse(exists(join(self._job_folder,
"1_job_result.txt")))
finally:
f = join(self._job_folder, "1_job_result.txt")
if not exists(f):
with open(f, 'w') as f:
f.write("job1result.txt")
def test_delete_folders(self):
try:
qdb.job.Job.delete(2)
with self.assertRaises(qdb.exceptions.QiitaDBUnknownIDError):
qdb.job.Job(2)
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.filepath WHERE filepath_id = 14")
self.assertEqual(obs, [])
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.job_results_filepath WHERE job_id = 2")
self.assertEqual(obs, [])
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.analysis_job WHERE job_id = 2")
self.assertEqual(obs, [])
self.assertFalse(exists(join(self._job_folder, "2_test_folder")))
finally:
# put the test data back
basedir = self._job_folder
if not exists(join(basedir, "2_test_folder")):
mkdir(join(basedir, "2_test_folder"))
mkdir(join(basedir, "2_test_folder", "subdir"))
with open(join(basedir, "2_test_folder",
"testfile.txt"), 'w') as f:
f.write("DATA")
with open(join(basedir, "2_test_folder",
"testres.htm"), 'w') as f:
f.write("DATA")
with open(join(basedir, "2_test_folder",
"subdir", "subres.html"), 'w') as f:
f.write("DATA")
def test_create(self):
"""Makes sure creation works as expected"""
# make first job
new = qdb.job.Job.create("18S", "Alpha Rarefaction", {"opt1": 4},
qdb.analysis.Analysis(1),
qdb.reference.Reference(1),
qdb.software.Command(3))
self.assertEqual(new.id, self.job_id)
# make sure job inserted correctly
obs = self.conn_handler.execute_fetchall("SELECT * FROM qiita.job "
"WHERE job_id = %d" %
self.job_id)
exp = [[self.job_id, 2, 1, 3, '{"opt1":4}', None, 1, 3]]
self.assertEqual(obs, exp)
# make sure job added to analysis correctly
obs = self.conn_handler.execute_fetchall("SELECT * FROM "
"qiita.analysis_job WHERE "
"job_id = %d" % self.job_id)
exp = [[1, self.job_id]]
self.assertEqual(obs, exp)
self.job_id += 1
# make second job with diff datatype and command to test column insert
new = qdb.job.Job.create("16S", "Beta Diversity", {"opt1": 4},
qdb.analysis.Analysis(1),
qdb.reference.Reference(2),
qdb.software.Command(3))
self.assertEqual(new.id, self.job_id)
# make sure job inserted correctly
obs = self.conn_handler.execute_fetchall("SELECT * FROM qiita.job "
"WHERE job_id = %d" %
self.job_id)
exp = [[self.job_id, 1, 1, 2, '{"opt1":4}', None, 2, 3]]
self.assertEqual(obs, exp)
# make sure job added to analysis correctly
obs = self.conn_handler.execute_fetchall("SELECT * FROM "
"qiita.analysis_job WHERE "
"job_id = %d" % self.job_id)
exp = [[1, self.job_id]]
self.assertEqual(obs, exp)
def test_create_exists(self):
"""Makes sure creation doesn't duplicate a job"""
with self.assertRaises(qdb.exceptions.QiitaDBDuplicateError):
qdb.job.Job.create(
"18S", "Beta Diversity",
{"--otu_table_fp": 1, "--mapping_fp": 1},
qdb.analysis.Analysis(1), qdb.reference.Reference(2),
qdb.software.Command(3))
def test_create_exists_return_existing(self):
"""Makes sure creation doesn't duplicate a job by returning existing"""
analysis = qdb.analysis.Analysis.create(
qdb.user.User("demo@microbio.me"), "new", "desc")
sql = """INSERT INTO qiita.analysis_sample
(analysis_id, artifact_id, sample_id)
VALUES ({0}, 4, '1.SKB8.640193'), ({0}, 4, '1.SKD8.640184'),
({0}, 4, '1.SKB7.640196'), ({0}, 4, '1.SKM9.640192'),
({0}, 4, '1.SKM4.640180')""".format(analysis.id)
self.conn_handler.execute(sql)
new = qdb.job.Job.create(
"18S", "Beta Diversity", {"--otu_table_fp": 1, "--mapping_fp": 1},
analysis, qdb.reference.Reference(2), qdb.software.Command(3),
return_existing=True)
self.assertEqual(new.id, self.job_id)
def test_retrieve_datatype(self):
"""Makes sure datatype retrieval is correct"""
self.assertEqual(self.job.datatype, '18S')
def test_retrieve_command(self):
"""Makes sure command retrieval is correct"""
self.assertEqual(self.job.command, ['Summarize Taxa',
'summarize_taxa_through_plots.py'])
def test_retrieve_options(self):
self.assertEqual(self.job.options, {
'--otu_table_fp': 1,
'--output_dir': join(
self._job_folder,
'1_summarize_taxa_through_plots.py_output_dir')})
def test_set_options(self):
new = qdb.job.Job.create("18S", "Alpha Rarefaction",
{"opt1": 4}, qdb.analysis.Analysis(1),
qdb.reference.Reference(2),
qdb.software.Command(3))
new.options = self.options
self.options['--output_dir'] = join(
self._job_folder,
'%d_alpha_rarefaction.py_output_dir' % self.job_id)
self.assertEqual(new.options, self.options)
def test_retrieve_results(self):
self.assertEqual(self.job.results, ["1_job_result.txt"])
def test_retrieve_results_folder(self):
job = qdb.job.Job(2)
self.assertEqual(job.results, ['2_test_folder/testres.htm',
'2_test_folder/subdir/subres.html'])
def test_retrieve_results_empty(self):
new = qdb.job.Job.create("18S", "Beta Diversity", {"opt1": 4},
qdb.analysis.Analysis(1),
qdb.reference.Reference(2),
qdb.software.Command(3))
self.assertEqual(new.results, [])
def test_set_error(self):
before = datetime.now()
self.job.set_error("TESTERROR")
after = datetime.now()
self.assertEqual(self.job.status, "error")
error = self.job.error
self.assertEqual(error.severity, 2)
self.assertEqual(error.msg, 'TESTERROR')
self.assertTrue(before < error.time < after)
def test_retrieve_error_blank(self):
self.assertEqual(self.job.error, None)
def test_set_error_completed(self):
self.job.status = "error"
with self.assertRaises(qdb.exceptions.QiitaDBStatusError):
self.job.set_error("TESTERROR")
def test_retrieve_error_exists(self):
self.job.set_error("TESTERROR")
self.assertEqual(self.job.error.msg, "TESTERROR")
def test_add_results(self):
fp_count = qdb.util.get_count('qiita.filepath')
self.job.add_results([(join(self._job_folder, "1_job_result.txt"),
"plain_text")])
# make sure files attached to job properly
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.job_results_filepath WHERE job_id = 1")
self.assertEqual(obs, [[1, 13], [1, fp_count + 1]])
def test_add_results_dir(self):
fp_count = qdb.util.get_count('qiita.filepath')
# Create a test directory
test_dir = join(self._job_folder, "2_test_folder")
# add folder to job
self.job.add_results([(test_dir, "directory")])
# make sure files attached to job properly
obs = self.conn_handler.execute_fetchall(
"SELECT * FROM qiita.job_results_filepath WHERE job_id = 1")
self.assertEqual(obs, [[1, 13], [1, fp_count + 1]])
def test_add_results_completed(self):
self.job.status = "completed"
with self.assertRaises(qdb.exceptions.QiitaDBStatusError):
self.job.add_results([("/fake/dir/", "directory")])
@qiita_test_checker()
class CommandTest(TestCase):
def setUp(self):
com1 = qdb.job.Command(
'Summarize Taxa', 'summarize_taxa_through_plots.py',
'{"--otu_table_fp":null}', '{}',
'{"--mapping_category":null, "--mapping_fp":null,'
'"--sort":null}', '{"--output_dir":null}')
com2 = qdb.job.Command(
'Beta Diversity', 'beta_diversity_through_plots.py',
'{"--otu_table_fp":null,"--mapping_fp":null}', '{}',
'{"--tree_fp":null,"--color_by_all_fields":null,'
'"--seqs_per_sample":null}', '{"--output_dir":null}')
com3 = qdb.job.Command(
'Alpha Rarefaction', 'alpha_rarefaction.py',
'{"--otu_table_fp":null,"--mapping_fp":null}', '{}',
'{"--tree_fp":null,"--num_steps":null,'
'"--min_rare_depth"'
':null,"--max_rare_depth":null,'
'"--retain_intermediate_files":false}',
'{"--output_dir":null}')
self.all_comms = {
"16S": [com1, com2, com3],
"18S": [com1, com2, com3],
"ITS": [com2, com3],
"Proteomic": [com2, com3],
"Metabolomic": [com2, com3],
"Metagenomic": [com2, com3],
}
def test_get_commands_by_datatype(self):
obs = qdb.job.Command.get_commands_by_datatype()
self.assertEqual(obs, self.all_comms)
obs = qdb.job.Command.get_commands_by_datatype(["16S", "Metabolomic"])
exp = {k: self.all_comms[k] for k in ('16S', 'Metabolomic')}
self.assertEqual(obs, exp)
def test_equal(self):
commands = qdb.job.Command.create_list()
self.assertTrue(commands[1] == commands[1])
self.assertFalse(commands[1] == commands[2])
self.assertFalse(commands[1] == qdb.job.Job(1))
def test_not_equal(self):
commands = qdb.job.Command.create_list()
self.assertFalse(commands[1] != commands[1])
self.assertTrue(commands[1] != commands[2])
self.assertTrue(commands[1] != qdb.job.Job(1))
if __name__ == "__main__":
main()
| {'content_hash': '1f7fcc279b4d9c1b37f75403311ceca1', 'timestamp': '', 'source': 'github', 'line_count': 390, 'max_line_length': 79, 'avg_line_length': 43.88717948717949, 'alnum_prop': 0.5240710446365974, 'repo_name': 'squirrelo/qiita', 'id': '35fed7167d78daac7a96182bfc86211e982c99d9', 'size': '17467', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'qiita_db/test/test_job.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '1692'}, {'name': 'HTML', 'bytes': '449930'}, {'name': 'JavaScript', 'bytes': '5876'}, {'name': 'Makefile', 'bytes': '6838'}, {'name': 'PLSQL', 'bytes': '2359'}, {'name': 'PLpgSQL', 'bytes': '45311'}, {'name': 'Python', 'bytes': '1696427'}, {'name': 'SQLPL', 'bytes': '6192'}, {'name': 'Shell', 'bytes': '3062'}]} |
package de.tudarmstadt.informatik.tk.assistance.sdk.db;
import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.SqlUtils;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "module_capability".
*/
public class DbModuleCapabilityDao extends AbstractDao<DbModuleCapability, Long> {
public static final String TABLENAME = "module_capability";
/**
* Properties of entity DbModuleCapability.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Type = new Property(1, String.class, "type", false, "TYPE");
public final static Property CollectionInterval = new Property(2, Double.class, "collectionInterval", false, "COLLECTION_INTERVAL");
public final static Property UpdateInterval = new Property(3, Double.class, "updateInterval", false, "UPDATE_INTERVAL");
public final static Property Accuracy = new Property(4, Integer.class, "accuracy", false, "ACCURACY");
public final static Property Permissions = new Property(5, String.class, "permissions", false, "PERMISSIONS");
public final static Property Required = new Property(6, boolean.class, "required", false, "REQUIRED");
public final static Property Active = new Property(7, boolean.class, "active", false, "ACTIVE");
public final static Property Created = new Property(8, String.class, "created", false, "CREATED");
public final static Property ModuleId = new Property(9, Long.class, "moduleId", false, "MODULE_ID");
}
private DaoSession daoSession;
private Query<DbModuleCapability> dbModule_DbModuleCapabilityListQuery;
public DbModuleCapabilityDao(DaoConfig config) {
super(config);
}
public DbModuleCapabilityDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
this.daoSession = daoSession;
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"module_capability\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"TYPE\" TEXT NOT NULL ," + // 1: type
"\"COLLECTION_INTERVAL\" REAL," + // 2: collectionInterval
"\"UPDATE_INTERVAL\" REAL," + // 3: updateInterval
"\"ACCURACY\" INTEGER," + // 4: accuracy
"\"PERMISSIONS\" TEXT," + // 5: permissions
"\"REQUIRED\" INTEGER NOT NULL ," + // 6: required
"\"ACTIVE\" INTEGER NOT NULL ," + // 7: active
"\"CREATED\" TEXT NOT NULL ," + // 8: created
"\"MODULE_ID\" INTEGER);"); // 9: moduleId
// Add Indexes
db.execSQL("CREATE INDEX " + constraint + "IDX_module_capability__id ON module_capability" +
" (\"_id\");");
db.execSQL("CREATE INDEX " + constraint + "IDX_module_capability_TYPE ON module_capability" +
" (\"TYPE\");");
db.execSQL("CREATE INDEX " + constraint + "IDX_module_capability_ACTIVE ON module_capability" +
" (\"ACTIVE\");");
db.execSQL("CREATE INDEX " + constraint + "IDX_module_capability_MODULE_ID ON module_capability" +
" (\"MODULE_ID\");");
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"module_capability\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, DbModuleCapability entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindString(2, entity.getType());
Double collectionInterval = entity.getCollectionInterval();
if (collectionInterval != null) {
stmt.bindDouble(3, collectionInterval);
}
Double updateInterval = entity.getUpdateInterval();
if (updateInterval != null) {
stmt.bindDouble(4, updateInterval);
}
Integer accuracy = entity.getAccuracy();
if (accuracy != null) {
stmt.bindLong(5, accuracy);
}
String permissions = entity.getPermissions();
if (permissions != null) {
stmt.bindString(6, permissions);
}
stmt.bindLong(7, entity.getRequired() ? 1L: 0L);
stmt.bindLong(8, entity.getActive() ? 1L: 0L);
stmt.bindString(9, entity.getCreated());
Long moduleId = entity.getModuleId();
if (moduleId != null) {
stmt.bindLong(10, moduleId);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, DbModuleCapability entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindString(2, entity.getType());
Double collectionInterval = entity.getCollectionInterval();
if (collectionInterval != null) {
stmt.bindDouble(3, collectionInterval);
}
Double updateInterval = entity.getUpdateInterval();
if (updateInterval != null) {
stmt.bindDouble(4, updateInterval);
}
Integer accuracy = entity.getAccuracy();
if (accuracy != null) {
stmt.bindLong(5, accuracy);
}
String permissions = entity.getPermissions();
if (permissions != null) {
stmt.bindString(6, permissions);
}
stmt.bindLong(7, entity.getRequired() ? 1L: 0L);
stmt.bindLong(8, entity.getActive() ? 1L: 0L);
stmt.bindString(9, entity.getCreated());
Long moduleId = entity.getModuleId();
if (moduleId != null) {
stmt.bindLong(10, moduleId);
}
}
@Override
protected final void attachEntity(DbModuleCapability entity) {
super.attachEntity(entity);
entity.__setDaoSession(daoSession);
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public DbModuleCapability readEntity(Cursor cursor, int offset) {
DbModuleCapability entity = new DbModuleCapability( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getString(offset + 1), // type
cursor.isNull(offset + 2) ? null : cursor.getDouble(offset + 2), // collectionInterval
cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3), // updateInterval
cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4), // accuracy
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // permissions
cursor.getShort(offset + 6) != 0, // required
cursor.getShort(offset + 7) != 0, // active
cursor.getString(offset + 8), // created
cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9) // moduleId
);
return entity;
}
@Override
public void readEntity(Cursor cursor, DbModuleCapability entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setType(cursor.getString(offset + 1));
entity.setCollectionInterval(cursor.isNull(offset + 2) ? null : cursor.getDouble(offset + 2));
entity.setUpdateInterval(cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3));
entity.setAccuracy(cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4));
entity.setPermissions(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setRequired(cursor.getShort(offset + 6) != 0);
entity.setActive(cursor.getShort(offset + 7) != 0);
entity.setCreated(cursor.getString(offset + 8));
entity.setModuleId(cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9));
}
@Override
protected final Long updateKeyAfterInsert(DbModuleCapability entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(DbModuleCapability entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(DbModuleCapability entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
/** Internal query to resolve the "dbModuleCapabilityList" to-many relationship of DbModule. */
public List<DbModuleCapability> _queryDbModule_DbModuleCapabilityList(Long moduleId) {
synchronized (this) {
if (dbModule_DbModuleCapabilityListQuery == null) {
QueryBuilder<DbModuleCapability> queryBuilder = queryBuilder();
queryBuilder.where(Properties.ModuleId.eq(null));
dbModule_DbModuleCapabilityListQuery = queryBuilder.build();
}
}
Query<DbModuleCapability> query = dbModule_DbModuleCapabilityListQuery.forCurrentThread();
query.setParameter(0, moduleId);
return query.list();
}
private String selectDeep;
protected String getSelectDeep() {
if (selectDeep == null) {
StringBuilder builder = new StringBuilder("SELECT ");
SqlUtils.appendColumns(builder, "T", getAllColumns());
builder.append(',');
SqlUtils.appendColumns(builder, "T0", daoSession.getDbModuleDao().getAllColumns());
builder.append(" FROM module_capability T");
builder.append(" LEFT JOIN module T0 ON T.\"MODULE_ID\"=T0.\"_id\"");
builder.append(' ');
selectDeep = builder.toString();
}
return selectDeep;
}
protected DbModuleCapability loadCurrentDeep(Cursor cursor, boolean lock) {
DbModuleCapability entity = loadCurrent(cursor, 0, lock);
int offset = getAllColumns().length;
DbModule dbModule = loadCurrentOther(daoSession.getDbModuleDao(), cursor, offset);
entity.setDbModule(dbModule);
return entity;
}
public DbModuleCapability loadDeep(Long key) {
assertSinglePk();
if (key == null) {
return null;
}
StringBuilder builder = new StringBuilder(getSelectDeep());
builder.append("WHERE ");
SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
String sql = builder.toString();
String[] keyArray = new String[] { key.toString() };
Cursor cursor = db.rawQuery(sql, keyArray);
try {
boolean available = cursor.moveToFirst();
if (!available) {
return null;
} else if (!cursor.isLast()) {
throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
}
return loadCurrentDeep(cursor, true);
} finally {
cursor.close();
}
}
/** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
public List<DbModuleCapability> loadAllDeepFromCursor(Cursor cursor) {
int count = cursor.getCount();
List<DbModuleCapability> list = new ArrayList<DbModuleCapability>(count);
if (cursor.moveToFirst()) {
if (identityScope != null) {
identityScope.lock();
identityScope.reserveRoom(count);
}
try {
do {
list.add(loadCurrentDeep(cursor, false));
} while (cursor.moveToNext());
} finally {
if (identityScope != null) {
identityScope.unlock();
}
}
}
return list;
}
protected List<DbModuleCapability> loadDeepAllAndCloseCursor(Cursor cursor) {
try {
return loadAllDeepFromCursor(cursor);
} finally {
cursor.close();
}
}
/** A raw-style query where you can pass any WHERE clause and arguments. */
public List<DbModuleCapability> queryDeep(String where, String... selectionArg) {
Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
return loadDeepAllAndCloseCursor(cursor);
}
}
| {'content_hash': '7aca29c0b9706d504ebd0c121f92c559', 'timestamp': '', 'source': 'github', 'line_count': 336, 'max_line_length': 140, 'avg_line_length': 39.50892857142857, 'alnum_prop': 0.6100188323917137, 'repo_name': 'Telecooperation/assistance-platform-client-sdk-android', 'id': '2e1e2ac3561c0c45f385322da3b19b2cf8164e6b', 'size': '13275', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AssistanceSDK/app/src-gen/main/java/de/tudarmstadt/informatik/tk/assistance/sdk/db/DbModuleCapabilityDao.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1458250'}]} |
layout: default
title: Guías
i18n: es
---
<h1>Guías</h1>
<p class="lead">Estas breves guías prácticas le brindan los pasos simples para lograr un objetivo bien definido.</p>
<h2>Instalación</h2>
<ul>
<li><a href="1.0/install_windows">Cómo instalar Mu en Windows con el instalador oficial</a>.</li>
<li><a href="1.0/install_macos">Cómo instalar Mu en Mac OSX con el instalador oficial</a>.</li>
<li><a href="1.0/use_portamu">Cómo usar PortaMu para ejecutar Mu en cualquier lugar</a>.</li>
<li><a href="1.0/install_with_python">Cómo instalar Mu con el paquete Python en Windows, OSX y Linux</a>.</li>
<li><a href="1.0/install_raspberry_pi">Cómo instalar Mu en una Raspberry Pi</a>.</li>
</ul>
<h2>Uso De Mu</h2>
<ul>
<li><a href="1.0/create_load_save">Cómo crear, cargar y guardar archivos en Mu</a>.</li>
<li><a href="1.0/read_logs">Cómo leer los registros en Mu</a>.</li>
<li><a href="1.0/copy_files_microbit">Cómo copiar archivos dentro y fuera de un Micro: bit</a>.</li>
<li><a href="1.0/python3_envars">Cómo usar las variables de entorno para configurar los GPIOZero en el modo de Python3</a>.</li>
<li><a href="1.0/microbit_settings">Cómo minimizar sus scripts de MicroPython y usar un tiempo de ejecución personalizado en el Micro: bit de la BBC</a>.</li>
<li><a href="1.0/pgzero_sounds_images">Cómo agregar nuevas imágenes, fuentes, sonido y música a Pygame Zero</a>.</li>
</ul>
<h2>Solución De Problemas</h2>
<ul>
<li><a href="1.0/bugs">Cómo informar de un error en Mu</a>.</li>
<li><a href="1.0/fix_code">Cómo intentar arreglar tu propio código</a>.</li>
</ul>
| {'content_hash': '0d8d0dfe171850f40c4853d934880bfc', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 162, 'avg_line_length': 45.25, 'alnum_prop': 0.6801718845917741, 'repo_name': 'mu-editor/mu-editor.github.io', 'id': 'ba4f030418cbfbeaca93db2a1edadc43c11d1b74', 'size': '1656', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'es/howto/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3164'}, {'name': 'HTML', 'bytes': '160684'}, {'name': 'JavaScript', 'bytes': '766'}, {'name': 'Ruby', 'bytes': '11847'}]} |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for icons</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../prettify.css" />
<link rel="stylesheet" href="../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../index.html">All files</a> icons
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">92.86% </span>
<span class="quiet">Statements</span>
<span class='fraction'>13/14</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">82.14% </span>
<span class="quiet">Branches</span>
<span class='fraction'>23/28</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Functions</span>
<span class='fraction'>1/1</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">92.86% </span>
<span class="quiet">Lines</span>
<span class='fraction'>13/14</span>
</div>
</div>
</div>
<div class='status-line high'></div>
<div class="pad1">
<table class="coverage-summary">
<thead>
<tr>
<th data-col="file" data-fmt="html" data-html="true" class="file">File</th>
<th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>
<th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>
<th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>
<th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>
<th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>
<th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>
</tr>
</thead>
<tbody><tr>
<td class="file high" data-value="Icon.js"><a href="Icon.js.html">Icon.js</a></td>
<td data-value="92.86" class="pic high"><div class="chart"><div class="cover-fill" style="width: 92%;"></div><div class="cover-empty" style="width:8%;"></div></div></td>
<td data-value="92.86" class="pct high">92.86%</td>
<td data-value="14" class="abs high">13/14</td>
<td data-value="82.14" class="pct high">82.14%</td>
<td data-value="28" class="abs high">23/28</td>
<td data-value="100" class="pct high">100%</td>
<td data-value="1" class="abs high">1/1</td>
<td data-value="92.86" class="pct high">92.86%</td>
<td data-value="14" class="abs high">13/14</td>
</tr>
</tbody>
</table>
</div><div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="https://istanbul.js.org/" target="_blank">istanbul</a> at Fri Jul 07 2017 01:55:28 GMT-0700 (PDT)
</div>
</div>
<script src="../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../sorter.js"></script>
</body>
</html>
| {'content_hash': '12e8c37701438d4b43b2ee4300b16ee7', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 170, 'avg_line_length': 38.13978494623656, 'alnum_prop': 0.6069918240766845, 'repo_name': 'VowelWeb/CoinTradePros.com', 'id': 'fac8c4b67c447a420ff767c401eb2f1236d565b0', 'size': '3547', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MobileApp/node_modules/react-native-elements/coverage/lcov-report/icons/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4048'}, {'name': 'Java', 'bytes': '1931611'}, {'name': 'JavaScript', 'bytes': '68832'}, {'name': 'Objective-C', 'bytes': '4426'}, {'name': 'Python', 'bytes': '1736'}]} |
<idea-plugin>
<actions>
<action id="IncrementalSearch" class="com.intellij.codeInsight.navigation.actions.IncrementalSearchAction"/>
<action id="AddToFavoritesPopup" class="com.intellij.ide.favoritesTreeView.actions.AddToFavoritesPopupAction"/>
<group id="AddToFavorites" class="com.intellij.ide.favoritesTreeView.actions.AddToFavoritesActionGroup" popup="true"/>
<group id="AddAllToFavorites" class="com.intellij.ide.favoritesTreeView.actions.AddAllToFavoritesActionGroup" popup="true"/>
<action id="AddNewFavoritesList" class="com.intellij.ide.favoritesTreeView.actions.AddNewFavoritesListAction"/>
<group id="SendToFavoritesGroup" class="com.intellij.ide.favoritesTreeView.actions.SendToFavoritesGroup" popup="true"/>
<action id="RunConfiguration" class="com.intellij.execution.actions.RunConfigurationsComboBoxAction"/>
<action id="ChooseRunConfiguration" class="com.intellij.execution.actions.ChooseRunConfigurationPopupAction" text="Run..." description="Choose and run configuration" icon="AllIcons.Toolwindows.ToolWindowRun"/>
<action id="ChooseDebugConfiguration" class="com.intellij.execution.actions.ChooseDebugConfigurationPopupAction" text="Debug..." description="Choose and debug configuration" icon="AllIcons.General.Debug"/>
<group id="RunContextGroup" popup="false">
<!-- A dynamic group filled with executor actions -->
<group id="RunContextGroupInner"/>
<separator/>
<action id="CreateRunConfiguration" class="com.intellij.execution.actions.CreateAction"/>
</group>
<group id="RunContextPopupGroup" popup="false">
<reference ref="RunContextGroup"/>
</group>
<group id="LangCodeInsightActions">
<action id="EditorSelectWord" class="com.intellij.openapi.editor.actions.SelectWordAtCaretAction"/>
<action id="EditorUnSelectWord" class="com.intellij.openapi.editor.actions.UnselectWordAtCaretAction"/>
<add-to-group group-id="EditorActions" anchor="last"/>
</group>
<action id="ClassNameCompletion" class="com.intellij.codeInsight.completion.actions.ClassNameCompletionAction"/>
<group id="GenerateGroup">
<action id="OverrideMethods" class="com.intellij.codeInsight.generation.actions.OverrideMethodsAction"/>
<action id="ImplementMethods" class="com.intellij.codeInsight.generation.actions.ImplementMethodsAction"/>
<action id="DelegateMethods" class="com.intellij.codeInsight.generation.actions.DelegateMethodsAction"/>
<action id="GeneratePattern" class="com.intellij.codeInsight.generation.GenerateByPatternAction" text="Generate by Pattern..."/>
</group>
<action id="ShowIntentionActions" class="com.intellij.codeInsight.intention.actions.ShowIntentionActionsAction"/>
<action id="TogglePopupHints" class="com.intellij.ide.actions.TogglePopupHintsAction"/>
<action id="FindModal" class="com.intellij.openapi.editor.actions.FindAction" icon="AllIcons.Actions.Menu_find"/>
<action id="CodeInspection.OnEditor" class="com.intellij.codeInspection.actions.CodeInspectionOnEditorAction"/>
<action id="ActivateNavBar" class="com.intellij.ide.navigationToolbar.ActivateNavigationBarAction" popup="true"/>
<action id="EditorIndentLineOrSelection" class="com.intellij.openapi.editor.actions.IndentLineOrSelectionAction"/>
<group id="CodeInsightEditorActions">
<reference ref="LookupActions"/>
<action id="EmacsStyleIndent" class="com.intellij.codeInsight.editorActions.EmacsStyleIndentAction"/>
<action id="EditorCodeBlockStart" class="com.intellij.codeInsight.editorActions.CodeBlockStartAction"/>
<action id="EditorCodeBlockEnd" class="com.intellij.codeInsight.editorActions.CodeBlockEndAction"/>
<action id="EditorMatchBrace" class="com.intellij.codeInsight.editorActions.MatchBraceAction"/>
<action id="EditorCodeBlockStartWithSelection" class="com.intellij.codeInsight.editorActions.CodeBlockStartWithSelectionAction"/>
<action id="EditorCodeBlockEndWithSelection" class="com.intellij.codeInsight.editorActions.CodeBlockEndWithSelectionAction"/>
<action id="EditorCompleteStatement" class="com.intellij.codeInsight.editorActions.smartEnter.SmartEnterAction"/>
<add-to-group group-id="EditorActions" anchor="last"/>
</group>
<!-- File -->
<action id="ReloadFromDisk" class="com.intellij.ide.actions.ReloadFromDiskAction">
<!--
<add-to-group group-id="FileMenu" anchor="after" relative-to-action="Synchronize"/>
-->
</action>
<group id="PrintExportGroup">
<separator/>
<action id="ExportToHTML" class="com.intellij.codeEditor.printing.ExportToHTMLAction"/>
<action id="Print" class="com.intellij.codeEditor.printing.PrintAction" icon="AllIcons.Graph.Print"/>
<reference ref="AddToFavorites"/>
<add-to-group group-id="FileMenu" anchor="after" relative-to-action="InvalidateCaches"/>
</group>
<action id="ChangeTemplateDataLanguage" class="com.intellij.psi.templateLanguages.ChangeTemplateDataLanguageAction">
<add-to-group group-id="FileMenu" anchor="before" relative-to-action="ToggleReadOnlyAttribute"/>
</action>
<group id="PowerSaveGroup">
<separator/>
<action id="TogglePowerSave" class="com.intellij.ide.actions.TogglePowerSaveAction"/>
<add-to-group group-id="FileMenu" anchor="after" relative-to-action="ToggleReadOnlyAttribute"/>
</group>
<!-- Edit -->
<action id="CopyReference" class="com.intellij.ide.actions.CopyReferenceAction">
<add-to-group group-id="CutCopyPasteGroup" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorTabPopupMenu" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorPopupMenu" anchor="after" relative-to-action="$Copy"/>
</action>
<action id="CopyAsRichText" class="com.intellij.openapi.editor.richcopy.CopyAsRichTextAction">
<add-to-group group-id="CutCopyPasteGroup" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorPopupMenu" anchor="after" relative-to-action="$Copy"/>
</action>
<action id="CopyAsPlainText" class="com.intellij.openapi.editor.richcopy.CopyAsPlainTextAction">
<add-to-group group-id="CutCopyPasteGroup" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorPopupMenu" anchor="after" relative-to-action="$Copy"/>
</action>
<group id="EditSelectWordGroup">
<reference ref="EditorSelectWord"/>
<reference ref="EditorUnSelectWord"/>
<add-to-group group-id="EditSelectGroup" anchor="last"/>
</group>
<group id="EditBookmarksGroup" popup="true">
<action id="ToggleBookmark" class="com.intellij.ide.bookmarks.actions.ToggleBookmarkAction"/>
<action id="ToggleBookmarkWithMnemonic" class="com.intellij.ide.bookmarks.actions.ToggleBookmarkWithMnemonicAction"/>
<action id="ShowBookmarks" class="com.intellij.ide.bookmarks.actions.BookmarksAction"/>
<action id="GotoNextBookmark" class="com.intellij.ide.bookmarks.actions.NextBookmarkAction"/>
<action id="GotoPreviousBookmark" class="com.intellij.ide.bookmarks.actions.PreviousBookmarkAction"/>
<separator/>
<add-to-group group-id="GoToMenu" anchor="after" relative-to-action="JumpToNextChange"/>
</group>
<group id="GoToCodeGroup">
<separator/>
<action id="SelectIn" class="com.intellij.ide.actions.SelectInAction"/>
<action id="ShowNavBar" class="com.intellij.ide.navigationToolbar.ShowNavBarAction"/>
<action id="GotoDeclaration" class="com.intellij.codeInsight.navigation.actions.GotoDeclarationAction"/>
<action id="GotoImplementation" class="com.intellij.codeInsight.navigation.actions.GotoImplementationAction"/>
<action id="GotoTypeDeclaration" class="com.intellij.codeInsight.navigation.actions.GotoTypeDeclarationAction"/>
<action id="GotoSuperMethod" class="com.intellij.codeInsight.navigation.actions.GotoSuperAction"/>
<action id="GotoTest" class="com.intellij.testIntegration.GotoTestOrCodeAction"/>
<action id="GotoRelated" class="com.intellij.ide.actions.GotoRelatedSymbolAction"/>
<separator/>
<action id="FileStructurePopup" class="com.intellij.ide.actions.ViewStructureAction"/>
<action id="ShowFilePath" class="com.intellij.ide.actions.ShowFilePathAction"/>
<group id="HierarchyGroup">
<action id="TypeHierarchy" class="com.intellij.ide.hierarchy.actions.BrowseTypeHierarchyAction"/>
<action id="MethodHierarchy" class="com.intellij.ide.hierarchy.actions.BrowseMethodHierarchyAction"/>
<action id="CallHierarchy" class="com.intellij.ide.hierarchy.actions.BrowseCallHierarchyAction"/>
</group>
<separator/>
<add-to-group group-id="GoToMenu" anchor="after" relative-to-action="EditBookmarksGroup"/>
</group>
<group id="GoToErrorGroup">
<separator/>
<action id="GotoNextError" class="com.intellij.codeInsight.daemon.impl.actions.GotoNextErrorAction"/>
<action id="GotoPreviousError" class="com.intellij.codeInsight.daemon.impl.actions.GotoPreviousErrorAction"/>
<add-to-group group-id="GoToMenu" anchor="after" relative-to-action="GoToCodeGroup"/>
</group>
<!-- View -->
<group id="QuickActions">
<separator/>
<action id="QuickImplementations" class="com.intellij.codeInsight.hint.actions.ShowImplementationsAction"/>
<action id="QuickJavaDoc" class="com.intellij.codeInsight.documentation.actions.ShowQuickDocInfoAction"/>
<add-to-group group-id="ViewMenu" anchor="after" relative-to-action="ToolWindowsGroup"/>
</group>
<group id="CodeEditorBaseGroup">
<group id="CodeEditorViewGroup">
<action id="ExternalJavaDoc" class="com.intellij.ide.actions.ExternalJavaDocAction"/>
<action id="ParameterInfo" class="com.intellij.codeInsight.hint.actions.ShowParameterInfoAction"/>
<action id="ExpressionTypeInfo" class="com.intellij.codeInsight.hint.actions.ShowExpressionTypeAction"/>
<action id="EditorContextInfo" class="com.intellij.codeInsight.hint.actions.ShowContainerInfoAction"/>
<action id="ShowErrorDescription" class="com.intellij.codeInsight.daemon.impl.actions.ShowErrorDescriptionAction"/>
</group>
<separator/>
<add-to-group group-id="ViewMenu" relative-to-action="QuickActions" anchor="after"/>
</group>
<action id="FixDocComment" class="com.intellij.codeInsight.editorActions.FixDocCommentAction"/>
<action id="ViewNavigationBar" class="com.intellij.ide.actions.ViewNavigationBarAction">
<add-to-group group-id="UIToggleActions" relative-to-action="ViewStatusBar" anchor="after"/>
</action>
<action id="ViewImportPopups" class="com.intellij.openapi.editor.actions.ToggleShowImportPopupsAction">
<add-to-group group-id="EditorToggleActions"/>
</action>
<action id="ProjectViewChangeView" class="com.intellij.ide.projectView.actions.ChangeProjectViewAction"/>
<action id="RecentChanges" class="com.intellij.history.integration.ui.actions.RecentChangesAction">
<keyboard-shortcut first-keystroke="alt shift C" keymap="$default"/>
<add-to-group group-id="ViewRecentActions" anchor="last"/>
</action>
<!-- Go To -->
<group id="GoToTargetEx">
<action id="GotoClass" class="com.intellij.ide.actions.GotoClassAction"/>
<action id="GotoFile" class="com.intellij.ide.actions.GotoFileAction"/>
<action id="GotoSymbol" class="com.intellij.ide.actions.GotoSymbolAction"/>
<action id="GotoCustomRegion" class="com.intellij.lang.customFolding.GotoCustomRegionAction"/>
<add-to-group group-id="GoToMenu" anchor="first"/>
</group>
<group id="GoToMenuEx">
<separator/>
<action id="MethodDown" class="com.intellij.codeInsight.navigation.actions.MethodDownAction"/>
<action id="MethodUp" class="com.intellij.codeInsight.navigation.actions.MethodUpAction"/>
<separator/>
<add-to-group group-id="GoToMenu" anchor="after" relative-to-action="GoToPreviousError"/>
</group>
<!-- Code -->
<group id="CodeMenu" popup="true">
<reference ref="OverrideMethods"/>
<reference ref="ImplementMethods"/>
<action id="Generate" class="com.intellij.codeInsight.generation.actions.GenerateAction"/>
<separator/>
<action id="SurroundWith" class="com.intellij.codeInsight.generation.actions.SurroundWithAction"/>
<action id="Unwrap" class="com.intellij.codeInsight.unwrap.UnwrapAction"/>
<separator/>
<group id="CodeCompletionGroup" class="com.intellij.codeInsight.completion.actions.CodeCompletionGroup" popup="true">
<action id="CodeCompletion" class="com.intellij.codeInsight.completion.actions.CodeCompletionAction"/>
<action id="SmartTypeCompletion" class="com.intellij.codeInsight.completion.actions.SmartCodeCompletionAction"/>
<separator/>
<action id="HippieCompletion" class="com.intellij.codeInsight.completion.actions.HippieCompletionAction"/>
<action id="HippieBackwardCompletion" class="com.intellij.codeInsight.completion.actions.HippieBackwardCompletionAction"/>
</group>
<group id="FoldingGroup" popup="true">
<action id="ExpandRegion" class="com.intellij.codeInsight.folding.impl.actions.ExpandRegionAction"/>
<action id="CollapseRegion" class="com.intellij.codeInsight.folding.impl.actions.CollapseRegionAction"/>
<separator/>
<action id="ExpandRegionRecursively" class="com.intellij.codeInsight.folding.impl.actions.ExpandRegionRecursivelyAction"/>
<action id="CollapseRegionRecursively" class="com.intellij.codeInsight.folding.impl.actions.CollapseRegionRecursivelyAction"/>
<separator/>
<action id="ExpandAllRegions" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllRegionsAction"/>
<action id="CollapseAllRegions" class="com.intellij.codeInsight.folding.impl.actions.CollapseAllRegionsAction"/>
<separator/>
<group id="ExpandToLevel" popup="true">
<action id="ExpandToLevel1" class="com.intellij.codeInsight.folding.impl.actions.ExpandToLevel1Action"/>
<action id="ExpandToLevel2" class="com.intellij.codeInsight.folding.impl.actions.ExpandToLevel2Action"/>
<action id="ExpandToLevel3" class="com.intellij.codeInsight.folding.impl.actions.ExpandToLevel3Action"/>
<action id="ExpandToLevel4" class="com.intellij.codeInsight.folding.impl.actions.ExpandToLevel4Action"/>
<action id="ExpandToLevel5" class="com.intellij.codeInsight.folding.impl.actions.ExpandToLevel5Action"/>
</group>
<group id="ExpandAllToLevel" popup="true">
<action id="ExpandAllToLevel1" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllToLevel1Action"/>
<action id="ExpandAllToLevel2" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllToLevel2Action"/>
<action id="ExpandAllToLevel3" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllToLevel3Action"/>
<action id="ExpandAllToLevel4" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllToLevel4Action"/>
<action id="ExpandAllToLevel5" class="com.intellij.codeInsight.folding.impl.actions.ExpandAllToLevel5Action"/>
</group>
<separator/>
<group id="LanguageSpecificFoldingGroup">
<action id="ExpandDocComments" class="com.intellij.codeInsight.folding.impl.actions.ExpandDocCommentsAction"/>
<action id="CollapseDocComments" class="com.intellij.codeInsight.folding.impl.actions.CollapseDocCommentsAction"/>
</group>
<separator/>
<action id="CollapseSelection" class="com.intellij.codeInsight.folding.impl.actions.CollapseSelectionAction"/>
</group>
<separator/>
<action id="InsertLiveTemplate" class="com.intellij.codeInsight.template.impl.actions.ListTemplatesAction"/>
<action id="SurroundWithLiveTemplate" class="com.intellij.codeInsight.template.impl.actions.SurroundWithTemplateAction"/>
<separator/>
<group id="CommentGroup">
<action id="CommentByLineComment" class="com.intellij.codeInsight.generation.actions.CommentByLineCommentAction"/>
<action id="CommentByBlockComment" class="com.intellij.codeInsight.generation.actions.CommentByBlockCommentAction"/>
</group>
<group id="CodeFormatGroup">
<action id="ReformatCode" class="com.intellij.codeInsight.actions.ReformatCodeAction"/>
<action id="AutoIndentLines" class="com.intellij.codeInsight.generation.actions.AutoIndentLinesAction"/>
<action id="OptimizeImports" class="com.intellij.codeInsight.actions.OptimizeImportsAction"/>
<action id="RearrangeCode" class="com.intellij.application.options.codeStyle.arrangement.action.RearrangeCodeAction"/>
</group>
<separator/>
<action id="MoveStatementDown" class="com.intellij.codeInsight.editorActions.moveUpDown.MoveStatementDownAction"/>
<action id="MoveStatementUp" class="com.intellij.codeInsight.editorActions.moveUpDown.MoveStatementUpAction"/>
<action id="MoveLineDown" class="com.intellij.codeInsight.editorActions.moveUpDown.MoveLineDownAction"/>
<action id="MoveLineUp" class="com.intellij.codeInsight.editorActions.moveUpDown.MoveLineUpAction"/>
<separator/>
<add-to-group group-id="MainMenu" anchor="after" relative-to-action="GoToMenu"/>
</group>
<!-- Refactor -->
<group id="RefactoringMenu" popup="true">
<action id="Refactorings.QuickListPopupAction"
class = "com.intellij.refactoring.actions.RefactoringQuickListPopupAction"
text = "Refactor This..." description="Context aware popup with list of refactoring actions"/>
<action id="RenameElement" class="com.intellij.refactoring.actions.RenameElementAction"/>
<action id="ChangeSignature" class="com.intellij.refactoring.actions.ChangeSignatureAction"/>
<separator/>
<action id="Move" class="com.intellij.refactoring.actions.MoveAction"/>
<action id="CopyElement" class="com.intellij.ide.actions.CopyElementAction"/>
<action id="SafeDelete" class="com.intellij.refactoring.actions.SafeDeleteAction"/>
<separator/>
<group id="IntroduceActionsGroup" popup="true">
<action id="IntroduceVariable" class="com.intellij.refactoring.actions.IntroduceVariableAction"/>
<action id="IntroduceConstant" class="com.intellij.refactoring.actions.IntroduceConstantAction"/>
<action id="IntroduceField" class="com.intellij.refactoring.actions.IntroduceFieldAction"/>
<action id="IntroduceParameter" class="com.intellij.refactoring.actions.IntroduceParameterAction"/>
<separator/>
<action id="ExtractMethod" class="com.intellij.refactoring.actions.ExtractMethodAction"/>
<separator/>
<action id="ExtractClass" class="com.intellij.refactoring.actions.ExtractClassAction"/>
<action id="ExtractInclude" class="com.intellij.refactoring.actions.ExtractIncludeAction"/>
<action id="ExtractInterface" class="com.intellij.refactoring.actions.ExtractInterfaceAction"/>
<action id="ExtractSuperclass" class="com.intellij.refactoring.actions.ExtractSuperclassAction"/>
<action id="ExtractModule" class="com.intellij.refactoring.actions.ExtractModuleAction"/>
</group>
<action id="Inline" class="com.intellij.refactoring.actions.InlineAction"/>
<separator/>
<action id="MembersPullUp" class="com.intellij.refactoring.actions.PullUpAction"/>
<action id="MemberPushDown" class="com.intellij.refactoring.actions.PushDownAction"/>
<add-to-group group-id="MainMenu" anchor="after" relative-to-action="CodeMenu"/>
</group>
<!-- Run -->
<group id="RunMenu" popup="true">
<group id="RunnerActions"/>
<reference ref="ChooseRunConfiguration"/>
<reference ref="ChooseDebugConfiguration"/>
<action id="editRunConfigurations" class="com.intellij.execution.actions.EditRunConfigurationsAction"/>
<action id="Stop" class="com.intellij.execution.actions.StopAction" icon="AllIcons.Actions.Suspend"/>
<action id="ShowLiveRunConfigurations" class="com.intellij.execution.actions.ShowRunningListAction"/>
<add-to-group group-id="MainMenu" anchor="after" relative-to-action="RefactoringMenu"/>
</group>
<!-- Tools -->
<group id="ToolsBasicGroup">
<action id="SaveAsTemplate" class="com.intellij.codeInsight.template.actions.SaveAsTemplateAction"/>
<action id="SaveFileAsTemplate" class="com.intellij.ide.actions.SaveFileAsTemplateAction"/>
<separator/>
<add-to-group group-id="ToolsMenu" anchor="first"/>
<action id="NewScratchFile" class="com.intellij.ide.scratch.ScratchFileActions$NewFileAction" />
<action id="IdeScriptingConsole" class="com.intellij.execution.console.RunIdeConsoleAction"/>
</group>
<action id="NewScratchBuffer" class="com.intellij.ide.scratch.ScratchFileActions$NewBufferAction"/>
<action id="Scratch.ChangeLanguage" class="com.intellij.ide.scratch.ScratchFileActions$LanguageAction">
<add-to-group group-id="EditorPopupMenu2"/>
</action>
<group id="ExternalToolsGroup" class="com.intellij.tools.ExternalToolsGroup">
<add-to-group group-id="ToolsMenu" anchor="last"/>
</group>
<group id="NewGroup" popup="true">
<action id="NewFile" class="com.intellij.ide.actions.CreateFileAction"/>
<action id="NewDir" class="com.intellij.ide.actions.CreateDirectoryOrPackageAction"/>
<separator/>
<action id="NewFromTemplate" class="com.intellij.ide.fileTemplates.actions.CreateFromTemplateGroup"/>
</group>
<group id="WeighingNewGroup" class="com.intellij.ide.actions.WeighingNewActionGroup"/>
<!-- Toolbar -->
<!--
<group id="ToolbarNewElement">
<action id="NewElementToolbarAction" class="com.intellij.ide.actions.NewElementToolbarAction" icon="/general/add.png"/>
<add-to-group group-id="MainToolBar" anchor="first"/>
</group>
-->
<group id="ToolbarFindGroup">
<separator/>
<reference ref="Find"/>
<reference ref="Replace"/>
<add-to-group group-id="MainToolBar" relative-to-action="$Paste" anchor="after"/>
</group>
<group id="ToolbarRunGroup">
<separator/>
<reference ref="RunConfiguration"/>
<reference ref="RunnerActions"/>
<add-to-group group-id="MainToolBar" relative-to-action="Forward" anchor="after"/>
</group>
<group id="NavBarToolBarOthers"/>
<group id="NavBarToolBar">
<reference ref="ToolbarRunGroup"/>
<separator/>
<reference ref="NavBarVcsGroup"/>
<separator/>
<reference id="NavBarToolBarOthers"/>
<separator/>
<reference ref="SearchEverywhere"/>
</group>
<group id="Bookmarks">
<reference ref="ToggleBookmark"/>
<reference ref="ShowBookmarks"/>
<reference ref="GotoNextBookmark"/>
<reference ref="GotoPreviousBookmark"/>
<action id="GotoBookmark0" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark0Action"/>
<action id="GotoBookmark1" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark1Action"/>
<action id="GotoBookmark2" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark2Action"/>
<action id="GotoBookmark3" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark3Action"/>
<action id="GotoBookmark4" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark4Action"/>
<action id="GotoBookmark5" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark5Action"/>
<action id="GotoBookmark6" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark6Action"/>
<action id="GotoBookmark7" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark7Action"/>
<action id="GotoBookmark8" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark8Action"/>
<action id="GotoBookmark9" class="com.intellij.ide.bookmarks.actions.GoToMnemonicBookmarkActionBase$GotoBookmark9Action"/>
<action id="ToggleBookmark0" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark0Action"/>
<action id="ToggleBookmark1" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark1Action"/>
<action id="ToggleBookmark2" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark2Action"/>
<action id="ToggleBookmark3" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark3Action"/>
<action id="ToggleBookmark4" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark4Action"/>
<action id="ToggleBookmark5" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark5Action"/>
<action id="ToggleBookmark6" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark6Action"/>
<action id="ToggleBookmark7" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark7Action"/>
<action id="ToggleBookmark8" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark8Action"/>
<action id="ToggleBookmark9" class="com.intellij.ide.bookmarks.actions.ToggleNumberedBookmarkActionBase$ToggleBookmark9Action"/>
</group>
<group id="ProjectViewPopupMenuRefactoringGroup" class="com.intellij.ide.actions.NonTrivialActionGroup">
<reference ref="RefactoringMenu"/>
</group>
<group id="ProjectViewPopupMenuModifyGroup">
<reference ref="$Delete"/>
<reference ref="Scratch.ChangeLanguage"/>
<group id="MarkFileAs" class="com.intellij.openapi.file.exclude.ui.MarkFileGroup">
<action id="MarkAsPlainTextAction" class="com.intellij.openapi.file.exclude.ui.MarkAsPlainTextAction"/>
<action id="MarkAsOriginalTypeAction" class="com.intellij.openapi.file.exclude.ui.MarkAsOriginalTypeAction"/>
</group>
</group>
<group id="ProjectViewPopupMenuRunGroup">
<reference ref="RunContextPopupGroup"/>
</group>
<group id="ProjectViewPopupMenuSettingsGroup">
<group id="MarkRootGroup" class="com.intellij.ide.projectView.actions.MarkRootGroup" popup="true">
</group>
</group>
<group id="ProjectViewPopupMenu">
<reference ref="WeighingNewGroup"/>
<action id="AssociateWithFileType" class="com.intellij.ide.actions.AssociateFileType"/>
<action id="RestoreDefaultExtensionScripts" class="com.intellij.ide.extensionResources.RestoreBundledExtensionsAction"/>
<separator/>
<reference ref="CutCopyPasteGroup"/>
<reference ref="EditSource"/>
<reference ref="ChangesView.ApplyPatch"/>
<separator/>
<reference ref="FindUsages"/>
<reference ref="FindInPath"/>
<reference ref="ReplaceInPath"/>
<separator/>
<reference ref="ProjectViewPopupMenuRefactoringGroup"/>
<separator/>
<reference ref="AddToFavorites"/>
<separator/>
<reference ref="ProjectViewPopupMenuModifyGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuRunGroup"/>
<separator/>
<reference ref="VersionControlsGroup"/>
<action id="SynchronizeCurrentFile" class="com.intellij.ide.actions.SynchronizeCurrentFileAction" icon="AllIcons.Actions.Refresh"/>
<separator/>
<action id="RevealIn" class="com.intellij.ide.actions.RevealFileAction"/>
<reference ref="ShowFilePath"/>
<action id="GoToLinkTarget" class="com.intellij.ide.actions.GoToLinkTargetAction"/>
<separator/>
<reference ref="CompareTwoFiles"/>
<reference ref="CompareFileWithEditor"/>
<separator/>
<reference ref="ExternalToolsGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuSettingsGroup"/>
</group>
<group id="NavbarPopupMenu">
<reference ref="WeighingNewGroup"/>
<reference ref="AssociateWithFileType"/>
<separator/>
<reference ref="CutCopyPasteGroup"/>
<reference ref="EditSource"/>
<reference ref="ChangesView.ApplyPatch"/>
<separator/>
<reference ref="FindUsages"/>
<reference ref="FindInPath"/>
<reference ref="ReplaceInPath"/>
<separator/>
<reference ref="ProjectViewPopupMenuRefactoringGroup"/>
<separator/>
<reference ref="AddToFavorites"/>
<separator/>
<reference ref="ProjectViewPopupMenuModifyGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuRunGroup"/>
<separator/>
<reference ref="VersionControlsGroup"/>
<reference ref="SynchronizeCurrentFile"/>
<separator/>
<reference ref="ExternalToolsGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuSettingsGroup"/>
</group>
<group id="FavoritesViewPopupMenu">
<reference ref="NewGroup"/>
<reference ref="AssociateWithFileType"/>
<separator/>
<reference ref="CutCopyPasteGroup"/>
<reference ref="EditSource"/>
<reference ref="ChangesView.ApplyPatch"/>
<separator/>
<reference ref="FindUsages"/>
<reference ref="FindInPath"/>
<reference ref="ReplaceInPath"/>
<separator/>
<reference ref="ProjectViewPopupMenuRefactoringGroup"/>
<separator/>
<action id="EditFavorites" class="com.intellij.ide.favoritesTreeView.actions.EditFavoritesAction"/>
<reference ref="AddToFavorites"/>
<reference ref="SendToFavoritesGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuModifyGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuRunGroup"/>
<separator/>
<reference ref="VersionControlsGroup"/>
<reference ref="SynchronizeCurrentFile"/>
<separator/>
<reference ref="RevealIn"/>
<reference ref="ShowFilePath"/>
<separator/>
<reference ref="CompareTwoFiles"/>
<reference ref="CompareFileWithEditor"/>
<separator/>
<reference ref="ExternalToolsGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuSettingsGroup"/>
</group>
<group id="ScopeViewPopupMenu">
<reference ref="ProjectViewPopupMenu"/>
<separator/>
<action id="ScopeView.EditScopes" class="com.intellij.ide.scopeView.EditScopesAction"/>
</group>
<group id="StructureViewPopupMenu">
<reference ref="EditSource"/>
<separator/>
<reference ref="FindUsages"/>
<reference ref="RefactoringMenu"/>
<separator/>
<reference ref="AddToFavorites"/>
<separator/>
<reference ref="CutCopyPasteGroup"/>
<separator/>
<reference ref="RunContextPopupGroup"/>
<reference ref="VersionControlsGroup"/>
<separator/>
<reference ref="CompareTwoFiles"/>
</group>
<group id="EditorPopupMenu1.FindRefactor">
<reference ref="FindUsages"/>
<reference ref="RefactoringMenu"/>
<separator/>
<reference ref="FoldingGroup"/>
<add-to-group group-id="EditorPopupMenu1"/>
</group>
<group id="EditorLangPopupMenu">
<separator/>
<group id="EditorPopupMenu.GoTo" popup="true">
<reference ref="ShowNavBar"/>
<reference ref="GotoDeclaration"/>
<reference ref="GotoImplementation"/>
<reference ref="GotoTypeDeclaration"/>
<reference ref="GotoSuperMethod"/>
<reference ref="GotoTest"/>
</group>
<reference ref="Generate"/>
<separator/>
<group id="EditorPopupMenu.Run">
<reference ref="RunContextPopupGroup"/>
</group>
<separator/>
<reference ref="VersionControlsGroup"/>
<separator/>
<reference ref="ExternalToolsGroup"/>
<add-to-group group-id="EditorPopupMenu" relative-to-action="CompareClipboardWithSelection" anchor="before"/>
</group>
<group id="EditorTabPopupMenuEx">
<separator/>
<reference ref="AddToFavorites"/>
<reference ref="AddAllToFavorites"/>
<separator/>
<reference ref="RunContextPopupGroup"/>
<separator/>
<reference ref="VersionControlsGroup"/>
<separator/>
<reference ref="ExternalToolsGroup"/>
<add-to-group group-id="EditorTabPopupMenu" anchor="last"/>
</group>
<reference ref="ChangeTemplateDataLanguage">
<add-to-group group-id="EditorPopupMenu" anchor="before" relative-to-action="ToggleReadOnlyAttribute"/>
</reference>
<group id="UsageView.Popup">
<action id="UsageView.Rerun" class="com.intellij.usages.actions.RerunSearchAction" icon="AllIcons.Actions.Rerun" use-shortcut-of="Rerun"/>
<separator/>
<reference ref="EditSource"/>
<action id="UsageView.Include" class="com.intellij.usages.actions.IncludeUsageAction"/>
<action id="UsageView.Exclude" class="com.intellij.usages.actions.ExcludeUsageAction" use-shortcut-of="$Delete"/>
<action id="UsageView.Remove" class="com.intellij.usages.actions.RemoveUsageAction" use-shortcut-of="SafeDelete"/>
<separator/>
<action id="UsageView.ShowRecentFindUsages" class="com.intellij.find.impl.ShowRecentFindUsagesAction" icon="AllIcons.Actions.Back"
use-shortcut-of="RecentFiles"/>
<separator/>
<reference ref="AddToFavorites"/>
</group>
<!-- <action id="UsageView.ImportToFavorites" class="com.intellij.ide.favoritesTreeView.ImportUsagesAction"/> -->
<action id="NewElementSamePlace" class="com.intellij.ide.actions.NewElementSamePlaceAction"/>
<action id="ChangeCodeStyleScheme" class="com.intellij.ide.actions.QuickChangeCodeStyleSchemeAction">
<add-to-group group-id="ChangeScheme" anchor="after" relative-to-action="ChangeColorScheme"/>
</action>
<action id="ChangeInspectionProfile" class="com.intellij.ide.actions.QuickChangeInspectionProfileAction">
<add-to-group group-id="ChangeScheme" anchor="after" relative-to-action="ChangeCodeStyleScheme"/>
</action>
<action id="TypeHierarchyBase.BaseOnThisType" text="Base on This Type" class="com.intellij.ide.hierarchy.TypeHierarchyBrowserBase$BaseOnThisTypeAction"/>
<action id="TypeHierarchy.Class" class="com.intellij.ide.hierarchy.ViewClassHierarchyAction"/>
<action id="TypeHierarchy.Subtypes" class="com.intellij.ide.hierarchy.ViewSubtypesHierarchyAction"/>
<action id="TypeHierarchy.Supertypes" class="com.intellij.ide.hierarchy.ViewSupertypesHierarchyAction"/>
<action id="EditBreakpoint" class="com.intellij.xdebugger.impl.actions.EditBreakpointAction"/>
<group id="DebugMainMenu">
<separator/>
<action id="StepOver" class="com.intellij.xdebugger.impl.actions.StepOverAction" icon="AllIcons.Actions.TraceOver"/>
<action id="ForceStepOver" class="com.intellij.xdebugger.impl.actions.ForceStepOverAction" icon="AllIcons.Debugger.Actions.Force_step_over"/>
<action id="StepInto" class="com.intellij.xdebugger.impl.actions.StepIntoAction" icon="AllIcons.Actions.TraceInto"/>
<action id="ForceStepInto" class="com.intellij.xdebugger.impl.actions.ForceStepIntoAction" icon="AllIcons.Debugger.Actions.Force_step_into"/>
<action id="SmartStepInto" class="com.intellij.xdebugger.impl.actions.SmartStepIntoAction" icon="AllIcons.Debugger.SmartStepInto"/>
<action id="StepOut" class="com.intellij.xdebugger.impl.actions.StepOutAction" icon="AllIcons.Actions.StepOut"/>
<action id="RunToCursor" class="com.intellij.xdebugger.impl.actions.RunToCursorAction" icon="AllIcons.Actions.RunToCursor"/>
<action id="ForceRunToCursor" class="com.intellij.xdebugger.impl.actions.ForceRunToCursorAction" icon="AllIcons.Debugger.Actions.Force_run_to_cursor"/>
<action id="Pause" class="com.intellij.xdebugger.impl.actions.PauseAction" icon="AllIcons.Actions.Pause"/>
<action id="Resume" class="com.intellij.xdebugger.impl.actions.ResumeAction" icon="AllIcons.Actions.Resume"/>
<separator/>
<action id="EvaluateExpression" class="com.intellij.xdebugger.impl.actions.EvaluateAction" icon="AllIcons.Debugger.EvaluateExpression"/>
<action id="QuickEvaluateExpression" class="com.intellij.xdebugger.impl.actions.QuickEvaluateAction"/>
<action id="ShowExecutionPoint" class="com.intellij.xdebugger.impl.actions.ShowExecutionPointAction"
icon="AllIcons.Debugger.ShowCurrentFrame"/>
<separator/>
<action id="ToggleLineBreakpoint" class="com.intellij.xdebugger.impl.actions.ToggleLineBreakpointAction"/>
<action id="ToggleTemporaryLineBreakpoint" class="com.intellij.xdebugger.impl.actions.ToggleTemporaryLineBreakpointAction"/>
<action id="ToggleBreakpointEnabled" class="com.intellij.xdebugger.impl.actions.ToggleBreakpointEnabledAction"/>
<action id="ViewBreakpoints" class="com.intellij.xdebugger.impl.actions.ViewBreakpointsAction" icon="AllIcons.Debugger.ViewBreakpoints"/>
<separator/>
<add-to-group group-id="RunMenu" anchor="last"/>
</group>
<action id="Debugger.AddToWatch" class="com.intellij.xdebugger.impl.actions.AddToWatchesAction" icon="AllIcons.Debugger.AddToWatch"/>
<action id="Debugger.EvaluateInConsole" class="com.intellij.xdebugger.impl.actions.EvaluateInConsoleAction"/>
<group id="EditorPopupMenuDebug">
<separator/>
<reference ref="EvaluateExpression"/>
<reference ref="RunToCursor"/>
<reference ref="ForceRunToCursor"/>
<reference ref="Debugger.AddToWatch"/>
<reference ref="Debugger.EvaluateInConsole"/>
<separator/>
<add-to-group group-id="EditorLangPopupMenu" relative-to-action="EditorPopupMenu.Run" anchor="before"/>
</group>
<group id="XDebugger.Actions">
<action id="XDebugger.SetValue" class="com.intellij.xdebugger.impl.ui.tree.actions.XSetValueAction"/>
<action id="XDebugger.CopyValue" class="com.intellij.xdebugger.impl.ui.tree.actions.XCopyValueAction"/>
<action id="XDebugger.CompareValueWithClipboard" class="com.intellij.xdebugger.impl.ui.tree.actions.XCompareWithClipboardAction"/>
<action id="XDebugger.CopyName" class="com.intellij.xdebugger.impl.ui.tree.actions.XCopyNameAction"/>
<action id="XDebugger.Inspect" class="com.intellij.xdebugger.impl.ui.tree.actions.XInspectAction"/>
<action id="XDebugger.JumpToSource" class="com.intellij.xdebugger.impl.ui.tree.actions.XJumpToSourceAction"/>
<action id="XDebugger.JumpToTypeSource" class="com.intellij.xdebugger.impl.ui.tree.actions.XJumpToTypeSourceAction"/>
<action id="Debugger.Tree.AddToWatches" class="com.intellij.xdebugger.impl.ui.tree.actions.XAddToWatchesAction" icon="AllIcons.Debugger.AddToWatch"/>
<action id="Debugger.Tree.EvaluateInConsole" class="com.intellij.xdebugger.impl.ui.tree.actions.EvaluateInConsoleFromTreeAction"/>
<action id="XDebugger.NewWatch" class="com.intellij.xdebugger.impl.frame.actions.XNewWatchAction" icon="AllIcons.Debugger.NewWatch"/>
<action id="XDebugger.EditWatch" class="com.intellij.xdebugger.impl.frame.actions.XEditWatchAction"/>
<action id="XDebugger.CopyWatch" class="com.intellij.xdebugger.impl.frame.actions.XCopyWatchAction" icon="AllIcons.Actions.Copy" text="Copy Watch"/>
<action id="XDebugger.RemoveWatch" class="com.intellij.xdebugger.impl.frame.actions.XRemoveWatchAction" icon="AllIcons.Actions.Delete"/>
<action id="XDebugger.RemoveAllWatches" class="com.intellij.xdebugger.impl.frame.actions.XRemoveAllWatchesAction"/>
<action id="XDebugger.MuteBreakpoints" class="com.intellij.xdebugger.impl.actions.MuteBreakpointAction"
icon="AllIcons.Debugger.MuteBreakpoints"/>
<action id="XDebugger.ToggleSortValues" class="com.intellij.xdebugger.impl.ui.tree.actions.SortValuesToggleAction" icon="AllIcons.ObjectBrowser.Sorted"/>
<action id="Debugger.MarkObject" class="com.intellij.xdebugger.impl.actions.MarkObjectAction"/>
<action id="Debugger.FocusOnBreakpoint" class="com.intellij.xdebugger.impl.actions.FocusOnBreakpointAction"/>
<action id="Debugger.ShowReferring" class="com.intellij.xdebugger.impl.ui.tree.actions.ShowReferringObjectsAction"/>
</group>
<group id="XDebugger.ToolWindow.TopToolbar">
<reference ref="ShowExecutionPoint"/>
<separator/>
<reference ref="StepOver"/>
<reference ref="StepInto"/>
<reference ref="ForceStepInto"/>
<reference ref="StepOut"/>
<reference ref="RunToCursor"/>
<separator/>
<reference ref="EvaluateExpression" />
</group>
<group id="XDebugger.ToolWindow.LeftToolbar">
<separator/>
<reference ref="Resume"/>
<reference ref="Pause"/>
<reference ref="Stop"/>
<separator/>
<reference ref="ViewBreakpoints"/>
<reference ref="XDebugger.MuteBreakpoints"/>
</group>
<group id="XDebugger.ValueGroup" popup="false">
<reference ref="XDebugger.Inspect"/>
<reference ref="Debugger.MarkObject"/>
<reference ref="XDebugger.SetValue"/>
<reference ref="XDebugger.CopyValue"/>
<reference ref="XDebugger.CompareValueWithClipboard"/>
<reference ref="XDebugger.CopyName"/>
<separator/>
<reference ref="EvaluateExpression"/>
<reference ref="Debugger.Tree.EvaluateInConsole"/>
<reference ref="Debugger.Tree.AddToWatches"/>
<reference ref="Debugger.ShowReferring"/>
<separator/>
<reference ref="XDebugger.JumpToSource"/>
<reference ref="XDebugger.JumpToTypeSource"/>
<separator/>
</group>
<group id="XDebugger.Evaluation.Dialog.Tree.Popup">
<reference ref="XDebugger.ValueGroup"/>
</group>
<group id="XDebugger.Frames.Tree.Popup">
</group>
<group id="XDebugger.Frames.TopToolbar">
</group>
<group id="XDebugger.Variables.Tree.Popup">
<reference ref="XDebugger.ValueGroup"/>
</group>
<group id="XDebugger.Variables.Tree.Toolbar">
</group>
<group id="XDebugger.Watches.Tree.Popup">
<reference ref="XDebugger.NewWatch"/>
<reference ref="XDebugger.RemoveWatch"/>
<reference ref="XDebugger.RemoveAllWatches"/>
<reference ref="XDebugger.EditWatch"/>
<separator/>
<reference ref="XDebugger.ValueGroup"/>
</group>
<group id="XDebugger.Watches.Tree.Toolbar">
<reference ref="XDebugger.NewWatch"/>
<reference ref="XDebugger.RemoveWatch"/>
</group>
<group id="XDebugger.Inspect.Tree.Popup">
<reference ref="XDebugger.ValueGroup"/>
</group>
<group id="XDebugger.Settings" icon="AllIcons.General.SecondaryGroup" popup="true">
<action id="XDebugger.Inline" class="com.intellij.xdebugger.impl.actions.UseInlineDebuggerAction"/>
<separator/>
<reference ref="XDebugger.ToggleSortValues"/>
<!--<action id="XDebugger.AutoTooltip" class="com.intellij.xdebugger.impl.actions.ValueTooltipAutoShowAction"/>-->
<!--<action id="XDebugger.AutoTooltipOnSelection" class="com.intellij.xdebugger.impl.actions.ValueTooltipAutoShowOnSelectionAction"/>-->
<separator/>
<action id="XDebugger.UnmuteOnStop" class="com.intellij.xdebugger.impl.actions.UnmuteOnStopAction" />
</group>
<group id="RunnerLayoutActions">
<group id="Runner.Layout">
<action id="Runner.RestoreLayout" class="com.intellij.execution.ui.layout.actions.RestoreLayoutAction"
icon="AllIcons.Debugger.RestoreLayout"/>
</group>
<group id="Runner.View.Close.Group" popup="false">
<action id="Runner.CloseView" class="com.intellij.execution.ui.layout.actions.CloseViewAction" icon="AllIcons.Actions.Cross"/>
<action id="Runner.CloseOtherViews" class="com.intellij.execution.ui.layout.actions.CloseOtherViewsAction" icon="AllIcons.Actions.Cross"/>
<action id="Runner.CloseAllViews" class="com.intellij.execution.ui.layout.actions.CloseAllViewsAction" icon="AllIcons.Actions.Cross"/>
<action id="Runner.CloseAllUnpinnedViews" class="com.intellij.execution.ui.layout.actions.CloseAllUnpinnedViewsAction" icon="AllIcons.Actions.Cross"/>
</group>
<group id="Runner.View.Popup">
<action id="Runner.MinimizeView" class="com.intellij.execution.ui.layout.actions.MinimizeViewAction" icon="AllIcons.Actions.Minimize"/>
<separator/>
<reference ref="Runner.View.Close.Group"/>
<separator/>
<group id="Runner.Focus">
<action id="Runner.FocusOnStartup" class="com.intellij.execution.ui.actions.FocusOnStartAction"/>
</group>
</group>
<group id="Runner.View.Toolbar">
<reference ref="Runner.MinimizeView"/>
<reference ref="Runner.CloseView"/>
</group>
</group>
<group id="LocalHistory" class="com.intellij.history.integration.ui.actions.LocalHistoryGroup" popup="true">
<action id="LocalHistory.ShowHistory" class="com.intellij.history.integration.ui.actions.ShowHistoryAction"/>
<action id="LocalHistory.ShowSelectionHistory" class="com.intellij.history.integration.ui.actions.ShowSelectionHistoryAction"/>
<action id="LocalHistory.PutLabel" class="com.intellij.history.integration.ui.actions.PutLabelAction"/>
<add-to-group group-id="VersionControlsGroup" anchor="first"/>
<add-to-group group-id="VcsGroups" anchor="first"/>
</group>
<group id="TestTreePopupMenu">
<reference ref="RunContextGroup"/>
<reference ref="EditSource"/>
<reference ref="ViewSource"/>
</group>
<group id="ConsoleView.PopupMenu">
<reference ref="ConsoleEditorPopupMenu"/>
<separator/>
<action id="ConsoleView.ClearAll" class="com.intellij.execution.impl.ConsoleViewImpl$ClearAllAction"/>
</group>
<action id="SendEOF" class="com.intellij.execution.actions.EOFAction" text="Send EOF"/>
<group>
<action class="com.intellij.execution.testframework.actions.ViewAssertEqualsDiffAction"
text="View assertEquals Difference" id="openAssertEqualsDiff" use-shortcut-of="Diff.ShowDiff"/>
<separator/>
<add-to-group anchor="first" group-id="TestTreePopupMenu"/>
</group>
<!-- SM Test Runner Actions -->
<group id="SMTestRunnerTestsTree">
<separator/>
<action id="com.intellij.execution.testframework.sm.runner.ui.statistics.ShowStatisticsAction"
class="com.intellij.execution.testframework.sm.runner.ui.statistics.ShowStatisticsAction"
text="Show Statistics"/>
<add-to-group group-id="TestTreePopupMenu" anchor="last"/>
</group>
<group id="SMTestRunnerStatistics">
<separator/>
<action id="com.intellij.execution.testframework.sm.runner.ui.statistics.ShowTestProxy"
class="com.intellij.execution.testframework.sm.runner.ui.statistics.ShowTestProxy"
text="Navigate to Test"/>
<add-to-group group-id="TestTreePopupMenu" anchor="last"/>
</group>
<group>
<action class="com.intellij.execution.testframework.sm.runner.history.actions.ImportTestsGroup"
text="Import Test Results" icon="AllIcons.ToolbarDecorator.Import" id="ImportTests"/>
<add-to-group group-id="RunMenu" anchor="after" relative-to-action="editRunConfigurations"/>
</group>
<action id="DumpLookupElementWeights" class="com.intellij.internal.DumpLookupElementWeights" text="Dump lookup element weights to log">
<add-to-group group-id="MaintenanceGroup" anchor="last"/>
</action>
<action id="Arrangement.Rule.Add"
class="com.intellij.application.options.codeStyle.arrangement.action.AddArrangementRuleAction"/>
<action id="Arrangement.Rule.Section.Add"
class="com.intellij.application.options.codeStyle.arrangement.action.AddArrangementSectionRuleAction"/>
<action id="Arrangement.Rule.Remove"
class="com.intellij.application.options.codeStyle.arrangement.action.RemoveArrangementRuleAction"/>
<action id="Arrangement.Rule.Edit"
class="com.intellij.application.options.codeStyle.arrangement.action.EditArrangementRuleAction"/>
<action id="Arrangement.Rule.Match.Condition.Move.Up"
class="com.intellij.application.options.codeStyle.arrangement.action.MoveArrangementMatchingRuleUpAction"/>
<action id="Arrangement.Rule.Match.Condition.Move.Down"
class="com.intellij.application.options.codeStyle.arrangement.action.MoveArrangementMatchingRuleDownAction"/>
<action id="Arrangement.Custom.Token.Rule.Edit"
class="com.intellij.application.options.codeStyle.arrangement.action.EditRuleAliasesDefinitionAction"/>
<action id="Arrangement.Rule.Group.Condition.Move.Up"
class="com.intellij.application.options.codeStyle.arrangement.action.MoveArrangementGroupingRuleUpAction"/>
<action id="Arrangement.Rule.Group.Condition.Move.Down"
class="com.intellij.application.options.codeStyle.arrangement.action.MoveArrangementGroupingRuleDownAction"/>
<action id="Arrangement.Alias.Rule.Edit"
class="com.intellij.application.options.codeStyle.arrangement.action.tokens.EditArrangementAliasRuleAction"/>
<action id="Arrangement.Alias.Rule.Add"
class="com.intellij.application.options.codeStyle.arrangement.action.tokens.AddArrangementAliasRuleAction"/>
<action id="Arrangement.Alias.Rule.Remove"
class="com.intellij.application.options.codeStyle.arrangement.action.tokens.RemoveArrangementAliasRuleAction"/>
<action id="Arrangement.Alias.Rule.Match.Condition.Move.Up"
class="com.intellij.application.options.codeStyle.arrangement.action.tokens.MoveArrangementAliasRuleUpAction"/>
<action id="Arrangement.Alias.Rule.Match.Condition.Move.Down"
class="com.intellij.application.options.codeStyle.arrangement.action.tokens.MoveArrangementAliasRuleDownAction"/>
<group id="Arrangement.Alias.Rule.ToolBar">
<reference ref="Arrangement.Alias.Rule.Add"/>
<reference ref="Arrangement.Alias.Rule.Remove"/>
<reference ref="Arrangement.Alias.Rule.Match.Condition.Move.Up"/>
<reference ref="Arrangement.Alias.Rule.Match.Condition.Move.Down"/>
</group>
<group id="Arrangement.Alias.Rule.Context.Menu">
<reference ref="Arrangement.Alias.Rule.Add"/>
<reference ref="Arrangement.Alias.Rule.Remove"/>
<reference ref="Arrangement.Alias.Rule.Edit"/>
</group>
<group id="Arrangement.Rule.Match.Control.Context.Menu">
<reference ref="Arrangement.Rule.Add"/>
<reference ref="Arrangement.Rule.Section.Add"/>
<reference ref="Arrangement.Rule.Remove"/>
<reference ref="Arrangement.Rule.Edit"/>
</group>
<group id="Arrangement.Rule.Match.Control.ToolBar">
<reference ref="Arrangement.Rule.Add"/>
<reference ref="Arrangement.Rule.Section.Add"/>
<reference ref="Arrangement.Rule.Remove"/>
<reference ref="Arrangement.Rule.Match.Condition.Move.Up"/>
<reference ref="Arrangement.Rule.Match.Condition.Move.Down"/>
<reference ref="Arrangement.Custom.Token.Rule.Edit"/>
</group>
<group id="Arrangement.Rule.Group.Control.ToolBar">
<reference ref="Arrangement.Rule.Group.Condition.Move.Up"/>
<reference ref="Arrangement.Rule.Group.Condition.Move.Down"/>
</group>
<action id="ShowReformatFileDialog" class="com.intellij.codeInsight.actions.ShowReformatFileDialog"/>
<action id="SeverityEditorDialog" class="com.intellij.codeInspection.ex.SeverityEditorDialogAction"/>
</actions>
</idea-plugin>
| {'content_hash': 'e11779e24c832e324a81dd5aed4af667', 'timestamp': '', 'source': 'github', 'line_count': 966, 'max_line_length': 213, 'avg_line_length': 53.66459627329193, 'alnum_prop': 0.7242862654320987, 'repo_name': 'caot/intellij-community', 'id': 'a31632735880c6d7623e219fae660e0f8d07787a', 'size': '51840', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'platform/platform-resources/src/idea/LangActions.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '63518'}, {'name': 'C', 'bytes': '214180'}, {'name': 'C#', 'bytes': '1538'}, {'name': 'C++', 'bytes': '190455'}, {'name': 'CSS', 'bytes': '111474'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Cucumber', 'bytes': '14382'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'FLUX', 'bytes': '57'}, {'name': 'Groff', 'bytes': '35232'}, {'name': 'Groovy', 'bytes': '2244978'}, {'name': 'HTML', 'bytes': '1728813'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '149631999'}, {'name': 'JavaScript', 'bytes': '125292'}, {'name': 'Kotlin', 'bytes': '669564'}, {'name': 'Lex', 'bytes': '166177'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '86287'}, {'name': 'Objective-C', 'bytes': '28878'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6570'}, {'name': 'Python', 'bytes': '21469995'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '63203'}, {'name': 'Smalltalk', 'bytes': '64'}, {'name': 'TeX', 'bytes': '60798'}, {'name': 'TypeScript', 'bytes': '6152'}, {'name': 'XSLT', 'bytes': '113040'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Global accept_ownership</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Interprocess">
<link rel="up" href="../../interprocess/indexes_reference.html#header.boost.interprocess.sync.lock_options_hpp" title="Header <boost/interprocess/sync/lock_options.hpp>">
<link rel="prev" href="try_to_lock.html" title="Global try_to_lock">
<link rel="next" href="mutex_family.html" title="Struct mutex_family">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="try_to_lock.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/indexes_reference.html#header.boost.interprocess.sync.lock_options_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="mutex_family.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.interprocess.accept_ownership"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Global accept_ownership</span></h2>
<p>boost::interprocess::accept_ownership</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../interprocess/indexes_reference.html#header.boost.interprocess.sync.lock_options_hpp" title="Header <boost/interprocess/sync/lock_options.hpp>">boost/interprocess/sync/lock_options.hpp</a>>
</span><span class="keyword">static</span> <span class="keyword">const</span> <a class="link" href="accept_ownership_type.html" title="Struct accept_ownership_type">accept_ownership_type</a> accept_ownership<span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp36587424"></a><h2>Description</h2>
<p>An object indicating that the ownership of lockable object must be accepted by the new owner. </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005-2015 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="try_to_lock.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/indexes_reference.html#header.boost.interprocess.sync.lock_options_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="mutex_family.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': '0805a8f5b5df517f60aca02acac52360', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 506, 'avg_line_length': 77.26415094339623, 'alnum_prop': 0.6600732600732601, 'repo_name': 'nicecapj/crossplatfromMmorpgServer', 'id': 'a9204fed7a29fd2008ffc147f6cdef49a0aa6d1c', 'size': '4095', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ThirdParty/boost_1_61_0/libs/interprocess/doc/html/boost/interprocess/accept_ownership.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '223360'}, {'name': 'Batchfile', 'bytes': '33694'}, {'name': 'C', 'bytes': '3967798'}, {'name': 'C#', 'bytes': '2093216'}, {'name': 'C++', 'bytes': '197077824'}, {'name': 'CMake', 'bytes': '203207'}, {'name': 'CSS', 'bytes': '427824'}, {'name': 'CWeb', 'bytes': '174166'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'Emacs Lisp', 'bytes': '7822'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Go', 'bytes': '8549'}, {'name': 'HTML', 'bytes': '234971359'}, {'name': 'IDL', 'bytes': '14'}, {'name': 'Java', 'bytes': '3809828'}, {'name': 'JavaScript', 'bytes': '1112586'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '135271'}, {'name': 'Makefile', 'bytes': '1266088'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '2928243'}, {'name': 'Objective-C++', 'bytes': '3527'}, {'name': 'PHP', 'bytes': '59372'}, {'name': 'Perl', 'bytes': '38649'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Protocol Buffer', 'bytes': '1576976'}, {'name': 'Python', 'bytes': '3257634'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Roff', 'bytes': '5189'}, {'name': 'Ruby', 'bytes': '97584'}, {'name': 'Shell', 'bytes': '787152'}, {'name': 'Swift', 'bytes': '20519'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'Vim script', 'bytes': '3759'}, {'name': 'XSLT', 'bytes': '552736'}, {'name': 'Yacc', 'bytes': '19623'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'c05d83a1fee310662b47a86fc4e8ac27', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'da8fe968b1eda9c0bb1ea1908ab5262e9c234352', 'size': '192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Bryophyta/Bryopsida/Leucodontales/Meteoriaceae/Meteorium/Meteorium aongstromii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.util.CachedValueProfiler;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.reference.SoftReference;
import com.intellij.util.containers.NotNullList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.Reference;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public abstract class CachedValueBase<T> {
private static final Logger LOG = Logger.getInstance(CachedValueImpl.class);
private final boolean myTrackValue;
private volatile SoftReference<Data<T>> myData;
protected CachedValueBase(boolean trackValue) {
myTrackValue = trackValue;
}
@NotNull
private Data<T> computeData(Computable<? extends CachedValueProvider.Result<T>> doCompute) {
CachedValueProvider.Result<T> result;
CachedValueProfiler.ValueTracker tracker;
if (CachedValueProfiler.isProfiling()) {
try (CachedValueProfiler.Frame frame = CachedValueProfiler.newFrame()) {
result = doCompute.compute();
tracker = frame.newValueTracker(result);
}
}
else {
result = doCompute.compute();
tracker = null;
}
if (result == null) {
return new Data<>(null, ArrayUtilRt.EMPTY_OBJECT_ARRAY, ArrayUtil.EMPTY_LONG_ARRAY, null);
}
T value = result.getValue();
Object[] inferredDependencies = normalizeDependencies(result);
long[] inferredTimeStamps = new long[inferredDependencies.length];
for (int i = 0; i < inferredDependencies.length; i++) {
inferredTimeStamps[i] = getTimeStamp(inferredDependencies[i]);
}
return new Data<>(value, inferredDependencies, inferredTimeStamps, tracker);
}
@Nullable
private synchronized Data<T> cacheOrGetData(@Nullable Data<T> expected, @Nullable Data<T> updatedValue) {
if (expected != getRawData()) return null;
if (updatedValue != null) {
setData(updatedValue);
return updatedValue;
}
return expected;
}
private synchronized void setData(@Nullable Data<T> data) {
myData = data == null ? null : new SoftReference<>(data);
}
protected Object @NotNull [] normalizeDependencies(@NotNull CachedValueProvider.Result<T> result) {
Object[] items = result.getDependencyItems();
T value = result.getValue();
Object[] rawDependencies = myTrackValue && value != null ? ArrayUtil.append(items, value) : items;
List<Object> flattened = new NotNullList<>(rawDependencies.length);
collectDependencies(flattened, rawDependencies);
return ArrayUtil.toObjectArray(flattened);
}
public void clear() {
setData(null);
}
public boolean hasUpToDateValue() {
return getUpToDateOrNull() != null;
}
@Nullable
public final Data<T> getUpToDateOrNull() {
Data<T> data = getRawData();
return data != null && checkUpToDate(data) ? data : null;
}
private boolean checkUpToDate(@NotNull Data<T> data) {
if (isUpToDate(data)) {
return true;
}
if (data.trackingInfo != null) {
data.trackingInfo.onValueInvalidated();
}
return false;
}
@Nullable
private Data<T> getRawData() {
return SoftReference.dereference(myData);
}
protected boolean isUpToDate(@NotNull Data<T> data) {
for (int i = 0; i < data.myDependencies.length; i++) {
Object dependency = data.myDependencies[i];
if (isDependencyOutOfDate(dependency, data.myTimeStamps[i])) return false;
}
return true;
}
protected boolean isDependencyOutOfDate(@NotNull Object dependency, long oldTimeStamp) {
if (dependency instanceof CachedValueBase) {
return !((CachedValueBase<?>)dependency).hasUpToDateValue();
}
final long timeStamp = getTimeStamp(dependency);
return timeStamp < 0 || timeStamp != oldTimeStamp;
}
private static void collectDependencies(@NotNull List<Object> resultingDeps, Object @NotNull [] dependencies) {
for (Object dependency : dependencies) {
if (dependency == ObjectUtils.NULL) continue;
if (dependency instanceof Object[]) {
collectDependencies(resultingDeps, (Object[])dependency);
}
else {
resultingDeps.add(dependency);
}
}
}
protected long getTimeStamp(@NotNull Object dependency) {
if (dependency instanceof VirtualFile) {
return ((VirtualFile)dependency).getModificationStamp();
}
if (dependency instanceof ModificationTracker) {
return ((ModificationTracker)dependency).getModificationCount();
}
else if (dependency instanceof Reference){
Object original = ((Reference<?>)dependency).get();
if(original == null) return -1;
return getTimeStamp(original);
}
else if (dependency instanceof Ref) {
Object original = ((Ref<?>)dependency).get();
if(original == null) return -1;
return getTimeStamp(original);
}
else if (dependency instanceof Document) {
return ((Document)dependency).getModificationStamp();
}
else if (dependency instanceof CachedValueBase) {
// to check for up to date for a cached value dependency we use .isUpToDate() method, not the timestamp
return 0;
}
else {
LOG.error("Wrong dependency type: " + dependency.getClass());
return -1;
}
}
public T setValue(@NotNull CachedValueProvider.Result<T> result) {
Data<T> data = computeData(() -> result);
setData(data);
return data.getValue();
}
public abstract boolean isFromMyProject(@NotNull Project project);
public abstract Object getValueProvider();
protected static final class Data<T> implements Getter<T> {
private final T myValue;
private final Object @NotNull [] myDependencies;
private final long @NotNull [] myTimeStamps;
final @Nullable CachedValueProfiler.ValueTracker trackingInfo;
Data(T value, Object @NotNull [] dependencies, long @NotNull [] timeStamps,
@Nullable CachedValueProfiler.ValueTracker trackingInfo) {
myValue = value;
myDependencies = dependencies;
myTimeStamps = timeStamps;
this.trackingInfo = trackingInfo;
}
public Object @NotNull [] getDependencies() {
return myDependencies;
}
public long @NotNull [] getTimeStamps() {
return myTimeStamps;
}
@Override
public final T get() {
return getValue();
}
public T getValue() {
if (trackingInfo != null) {
trackingInfo.onValueUsed();
}
return myValue;
}
}
@Nullable
protected <P> T getValueWithLock(P param) {
Data<T> data = getUpToDateOrNull();
if (data != null) {
if (IdempotenceChecker.areRandomChecksEnabled()) {
IdempotenceChecker.applyForRandomCheck(data, getValueProvider(), () -> computeData(() -> doCompute(param)));
}
return data.getValue();
}
RecursionGuard.StackStamp stamp = RecursionManager.markStack();
Computable<Data<T>> calcData = () -> computeData(() -> doCompute(param));
data = RecursionManager.doPreventingRecursion(this, true, calcData);
if (data == null) {
data = calcData.compute();
}
else if (stamp.mayCacheNow()) {
while (true) {
Data<T> alreadyComputed = getRawData();
boolean reuse = alreadyComputed != null && checkUpToDate(alreadyComputed);
if (reuse) {
IdempotenceChecker.checkEquivalence(alreadyComputed, data, getValueProvider().getClass(), calcData);
}
Data<T> toReturn = cacheOrGetData(alreadyComputed, reuse ? null : data);
if (toReturn != null) {
if (data != toReturn && data.trackingInfo != null) {
data.trackingInfo.onValueRejected();
}
return toReturn.getValue();
}
}
}
return data.getValue();
}
protected abstract <P> CachedValueProvider.Result<T> doCompute(P param);
@Override
public String toString() {
return getClass().getSimpleName() + "{" + getValueProvider() + "}";
}
}
| {'content_hash': '4735e9c6f3a30ab0707ace271ac373d2', 'timestamp': '', 'source': 'github', 'line_count': 257, 'max_line_length': 140, 'avg_line_length': 32.36575875486381, 'alnum_prop': 0.6805722529454196, 'repo_name': 'zdary/intellij-community', 'id': '6c475776405cdb109c20343618fa6b4ec2ec78ff', 'size': '8318', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'platform/core-impl/src/com/intellij/util/CachedValueBase.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
require 'spec_helper'
describe Rdpl::Label do
def end_with_new_line
simple_matcher('creates a new line') { |actual| actual[-2..-1] == CR + LF }
end
describe "::DEFAULT_DOT_SIZE" do
subject { Rdpl::Label::DEFAULT_DOT_SIZE }
it { should == 11 }
end
describe "::DEFAULT_HEAT" do
subject { Rdpl::Label::DEFAULT_HEAT }
it { should == 14 }
end
its(:state) { should == :open }
describe "mm?" do
it "delegates to the printing job" do
label = Rdpl::Label.new
label.job = Rdpl::Job.new :printer => 'foobar', :measurement => :metric
label.should be_mm
end
it "returns false if the label has no job" do
Rdpl::Label.new.should_not be_mm
end
end
describe "#contents" do
it "is always started with STX L (for Label start), plus the dot size and heating settings" do
label = Rdpl::Label.new
expected = Rdpl::STX +
Rdpl::Label::START +
Rdpl::NEW_LINE +
"H#{Rdpl::Label::DEFAULT_HEAT}" +
Rdpl::NEW_LINE +
"D#{Rdpl::Label::DEFAULT_DOT_SIZE}" +
Rdpl::NEW_LINE
label.dump.should == expected
end
end
describe "#end!" do
let(:label) { Rdpl::Label.new }
it "marks the label's end" do
label.end!
label[-3..-1].should == 'E' + Rdpl::NEW_LINE
end
it "alters the state to :closed" do
expect {
label.end!
}.to change { label.state }.to(:finished)
end
it "adds the quantity command if a quantity was specified" do
label = Rdpl::Label.new
label.quantity = 5
label.end!
label.dump[-10..-6].should == 'Q0005'
end
end
it "raises Rdpl::EndedElementError if it's ended and we try to add new content" do
label = Rdpl::Label.new
label.end!
lambda do
label << 'some content'
end.should raise_error(Rdpl::EndedElementError)
end
describe "#command" do
let(:label) { Rdpl::Label.new }
before(:each) { label.command 'FOO' }
it { end_with_new_line }
it "records the command in the label's contents" do
expected = Rdpl::STX + 'FOO'
label.dump.should include(expected)
end
it "ends with CR/LF" do
expected = Rdpl::CR + Rdpl::LF
label[-2..-1].should == expected
end
end
describe "#<<" do
let(:label) { Rdpl::Label.new }
before(:each) { label << 'BAR' }
it { end_with_new_line }
it "puts the text inside the label" do
label.dump.should include('BAR')
end
it "allows inserting non-string elements" do
label << Rdpl::Barcode.new(:data => 'BARCODE')
label.dump.should include('BARCODE')
end
end
describe "#dot_size" do
it "returns the current dot size" do
Rdpl::Label.new(:dot_size => 20).dot_size.should == 20
end
it "returns Label::DEFAULT_DOT_SIZE by default" do
Rdpl::Label.new.dot_size.should == Rdpl::Label::DEFAULT_DOT_SIZE
end
end
describe "#heat" do
it "returns the current heat setting" do
Rdpl::Label.new(:heat => 25).heat.should == 25
end
it "returns Label::DEFAULT_HEAT by default" do
Rdpl::Label.new.heat.should == Rdpl::Label::DEFAULT_HEAT
end
end
describe "#start_of_print" do
it "returns nil if start_of_print was not specified" do
Rdpl::Label.new.start_of_print.should be_nil
end
describe "when the measurenemt mode is inches" do
it "returns the configured start of print" do
Rdpl::Label.new(:start_of_print => '0123').start_of_print.should == 1.23
end
end
describe "when the measurement mode is metric" do
it "returns the configured start of print" do
label = Rdpl::Label.new(:start_of_print => '0123')
label.job = Rdpl::Job.new :printer => 'foo', :measurement => :metric
label.start_of_print.should == 12.3
end
end
end
describe "#add_line" do
it "should add a line element to the label's contents" do
label = Rdpl::Label.new
label.add_line do |line|
line.horizontal_width = 12.2
line.vertical_width = 14.3
line.row_position = 23.4
line.column_position = 24.5
end
label.dump.should include("1X1100002340245l01220143#{Rdpl::NEW_LINE}")
end
end
describe "#add_box" do
it "should add a box element to the label's contents" do
label = Rdpl::Label.new
label.add_box do |box|
box.horizontal_width = 12.2
box.vertical_width = 14.3
box.row_position = 23.4
box.column_position = 24.5
box.bottom_and_top_thickness = 34.6
box.sides_thickness = 45.6
end
label.dump.should include("1X1100002340245b0122014303460456#{Rdpl::NEW_LINE}")
end
end
describe "#add_barcode" do
it "should add a barcode element to the label's contents" do
label = Rdpl::Label.new
label.add_barcode do |barcode|
barcode.rotation = 4
barcode.font_id = 'e'
barcode.data = 'SOME DATA 12345'
barcode.height = 123
barcode.wide_bar_multiplier = 3
barcode.narrow_bar_multiplier = 4
barcode.row_position = 123
barcode.column_position = 234
end
label.dump.should include('4e3412301230234SOME DATA 12345')
end
end
describe "#add_bitmapped_text" do
it "should add a bitmapped text element to the labe's contents" do
label = Rdpl::Label.new
label.add_bitmapped_text do |text|
text.font_id = 2
text.width_multiplier = 2
text.height_multiplier = 3
text.row_position = 20
text.column_position = 30
text.data = 'HEY LOOK AT ME'
end
label.dump.should include('122300000200030HEY LOOK AT ME')
end
end
end
| {'content_hash': '0a2f9aadcdc76d89b179bb249c0a53e2', 'timestamp': '', 'source': 'github', 'line_count': 210, 'max_line_length': 98, 'avg_line_length': 28.238095238095237, 'alnum_prop': 0.5881956155143339, 'repo_name': 'cassiomarques/rdpl', 'id': 'abab75c0c9f001dd3c4b9d03a871dd16741b6a19', 'size': '5930', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/label_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '41388'}]} |
// Copyright (C) 2014 dot42
//
// Original filename: Dalvik.System.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Dalvik.System
{
/// <summary>
/// <para>A class loader that loads classes from <c> .jar </c> and <c> .apk </c> files containing a <c> classes.dex </c> entry. This can be used to execute code not installed as part of an application.</para><para>This class loader requires an application-private, writable directory to cache optimized classes. Use <c> Context.getDir(String, int) </c> to create such a directory: <pre> File dexOutputDir = context.getDir("dex", 0);
///
/// </pre></para><para><b>Do not cache optimized classes on external storage.</b> External storage does not provide access controls necessary to protect your application from code injection attacks. </para>
/// </summary>
/// <java-name>
/// dalvik/system/DexClassLoader
/// </java-name>
[Dot42.DexImport("dalvik/system/DexClassLoader", AccessFlags = 33)]
public partial class DexClassLoader : global::Java.Lang.ClassLoader
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a <c> DexClassLoader </c> that finds interpreted and native code. Interpreted classes are found in a set of DEX files contained in Jar or APK files.</para><para>The path lists are separated using the character specified by the <c> path.separator </c> system property, which defaults to <c> : </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)]
public DexClassLoader(string dexPath, string optimizedDirectory, string libraryPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// findClass
/// </java-name>
[Dot42.DexImport("findClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/lang/Class<*>;")]
protected internal override global::System.Type FindClass(string @string) /* MethodBuilder.Create */
{
return default(global::System.Type);
}
/// <java-name>
/// findResource
/// </java-name>
[Dot42.DexImport("findResource", "(Ljava/lang/String;)Ljava/net/URL;", AccessFlags = 4)]
protected internal override global::Java.Net.URL FindResource(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Net.URL);
}
/// <java-name>
/// findLibrary
/// </java-name>
[Dot42.DexImport("findLibrary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 4)]
protected internal override string FindLibrary(string @string) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPackage
/// </java-name>
[Dot42.DexImport("getPackage", "(Ljava/lang/String;)Ljava/lang/Package;", AccessFlags = 4)]
protected internal override global::Java.Lang.Package GetPackage(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Lang.Package);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DexClassLoader() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Manipulates DEX files. The class is similar in principle to java.util.zip.ZipFile. It is used primarily by class loaders. </para><para>Note we don't directly open and read the DEX file here. They're memory-mapped read-only by the VM. </para>
/// </summary>
/// <java-name>
/// dalvik/system/DexFile
/// </java-name>
[Dot42.DexImport("dalvik/system/DexFile", AccessFlags = 49)]
public sealed partial class DexFile
/* scope: __dot42__ */
{
/// <summary>
/// <para>Opens a DEX file from a given File object. This will usually be a ZIP/JAR file with a "classes.dex" inside.</para><para>The VM will generate the name of the corresponding file in /data/dalvik-cache and open it, possibly creating or updating it first if system permissions allow. Don't pass in the name of a file in /data/dalvik-cache, as the named file is expected to be in its original (pre-dexopt) state.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)]
public DexFile(global::Java.Io.File file) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Opens a DEX file from a given File object. This will usually be a ZIP/JAR file with a "classes.dex" inside.</para><para>The VM will generate the name of the corresponding file in /data/dalvik-cache and open it, possibly creating or updating it first if system permissions allow. Don't pass in the name of a file in /data/dalvik-cache, as the named file is expected to be in its original (pre-dexopt) state.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public DexFile(string file) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Open a DEX file, specifying the file in which the optimized DEX data should be written. If the optimized form exists and appears to be current, it will be used; if not, the VM will attempt to regenerate it.</para><para>This is intended for use by applications that wish to download and execute DEX files outside the usual application installation mechanism. This function should not be called directly by an application; instead, use a class loader such as dalvik.system.DexClassLoader.</para><para></para>
/// </summary>
/// <returns>
/// <para>A new or previously-opened DexFile. </para>
/// </returns>
/// <java-name>
/// loadDex
/// </java-name>
[Dot42.DexImport("loadDex", "(Ljava/lang/String;Ljava/lang/String;I)Ldalvik/system/DexFile;", AccessFlags = 9)]
public static global::Dalvik.System.DexFile LoadDex(string sourcePathName, string outputPathName, int flags) /* MethodBuilder.Create */
{
return default(global::Dalvik.System.DexFile);
}
/// <summary>
/// <para>Gets the name of the (already opened) DEX file.</para><para></para>
/// </summary>
/// <returns>
/// <para>the file name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Closes the DEX file. </para><para>This may not be able to release any resources. If classes from this DEX file are still resident, the DEX file can't be unmapped.</para><para></para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 1)]
public void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Loads a class. Returns the class on success, or a <c> null </c> reference on failure. </para><para>If you are not calling this from a class loader, this is most likely not going to do what you want. Use Class#forName(String) instead. </para><para>The method does not throw ClassNotFoundException if the class isn't found because it isn't reasonable to throw exceptions wildly every time a class is not found in the first DEX file we look at.</para><para></para>
/// </summary>
/// <returns>
/// <para>the Class object representing the class, or <c> null </c> if the class cannot be loaded </para>
/// </returns>
/// <java-name>
/// loadClass
/// </java-name>
[Dot42.DexImport("loadClass", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/Class;", AccessFlags = 1)]
public global::System.Type LoadClass(string name, global::Java.Lang.ClassLoader loader) /* MethodBuilder.Create */
{
return default(global::System.Type);
}
/// <summary>
/// <para>Enumerate the names of the classes in this DEX file.</para><para></para>
/// </summary>
/// <returns>
/// <para>an enumeration of names of classes contained in the DEX file, in the usual internal form (like "java/lang/String"). </para>
/// </returns>
/// <java-name>
/// entries
/// </java-name>
[Dot42.DexImport("entries", "()Ljava/util/Enumeration;", AccessFlags = 1, Signature = "()Ljava/util/Enumeration<Ljava/lang/String;>;")]
public global::Java.Util.IEnumeration<string> Entries() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<string>);
}
/// <summary>
/// <para>Called when the class is finalized. Makes sure the DEX file is closed.</para><para></para>
/// </summary>
/// <java-name>
/// finalize
/// </java-name>
[Dot42.DexImport("finalize", "()V", AccessFlags = 4)]
extern ~DexFile() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if the VM believes that the apk/jar file is out of date and should be passed through "dexopt" again.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if dexopt should be called on the file, false otherwise. </para>
/// </returns>
/// <java-name>
/// isDexOptNeeded
/// </java-name>
[Dot42.DexImport("isDexOptNeeded", "(Ljava/lang/String;)Z", AccessFlags = 265)]
public static bool IsDexOptNeeded(string fileName) /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DexFile() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the name of the (already opened) DEX file.</para><para></para>
/// </summary>
/// <returns>
/// <para>the file name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
}
}
/// <summary>
/// <para>Provides a simple ClassLoader implementation that operates on a list of files and directories in the local file system, but does not attempt to load classes from the network. Android uses this class for its system class loader and for its application class loader(s). </para>
/// </summary>
/// <java-name>
/// dalvik/system/PathClassLoader
/// </java-name>
[Dot42.DexImport("dalvik/system/PathClassLoader", AccessFlags = 33)]
public partial class PathClassLoader : global::Java.Lang.ClassLoader
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a <c> PathClassLoader </c> that operates on a given list of files and directories. This method is equivalent to calling PathClassLoader(String, String, ClassLoader) with a <c> null </c> value for the second argument (see description there).</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)]
public PathClassLoader(string dexPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a <c> PathClassLoader </c> that operates on two given lists of files and directories. The entries of the first list should be one of the following:</para><para><ul><li><para>JAR/ZIP/APK files, possibly containing a "classes.dex" file as well as arbitrary resources. </para></li><li><para>Raw ".dex" files (not inside a zip file). </para></li></ul></para><para>The entries of the second list should be directories containing native library files.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)]
public PathClassLoader(string dexPath, string libraryPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// findClass
/// </java-name>
[Dot42.DexImport("findClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/lang/Class<*>;")]
protected internal override global::System.Type FindClass(string @string) /* MethodBuilder.Create */
{
return default(global::System.Type);
}
/// <java-name>
/// findResource
/// </java-name>
[Dot42.DexImport("findResource", "(Ljava/lang/String;)Ljava/net/URL;", AccessFlags = 4)]
protected internal override global::Java.Net.URL FindResource(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Net.URL);
}
/// <java-name>
/// findResources
/// </java-name>
[Dot42.DexImport("findResources", "(Ljava/lang/String;)Ljava/util/Enumeration;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/util/Enumeration<Ljava/net/URL;>;")]
protected internal override global::Java.Util.IEnumeration<global::Java.Net.URL> FindResources(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<global::Java.Net.URL>);
}
/// <java-name>
/// findLibrary
/// </java-name>
[Dot42.DexImport("findLibrary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public new virtual string FindLibrary(string @string) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPackage
/// </java-name>
[Dot42.DexImport("getPackage", "(Ljava/lang/String;)Ljava/lang/Package;", AccessFlags = 4)]
protected internal override global::Java.Lang.Package GetPackage(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Lang.Package);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PathClassLoader() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| {'content_hash': '3927d7a8c631d25aa4c57d2b82158750', 'timestamp': '', 'source': 'github', 'line_count': 314, 'max_line_length': 528, 'avg_line_length': 47.10191082802548, 'alnum_prop': 0.6613252197430697, 'repo_name': 'Dot42Xna/master', 'id': '1c2ae20655c34246be6ea4f9a1c26f6eb86a79f6', 'size': '14790', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Generated/v3.1/Dalvik.System.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package com.ib.booking.basket.proxies;
import com.ib.commercial.model.Product;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Iterator;
import java.util.List;
/**
* Created by justin on 13/10/2015.
*/
@Component("ProductRepositoryProxy")
@EnableCircuitBreaker
public class ProductRepositoryProxy {
private Log log = LogFactory.getLog(ProductRepositoryProxy.class);
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate loadBalancedRestTemplate;
@HystrixCommand(fallbackMethod = "handleProductNotAvailError")
public Product getProduct(String id) {
getProductServices();
ResponseEntity<Product> exchange =
this.loadBalancedRestTemplate.exchange(
"http://product/product/{id}",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Product>() {},
id);
Product resp = exchange.getBody();
log.debug("Product Response : "+resp);
if (resp == null)
throw new RuntimeException();
return resp;
}
public Object handleProductNotAvailError(String id) {
log.error("TRIGGERED HYSTRIX CIRCUIT BREAKER");
return new Product(id, "product not available");
}
@HystrixCommand(fallbackMethod = "handleProductServiceError")
private void getProductServices() {
List<String> services = discoveryClient.getServices();
Iterator it = services.iterator();
while (it.hasNext()) {
log.debug("Service : "+(String)it.next());
}
log.debug("Discovery Client description : " + discoveryClient.description());
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("product");
it = serviceInstances.iterator();
while (it.hasNext()) {
ServiceInstance instance = (ServiceInstance)it.next();
log.debug("ServiceInstance : "+instance);
log.debug("ServiceInstance Host : "+instance.getHost());
log.debug("ServiceInstance Port : "+instance.getPort());
log.debug("ServiceInstance Uri : "+instance.getUri());
log.debug("ServiceInstance id : "+instance.getServiceId());
}
this.loadBalancedRestTemplate.getForEntity("http://product/", String.class);
}
public Object handleProductServiceError(String id) {
log.error("TRIGGERED HYSTRIX CIRCUIT BREAKER");
return new Product(id, "product repository down");
}
}
| {'content_hash': 'cc9f4cbedf382dae1ff00277f53f47ed', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 89, 'avg_line_length': 35.833333333333336, 'alnum_prop': 0.6843410852713179, 'repo_name': 'justindav1s/spring-boot-cloud', 'id': '17bb288ce8a6607dfce3b291dd6f2a9190d042e6', 'size': '3225', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'basket/src/main/java/com/ib/booking/basket/proxies/ProductRepositoryProxy.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '23438'}, {'name': 'Shell', 'bytes': '1970'}]} |
local DEBUG = false
-- local DEBUG = true
local http = require "resty.http"
local cjson = require "cjson.safe"
local ngx = require "ngx"
local pgmoon = require "pgmoon"
local tab_clear = require "table.clear"
local limit_req = require "resty.limit.req"
local templates = require "opmserver.templates"
local email = require "opmserver.email"
local send_email = email.send_mail
local re_find = ngx.re.find
local re_match = ngx.re.match
local str_find = string.find
local ngx_var = ngx.var
local say = ngx.say
local req_read_body = ngx.req.read_body
local decode_json = cjson.decode
local encode_json = cjson.encode
local req_method = ngx.req.get_method
local req_body_file = ngx.req.get_body_file
local os_exec = os.execute
local io_open = io.open
local io_close = io.close
local set_quote_sql_str = ndk.set_var.set_quote_pgsql_str
local assert = assert
local sub = string.sub
local ngx_null = ngx.null
local tab_concat = table.concat
local shdict_bad_users = ngx.shared.bad_users
local incoming_directory = "/tmp/incoming"
local final_directory = "/tmp/final"
local MIN_TARBALL_SIZE = 136
cjson.encode_empty_table_as_object(false)
local _M = {
version = "0.0.3"
}
local dd
if DEBUG then
function dd(...)
ngx.req.discard_body()
say("DD ", ...)
end
else
function dd() end
end
local out_err, log_err, log_and_out_err
local shell, query_db, quote_sql_str
local query_github, query_github_user, query_github_org
local query_github_org_ownership, query_github_user_verified_email
local db_insert_user_info, db_update_user_info
local db_insert_org_info, db_insert_org_ownership
local db_insert_user_verified_email
local match_table = {}
local ver2pg_array, tab2pg_array
local count_bad_users
-- an entry point
function _M.do_upload()
local ctx = ngx.ctx
-- check request method.
if req_method() ~= "PUT" then
return ngx.exit(405)
end
-- check user-agent.
local user_agent = ngx_var.http_user_agent
if not re_find(user_agent, [[^opm \d+\.\d+\.\d+]], "jo") then
return ngx.exit(405)
end
-- check content-length request header.
-- XXX we do not support chunked encoded request bodies yet.
local size = tonumber(ngx_var.http_content_length)
if not size or size < MIN_TARBALL_SIZE then
return ngx.exit(400)
end
-- extract the github account name from the request.
local account = ngx_var.http_x_account
ctx.account = account
if not re_find(account, [[^[-\w]+$]], "jo") then
return log_and_out_err(ctx, 400, "bad github account name.")
end
if re_find(account, [[^luarocks$]], "joi") then
return log_and_out_err(ctx, 400,
"the luarocks account is reserved by opm.")
end
dd("account: ", account)
-- extract the github personal access token from the request.
local token = ngx_var.http_x_token
if not re_find(token, [[^[a-f0-9]{40}$]], "ijo") then
return log_and_out_err(ctx, 400, "bad github personal access token.")
end
dd("token: ", token)
ctx.auth = "token " .. token
-- extract the uploaded file name from the request.
local fname = ngx_var.http_x_file
local m, err = re_match(fname, [[^ ([-\w]+) - ([.\w]+) \.tar\.gz $]],
"xjo", nil, match_table)
if not m then
assert(not err)
ngx.status = 400
out_err("bad uploaded file name.")
return ngx.exit(400)
end
local pkg_name = m[1]
local pkg_version = m[2]
if not re_find(pkg_version, [[\d]], "jo") then
assert(not err)
ngx.status = 400
out_err("bad version number in the uploaded file name.")
return ngx.exit(400)
end
-- extract the file checksum.
local user_md5 = ngx_var.http_x_file_checksum
if not user_md5
or not re_find(user_md5, [[ ^ [a-z0-9]{32} $ ]], "jox")
then
return log_and_out_err(ctx, 400, "bad user file checksum.")
end
-- verify the user github token.
local sql = "select user_id, login, scopes, verified_email"
.. " from access_tokens"
.. " left join users on access_tokens.user_id = users.id"
.. " where token_hash = crypt("
.. quote_sql_str(token)
.. ", token_hash) limit 1"
-- say(sql)
local rows = query_db(sql)
local login, scopes, user_id, verified_email, new_user
-- say(cjson.encode(rows))
if #rows == 0 then
-- say("no token matched in the database")
local user_info
user_info, scopes = query_github_user(ctx, token)
login = user_info.login
sql = "select id from users where login = "
.. quote_sql_str(login) .. " limit 1"
local rows = query_db(sql)
if #rows == 0 then
dd("user not found in db.")
user_id = db_insert_user_info(ctx, user_info)
-- say("user id: ", user_id)
new_user = true
else
dd("user already in db, updating db record")
-- say('user info: ', cjson.encode(user_info))
user_id = assert(rows[1].id)
db_update_user_info(ctx, user_info, user_id)
end
-- save the github token into our database.
local sql = "insert into access_tokens (user_id, token_hash, scopes)"
.. " values(" .. user_id -- user_id is from database
.. ", crypt(" .. quote_sql_str(token)
.. ", gen_salt('md5')), " .. quote_sql_str(scopes) .. ")"
-- say(sql)
query_db(sql)
else
dd("token matched in the database.")
user_id = assert(rows[1].user_id)
scopes = assert(rows[1].scopes)
login = assert(rows[1].login)
verified_email = rows[1].verified_email
dd("found verified email from db: ", verified_email)
end
local new_org = false
local org_id
if login ~= account then
-- check if the user account is a github org.
if not scopes or not str_find(scopes, "read:org", nil, true) then
return log_and_out_err(ctx, 403,
"personal access token lacking ",
"the read:org scope: ", scopes)
end
do
local sql = "select id from orgs where login = "
.. quote_sql_str(account)
local rows = query_db(sql)
if #rows == 0 then
dd("no org found in the db.")
local org_info = query_github_org(ctx, account)
-- say("org json: ", cjson.encode(org_info))
org_id = db_insert_org_info(ctx, org_info)
new_org = true
else
dd("found org in the db.")
org_id = assert(rows[1].id)
end
end
if not new_user then
-- both user_id and org_id are from our own database.
local sql = "select id from org_ownership where user_id = "
.. user_id .. " and org_id = " .. org_id
local rows = query_db(sql)
if #rows == 0 then
dd("no membership found in the database.")
query_github_org_ownership(ctx, account, login)
db_insert_org_ownership(ctx, org_id, user_id)
else
dd("found membership in the databse.")
end
else
-- new user
dd("no membership found in the database.")
query_github_org_ownership(ctx, account, login)
db_insert_org_ownership(ctx, org_id, user_id)
end
end
if not verified_email then
dd("verified email not found, querying github...")
verified_email = query_github_user_verified_email(ctx)
db_insert_user_verified_email(ctx, user_id, verified_email)
end
-- check if there is too many uploads.
local block_key = "block-" .. login
-- ngx.log(ngx.WARN, "block key: ", block_key)
do
local val = shdict_bad_users:get(block_key)
if val then
return log_and_out_err(ctx, 403, "github ID ", login,
" blocked temporarily due to ",
"too many uploads. Please retry ",
"in a few hours.")
end
end
local quoted_pkg_name = quote_sql_str(pkg_name)
local ver_v = ver2pg_array(pkg_version)
if new_org or (new_user and login == account) then
dd("new account, no need to check duplicate uploads")
else
dd("check if the package with the same version under ",
"the same account is already uploaded.")
local sql
if login == account then
-- user account
assert(user_id)
sql = "select version_s, created_at from uploads where uploader = "
.. user_id -- user_id is from our own db
.. " and org_account is null and version_v = "
.. ver_v
.. " and package_name = " .. quoted_pkg_name
.. " and failed != true"
else
-- org account
assert(user_id)
assert(org_id)
sql = "select version_s, created_at from uploads where uploader = "
.. user_id
.. " and org_account = "
.. org_id
.. " and version_v = " .. ver_v
.. " and package_name = " .. quoted_pkg_name
.. " and failed != true"
end
local rows = query_db(sql)
if #rows == 0 then
dd("no duplicate uploads found in db")
else
local prev_ver_s = rows[1].version_s
local created_at = rows[1].created_at
return log_and_out_err(ctx, 400, "duplicate upload: ",
pkg_name, "-", prev_ver_s,
" (previously uploaded at ", created_at,
").")
end
end
do
req_read_body()
local file = req_body_file()
if not file then
log_err(ctx, "no request body file")
return ngx.exit(500)
end
local dst_dir = incoming_directory .. "/" .. account
shell(ctx, "mkdir -p " .. dst_dir)
local dst_file = dst_dir .. "/" .. fname
-- we simply override the existing file with the same name (if any).
dd("cp ", file, " ", dst_file)
shell(ctx, "cp " .. file .. " " .. dst_file)
dd("user file: ", fname)
end
-- insert the new uploaded task to the uplaods database.
local sql1 = "insert into uploads (uploader, size, package_name, "
.. "orig_checksum, version_v, version_s, client_addr"
local sql2 = ""
if login ~= account then
sql2 = ", org_account"
end
local sql3 = ") values (" .. user_id .. ", " .. size
.. ", " .. quoted_pkg_name -- from our own db
.. ", " .. quote_sql_str(user_md5)
.. ", " .. ver_v
.. ", " .. quote_sql_str(pkg_version)
.. ", " .. quote_sql_str(ngx_var.remote_addr)
local sql4
if login ~= account then
sql4 = ", " .. org_id .. ") returning id"
else
sql4 = ") returning id"
end
local sql = sql1 .. sql2 .. sql3 .. sql4
local res = query_db(sql)
assert(res.affected_rows == 1)
do
local count_key = "count-" .. login
-- ngx.log(ngx.WARN, "count key: ", count_key)
-- we add the github login name to the black list for 2 hours after 10
-- uploads in 5 hours.
count_bad_users(count_key, block_key, 10, 3600 * 5, 3600 * 2)
end
say("File ", fname, " has been successfully uploaded ",
"and will be processed by the server shortly.\n",
"The uploaded task ID is ", res[1].id, ".")
end
function db_insert_user_info(ctx, user_info)
local u = user_info
local q = quote_sql_str
local sql
sql = "insert into users (login, name, avatar_url, bio, blog, "
.. "company, location, followers, following, public_email, "
.. "public_repos, github_created_at, github_updated_at) "
.. "values ("
.. q(u.login) .. ", "
.. q(u.name) .. ", "
.. q(u.avatar_url) .. ", "
.. q(u.bio) .. ", "
.. q(u.blog) .. ", "
.. q(u.company) .. ", "
.. q(u.location) .. ", "
.. q(u.followers) .. ", "
.. q(u.following) .. ", "
.. q(u.email) .. ", "
.. q(u.public_repos) .. ", "
.. q(u.created_at) .. ", "
.. q(u.updated_at) .. ") returning id"
local res = query_db(sql)
-- say("insert user res: ", cjson.encode(res))
local user_id = res[1].id
if not user_id then
return log_and_out_err(ctx, 500,
"failed to create user record ",
"in the database")
end
return user_id
end
function db_update_user_info(ctx, user_info, user_id)
local u = user_info
local q = quote_sql_str
local sql
sql = "update users set login = " .. q(u.login)
.. ", name = " .. q(u.name)
.. ", avatar_url = " .. q(u.avatar_url)
.. ", bio = " .. q(u.bio)
.. ", blog = " .. q(u.blog)
.. ", company = " .. q(u.company)
.. ", location = " .. q(u.location)
.. ", followers = " .. q(u.followers)
.. ", following = " .. q(u.following)
.. ", public_email = " .. q(u.email)
.. ", public_repos = " .. q(u.public_repos)
.. ", github_created_at = " .. q(u.created_at)
.. ", github_updated_at = " .. q(u.updated_at)
.. ", updated_at = now() where id = " .. user_id
-- user_id is from db,
-- so no injection possible
local res = query_db(sql)
-- say("update user res: ", cjson.encode(res))
assert(res.affected_rows == 1)
end
function query_github_user(ctx, token)
-- limit github accesses globally
local zone = "global_github_limit"
local lim, err = limit_req.new(zone, 1, 5)
if not lim then
return log_and_out_err(ctx, 500, "failed to new resty.limit.req: ", err)
end
local delay, err = lim:incoming("github", true)
if not delay then
if err == "rejected" then
return log_and_out_err(ctx, 503, "server too busy");
end
return log_and_out_err(ctx, 500, "failed to limit req: ", err)
end
if delay >= 0.001 then
local excess = err
ngx.log(ngx.WARN, "delaying github request, excess: ", excess,
" by zone ", zone)
ngx.sleep(delay)
end
-- query github
local path = "/user"
local res = query_github(ctx, path)
local scopes = res.headers["X-OAuth-Scopes"]
if not scopes or not str_find(scopes, "user:email", nil, true) then
return log_and_out_err(ctx, 403,
"personal access token lacking ",
"the user:email scope: ", scopes)
end
if #scopes > #"read:org, user:email" then
return log_and_out_err(ctx, 403,
"personal access token is too permissive; ",
"only the scopes user:email and read:org ",
"should be allowed.")
end
-- say(cjson.encode(res.headers))
local json = res.body
-- say("user json: ", json)
local data, err = decode_json(json)
if not data then
return log_and_out_err(ctx, 502, "failed to parse user json: ",
err, " (", json, ")")
end
local login = data.login
if not login then
return log_and_out_err(ctx, 502,
"login name cannot found in the ",
"github /user API call: ", json)
end
return data, scopes
end
function db_insert_org_info(ctx, org_info)
local o = org_info
local q = quote_sql_str
local sql
sql = "insert into orgs (login, name, avatar_url, description, blog, "
.. "company, location, public_email, "
.. "public_repos, github_created_at, github_updated_at) "
.. "values ("
.. q(o.login) .. ", "
.. q(o.name) .. ", "
.. q(o.avatar_url) .. ", "
.. q(o.description) .. ", "
.. q(o.blog) .. ", "
.. q(o.company) .. ", "
.. q(o.location) .. ", "
.. q(o.email) .. ", "
.. q(o.public_repos) .. ", "
.. q(o.created_at) .. ", "
.. q(o.updated_at) .. ") returning id"
local res = query_db(sql)
-- say("insert orgs res: ", cjson.encode(res))
local org_id = res[1].id
if not org_id then
return log_and_out_err(ctx, 500,
"failed to create org record ",
"in the database")
end
return org_id
end
function db_insert_org_ownership(ctx, org_id, user_id)
-- both org_id and user_id are from our own database.
local sql = "insert into org_ownership (org_id, user_id) values ("
.. org_id .. ", " .. user_id .. ")"
local res = query_db(sql)
assert(res.affected_rows == 1)
end
function query_github_org(ctx, account)
local path = "/orgs/" .. account
local res = query_github(ctx, path)
local json = res.body
local data, err = decode_json(json)
if not data then
return log_and_out_err(ctx, 502,
"failed to parse org membership json: ",
err, " (",
json, ")")
end
return data
end
function query_github_org_ownership(ctx, org, user)
local path = "/orgs/" .. org .. "/memberships/" .. user
local res = query_github(ctx, path)
local json = res.body
-- say("org membership json: ", json)
local data, err = decode_json(json)
if not data then
return log_and_out_err(ctx, 502,
"failed to parse org membership json: ",
err, " (",
json, ")")
end
if data.state ~= "active" or data.role ~= "admin" then
return log_and_out_err(ctx, 403,
'your github account "', user,
'" does not own organization "', org,
'": ', json)
end
end
function db_insert_user_verified_email(ctx, user_id, email)
local sql = "update users set verified_email = " .. quote_sql_str(email)
.. ", updated_at = now() where id = " .. user_id
local res = query_db(sql)
assert(res.affected_rows == 1)
end
function query_github_user_verified_email(ctx)
local path = "/user/emails"
local res = query_github(ctx, path)
local json = res.body
-- say("email json: ", json)
local data, err = decode_json(json)
if not data then
return log_and_out_err(ctx, 502,
"failed to parse user email json: ",
err, " (", json, ")")
end
local email
for _, item in ipairs(data) do
if item.primary and item.verified then
email = item.email
break
end
end
if not email then
for _, item in ipairs(data) do
if item.verified then
email = item.email
break
end
end
end
if not email then
return log_and_out_err(ctx, 400,
"no verified email address found from ",
"github: ", json)
end
return email
end
do
local opm_user_agent = "opm server " .. _M.version
local MAX_GITHUB_TRIES = 2
function query_github(ctx, path)
local httpc = ctx.httpc
local auth = ctx.auth
local client_addr = ctx.client_addr
if not client_addr then
client_addr = ngx_var.binary_remote_addr
ctx.client_addr = client_addr
end
local block_key = "block-" .. client_addr
do
local val = shdict_bad_users:get(block_key)
if val then
return log_and_out_err(ctx, 403, "client blocked temporarily ",
"due to too many failed attempt. ",
"Please retry in a few minutes.")
end
end
if not httpc then
httpc = http.new()
ctx.httpc = httpc
end
httpc:set_timeout(10 * 1000) -- 10 sec
local host = "api.github.com"
local res, err
for i = 1, MAX_GITHUB_TRIES do
local ok
ok, err = httpc:connect(host, 443)
if not ok then
log_err(ctx, i, ": failed to connect to ", host, ": ", err)
goto continue
end
if httpc:get_reused_times() == 0 then
local ssl_session, err = httpc:ssl_handshake(nil, host, true)
if not ssl_session then
log_err(ctx, i, ": ssl handshake failed with ",
host, ": ", err)
goto continue
end
end
res, err = httpc:request{
path = path,
headers = {
Host = host,
["User-Agent"] = opm_user_agent,
Authorization = auth,
Accept = "application/vnd.github.v3+json",
},
}
if not res then
log_err(ctx, i, ": failed to send ", host, " request to ",
path, ": ", err)
goto continue
end
res.body = res:read_body()
ok, err = httpc:set_keepalive(10*1000, 2)
if not ok then
log_err(ctx, i, ": failed to put the ", host,
" conn into pool: ", err)
goto continue
end
break
::continue::
end
if not res then
return ngx.exit(500)
end
if res.status == 401 or res.status == 403 then
local count_key = "count-" .. client_addr
-- we add the client IP to the black list for 1 min after 5
-- failed attempts in the last 3 min.
count_bad_users(count_key, block_key, 5, 60 * 3, 60)
ngx.status = 403
out_err(res.body)
return ngx.exit(403)
end
if res.status ~= 200 then
local msg = "server " .. host .. " returns bad status code for "
.. path .. ": " .. res.status
log_err(ctx, msg)
out_err(msg)
return ngx.exit(500)
end
return res
end
end -- do
function shell(ctx, cmd)
-- FIXME we should avoid blocking the nginx worker process with shell
-- commands via something like lua-resty-shell.
-- assuming the Lua 5.2 semantics of os.execute().
local status, reason = os_exec(cmd)
if not status or reason == "signal" then
log_err(ctx, "failed to run command ", cmd, ": ", reason)
return ngx.exit(500)
end
end
local db_spec = {
host = "127.0.0.1",
port = "5432",
database = "opm",
user = "opm",
password = "buildecosystem",
}
do
local MAX_DATABASE_TRIES = 2
function query_db(query)
local pg = pgmoon.new(db_spec)
-- ngx.log(ngx.WARN, "sql query: ", query)
local ok, err
for i = 1, MAX_DATABASE_TRIES do
ok, err = pg:connect()
if not ok then
ngx.log(ngx.ERR, "failed to connect to database: ", err)
ngx.sleep(0.1)
else
break
end
end
if not ok then
ngx.log(ngx.ERR, "fatal response due to query failures")
return ngx.exit(500)
end
-- the caller should ensure that the query has no side effects
local res
for i = 1, MAX_DATABASE_TRIES do
res, err = pg:query(query)
if not res then
ngx.log(ngx.ERR, "failed to send query \"", query, "\": ", err)
ngx.sleep(0.1)
ok, err = pg:connect()
if not ok then
ngx.log(ngx.ERR, "failed to connect to database: ", err)
break
end
else
break
end
end
if not res then
ngx.log(ngx.ERR, "fatal response due to query failures")
return ngx.exit(500)
end
local ok, err = pg:keepalive(0, 5)
if not ok then
ngx.log(ngx.ERR, "failed to keep alive: ", err)
end
return res
end
end -- do
function quote_sql_str(v)
if not v or v == ngx_null then
return "null"
end
local typ = type(v)
if typ == "number" or typ == "boolean" then
return tostring(v)
end
return set_quote_sql_str(v)
end
function out_err(...)
ngx.req.discard_body()
say("ERROR: ", ...)
end
function log_err(ctx, ...)
ngx.log(ngx.ERR, "[opm] [", ctx.account or "", "] ", ...)
end
function log_and_out_err(ctx, status, ...)
ngx.status = status
out_err(...)
log_err(ctx, ...)
ngx.exit(status)
end
do
local ctx = { pos = 1 }
local bits = {}
function ver2pg_array(ver_s)
tab_clear(bits)
ctx.pos = 1
local i = 0
while true do
local fr, to, err = re_find(ver_s, [[\d+]], "jo", ctx)
if not fr then
assert(not err)
break
end
i = i + 1
bits[i] = sub(ver_s, fr, to)
end
return "'{" .. tab_concat(bits, ",") .. "}'"
end
function tab2pg_array(list)
tab_clear(bits)
for i, item in ipairs(list) do
bits[i] = quote_sql_str(item)
end
if #bits == 0 then
return "'{}'"
end
return "ARRAY[" .. tab_concat(bits, ", ") .. "]"
end
end
-- only for internal use in util/opm-pkg-indexer.pl
function _M.do_incoming()
local sql = "select uploads.id as id, uploads.package_name as name,"
.. " version_s, orig_checksum,"
.. " users.login as uploader, orgs.login as org_account"
.. " from uploads"
.. " left join users on uploads.uploader = users.id"
.. " left join orgs on uploads.org_account = orgs.id"
.. " where uploads.failed = false and uploads.indexed = false"
.. " order by uploads.created_at asc limit 50"
local rows = query_db(sql)
say(encode_json{
incoming_dir = incoming_directory,
final_dir = final_directory,
uploads = rows
})
end
do
local req_body_data = ngx.req.get_body_data
local rmfile = os.remove
-- only for internal use in util/opm-pkg-indexer.pl
function _M.do_processed()
if req_method() ~= "PUT" then
return ngx.exit(405)
end
local ctx = {}
req_read_body()
local json = req_body_data()
if not json then
return log_and_out_err(ctx, 400, "no request body found")
end
-- do return log_and_out_err(ctx, 400, json) end
local data, err = decode_json(json)
if not data then
return log_and_out_err(ctx, 400,
"failed to parse the request body as JSON: ",
json)
end
local id = tonumber(data.id)
if not id then
return log_and_out_err(ctx, 400, "bad id value: ", data.id)
end
local sql
local failed = data.failed
if failed then
sql = "update uploads set failed = true"
.. ", updated_at = now() where id = "
.. quote_sql_str(id)
else
local authors = data.authors
if not authors then
return log_and_out_err(ctx, 400, "no authors defined")
end
local authors_v = tab2pg_array(authors)
local repo_link = data.repo_link
if not repo_link then
return log_and_out_err(ctx, 400, "no repo_link defined")
end
local is_orig = data.is_original
if not is_orig or is_orig == ngx_null or is_orig == 0 then
is_orig = "false"
else
is_orig = "true"
end
local abstract = data.abstract
if not abstract then
return log_and_out_err(ctx, 400, "no abstract defined")
end
local licenses = data.licenses
if not licenses then
return log_and_out_err(ctx, 400, "no licenses defined")
end
for i, license in ipairs(licenses) do
licenses[i] = quote_sql_str(license)
end
local licenses_v = "ARRAY[" .. tab_concat(licenses, ", ") .. "]"
local final_md5 = data.final_checksum
if not final_md5 then
return log_and_out_err(ctx, 400, "no final_checksum defined")
end
local dep_pkgs = data.dep_packages
if not dep_pkgs then
return log_and_out_err(ctx, 400, "no dep_packages defined")
end
local dep_ops = data.dep_operators
if not dep_ops then
return log_and_out_err(ctx, 400, "no dep_operators defined")
end
local dep_vers = data.dep_versions
if not dep_vers then
return log_and_out_err(ctx, 400, "no dep_versions defined")
end
-- ngx.log(ngx.WARN, "abstract: ", abstract)
sql = "update uploads set indexed = true"
.. ", updated_at = now(), authors = "
.. authors_v .. ", repo_link = "
.. quote_sql_str(repo_link) .. ", is_original = "
.. is_orig .. ", abstract = "
.. quote_sql_str(abstract) .. ", licenses = "
.. licenses_v .. ", final_checksum = "
.. quote_sql_str(final_md5) .. ", dep_packages = "
.. tab2pg_array(dep_pkgs) .. ", dep_operators = "
.. tab2pg_array(dep_ops) .. ", dep_versions = "
.. tab2pg_array(dep_vers)
.. " where id = " .. quote_sql_str(id)
end
local res = query_db(sql)
assert(res.affected_rows == 1)
local file = data.file
if not re_find(file, [[.tar.gz$]], "jo") then
return log_and_out_err(ctx, 400, "bad file path: ", file)
end
local ok, err = rmfile(file)
if not ok then
log_err("failed to remove file ", file, ": ", err)
end
say([[{"success":true}]])
if failed then
local sql = "select uploads.version_s as version"
.. ", uploads.package_name as pkg"
.. ", uploads.created_at as created_at"
.. ", users.name as name, users.login as login"
.. ", users.verified_email as email"
.. ", orgs.login as org"
.. " from uploads left join users"
.. " on uploads.uploader = users.id"
.. " left join orgs on"
.. " uploads.org_account = orgs.id"
.. " where uploads.id = " .. id
local rows = query_db(sql)
if #rows == 0 then
return log_and_out_err(ctx, 400, "bad id value: ", id)
end
local r = rows[1]
local email = r.email
assert(email)
assert(r.login)
local account
if r.org and r.org ~= "" and r.org ~= ngx_null then
account = r.org
else
account = r.login
end
ctx.account = account
local block_key = "block-" .. email
-- ngx.log(ngx.WARN, "block key: ", block_key)
do
local val = shdict_bad_users:get(block_key)
if val then
return log_err(ctx, "recipient email address ", email,
" blocked temporarily due to ",
"too many emails.")
end
end
local name = r.name
if not name or name == "" or name == ngx_null then
name = r.login
end
local version = r.version
if not version or version == "" or version == ngx_null then
version = ""
end
local title = "FAILED: " .. account .. "/" .. r.pkg
.. " " .. version
local content = data.reason
if not content or content == "" or content == ngx_null then
content = "unknown internal error"
end
local body = tab_concat{
"Dear ", name, ",\n\n",
"I am the indexer program on the OPM package server.\n\n",
"I just ran into a fatal error ",
"while processing your package ", account, "/",
r.pkg, " ", version, ", which was recently uploaded at ",
r.created_at, " as Task No. ", id,
".\n\nThe details are as follows. ",
"If you still have no clues about the issue,",
" please concact us through <info@openresty.org>.\n\n",
"Please remember to provide this ",
"mail for the reference. Thank you!\n\n------\n",
content,
"\n------\n\nBest regards,\nOPM Indexer\n",
}
local ok, err = send_email(email, name, title, body)
if not ok then
log_err(ctx, "failed to send email to ", email, ": ", err)
return
end
local count_key = "count-" .. email
-- we add the email address to the black list for 12 hours after
-- sending 20 emails in the last 24 hours.
count_bad_users(count_key, block_key, 20, 3600 * 24, 3600 * 12)
end
end
end -- do
do
local unescape_uri = ngx.unescape_uri
local pkg_fetch
local bits = {}
local req_set_uri = ngx.req.set_uri
local ngx_redirect = ngx.redirect
function _M.do_pkg_exists()
local ctx = {}
local account = unescape_uri(ngx_var.arg_account)
if not account or account == "" then
return log_and_out_err(ctx, 400, "no account specified")
end
ctx.account = account
local pkg_name = unescape_uri(ngx_var.arg_name)
if not pkg_name or pkg_name == "" then
return log_and_out_err(ctx, 400, "no name specified")
end
local op = unescape_uri(ngx_var.arg_op)
local pkg_ver = unescape_uri(ngx_var.arg_version)
local found_ver, _, err = pkg_fetch(ctx, account, pkg_name, op,
pkg_ver)
if not found_ver then
ngx.status = 404
say(err)
ngx.exit(404)
end
say(encode_json{found_version = found_ver})
end
function _M.do_pkg_fetch()
local ctx = {}
local account = unescape_uri(ngx_var.arg_account)
if not account or account == "" then
return log_and_out_err(ctx, 400, "no account specified")
end
ctx.account = account
local pkg_name = unescape_uri(ngx_var.arg_name)
if not pkg_name or pkg_name == "" then
return log_and_out_err(ctx, 400, "no name specified")
end
local op = unescape_uri(ngx_var.arg_op)
local pkg_ver = unescape_uri(ngx_var.arg_version)
local found_ver, md5, err = pkg_fetch(ctx, account, pkg_name, op,
pkg_ver, true --[[ latest ]])
if not found_ver then
ngx.status = 404
say(err, ".")
ngx.exit(404)
end
if not md5 then
return log_and_out_err(ctx, 500, "MD5 checksum not found")
end
ngx.header["X-File-Checksum"] = md5
-- log_err(ctx, "md5: ", encode_json(md5))
local fname = pkg_name .. "-" .. found_ver .. ".opm.tar.gz"
ngx_redirect("/api/pkg/tarball/" .. account .. "/" .. fname, 302)
end
function pkg_fetch(ctx, account, pkg_name, op, pkg_ver, latest)
local quoted_pkg_name = quote_sql_str(pkg_name)
local quoted_account = quote_sql_str(account)
local user_id, org_id
local sql = "select id from users where login = " .. quoted_account
local rows = query_db(sql)
if #rows == 0 then
sql = "select id from orgs where login = " .. quoted_account
rows = query_db(sql)
if #rows == 0 then
return nil, nil, "account name " .. account .. " not found"
end
org_id = assert(rows[1].id)
else
user_id = assert(rows[1].id)
end
tab_clear(bits)
local i = 0
i = i + 1
bits[i] = "select version_s"
if latest then
i = i + 1
bits[i] = ", final_checksum"
end
i = i + 1
bits[i] = " from uploads where indexed = true"
.. " and package_name = "
i = i + 1
bits[i] = quoted_pkg_name
-- ngx.log(ngx.WARN, "op = ", op, ", pkg ver = ", pkg_ver)
if op and op ~= "" and pkg_ver and pkg_ver ~= "" then
if op == "eq" then
i = i + 1
bits[i] = " and version_s = "
i = i + 1
bits[i] = quote_sql_str(pkg_ver)
elseif op == "ge" then
i = i + 1
bits[i] = " and version_v >= "
i = i + 1
bits[i] = ver2pg_array(pkg_ver)
elseif op == "gt" then
i = i + 1
bits[i] = " and version_v > "
i = i + 1
bits[i] = ver2pg_array(pkg_ver)
else
return nil, nil, "bad op argument value: " .. op
end
else
op = nil
pkg_ver = nil
end
if user_id then
i = i + 1
bits[i] = " and org_account is null and uploader = "
i = i + 1
bits[i] = user_id
else
i = i + 1
bits[i] = " and org_account = "
i = i + 1
bits[i] = org_id
end
if latest then
i = i + 1
bits[i] = " order by version_v desc"
end
i = i + 1
bits[i] = " limit 1"
sql = tab_concat(bits)
rows = query_db(sql)
if #rows == 0 then
local spec
if op then
if op == 'ge' then
spec = ' >= ' .. pkg_ver
elseif op == 'gt' then
spec = ' > ' .. pkg_ver
else
spec = ' = ' .. pkg_ver
end
else
spec = ""
end
return nil, nil, "package " .. pkg_name .. spec
.. " not found under account " .. account
end
return assert(rows[1].version_s),
latest and assert(rows[1].final_checksum) or nil
end
end -- do
function _M.get_final_directory()
return final_directory
end
function count_bad_users(count_key, block_key, max_failed, count_time, ban_time)
local ok, err = shdict_bad_users:add(count_key, 0, count_time)
if not ok and err ~= "exists" then
ngx.log(ngx.ERR, "failed to add key ", count_key, ": ",
err)
return
end
local newval, err = shdict_bad_users:incr(count_key, 1)
if not newval then
ngx.log(ngx.ERR, "failed to incr ", count_key, ": ", err)
return
end
if newval and newval >= max_failed then
shdict_bad_users:delete(count_key)
local ok, err =
shdict_bad_users:add(block_key, 1, ban_time)
if not ok and err ~= "exists" then
ngx.log(ngx.ERR, "failed to add key ", block_key, ": ",
err)
return
end
end
end
do
local unescape_uri = ngx.unescape_uri
local results = {}
local str_rep = string.rep
local ngx_print = ngx.print
function _M.do_pkg_search()
local query = unescape_uri(ngx_var.arg_q)
local ctx = {}
if not query or query == "" or #query > 128 then
return log_and_out_err(ctx, 400, "bad search query value.")
end
if re_find(query, [=[[^-. \w]]=], "jo") then
return log_and_out_err(ctx, 400, "bad search query value.")
end
local sql = "select abstract, package_name, orgs.login as org_name"
.. ", users.login as uploader_name"
.. " from (select last(abstract) as abstract"
.. ", package_name, org_account, uploader"
.. ", ts_rank_cd(last(ts_idx), last(q), 1) as rank"
.. " from uploads, plainto_tsquery("
.. quote_sql_str(query) .. ") q"
.. " where indexed = true and ts_idx @@ q"
.. " group by package_name, uploader, org_account"
.. " order by rank desc limit 50) as tmp"
.. " left join users on tmp.uploader = users.id"
.. " left join orgs on tmp.org_account = orgs.id"
local rows = query_db(sql)
-- say(encode_json(rows))
if #rows == 0 then
ngx.status = 404
say("no search result found.")
return ngx.exit(404)
end
tab_clear(results)
local i = 0
for _, row in ipairs(rows) do
local uploader = row.uploader_name
local org = row.org_name
local pkg = row.package_name
local account
if org and org ~= ngx_null then
account = org
else
account = uploader
end
i = i + 1
results[i] = account
i = i + 1
results[i] = "/"
i = i + 1
results[i] = pkg
local len = #account + #pkg + 1
if len < 50 then
len = 50 - len
else
len = 4
end
i = i + 1
results[i] = str_rep(" ", len)
i = i + 1
results[i] = row.abstract
i = i + 1
results[i] = "\n"
end
ngx_print(results)
end
function _M.do_pkg_name_search()
local query = unescape_uri(ngx_var.arg_q)
local ctx = {}
if not query or query == "" or #query > 256 then
return log_and_out_err(ctx, 400, "bad search query value")
end
if not re_find(query, [[^[-\w]+$]], "jo") then
return log_and_out_err(ctx, 400, "bad search query value")
end
local sql = "select is_original, abstract, package_name"
.. ", users.login as uploader_name"
.. ", orgs.login as org_name"
.. " from (select last(is_original) as is_original"
.. ", last(abstract) as abstract"
.. ", package_name, org_account, uploader"
.. " from uploads"
.. " where indexed = true and"
.. " package_name = " .. quote_sql_str(query)
.. " group by package_name, uploader, org_account) as tmp"
.. " left join users on tmp.uploader = users.id"
.. " left join orgs on tmp.org_account = orgs.id"
.. " order by is_original desc, users.followers desc"
.. " limit 50"
local rows = query_db(sql)
-- say(encode_json(rows))
if #rows == 0 then
ngx.status = 404
say("package not found.")
return ngx.exit(404)
end
tab_clear(results)
local i = 0
for _, row in ipairs(rows) do
local uploader = row.uploader_name
local org = row.org_name
local pkg = row.package_name
local account
if org and org ~= "" and org ~= ngx_null then
account = org
else
account = uploader
end
i = i + 1
results[i] = account
i = i + 1
results[i] = "/"
i = i + 1
results[i] = pkg
local len = #account + #pkg + 1
if len < 50 then
len = 50 - len
else
len = 4
end
i = i + 1
results[i] = str_rep(" ", len)
i = i + 1
results[i] = row.abstract
i = i + 1
results[i] = "\n"
end
ngx_print(results)
end
end
function _M.do_index_page()
local sql = [[select package_name, version_s, abstract, indexed]]
.. [[, failed, users.login as uploader_name]]
.. [[, orgs.login as org_name, repo_link]]
.. [[, uploads.created_at as created_at]]
.. [[ from uploads]]
.. [[ left join users on uploads.uploader = users.id]]
.. [[ left join orgs on uploads.org_account = orgs.id]]
.. [[ order by uploads.updated_at desc limit 1000]]
local recent_uploads = query_db(sql)
sql = [[select count(*) as total,
count(distinct uploader) as uploaders,
count(distinct package_name) as pkg_count
from uploads where indexed = true]]
local rows = query_db(sql)
assert(#rows == 1)
local row = rows[1]
local total_uploads = row.total
local uploader_count = row.uploaders
local pkg_count = row.pkg_count
local html = templates.process("index.tt2", {
recent_uploads = recent_uploads,
total_uploads = total_uploads,
uploader_count = uploader_count,
package_count = pkg_count,
})
say(html)
end
return _M
| {'content_hash': 'f42f435bda23babe3c0ec5447eda1e3e', 'timestamp': '', 'source': 'github', 'line_count': 1652, 'max_line_length': 80, 'avg_line_length': 28.57082324455206, 'alnum_prop': 0.49142990317591473, 'repo_name': 'LomoX-Offical/nginx-openresty-windows', 'id': 'fc3e3cf448674a58f639cc30715218be56078b40', 'size': '47241', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/opm-0.0.3/web/lua/opmserver.lua', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ada', 'bytes': '178158'}, {'name': 'Assembly', 'bytes': '951774'}, {'name': 'Batchfile', 'bytes': '165704'}, {'name': 'C', 'bytes': '55218965'}, {'name': 'C#', 'bytes': '108026'}, {'name': 'C++', 'bytes': '2901769'}, {'name': 'CMake', 'bytes': '95691'}, {'name': 'CSS', 'bytes': '10263'}, {'name': 'DIGITAL Command Language', 'bytes': '698640'}, {'name': 'DTrace', 'bytes': '4149'}, {'name': 'Emacs Lisp', 'bytes': '10594'}, {'name': 'Erlang', 'bytes': '1044'}, {'name': 'GDB', 'bytes': '8725'}, {'name': 'HTML', 'bytes': '2000171'}, {'name': 'JavaScript', 'bytes': '48992'}, {'name': 'Lua', 'bytes': '1486040'}, {'name': 'M4', 'bytes': '216644'}, {'name': 'Makefile', 'bytes': '2261503'}, {'name': 'Module Management System', 'bytes': '3090'}, {'name': 'Nginx', 'bytes': '12160'}, {'name': 'Objective-C', 'bytes': '25760'}, {'name': 'PLpgSQL', 'bytes': '4460'}, {'name': 'Pascal', 'bytes': '200868'}, {'name': 'Perl', 'bytes': '1986747'}, {'name': 'Perl 6', 'bytes': '4783690'}, {'name': 'Prolog', 'bytes': '653788'}, {'name': 'Protocol Buffer', 'bytes': '5528'}, {'name': 'Ragel', 'bytes': '26690'}, {'name': 'Roff', 'bytes': '1302697'}, {'name': 'Ruby', 'bytes': '388048'}, {'name': 'SAS', 'bytes': '3694'}, {'name': 'Scheme', 'bytes': '8498'}, {'name': 'Shell', 'bytes': '1274554'}, {'name': 'Vim script', 'bytes': '124420'}, {'name': 'XS', 'bytes': '29996'}, {'name': 'XSLT', 'bytes': '5400'}, {'name': 'eC', 'bytes': '10316'}]} |
package lv.ddgatve.games.game15;
import lv.ddgatve.games.main.R;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Game15Activity extends ActionBarActivity {
public int ROWS = 1;
public int COLS = 1;
public static Game15Frame theFrame = Game15Frame.getInstance();
public int sqSize = 120;
public ImageAdapter theAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game15);
PickFrameDialogFragment dFragment = new PickFrameDialogFragment();
dFragment.setActivity(this);
FragmentManager fm = getFragmentManager();
dFragment.show(fm, "MyDF");
GridView gridView = (GridView) findViewById(R.id.gridview);
sqSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
280 / COLS, getResources().getDisplayMetrics());
theAdapter = new ImageAdapter(this);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
theFrame.move(position);
theAdapter.notifyDataSetChanged();
if (theFrame.isFinished()) {
Intent intent = new Intent(Game15Activity.this, SummaryActivity.class);
startActivity(intent);
}
}
});
}
public void resetGame(int rows, int cols) {
theFrame.erase();
this.ROWS = rows;
this.COLS = cols;
theFrame.initialize(rows, cols);
sqSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
280 / cols, getResources().getDisplayMetrics());
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(COLS);
gridView.setColumnWidth(sqSize);
ViewGroup.LayoutParams layoutParams = gridView.getLayoutParams();
layoutParams.height = ROWS * sqSize;
layoutParams.width = COLS * sqSize;
gridView.setAdapter(theAdapter);
theAdapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.game15, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| {'content_hash': 'a5895e2adaddc6d0fc799ef70fe84f35', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 76, 'avg_line_length': 31.414634146341463, 'alnum_prop': 0.7569875776397516, 'repo_name': 'kapsitis/ddgatve-android', 'id': 'f1cd65af18b6eb3f5bc5241ff9f8093c82b9978a', 'size': '2576', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ddgatve-games/src/lv/ddgatve/games/game15/Game15Activity.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '51623'}, {'name': 'R', 'bytes': '2682'}]} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется следующим образом
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных с этой сборкой.
[assembly: AssemblyTitle("RealtyInvest.Core.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RealtyInvest.Core.Tests")]
[assembly: AssemblyCopyright("© , 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False в параметре ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение true для требуемого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для ID библиотеки типов typelib, если этот проект видим для COM
[assembly: Guid("e93abaec-a1a6-45f7-871d-b1ef078d2774")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// основной номер версии;
// Дополнительный номер версии
// номер сборки;
// редакция.
//
// Можно задать все значения или принять номер редакции и номер сборки по умолчанию,
// используя "*", как показано ниже:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {'content_hash': 'ca4a30a783dc0eee1a38dcd2e50d3afd', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 88, 'avg_line_length': 40.34285714285714, 'alnum_prop': 0.7634560906515581, 'repo_name': 'quaternion1994/RealtyInvest', 'id': '0d34c33204629ac5afee43df8be4b11af13ca50a', 'size': '1987', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'RealtyInvest.Core.Tests/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '107'}, {'name': 'C#', 'bytes': '90707'}, {'name': 'CSS', 'bytes': '5290'}, {'name': 'HTML', 'bytes': '31712'}, {'name': 'JavaScript', 'bytes': '643611'}]} |
class NetoptMenu < ActiveRecord::Base
#
# 创建用户的菜单对象
# Input : 用户的登录ID
# Output : Array of NetoptMenu,可以为空
#
def user_menu(username)
user_menu = Array.new
# Step.1 Find All Menu
menus = NetoptMenu.order(parent_id: :asc).all
unless menus.empty?
# Step 1.1 Build Root Menu
left_menus = Array.new
while !target_menu.empty?
# Setup Root Menu
menus.each { |menu_item|
if 0 == menu_item.parent_id
user_menu.push menu_item
left_menus.push menu_item
end
}
# Add Submenu
left_menus.each { |menu_item|
}
end
end
# Step.2 Clear No MenuItems Menu
# return result
user_menu
end
end
| {'content_hash': '4826073b0885814bd52a7ec3e934b591', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 49, 'avg_line_length': 19.605263157894736, 'alnum_prop': 0.5597315436241611, 'repo_name': 'billwen/netopt', 'id': '43ae53939d3a09110eb5e407278bba5d59192b8c', 'size': '929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'harpy3/app/models/netopt_menu.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '7288721'}, {'name': 'CoffeeScript', 'bytes': '1268'}, {'name': 'JavaScript', 'bytes': '87001758'}, {'name': 'Ruby', 'bytes': '111605'}]} |
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
let debugElement: DebugElement = undefined!;
class MyDirective {}
// #docregion by_all
debugElement.query(By.all());
// #enddocregion
// #docregion by_css
debugElement.query(By.css('[attribute]'));
// #enddocregion
// #docregion by_directive
debugElement.query(By.directive(MyDirective));
// #enddocregion
| {'content_hash': 'c776c827abeae59fdf7a29a135aa8e9b', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 46, 'avg_line_length': 21.157894736842106, 'alnum_prop': 0.7338308457711443, 'repo_name': 'matsko/angular', 'id': '4bdffd8585ecf6e63b0048e50e63e6278bf5d5e4', 'size': '604', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/examples/platform-browser/dom/debug/ts/by/by.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '346628'}, {'name': 'Dockerfile', 'bytes': '11884'}, {'name': 'HTML', 'bytes': '487784'}, {'name': 'JSONiq', 'bytes': '619'}, {'name': 'JavaScript', 'bytes': '2490486'}, {'name': 'PHP', 'bytes': '7222'}, {'name': 'PowerShell', 'bytes': '3909'}, {'name': 'Shell', 'bytes': '98819'}, {'name': 'Starlark', 'bytes': '453276'}, {'name': 'TypeScript', 'bytes': '22544767'}]} |
<?php
namespace TwbBundle\Options;
use Zend\Stdlib\AbstractOptions;
/**
* Hold options for TwbBundle module
*/
class ModuleOptions extends AbstractOptions
{
protected $ignoredViewHelpers;
protected $classMap;
protected $typeMap;
/**
* Constructor
*
* @param array|Traversable|null $options
*/
public function __construct($options = null)
{
parent::__construct($options);
}
public function getIgnoredViewHelpers()
{
return $this->ignoredViewHelpers;
}
public function setIgnoredViewHelpers($ignoredViewHelpers)
{
$this->ignoredViewHelpers = $ignoredViewHelpers;
}
public function getClassMap()
{
return $this->classMap;
}
public function setClassMap($classMap)
{
$this->classMap = $classMap;
}
public function getTypeMap()
{
return $this->typeMap;
}
public function setTypeMap($typeMap)
{
$this->typeMap = $typeMap;
}
}
| {'content_hash': '013c3bd56aebd0bdb025819a399fa680', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 62, 'avg_line_length': 19.944444444444443, 'alnum_prop': 0.5812441968430826, 'repo_name': 'alejandro-fiore/zf2-twb-bundle', 'id': 'e901724c78bcab1894d3df297c17a54087a80a57', 'size': '1077', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/TwbBundle/Options/ModuleOptions.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15284'}, {'name': 'HTML', 'bytes': '1855569'}, {'name': 'JavaScript', 'bytes': '20709'}, {'name': 'PHP', 'bytes': '208178'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>node_modules\cassproject\src\org\schema\TechArticle.js - CASS Javascript Library</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="icon" href="../assets/favicon.ico">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="http://docs.cassproject.org/img/customLogo-blue.png" title="CASS Javascript Library"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 0.5.4</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/3DModel.html">3DModel</a></li>
<li><a href="../classes/AboutPage.html">AboutPage</a></li>
<li><a href="../classes/AcceptAction.html">AcceptAction</a></li>
<li><a href="../classes/Accommodation.html">Accommodation</a></li>
<li><a href="../classes/AccountingService.html">AccountingService</a></li>
<li><a href="../classes/AccreditAction.html">AccreditAction</a></li>
<li><a href="../classes/AchieveAction.html">AchieveAction</a></li>
<li><a href="../classes/Action.html">Action</a></li>
<li><a href="../classes/ActionAccessSpecification.html">ActionAccessSpecification</a></li>
<li><a href="../classes/ActionStatusType.html">ActionStatusType</a></li>
<li><a href="../classes/ActivateAction.html">ActivateAction</a></li>
<li><a href="../classes/AddAction.html">AddAction</a></li>
<li><a href="../classes/AdministrativeArea.html">AdministrativeArea</a></li>
<li><a href="../classes/AdultEntertainment.html">AdultEntertainment</a></li>
<li><a href="../classes/AdvancedStandingAction.html">AdvancedStandingAction</a></li>
<li><a href="../classes/AdvertiserContentArticle.html">AdvertiserContentArticle</a></li>
<li><a href="../classes/Agent.html">Agent</a></li>
<li><a href="../classes/AggregateDataProfile.html">AggregateDataProfile</a></li>
<li><a href="../classes/AggregateOffer.html">AggregateOffer</a></li>
<li><a href="../classes/AggregateRating.html">AggregateRating</a></li>
<li><a href="../classes/AgreeAction.html">AgreeAction</a></li>
<li><a href="../classes/Airline.html">Airline</a></li>
<li><a href="../classes/Airport.html">Airport</a></li>
<li><a href="../classes/AlignmentMap.html">AlignmentMap</a></li>
<li><a href="../classes/AlignmentObject.html">AlignmentObject</a></li>
<li><a href="../classes/AllocateAction.html">AllocateAction</a></li>
<li><a href="../classes/AmpStory.html">AmpStory</a></li>
<li><a href="../classes/AMRadioChannel.html">AMRadioChannel</a></li>
<li><a href="../classes/AmusementPark.html">AmusementPark</a></li>
<li><a href="../classes/AnalysisNewsArticle.html">AnalysisNewsArticle</a></li>
<li><a href="../classes/AnatomicalStructure.html">AnatomicalStructure</a></li>
<li><a href="../classes/AnatomicalSystem.html">AnatomicalSystem</a></li>
<li><a href="../classes/AnimalShelter.html">AnimalShelter</a></li>
<li><a href="../classes/Answer.html">Answer</a></li>
<li><a href="../classes/Apartment.html">Apartment</a></li>
<li><a href="../classes/ApartmentComplex.html">ApartmentComplex</a></li>
<li><a href="../classes/APIReference.html">APIReference</a></li>
<li><a href="../classes/AppendAction.html">AppendAction</a></li>
<li><a href="../classes/ApplyAction.html">ApplyAction</a></li>
<li><a href="../classes/ApprenticeshipCertificate.html">ApprenticeshipCertificate</a></li>
<li><a href="../classes/ApproveAction.html">ApproveAction</a></li>
<li><a href="../classes/ApprovedIndication.html">ApprovedIndication</a></li>
<li><a href="../classes/Aquarium.html">Aquarium</a></li>
<li><a href="../classes/ArchiveComponent.html">ArchiveComponent</a></li>
<li><a href="../classes/ArchiveOrganization.html">ArchiveOrganization</a></li>
<li><a href="../classes/ArriveAction.html">ArriveAction</a></li>
<li><a href="../classes/Artery.html">Artery</a></li>
<li><a href="../classes/ArtGallery.html">ArtGallery</a></li>
<li><a href="../classes/Article.html">Article</a></li>
<li><a href="../classes/AskAction.html">AskAction</a></li>
<li><a href="../classes/AskPublicNewsArticle.html">AskPublicNewsArticle</a></li>
<li><a href="../classes/ASNImport.html">ASNImport</a></li>
<li><a href="../classes/Assertion.html">Assertion</a></li>
<li><a href="../classes/AssertionEnvelope.html">AssertionEnvelope</a></li>
<li><a href="../classes/AssessAction.html">AssessAction</a></li>
<li><a href="../classes/Assessment.html">Assessment</a></li>
<li><a href="../classes/AssessmentComponent.html">AssessmentComponent</a></li>
<li><a href="../classes/AssessmentProfile.html">AssessmentProfile</a></li>
<li><a href="../classes/AssignAction.html">AssignAction</a></li>
<li><a href="../classes/AssociateDegree.html">AssociateDegree</a></li>
<li><a href="../classes/Atlas.html">Atlas</a></li>
<li><a href="../classes/Attitude.html">Attitude</a></li>
<li><a href="../classes/Attorney.html">Attorney</a></li>
<li><a href="../classes/Audience.html">Audience</a></li>
<li><a href="../classes/Audiobook.html">Audiobook</a></li>
<li><a href="../classes/AudioObject.html">AudioObject</a></li>
<li><a href="../classes/AuthorizeAction.html">AuthorizeAction</a></li>
<li><a href="../classes/AutoBodyShop.html">AutoBodyShop</a></li>
<li><a href="../classes/AutoDealer.html">AutoDealer</a></li>
<li><a href="../classes/AutomatedTeller.html">AutomatedTeller</a></li>
<li><a href="../classes/AutomotiveBusiness.html">AutomotiveBusiness</a></li>
<li><a href="../classes/AutoPartsStore.html">AutoPartsStore</a></li>
<li><a href="../classes/AutoRental.html">AutoRental</a></li>
<li><a href="../classes/AutoRepair.html">AutoRepair</a></li>
<li><a href="../classes/AutoWash.html">AutoWash</a></li>
<li><a href="../classes/BachelorDegree.html">BachelorDegree</a></li>
<li><a href="../classes/BackgroundNewsArticle.html">BackgroundNewsArticle</a></li>
<li><a href="../classes/Badge.html">Badge</a></li>
<li><a href="../classes/Bakery.html">Bakery</a></li>
<li><a href="../classes/BankAccount.html">BankAccount</a></li>
<li><a href="../classes/BankOrCreditUnion.html">BankOrCreditUnion</a></li>
<li><a href="../classes/Barcode.html">Barcode</a></li>
<li><a href="../classes/BarOrPub.html">BarOrPub</a></li>
<li><a href="../classes/BasicComponent.html">BasicComponent</a></li>
<li><a href="../classes/Beach.html">Beach</a></li>
<li><a href="../classes/BeautySalon.html">BeautySalon</a></li>
<li><a href="../classes/BedAndBreakfast.html">BedAndBreakfast</a></li>
<li><a href="../classes/BedDetails.html">BedDetails</a></li>
<li><a href="../classes/BedType.html">BedType</a></li>
<li><a href="../classes/BefriendAction.html">BefriendAction</a></li>
<li><a href="../classes/Belief.html">Belief</a></li>
<li><a href="../classes/BikeStore.html">BikeStore</a></li>
<li><a href="../classes/Blog.html">Blog</a></li>
<li><a href="../classes/BlogPosting.html">BlogPosting</a></li>
<li><a href="../classes/BloodTest.html">BloodTest</a></li>
<li><a href="../classes/BoardingPolicyType.html">BoardingPolicyType</a></li>
<li><a href="../classes/BoatReservation.html">BoatReservation</a></li>
<li><a href="../classes/BoatTerminal.html">BoatTerminal</a></li>
<li><a href="../classes/BoatTrip.html">BoatTrip</a></li>
<li><a href="../classes/BodyMeasurementTypeEnumeration.html">BodyMeasurementTypeEnumeration</a></li>
<li><a href="../classes/BodyOfWater.html">BodyOfWater</a></li>
<li><a href="../classes/Bone.html">Bone</a></li>
<li><a href="../classes/Book.html">Book</a></li>
<li><a href="../classes/BookFormatType.html">BookFormatType</a></li>
<li><a href="../classes/BookmarkAction.html">BookmarkAction</a></li>
<li><a href="../classes/BookSeries.html">BookSeries</a></li>
<li><a href="../classes/BookStore.html">BookStore</a></li>
<li><a href="../classes/BorrowAction.html">BorrowAction</a></li>
<li><a href="../classes/BowlingAlley.html">BowlingAlley</a></li>
<li><a href="../classes/BrainStructure.html">BrainStructure</a></li>
<li><a href="../classes/Brand.html">Brand</a></li>
<li><a href="../classes/BreadcrumbList.html">BreadcrumbList</a></li>
<li><a href="../classes/Brewery.html">Brewery</a></li>
<li><a href="../classes/Bridge.html">Bridge</a></li>
<li><a href="../classes/BroadcastChannel.html">BroadcastChannel</a></li>
<li><a href="../classes/BroadcastEvent.html">BroadcastEvent</a></li>
<li><a href="../classes/BroadcastFrequencySpecification.html">BroadcastFrequencySpecification</a></li>
<li><a href="../classes/BroadcastService.html">BroadcastService</a></li>
<li><a href="../classes/BrokerageAccount.html">BrokerageAccount</a></li>
<li><a href="../classes/BuddhistTemple.html">BuddhistTemple</a></li>
<li><a href="../classes/BusinessAudience.html">BusinessAudience</a></li>
<li><a href="../classes/BusinessEntityType.html">BusinessEntityType</a></li>
<li><a href="../classes/BusinessEvent.html">BusinessEvent</a></li>
<li><a href="../classes/BusinessFunction.html">BusinessFunction</a></li>
<li><a href="../classes/BusOrCoach.html">BusOrCoach</a></li>
<li><a href="../classes/BusReservation.html">BusReservation</a></li>
<li><a href="../classes/BusStation.html">BusStation</a></li>
<li><a href="../classes/BusStop.html">BusStop</a></li>
<li><a href="../classes/BusTrip.html">BusTrip</a></li>
<li><a href="../classes/BuyAction.html">BuyAction</a></li>
<li><a href="../classes/CableOrSatelliteService.html">CableOrSatelliteService</a></li>
<li><a href="../classes/CafeOrCoffeeShop.html">CafeOrCoffeeShop</a></li>
<li><a href="../classes/Campground.html">Campground</a></li>
<li><a href="../classes/CampingPitch.html">CampingPitch</a></li>
<li><a href="../classes/Canal.html">Canal</a></li>
<li><a href="../classes/CancelAction.html">CancelAction</a></li>
<li><a href="../classes/Car.html">Car</a></li>
<li><a href="../classes/CarUsageType.html">CarUsageType</a></li>
<li><a href="../classes/Casino.html">Casino</a></li>
<li><a href="../classes/Cass.html">Cass</a></li>
<li><a href="../classes/CategoryCode.html">CategoryCode</a></li>
<li><a href="../classes/CategoryCodeSet.html">CategoryCodeSet</a></li>
<li><a href="../classes/CatholicChurch.html">CatholicChurch</a></li>
<li><a href="../classes/CDCPMDRecord.html">CDCPMDRecord</a></li>
<li><a href="../classes/Cemetery.html">Cemetery</a></li>
<li><a href="../classes/Certificate.html">Certificate</a></li>
<li><a href="../classes/CertificateOfCompletion.html">CertificateOfCompletion</a></li>
<li><a href="../classes/Certification.html">Certification</a></li>
<li><a href="../classes/CfdAssessment.html">CfdAssessment</a></li>
<li><a href="../classes/CfdReference.html">CfdReference</a></li>
<li><a href="../classes/Chapter.html">Chapter</a></li>
<li><a href="../classes/CheckAction.html">CheckAction</a></li>
<li><a href="../classes/CheckInAction.html">CheckInAction</a></li>
<li><a href="../classes/CheckOutAction.html">CheckOutAction</a></li>
<li><a href="../classes/CheckoutPage.html">CheckoutPage</a></li>
<li><a href="../classes/ChildCare.html">ChildCare</a></li>
<li><a href="../classes/ChildrensEvent.html">ChildrensEvent</a></li>
<li><a href="../classes/ChooseAction.html">ChooseAction</a></li>
<li><a href="../classes/Church.html">Church</a></li>
<li><a href="../classes/City.html">City</a></li>
<li><a href="../classes/CityHall.html">CityHall</a></li>
<li><a href="../classes/CivicStructure.html">CivicStructure</a></li>
<li><a href="../classes/Claim.html">Claim</a></li>
<li><a href="../classes/ClaimReview.html">ClaimReview</a></li>
<li><a href="../classes/Class.html">Class</a></li>
<li><a href="../classes/Clip.html">Clip</a></li>
<li><a href="../classes/ClothingStore.html">ClothingStore</a></li>
<li><a href="../classes/CocurricularComponent.html">CocurricularComponent</a></li>
<li><a href="../classes/Code.html">Code</a></li>
<li><a href="../classes/Collection.html">Collection</a></li>
<li><a href="../classes/CollectionPage.html">CollectionPage</a></li>
<li><a href="../classes/CollegeOrUniversity.html">CollegeOrUniversity</a></li>
<li><a href="../classes/ComedyClub.html">ComedyClub</a></li>
<li><a href="../classes/ComedyEvent.html">ComedyEvent</a></li>
<li><a href="../classes/ComicCoverArt.html">ComicCoverArt</a></li>
<li><a href="../classes/ComicIssue.html">ComicIssue</a></li>
<li><a href="../classes/ComicSeries.html">ComicSeries</a></li>
<li><a href="../classes/ComicStory.html">ComicStory</a></li>
<li><a href="../classes/Comment.html">Comment</a></li>
<li><a href="../classes/CommentAction.html">CommentAction</a></li>
<li><a href="../classes/CommunicateAction.html">CommunicateAction</a></li>
<li><a href="../classes/Competency.html">Competency</a></li>
<li><a href="../classes/CompetencyComponent.html">CompetencyComponent</a></li>
<li><a href="../classes/CompetencyFramework.html">CompetencyFramework</a></li>
<li><a href="../classes/CompleteDataFeed.html">CompleteDataFeed</a></li>
<li><a href="../classes/ComponentCondition.html">ComponentCondition</a></li>
<li><a href="../classes/CompoundPriceSpecification.html">CompoundPriceSpecification</a></li>
<li><a href="../classes/ComputerLanguage.html">ComputerLanguage</a></li>
<li><a href="../classes/ComputerStore.html">ComputerStore</a></li>
<li><a href="../classes/Concept.html">Concept</a></li>
<li><a href="../classes/ConceptScheme.html">ConceptScheme</a></li>
<li><a href="../classes/ConditionManifest.html">ConditionManifest</a></li>
<li><a href="../classes/ConditionProfile.html">ConditionProfile</a></li>
<li><a href="../classes/ConfirmAction.html">ConfirmAction</a></li>
<li><a href="../classes/Consortium.html">Consortium</a></li>
<li><a href="../classes/ConsumeAction.html">ConsumeAction</a></li>
<li><a href="../classes/ContactPage.html">ContactPage</a></li>
<li><a href="../classes/ContactPoint.html">ContactPoint</a></li>
<li><a href="../classes/ContactPointOption.html">ContactPointOption</a></li>
<li><a href="../classes/Continent.html">Continent</a></li>
<li><a href="../classes/ControlAction.html">ControlAction</a></li>
<li><a href="../classes/ConvenienceStore.html">ConvenienceStore</a></li>
<li><a href="../classes/Conversation.html">Conversation</a></li>
<li><a href="../classes/CookAction.html">CookAction</a></li>
<li><a href="../classes/Corporation.html">Corporation</a></li>
<li><a href="../classes/CorrectionComment.html">CorrectionComment</a></li>
<li><a href="../classes/CostManifest.html">CostManifest</a></li>
<li><a href="../classes/CostProfile.html">CostProfile</a></li>
<li><a href="../classes/Country.html">Country</a></li>
<li><a href="../classes/Course.html">Course</a></li>
<li><a href="../classes/CourseComponent.html">CourseComponent</a></li>
<li><a href="../classes/CourseInstance.html">CourseInstance</a></li>
<li><a href="../classes/Courthouse.html">Courthouse</a></li>
<li><a href="../classes/CoverArt.html">CoverArt</a></li>
<li><a href="../classes/CovidTestingFacility.html">CovidTestingFacility</a></li>
<li><a href="../classes/CreateAction.html">CreateAction</a></li>
<li><a href="../classes/CreativeWork.html">CreativeWork</a></li>
<li><a href="../classes/CreativeWorkSeason.html">CreativeWorkSeason</a></li>
<li><a href="../classes/CreativeWorkSeries.html">CreativeWorkSeries</a></li>
<li><a href="../classes/Credential.html">Credential</a></li>
<li><a href="../classes/CredentialAlignmentObject.html">CredentialAlignmentObject</a></li>
<li><a href="../classes/CredentialAssertion.html">CredentialAssertion</a></li>
<li><a href="../classes/CredentialComponent.html">CredentialComponent</a></li>
<li><a href="../classes/CredentialFramework.html">CredentialFramework</a></li>
<li><a href="../classes/CredentialingAction.html">CredentialingAction</a></li>
<li><a href="../classes/CredentialOrganization.html">CredentialOrganization</a></li>
<li><a href="../classes/CredentialPerson.html">CredentialPerson</a></li>
<li><a href="../classes/CreditCard.html">CreditCard</a></li>
<li><a href="../classes/Crematorium.html">Crematorium</a></li>
<li><a href="../classes/CriticReview.html">CriticReview</a></li>
<li><a href="../classes/CssSelectorType.html">CssSelectorType</a></li>
<li><a href="../classes/CSVExport.html">CSVExport</a></li>
<li><a href="../classes/CSVImport.html">CSVImport</a></li>
<li><a href="../classes/CurrencyConversionService.html">CurrencyConversionService</a></li>
<li><a href="../classes/DanceEvent.html">DanceEvent</a></li>
<li><a href="../classes/DanceGroup.html">DanceGroup</a></li>
<li><a href="../classes/DataCatalog.html">DataCatalog</a></li>
<li><a href="../classes/DataDownload.html">DataDownload</a></li>
<li><a href="../classes/DataFeed.html">DataFeed</a></li>
<li><a href="../classes/DataFeedItem.html">DataFeedItem</a></li>
<li><a href="../classes/Dataset.html">Dataset</a></li>
<li><a href="../classes/DatedMoneySpecification.html">DatedMoneySpecification</a></li>
<li><a href="../classes/DayOfWeek.html">DayOfWeek</a></li>
<li><a href="../classes/DaySpa.html">DaySpa</a></li>
<li><a href="../classes/DDxElement.html">DDxElement</a></li>
<li><a href="../classes/DeactivateAction.html">DeactivateAction</a></li>
<li><a href="../classes/DefenceEstablishment.html">DefenceEstablishment</a></li>
<li><a href="../classes/DefinedRegion.html">DefinedRegion</a></li>
<li><a href="../classes/DefinedTerm.html">DefinedTerm</a></li>
<li><a href="../classes/DefinedTermSet.html">DefinedTermSet</a></li>
<li><a href="../classes/Degree.html">Degree</a></li>
<li><a href="../classes/DeleteAction.html">DeleteAction</a></li>
<li><a href="../classes/DeliveryChargeSpecification.html">DeliveryChargeSpecification</a></li>
<li><a href="../classes/DeliveryEvent.html">DeliveryEvent</a></li>
<li><a href="../classes/DeliveryMethod.html">DeliveryMethod</a></li>
<li><a href="../classes/DeliveryTimeSettings.html">DeliveryTimeSettings</a></li>
<li><a href="../classes/Demand.html">Demand</a></li>
<li><a href="../classes/Dentist.html">Dentist</a></li>
<li><a href="../classes/DepartAction.html">DepartAction</a></li>
<li><a href="../classes/DepartmentStore.html">DepartmentStore</a></li>
<li><a href="../classes/DepositAccount.html">DepositAccount</a></li>
<li><a href="../classes/DiagnosticLab.html">DiagnosticLab</a></li>
<li><a href="../classes/DiagnosticProcedure.html">DiagnosticProcedure</a></li>
<li><a href="../classes/Diet.html">Diet</a></li>
<li><a href="../classes/DietarySupplement.html">DietarySupplement</a></li>
<li><a href="../classes/DigitalBadge.html">DigitalBadge</a></li>
<li><a href="../classes/DigitalDocument.html">DigitalDocument</a></li>
<li><a href="../classes/DigitalDocumentPermission.html">DigitalDocumentPermission</a></li>
<li><a href="../classes/DigitalDocumentPermissionType.html">DigitalDocumentPermissionType</a></li>
<li><a href="../classes/Diploma.html">Diploma</a></li>
<li><a href="../classes/Directory.html">Directory</a></li>
<li><a href="../classes/DisagreeAction.html">DisagreeAction</a></li>
<li><a href="../classes/DiscoverAction.html">DiscoverAction</a></li>
<li><a href="../classes/DiscussionForumPosting.html">DiscussionForumPosting</a></li>
<li><a href="../classes/DislikeAction.html">DislikeAction</a></li>
<li><a href="../classes/Distance.html">Distance</a></li>
<li><a href="../classes/Distillery.html">Distillery</a></li>
<li><a href="../classes/DoctoralDegree.html">DoctoralDegree</a></li>
<li><a href="../classes/DonateAction.html">DonateAction</a></li>
<li><a href="../classes/DoseSchedule.html">DoseSchedule</a></li>
<li><a href="../classes/DownloadAction.html">DownloadAction</a></li>
<li><a href="../classes/DrawAction.html">DrawAction</a></li>
<li><a href="../classes/Drawing.html">Drawing</a></li>
<li><a href="../classes/DrinkAction.html">DrinkAction</a></li>
<li><a href="../classes/DriveWheelConfigurationValue.html">DriveWheelConfigurationValue</a></li>
<li><a href="../classes/Drug.html">Drug</a></li>
<li><a href="../classes/DrugClass.html">DrugClass</a></li>
<li><a href="../classes/DrugCost.html">DrugCost</a></li>
<li><a href="../classes/DrugCostCategory.html">DrugCostCategory</a></li>
<li><a href="../classes/DrugLegalStatus.html">DrugLegalStatus</a></li>
<li><a href="../classes/DrugPregnancyCategory.html">DrugPregnancyCategory</a></li>
<li><a href="../classes/DrugPrescriptionStatus.html">DrugPrescriptionStatus</a></li>
<li><a href="../classes/DrugStrength.html">DrugStrength</a></li>
<li><a href="../classes/DryCleaningOrLaundry.html">DryCleaningOrLaundry</a></li>
<li><a href="../classes/Duration.html">Duration</a></li>
<li><a href="../classes/DurationProfile.html">DurationProfile</a></li>
<li><a href="../classes/EarningsProfile.html">EarningsProfile</a></li>
<li><a href="../classes/EatAction.html">EatAction</a></li>
<li><a href="../classes/Ebac.html">Ebac</a></li>
<li><a href="../classes/EbacContact.html">EbacContact</a></li>
<li><a href="../classes/EbacContactGrant.html">EbacContactGrant</a></li>
<li><a href="../classes/EbacCredential.html">EbacCredential</a></li>
<li><a href="../classes/EbacCredentialCommit.html">EbacCredentialCommit</a></li>
<li><a href="../classes/EbacCredentialRequest.html">EbacCredentialRequest</a></li>
<li><a href="../classes/EbacCredentials.html">EbacCredentials</a></li>
<li><a href="../classes/EbacEncryptedSecret.html">EbacEncryptedSecret</a></li>
<li><a href="../classes/EbacEncryptedValue.html">EbacEncryptedValue</a></li>
<li><a href="../classes/EbacSignature.html">EbacSignature</a></li>
<li><a href="../classes/EcAes.html">EcAes</a></li>
<li><a href="../classes/EcAesCtr.html">EcAesCtr</a></li>
<li><a href="../classes/EcAesCtrAsync.html">EcAesCtrAsync</a></li>
<li><a href="../classes/EcAesCtrAsyncWorker.html">EcAesCtrAsyncWorker</a></li>
<li><a href="../classes/EcAlignment.html">EcAlignment</a></li>
<li><a href="../classes/EcArray.html">EcArray</a></li>
<li><a href="../classes/EcAsyncHelper.html">EcAsyncHelper</a></li>
<li><a href="../classes/EcCompetency.html">EcCompetency</a></li>
<li><a href="../classes/EcContact.html">EcContact</a></li>
<li><a href="../classes/EcCrypto.html">EcCrypto</a></li>
<li><a href="../classes/EcDirectedGraph.html">EcDirectedGraph</a></li>
<li><a href="../classes/EcDirectory.html">EcDirectory</a></li>
<li><a href="../classes/EcEncryptedValue.html">EcEncryptedValue</a></li>
<li><a href="../classes/EcFile.html">EcFile</a></li>
<li><a href="../classes/EcFramework.html">EcFramework</a></li>
<li><a href="../classes/EcFrameworkGraph.html">EcFrameworkGraph</a></li>
<li><a href="../classes/EcIdentity.html">EcIdentity</a></li>
<li><a href="../classes/EcIdentityManager.html">EcIdentityManager</a></li>
<li><a href="../classes/EcLevel.html">EcLevel</a></li>
<li><a href="../classes/EcLinkedData
/ module.exports = class EcLinkedData {
constructor(context, type) {
this.setContextAndType(context, type);
}
static atProperties = ["id", "type", "schema", "context", "graph"];
/**
JSON-LD @type field..html">EcLinkedData
/ module.exports = class EcLinkedData {
constructor(context, type) {
this.setContextAndType(context, type);
}
static atProperties = ["id", "type", "schema", "context", "graph"];
/**
JSON-LD @type field.</a></li>
<li><a href="../classes/EcObject.html">EcObject</a></li>
<li><a href="../classes/EcPk.html">EcPk</a></li>
<li><a href="../classes/EcPpk.html">EcPpk</a></li>
<li><a href="../classes/EcRemote.html">EcRemote</a></li>
<li><a href="../classes/EcRemoteIdentityManager.html">EcRemoteIdentityManager</a></li>
<li><a href="../classes/EcRemoteLinkedData.html">EcRemoteLinkedData</a></li>
<li><a href="../classes/EcRepository.html">EcRepository</a></li>
<li><a href="../classes/EcRollupRule.html">EcRollupRule</a></li>
<li><a href="../classes/EcRsaOaep.html">EcRsaOaep</a></li>
<li><a href="../classes/EcRsaOaepAsync.html">EcRsaOaepAsync</a></li>
<li><a href="../classes/EducationalAudience.html">EducationalAudience</a></li>
<li><a href="../classes/EducationalOccupationalCredential.html">EducationalOccupationalCredential</a></li>
<li><a href="../classes/EducationalOccupationalProgram.html">EducationalOccupationalProgram</a></li>
<li><a href="../classes/EducationalOrganization.html">EducationalOrganization</a></li>
<li><a href="../classes/EducationEvent.html">EducationEvent</a></li>
<li><a href="../classes/Electrician.html">Electrician</a></li>
<li><a href="../classes/ElectronicsStore.html">ElectronicsStore</a></li>
<li><a href="../classes/ElementarySchool.html">ElementarySchool</a></li>
<li><a href="../classes/EmailMessage.html">EmailMessage</a></li>
<li><a href="../classes/Embassy.html">Embassy</a></li>
<li><a href="../classes/EmergencyService.html">EmergencyService</a></li>
<li><a href="../classes/EmployeeRole.html">EmployeeRole</a></li>
<li><a href="../classes/EmployerAggregateRating.html">EmployerAggregateRating</a></li>
<li><a href="../classes/EmployerReview.html">EmployerReview</a></li>
<li><a href="../classes/EmploymentAgency.html">EmploymentAgency</a></li>
<li><a href="../classes/EmploymentOutcomeProfile.html">EmploymentOutcomeProfile</a></li>
<li><a href="../classes/EndorseAction.html">EndorseAction</a></li>
<li><a href="../classes/EndorsementRating.html">EndorsementRating</a></li>
<li><a href="../classes/Energy.html">Energy</a></li>
<li><a href="../classes/EnergyConsumptionDetails.html">EnergyConsumptionDetails</a></li>
<li><a href="../classes/EnergyEfficiencyEnumeration.html">EnergyEfficiencyEnumeration</a></li>
<li><a href="../classes/EnergyStarEnergyEfficiencyEnumeration.html">EnergyStarEnergyEfficiencyEnumeration</a></li>
<li><a href="../classes/EngineSpecification.html">EngineSpecification</a></li>
<li><a href="../classes/EntertainmentBusiness.html">EntertainmentBusiness</a></li>
<li><a href="../classes/EntryPoint.html">EntryPoint</a></li>
<li><a href="../classes/Enumeration.html">Enumeration</a></li>
<li><a href="../classes/Episode.html">Episode</a></li>
<li><a href="../classes/EUEnergyEfficiencyEnumeration.html">EUEnergyEfficiencyEnumeration</a></li>
<li><a href="../classes/Event.html">Event</a></li>
<li><a href="../classes/EventAttendanceModeEnumeration.html">EventAttendanceModeEnumeration</a></li>
<li><a href="../classes/EventReservation.html">EventReservation</a></li>
<li><a href="../classes/EventSeries.html">EventSeries</a></li>
<li><a href="../classes/EventStatusType.html">EventStatusType</a></li>
<li><a href="../classes/EventVenue.html">EventVenue</a></li>
<li><a href="../classes/ExchangeRateSpecification.html">ExchangeRateSpecification</a></li>
<li><a href="../classes/ExerciseAction.html">ExerciseAction</a></li>
<li><a href="../classes/ExerciseGym.html">ExerciseGym</a></li>
<li><a href="../classes/ExercisePlan.html">ExercisePlan</a></li>
<li><a href="../classes/ExhibitionEvent.html">ExhibitionEvent</a></li>
<li><a href="../classes/Exporter.html">Exporter</a></li>
<li><a href="../classes/ExtracurricularComponent.html">ExtracurricularComponent</a></li>
<li><a href="../classes/FAQPage.html">FAQPage</a></li>
<li><a href="../classes/FastFoodRestaurant.html">FastFoodRestaurant</a></li>
<li><a href="../classes/Festival.html">Festival</a></li>
<li><a href="../classes/FilmAction.html">FilmAction</a></li>
<li><a href="../classes/FinancialAssistanceProfile.html">FinancialAssistanceProfile</a></li>
<li><a href="../classes/FinancialProduct.html">FinancialProduct</a></li>
<li><a href="../classes/FinancialService.html">FinancialService</a></li>
<li><a href="../classes/FindAction.html">FindAction</a></li>
<li><a href="../classes/FireStation.html">FireStation</a></li>
<li><a href="../classes/Flight.html">Flight</a></li>
<li><a href="../classes/FlightReservation.html">FlightReservation</a></li>
<li><a href="../classes/FloorPlan.html">FloorPlan</a></li>
<li><a href="../classes/Florist.html">Florist</a></li>
<li><a href="../classes/FMRadioChannel.html">FMRadioChannel</a></li>
<li><a href="../classes/FollowAction.html">FollowAction</a></li>
<li><a href="../classes/FoodEstablishment.html">FoodEstablishment</a></li>
<li><a href="../classes/FoodEstablishmentReservation.html">FoodEstablishmentReservation</a></li>
<li><a href="../classes/FoodEvent.html">FoodEvent</a></li>
<li><a href="../classes/FoodService.html">FoodService</a></li>
<li><a href="../classes/Framework.html">Framework</a></li>
<li><a href="../classes/FrameworkImport.html">FrameworkImport</a></li>
<li><a href="../classes/FundingAgency.html">FundingAgency</a></li>
<li><a href="../classes/FundingScheme.html">FundingScheme</a></li>
<li><a href="../classes/FurnitureStore.html">FurnitureStore</a></li>
<li><a href="../classes/Game.html">Game</a></li>
<li><a href="../classes/GamePlayMode.html">GamePlayMode</a></li>
<li><a href="../classes/GameServer.html">GameServer</a></li>
<li><a href="../classes/GameServerStatus.html">GameServerStatus</a></li>
<li><a href="../classes/GardenStore.html">GardenStore</a></li>
<li><a href="../classes/GasStation.html">GasStation</a></li>
<li><a href="../classes/GatedResidenceCommunity.html">GatedResidenceCommunity</a></li>
<li><a href="../classes/GenderType.html">GenderType</a></li>
<li><a href="../classes/General.html">General</a></li>
<li><a href="../classes/GeneralContractor.html">GeneralContractor</a></li>
<li><a href="../classes/GeneralEducationDevelopment.html">GeneralEducationDevelopment</a></li>
<li><a href="../classes/GeneralFile.html">GeneralFile</a></li>
<li><a href="../classes/GeoCircle.html">GeoCircle</a></li>
<li><a href="../classes/GeoCoordinates.html">GeoCoordinates</a></li>
<li><a href="../classes/GeoShape.html">GeoShape</a></li>
<li><a href="../classes/GeospatialGeometry.html">GeospatialGeometry</a></li>
<li><a href="../classes/GiveAction.html">GiveAction</a></li>
<li><a href="../classes/GolfCourse.html">GolfCourse</a></li>
<li><a href="../classes/GovernmentBenefitsType.html">GovernmentBenefitsType</a></li>
<li><a href="../classes/GovernmentBuilding.html">GovernmentBuilding</a></li>
<li><a href="../classes/GovernmentOffice.html">GovernmentOffice</a></li>
<li><a href="../classes/GovernmentOrganization.html">GovernmentOrganization</a></li>
<li><a href="../classes/GovernmentPermit.html">GovernmentPermit</a></li>
<li><a href="../classes/GovernmentService.html">GovernmentService</a></li>
<li><a href="../classes/Grant.html">Grant</a></li>
<li><a href="../classes/Graph.html">Graph</a></li>
<li><a href="../classes/GroceryStore.html">GroceryStore</a></li>
<li><a href="../classes/Guide.html">Guide</a></li>
<li><a href="../classes/Hackathon.html">Hackathon</a></li>
<li><a href="../classes/HairSalon.html">HairSalon</a></li>
<li><a href="../classes/HardwareStore.html">HardwareStore</a></li>
<li><a href="../classes/HealthAndBeautyBusiness.html">HealthAndBeautyBusiness</a></li>
<li><a href="../classes/HealthAspectEnumeration.html">HealthAspectEnumeration</a></li>
<li><a href="../classes/HealthClub.html">HealthClub</a></li>
<li><a href="../classes/HealthInsurancePlan.html">HealthInsurancePlan</a></li>
<li><a href="../classes/HealthPlanCostSharingSpecification.html">HealthPlanCostSharingSpecification</a></li>
<li><a href="../classes/HealthPlanFormulary.html">HealthPlanFormulary</a></li>
<li><a href="../classes/HealthPlanNetwork.html">HealthPlanNetwork</a></li>
<li><a href="../classes/HealthTopicContent.html">HealthTopicContent</a></li>
<li><a href="../classes/HighSchool.html">HighSchool</a></li>
<li><a href="../classes/HinduTemple.html">HinduTemple</a></li>
<li><a href="../classes/HobbyShop.html">HobbyShop</a></li>
<li><a href="../classes/HoldersProfile.html">HoldersProfile</a></li>
<li><a href="../classes/HomeAndConstructionBusiness.html">HomeAndConstructionBusiness</a></li>
<li><a href="../classes/HomeGoodsStore.html">HomeGoodsStore</a></li>
<li><a href="../classes/Hospital.html">Hospital</a></li>
<li><a href="../classes/Hostel.html">Hostel</a></li>
<li><a href="../classes/Hotel.html">Hotel</a></li>
<li><a href="../classes/HotelRoom.html">HotelRoom</a></li>
<li><a href="../classes/House.html">House</a></li>
<li><a href="../classes/HousePainter.html">HousePainter</a></li>
<li><a href="../classes/HowTo.html">HowTo</a></li>
<li><a href="../classes/HowToDirection.html">HowToDirection</a></li>
<li><a href="../classes/HowToItem.html">HowToItem</a></li>
<li><a href="../classes/HowToSection.html">HowToSection</a></li>
<li><a href="../classes/HowToStep.html">HowToStep</a></li>
<li><a href="../classes/HowToSupply.html">HowToSupply</a></li>
<li><a href="../classes/HowToTip.html">HowToTip</a></li>
<li><a href="../classes/HowToTool.html">HowToTool</a></li>
<li><a href="../classes/HVACBusiness.html">HVACBusiness</a></li>
<li><a href="../classes/Hypergraph.html">Hypergraph</a></li>
<li><a href="../classes/HyperToc.html">HyperToc</a></li>
<li><a href="../classes/HyperTocEntry.html">HyperTocEntry</a></li>
<li><a href="../classes/IceCreamShop.html">IceCreamShop</a></li>
<li><a href="../classes/IdentifierValue.html">IdentifierValue</a></li>
<li><a href="../classes/IgnoreAction.html">IgnoreAction</a></li>
<li><a href="../classes/ImageGallery.html">ImageGallery</a></li>
<li><a href="../classes/ImageObject.html">ImageObject</a></li>
<li><a href="../classes/ImagingTest.html">ImagingTest</a></li>
<li><a href="../classes/Importer.html">Importer</a></li>
<li><a href="../classes/IndividualProduct.html">IndividualProduct</a></li>
<li><a href="../classes/IndustryClassification.html">IndustryClassification</a></li>
<li><a href="../classes/InfectiousAgentClass.html">InfectiousAgentClass</a></li>
<li><a href="../classes/InfectiousDisease.html">InfectiousDisease</a></li>
<li><a href="../classes/InformAction.html">InformAction</a></li>
<li><a href="../classes/InsertAction.html">InsertAction</a></li>
<li><a href="../classes/InstallAction.html">InstallAction</a></li>
<li><a href="../classes/InstructionalProgramClassification.html">InstructionalProgramClassification</a></li>
<li><a href="../classes/InsuranceAgency.html">InsuranceAgency</a></li>
<li><a href="../classes/Intangible.html">Intangible</a></li>
<li><a href="../classes/InteractAction.html">InteractAction</a></li>
<li><a href="../classes/InteractionCounter.html">InteractionCounter</a></li>
<li><a href="../classes/InternetCafe.html">InternetCafe</a></li>
<li><a href="../classes/InvestmentFund.html">InvestmentFund</a></li>
<li><a href="../classes/InvestmentOrDeposit.html">InvestmentOrDeposit</a></li>
<li><a href="../classes/InviteAction.html">InviteAction</a></li>
<li><a href="../classes/Invoice.html">Invoice</a></li>
<li><a href="../classes/ItemAvailability.html">ItemAvailability</a></li>
<li><a href="../classes/ItemList.html">ItemList</a></li>
<li><a href="../classes/ItemListOrderType.html">ItemListOrderType</a></li>
<li><a href="../classes/ItemPage.html">ItemPage</a></li>
<li><a href="../classes/JewelryStore.html">JewelryStore</a></li>
<li><a href="../classes/Job.html">Job</a></li>
<li><a href="../classes/JobComponent.html">JobComponent</a></li>
<li><a href="../classes/JobPosting.html">JobPosting</a></li>
<li><a href="../classes/JoinAction.html">JoinAction</a></li>
<li><a href="../classes/Joint.html">Joint</a></li>
<li><a href="../classes/JourneymanCertificate.html">JourneymanCertificate</a></li>
<li><a href="../classes/JurisdictionProfile.html">JurisdictionProfile</a></li>
<li><a href="../classes/Knowledge.html">Knowledge</a></li>
<li><a href="../classes/LakeBodyOfWater.html">LakeBodyOfWater</a></li>
<li><a href="../classes/Landform.html">Landform</a></li>
<li><a href="../classes/LandmarksOrHistoricalBuildings.html">LandmarksOrHistoricalBuildings</a></li>
<li><a href="../classes/Language.html">Language</a></li>
<li><a href="../classes/LearningOpportunity.html">LearningOpportunity</a></li>
<li><a href="../classes/LearningOpportunityProfile.html">LearningOpportunityProfile</a></li>
<li><a href="../classes/LearningResource.html">LearningResource</a></li>
<li><a href="../classes/LeaveAction.html">LeaveAction</a></li>
<li><a href="../classes/LegalForceStatus.html">LegalForceStatus</a></li>
<li><a href="../classes/LegalService.html">LegalService</a></li>
<li><a href="../classes/LegalValueLevel.html">LegalValueLevel</a></li>
<li><a href="../classes/Legislation.html">Legislation</a></li>
<li><a href="../classes/LegislationObject.html">LegislationObject</a></li>
<li><a href="../classes/LegislativeBuilding.html">LegislativeBuilding</a></li>
<li><a href="../classes/LendAction.html">LendAction</a></li>
<li><a href="../classes/Level.html">Level</a></li>
<li><a href="../classes/Library.html">Library</a></li>
<li><a href="../classes/LibrarySystem.html">LibrarySystem</a></li>
<li><a href="../classes/License.html">License</a></li>
<li><a href="../classes/LifestyleModification.html">LifestyleModification</a></li>
<li><a href="../classes/Ligament.html">Ligament</a></li>
<li><a href="../classes/LikeAction.html">LikeAction</a></li>
<li><a href="../classes/LinkRole.html">LinkRole</a></li>
<li><a href="../classes/LiquorStore.html">LiquorStore</a></li>
<li><a href="../classes/ListenAction.html">ListenAction</a></li>
<li><a href="../classes/ListItem.html">ListItem</a></li>
<li><a href="../classes/LiteraryEvent.html">LiteraryEvent</a></li>
<li><a href="../classes/LiveBlogPosting.html">LiveBlogPosting</a></li>
<li><a href="../classes/LoanOrCredit.html">LoanOrCredit</a></li>
<li><a href="../classes/LocalBusiness.html">LocalBusiness</a></li>
<li><a href="../classes/LocationFeatureSpecification.html">LocationFeatureSpecification</a></li>
<li><a href="../classes/Locksmith.html">Locksmith</a></li>
<li><a href="../classes/LodgingBusiness.html">LodgingBusiness</a></li>
<li><a href="../classes/LodgingReservation.html">LodgingReservation</a></li>
<li><a href="../classes/LoseAction.html">LoseAction</a></li>
<li><a href="../classes/LymphaticVessel.html">LymphaticVessel</a></li>
<li><a href="../classes/Manuscript.html">Manuscript</a></li>
<li><a href="../classes/Map.html">Map</a></li>
<li><a href="../classes/MapCategoryType.html">MapCategoryType</a></li>
<li><a href="../classes/MarryAction.html">MarryAction</a></li>
<li><a href="../classes/Mass.html">Mass</a></li>
<li><a href="../classes/MasterCertificate.html">MasterCertificate</a></li>
<li><a href="../classes/MasterDegree.html">MasterDegree</a></li>
<li><a href="../classes/MathSolver.html">MathSolver</a></li>
<li><a href="../classes/MaximumDoseSchedule.html">MaximumDoseSchedule</a></li>
<li><a href="../classes/MeasurementTypeEnumeration.html">MeasurementTypeEnumeration</a></li>
<li><a href="../classes/MedbiqImport.html">MedbiqImport</a></li>
<li><a href="../classes/MediaGallery.html">MediaGallery</a></li>
<li><a href="../classes/MediaManipulationRatingEnumeration.html">MediaManipulationRatingEnumeration</a></li>
<li><a href="../classes/MediaObject.html">MediaObject</a></li>
<li><a href="../classes/MediaReview.html">MediaReview</a></li>
<li><a href="../classes/MediaSubscription.html">MediaSubscription</a></li>
<li><a href="../classes/MedicalAudience.html">MedicalAudience</a></li>
<li><a href="../classes/MedicalAudienceType.html">MedicalAudienceType</a></li>
<li><a href="../classes/MedicalBusiness.html">MedicalBusiness</a></li>
<li><a href="../classes/MedicalCause.html">MedicalCause</a></li>
<li><a href="../classes/MedicalClinic.html">MedicalClinic</a></li>
<li><a href="../classes/MedicalCode.html">MedicalCode</a></li>
<li><a href="../classes/MedicalCondition.html">MedicalCondition</a></li>
<li><a href="../classes/MedicalConditionStage.html">MedicalConditionStage</a></li>
<li><a href="../classes/MedicalContraindication.html">MedicalContraindication</a></li>
<li><a href="../classes/MedicalDevice.html">MedicalDevice</a></li>
<li><a href="../classes/MedicalDevicePurpose.html">MedicalDevicePurpose</a></li>
<li><a href="../classes/MedicalEntity.html">MedicalEntity</a></li>
<li><a href="../classes/MedicalEnumeration.html">MedicalEnumeration</a></li>
<li><a href="../classes/MedicalEvidenceLevel.html">MedicalEvidenceLevel</a></li>
<li><a href="../classes/MedicalGuideline.html">MedicalGuideline</a></li>
<li><a href="../classes/MedicalGuidelineContraindication.html">MedicalGuidelineContraindication</a></li>
<li><a href="../classes/MedicalGuidelineRecommendation.html">MedicalGuidelineRecommendation</a></li>
<li><a href="../classes/MedicalImagingTechnique.html">MedicalImagingTechnique</a></li>
<li><a href="../classes/MedicalIndication.html">MedicalIndication</a></li>
<li><a href="../classes/MedicalIntangible.html">MedicalIntangible</a></li>
<li><a href="../classes/MedicalObservationalStudy.html">MedicalObservationalStudy</a></li>
<li><a href="../classes/MedicalObservationalStudyDesign.html">MedicalObservationalStudyDesign</a></li>
<li><a href="../classes/MedicalOrganization.html">MedicalOrganization</a></li>
<li><a href="../classes/MedicalProcedure.html">MedicalProcedure</a></li>
<li><a href="../classes/MedicalProcedureType.html">MedicalProcedureType</a></li>
<li><a href="../classes/MedicalRiskCalculator.html">MedicalRiskCalculator</a></li>
<li><a href="../classes/MedicalRiskEstimator.html">MedicalRiskEstimator</a></li>
<li><a href="../classes/MedicalRiskFactor.html">MedicalRiskFactor</a></li>
<li><a href="../classes/MedicalRiskScore.html">MedicalRiskScore</a></li>
<li><a href="../classes/MedicalScholarlyArticle.html">MedicalScholarlyArticle</a></li>
<li><a href="../classes/MedicalSign.html">MedicalSign</a></li>
<li><a href="../classes/MedicalSignOrSymptom.html">MedicalSignOrSymptom</a></li>
<li><a href="../classes/MedicalSpecialty.html">MedicalSpecialty</a></li>
<li><a href="../classes/MedicalStudy.html">MedicalStudy</a></li>
<li><a href="../classes/MedicalStudyStatus.html">MedicalStudyStatus</a></li>
<li><a href="../classes/MedicalSymptom.html">MedicalSymptom</a></li>
<li><a href="../classes/MedicalTest.html">MedicalTest</a></li>
<li><a href="../classes/MedicalTestPanel.html">MedicalTestPanel</a></li>
<li><a href="../classes/MedicalTherapy.html">MedicalTherapy</a></li>
<li><a href="../classes/MedicalTrial.html">MedicalTrial</a></li>
<li><a href="../classes/MedicalTrialDesign.html">MedicalTrialDesign</a></li>
<li><a href="../classes/MedicalWebPage.html">MedicalWebPage</a></li>
<li><a href="../classes/MedicineSystem.html">MedicineSystem</a></li>
<li><a href="../classes/MeetingRoom.html">MeetingRoom</a></li>
<li><a href="../classes/MensClothingStore.html">MensClothingStore</a></li>
<li><a href="../classes/Menu.html">Menu</a></li>
<li><a href="../classes/MenuItem.html">MenuItem</a></li>
<li><a href="../classes/MenuSection.html">MenuSection</a></li>
<li><a href="../classes/MerchantReturnEnumeration.html">MerchantReturnEnumeration</a></li>
<li><a href="../classes/MerchantReturnPolicy.html">MerchantReturnPolicy</a></li>
<li><a href="../classes/Message.html">Message</a></li>
<li><a href="../classes/MicroCredential.html">MicroCredential</a></li>
<li><a href="../classes/MiddleSchool.html">MiddleSchool</a></li>
<li><a href="../classes/MobileApplication.html">MobileApplication</a></li>
<li><a href="../classes/MobilePhoneStore.html">MobilePhoneStore</a></li>
<li><a href="../classes/MonetaryAmount.html">MonetaryAmount</a></li>
<li><a href="../classes/MonetaryAmountDistribution.html">MonetaryAmountDistribution</a></li>
<li><a href="../classes/MonetaryGrant.html">MonetaryGrant</a></li>
<li><a href="../classes/MoneyTransfer.html">MoneyTransfer</a></li>
<li><a href="../classes/MortgageLoan.html">MortgageLoan</a></li>
<li><a href="../classes/Mosque.html">Mosque</a></li>
<li><a href="../classes/Motel.html">Motel</a></li>
<li><a href="../classes/Motorcycle.html">Motorcycle</a></li>
<li><a href="../classes/MotorcycleDealer.html">MotorcycleDealer</a></li>
<li><a href="../classes/MotorcycleRepair.html">MotorcycleRepair</a></li>
<li><a href="../classes/MotorizedBicycle.html">MotorizedBicycle</a></li>
<li><a href="../classes/Mountain.html">Mountain</a></li>
<li><a href="../classes/MoveAction.html">MoveAction</a></li>
<li><a href="../classes/Movie.html">Movie</a></li>
<li><a href="../classes/MovieClip.html">MovieClip</a></li>
<li><a href="../classes/MovieRentalStore.html">MovieRentalStore</a></li>
<li><a href="../classes/MovieSeries.html">MovieSeries</a></li>
<li><a href="../classes/MovieTheater.html">MovieTheater</a></li>
<li><a href="../classes/MovingCompany.html">MovingCompany</a></li>
<li><a href="../classes/Muscle.html">Muscle</a></li>
<li><a href="../classes/Museum.html">Museum</a></li>
<li><a href="../classes/MusicAlbum.html">MusicAlbum</a></li>
<li><a href="../classes/MusicAlbumProductionType.html">MusicAlbumProductionType</a></li>
<li><a href="../classes/MusicAlbumReleaseType.html">MusicAlbumReleaseType</a></li>
<li><a href="../classes/MusicComposition.html">MusicComposition</a></li>
<li><a href="../classes/MusicEvent.html">MusicEvent</a></li>
<li><a href="../classes/MusicGroup.html">MusicGroup</a></li>
<li><a href="../classes/MusicPlaylist.html">MusicPlaylist</a></li>
<li><a href="../classes/MusicRecording.html">MusicRecording</a></li>
<li><a href="../classes/MusicRelease.html">MusicRelease</a></li>
<li><a href="../classes/MusicReleaseFormatType.html">MusicReleaseFormatType</a></li>
<li><a href="../classes/MusicStore.html">MusicStore</a></li>
<li><a href="../classes/MusicVenue.html">MusicVenue</a></li>
<li><a href="../classes/MusicVideoObject.html">MusicVideoObject</a></li>
<li><a href="../classes/NailSalon.html">NailSalon</a></li>
<li><a href="../classes/Nerve.html">Nerve</a></li>
<li><a href="../classes/NewsArticle.html">NewsArticle</a></li>
<li><a href="../classes/NewsMediaOrganization.html">NewsMediaOrganization</a></li>
<li><a href="../classes/Newspaper.html">Newspaper</a></li>
<li><a href="../classes/NGO.html">NGO</a></li>
<li><a href="../classes/NightClub.html">NightClub</a></li>
<li><a href="../classes/NLNonprofitType.html">NLNonprofitType</a></li>
<li><a href="../classes/NonprofitType.html">NonprofitType</a></li>
<li><a href="../classes/Notary.html">Notary</a></li>
<li><a href="../classes/NoteDigitalDocument.html">NoteDigitalDocument</a></li>
<li><a href="../classes/NutritionInformation.html">NutritionInformation</a></li>
<li><a href="../classes/Observation.html">Observation</a></li>
<li><a href="../classes/Occupation.html">Occupation</a></li>
<li><a href="../classes/OccupationalExperienceRequirements.html">OccupationalExperienceRequirements</a></li>
<li><a href="../classes/OccupationalTherapy.html">OccupationalTherapy</a></li>
<li><a href="../classes/OccupationClassification.html">OccupationClassification</a></li>
<li><a href="../classes/OceanBodyOfWater.html">OceanBodyOfWater</a></li>
<li><a href="../classes/Offer.html">Offer</a></li>
<li><a href="../classes/OfferAction.html">OfferAction</a></li>
<li><a href="../classes/OfferCatalog.html">OfferCatalog</a></li>
<li><a href="../classes/OfferForLease.html">OfferForLease</a></li>
<li><a href="../classes/OfferForPurchase.html">OfferForPurchase</a></li>
<li><a href="../classes/OfferItemCondition.html">OfferItemCondition</a></li>
<li><a href="../classes/OfferShippingDetails.html">OfferShippingDetails</a></li>
<li><a href="../classes/OfficeEquipmentStore.html">OfficeEquipmentStore</a></li>
<li><a href="../classes/OnDemandEvent.html">OnDemandEvent</a></li>
<li><a href="../classes/OpenBadge.html">OpenBadge</a></li>
<li><a href="../classes/OpeningHoursSpecification.html">OpeningHoursSpecification</a></li>
<li><a href="../classes/OpinionNewsArticle.html">OpinionNewsArticle</a></li>
<li><a href="../classes/Optician.html">Optician</a></li>
<li><a href="../classes/Order.html">Order</a></li>
<li><a href="../classes/OrderAction.html">OrderAction</a></li>
<li><a href="../classes/OrderedCollection.html">OrderedCollection</a></li>
<li><a href="../classes/OrderItem.html">OrderItem</a></li>
<li><a href="../classes/OrderStatus.html">OrderStatus</a></li>
<li><a href="../classes/Organization.html">Organization</a></li>
<li><a href="../classes/OrganizationRole.html">OrganizationRole</a></li>
<li><a href="../classes/OrganizeAction.html">OrganizeAction</a></li>
<li><a href="../classes/OutletStore.html">OutletStore</a></li>
<li><a href="../classes/OwnershipInfo.html">OwnershipInfo</a></li>
<li><a href="../classes/PaintAction.html">PaintAction</a></li>
<li><a href="../classes/Painting.html">Painting</a></li>
<li><a href="../classes/PalliativeProcedure.html">PalliativeProcedure</a></li>
<li><a href="../classes/ParcelDelivery.html">ParcelDelivery</a></li>
<li><a href="../classes/ParentAudience.html">ParentAudience</a></li>
<li><a href="../classes/Park.html">Park</a></li>
<li><a href="../classes/ParkingFacility.html">ParkingFacility</a></li>
<li><a href="../classes/PathologyTest.html">PathologyTest</a></li>
<li><a href="../classes/Pathway.html">Pathway</a></li>
<li><a href="../classes/PathwayComponent.html">PathwayComponent</a></li>
<li><a href="../classes/PathwaySet.html">PathwaySet</a></li>
<li><a href="../classes/Patient.html">Patient</a></li>
<li><a href="../classes/PawnShop.html">PawnShop</a></li>
<li><a href="../classes/PayAction.html">PayAction</a></li>
<li><a href="../classes/PaymentCard.html">PaymentCard</a></li>
<li><a href="../classes/PaymentChargeSpecification.html">PaymentChargeSpecification</a></li>
<li><a href="../classes/PaymentMethod.html">PaymentMethod</a></li>
<li><a href="../classes/PaymentService.html">PaymentService</a></li>
<li><a href="../classes/PaymentStatusType.html">PaymentStatusType</a></li>
<li><a href="../classes/PeopleAudience.html">PeopleAudience</a></li>
<li><a href="../classes/PerformAction.html">PerformAction</a></li>
<li><a href="../classes/PerformanceRole.html">PerformanceRole</a></li>
<li><a href="../classes/PerformingArtsTheater.html">PerformingArtsTheater</a></li>
<li><a href="../classes/PerformingGroup.html">PerformingGroup</a></li>
<li><a href="../classes/Periodical.html">Periodical</a></li>
<li><a href="../classes/Permit.html">Permit</a></li>
<li><a href="../classes/Person.html">Person</a></li>
<li><a href="../classes/PetStore.html">PetStore</a></li>
<li><a href="../classes/Pharmacy.html">Pharmacy</a></li>
<li><a href="../classes/Photograph.html">Photograph</a></li>
<li><a href="../classes/PhotographAction.html">PhotographAction</a></li>
<li><a href="../classes/PhysicalActivity.html">PhysicalActivity</a></li>
<li><a href="../classes/PhysicalActivityCategory.html">PhysicalActivityCategory</a></li>
<li><a href="../classes/PhysicalExam.html">PhysicalExam</a></li>
<li><a href="../classes/PhysicalTherapy.html">PhysicalTherapy</a></li>
<li><a href="../classes/Physician.html">Physician</a></li>
<li><a href="../classes/Place.html">Place</a></li>
<li><a href="../classes/PlaceOfWorship.html">PlaceOfWorship</a></li>
<li><a href="../classes/PlanAction.html">PlanAction</a></li>
<li><a href="../classes/Play.html">Play</a></li>
<li><a href="../classes/PlayAction.html">PlayAction</a></li>
<li><a href="../classes/Playground.html">Playground</a></li>
<li><a href="../classes/Plumber.html">Plumber</a></li>
<li><a href="../classes/PodcastEpisode.html">PodcastEpisode</a></li>
<li><a href="../classes/PodcastSeason.html">PodcastSeason</a></li>
<li><a href="../classes/PodcastSeries.html">PodcastSeries</a></li>
<li><a href="../classes/PoliceStation.html">PoliceStation</a></li>
<li><a href="../classes/Pond.html">Pond</a></li>
<li><a href="../classes/PostalAddress.html">PostalAddress</a></li>
<li><a href="../classes/PostalCodeRangeSpecification.html">PostalCodeRangeSpecification</a></li>
<li><a href="../classes/Poster.html">Poster</a></li>
<li><a href="../classes/PostOffice.html">PostOffice</a></li>
<li><a href="../classes/PreOrderAction.html">PreOrderAction</a></li>
<li><a href="../classes/PrependAction.html">PrependAction</a></li>
<li><a href="../classes/Preschool.html">Preschool</a></li>
<li><a href="../classes/PresentationDigitalDocument.html">PresentationDigitalDocument</a></li>
<li><a href="../classes/PreventionIndication.html">PreventionIndication</a></li>
<li><a href="../classes/PriceComponentTypeEnumeration.html">PriceComponentTypeEnumeration</a></li>
<li><a href="../classes/PriceSpecification.html">PriceSpecification</a></li>
<li><a href="../classes/PriceTypeEnumeration.html">PriceTypeEnumeration</a></li>
<li><a href="../classes/ProcessProfile.html">ProcessProfile</a></li>
<li><a href="../classes/Product.html">Product</a></li>
<li><a href="../classes/ProductCollection.html">ProductCollection</a></li>
<li><a href="../classes/ProductGroup.html">ProductGroup</a></li>
<li><a href="../classes/ProductModel.html">ProductModel</a></li>
<li><a href="../classes/ProductReturnEnumeration.html">ProductReturnEnumeration</a></li>
<li><a href="../classes/ProductReturnPolicy.html">ProductReturnPolicy</a></li>
<li><a href="../classes/ProfessionalDoctorate.html">ProfessionalDoctorate</a></li>
<li><a href="../classes/ProfessionalService.html">ProfessionalService</a></li>
<li><a href="../classes/ProficiencyScale.html">ProficiencyScale</a></li>
<li><a href="../classes/ProfilePage.html">ProfilePage</a></li>
<li><a href="../classes/ProgramMembership.html">ProgramMembership</a></li>
<li><a href="../classes/ProgressionLevel.html">ProgressionLevel</a></li>
<li><a href="../classes/ProgressionModel.html">ProgressionModel</a></li>
<li><a href="../classes/Project.html">Project</a></li>
<li><a href="../classes/PronounceableText.html">PronounceableText</a></li>
<li><a href="../classes/Property.html">Property</a></li>
<li><a href="../classes/PropertyValue.html">PropertyValue</a></li>
<li><a href="../classes/PropertyValueSpecification.html">PropertyValueSpecification</a></li>
<li><a href="../classes/PsychologicalTreatment.html">PsychologicalTreatment</a></li>
<li><a href="../classes/PublicationEvent.html">PublicationEvent</a></li>
<li><a href="../classes/PublicationIssue.html">PublicationIssue</a></li>
<li><a href="../classes/PublicationVolume.html">PublicationVolume</a></li>
<li><a href="../classes/PublicSwimmingPool.html">PublicSwimmingPool</a></li>
<li><a href="../classes/PublicToilet.html">PublicToilet</a></li>
<li><a href="../classes/QACredentialOrganization.html">QACredentialOrganization</a></li>
<li><a href="../classes/QAPage.html">QAPage</a></li>
<li><a href="../classes/QualitativeValue.html">QualitativeValue</a></li>
<li><a href="../classes/QualityAssuranceCredential.html">QualityAssuranceCredential</a></li>
<li><a href="../classes/QuantitativeValue.html">QuantitativeValue</a></li>
<li><a href="../classes/QuantitativeValueDistribution.html">QuantitativeValueDistribution</a></li>
<li><a href="../classes/Quantity.html">Quantity</a></li>
<li><a href="../classes/Question.html">Question</a></li>
<li><a href="../classes/Quiz.html">Quiz</a></li>
<li><a href="../classes/Quotation.html">Quotation</a></li>
<li><a href="../classes/QuoteAction.html">QuoteAction</a></li>
<li><a href="../classes/RadiationTherapy.html">RadiationTherapy</a></li>
<li><a href="../classes/RadioBroadcastService.html">RadioBroadcastService</a></li>
<li><a href="../classes/RadioChannel.html">RadioChannel</a></li>
<li><a href="../classes/RadioClip.html">RadioClip</a></li>
<li><a href="../classes/RadioEpisode.html">RadioEpisode</a></li>
<li><a href="../classes/RadioSeason.html">RadioSeason</a></li>
<li><a href="../classes/RadioSeries.html">RadioSeries</a></li>
<li><a href="../classes/RadioStation.html">RadioStation</a></li>
<li><a href="../classes/Rating.html">Rating</a></li>
<li><a href="../classes/ReactAction.html">ReactAction</a></li>
<li><a href="../classes/ReadAction.html">ReadAction</a></li>
<li><a href="../classes/RealEstateAgent.html">RealEstateAgent</a></li>
<li><a href="../classes/RealEstateListing.html">RealEstateListing</a></li>
<li><a href="../classes/ReceiveAction.html">ReceiveAction</a></li>
<li><a href="../classes/Recipe.html">Recipe</a></li>
<li><a href="../classes/RecognizeAction.html">RecognizeAction</a></li>
<li><a href="../classes/Recommendation.html">Recommendation</a></li>
<li><a href="../classes/RecommendedDoseSchedule.html">RecommendedDoseSchedule</a></li>
<li><a href="../classes/RecyclingCenter.html">RecyclingCenter</a></li>
<li><a href="../classes/RefundTypeEnumeration.html">RefundTypeEnumeration</a></li>
<li><a href="../classes/RegisterAction.html">RegisterAction</a></li>
<li><a href="../classes/RegulateAction.html">RegulateAction</a></li>
<li><a href="../classes/RejectAction.html">RejectAction</a></li>
<li><a href="../classes/Relation.html">Relation</a></li>
<li><a href="../classes/RenewAction.html">RenewAction</a></li>
<li><a href="../classes/RentAction.html">RentAction</a></li>
<li><a href="../classes/RentalCarReservation.html">RentalCarReservation</a></li>
<li><a href="../classes/RepaymentSpecification.html">RepaymentSpecification</a></li>
<li><a href="../classes/ReplaceAction.html">ReplaceAction</a></li>
<li><a href="../classes/ReplyAction.html">ReplyAction</a></li>
<li><a href="../classes/Report.html">Report</a></li>
<li><a href="../classes/ReportageNewsArticle.html">ReportageNewsArticle</a></li>
<li><a href="../classes/ReportedDoseSchedule.html">ReportedDoseSchedule</a></li>
<li><a href="../classes/ResearchDoctorate.html">ResearchDoctorate</a></li>
<li><a href="../classes/Researcher.html">Researcher</a></li>
<li><a href="../classes/ResearchProject.html">ResearchProject</a></li>
<li><a href="../classes/Reservation.html">Reservation</a></li>
<li><a href="../classes/ReservationPackage.html">ReservationPackage</a></li>
<li><a href="../classes/ReservationStatusType.html">ReservationStatusType</a></li>
<li><a href="../classes/ReserveAction.html">ReserveAction</a></li>
<li><a href="../classes/Reservoir.html">Reservoir</a></li>
<li><a href="../classes/Residence.html">Residence</a></li>
<li><a href="../classes/Resort.html">Resort</a></li>
<li><a href="../classes/Restaurant.html">Restaurant</a></li>
<li><a href="../classes/RestrictedDiet.html">RestrictedDiet</a></li>
<li><a href="../classes/ResumeAction.html">ResumeAction</a></li>
<li><a href="../classes/ReturnAction.html">ReturnAction</a></li>
<li><a href="../classes/ReturnFeesEnumeration.html">ReturnFeesEnumeration</a></li>
<li><a href="../classes/Review.html">Review</a></li>
<li><a href="../classes/ReviewAction.html">ReviewAction</a></li>
<li><a href="../classes/ReviewNewsArticle.html">ReviewNewsArticle</a></li>
<li><a href="../classes/RevocationProfile.html">RevocationProfile</a></li>
<li><a href="../classes/RevokeAction.html">RevokeAction</a></li>
<li><a href="../classes/RightsAction.html">RightsAction</a></li>
<li><a href="../classes/RiverBodyOfWater.html">RiverBodyOfWater</a></li>
<li><a href="../classes/Role.html">Role</a></li>
<li><a href="../classes/Rollup.html">Rollup</a></li>
<li><a href="../classes/RollupRule.html">RollupRule</a></li>
<li><a href="../classes/RoofingContractor.html">RoofingContractor</a></li>
<li><a href="../classes/Room.html">Room</a></li>
<li><a href="../classes/RsvpAction.html">RsvpAction</a></li>
<li><a href="../classes/RsvpResponseType.html">RsvpResponseType</a></li>
<li><a href="../classes/RuleSet.html">RuleSet</a></li>
<li><a href="../classes/RuleSetProfile.html">RuleSetProfile</a></li>
<li><a href="../classes/RVPark.html">RVPark</a></li>
<li><a href="../classes/SaleEvent.html">SaleEvent</a></li>
<li><a href="../classes/SatiricalArticle.html">SatiricalArticle</a></li>
<li><a href="../classes/Schedule.html">Schedule</a></li>
<li><a href="../classes/ScheduleAction.html">ScheduleAction</a></li>
<li><a href="../classes/ScholarlyArticle.html">ScholarlyArticle</a></li>
<li><a href="../classes/School.html">School</a></li>
<li><a href="../classes/SchoolDistrict.html">SchoolDistrict</a></li>
<li><a href="../classes/ScreeningEvent.html">ScreeningEvent</a></li>
<li><a href="../classes/Sculpture.html">Sculpture</a></li>
<li><a href="../classes/SeaBodyOfWater.html">SeaBodyOfWater</a></li>
<li><a href="../classes/SearchAction.html">SearchAction</a></li>
<li><a href="../classes/SearchResultsPage.html">SearchResultsPage</a></li>
<li><a href="../classes/Season.html">Season</a></li>
<li><a href="../classes/Seat.html">Seat</a></li>
<li><a href="../classes/SecondarySchoolDiploma.html">SecondarySchoolDiploma</a></li>
<li><a href="../classes/SeekToAction.html">SeekToAction</a></li>
<li><a href="../classes/SelectionComponent.html">SelectionComponent</a></li>
<li><a href="../classes/SelfStorage.html">SelfStorage</a></li>
<li><a href="../classes/SellAction.html">SellAction</a></li>
<li><a href="../classes/SendAction.html">SendAction</a></li>
<li><a href="../classes/Series.html">Series</a></li>
<li><a href="../classes/Service.html">Service</a></li>
<li><a href="../classes/ServiceChannel.html">ServiceChannel</a></li>
<li><a href="../classes/ShareAction.html">ShareAction</a></li>
<li><a href="../classes/SheetMusic.html">SheetMusic</a></li>
<li><a href="../classes/ShippingDeliveryTime.html">ShippingDeliveryTime</a></li>
<li><a href="../classes/ShippingRateSettings.html">ShippingRateSettings</a></li>
<li><a href="../classes/ShoeStore.html">ShoeStore</a></li>
<li><a href="../classes/ShoppingCenter.html">ShoppingCenter</a></li>
<li><a href="../classes/ShortStory.html">ShortStory</a></li>
<li><a href="../classes/SingleFamilyResidence.html">SingleFamilyResidence</a></li>
<li><a href="../classes/SiteNavigationElement.html">SiteNavigationElement</a></li>
<li><a href="../classes/SizeGroupEnumeration.html">SizeGroupEnumeration</a></li>
<li><a href="../classes/SizeSpecification.html">SizeSpecification</a></li>
<li><a href="../classes/SizeSystemEnumeration.html">SizeSystemEnumeration</a></li>
<li><a href="../classes/Skill.html">Skill</a></li>
<li><a href="../classes/SkiResort.html">SkiResort</a></li>
<li><a href="../classes/SocialEvent.html">SocialEvent</a></li>
<li><a href="../classes/SocialMediaPosting.html">SocialMediaPosting</a></li>
<li><a href="../classes/SoftwareApplication.html">SoftwareApplication</a></li>
<li><a href="../classes/SoftwareSourceCode.html">SoftwareSourceCode</a></li>
<li><a href="../classes/SolveMathAction.html">SolveMathAction</a></li>
<li><a href="../classes/SomeProducts.html">SomeProducts</a></li>
<li><a href="../classes/SpeakableSpecification.html">SpeakableSpecification</a></li>
<li><a href="../classes/SpecialAnnouncement.html">SpecialAnnouncement</a></li>
<li><a href="../classes/Specialty.html">Specialty</a></li>
<li><a href="../classes/SportingGoodsStore.html">SportingGoodsStore</a></li>
<li><a href="../classes/SportsActivityLocation.html">SportsActivityLocation</a></li>
<li><a href="../classes/SportsClub.html">SportsClub</a></li>
<li><a href="../classes/SportsEvent.html">SportsEvent</a></li>
<li><a href="../classes/SportsOrganization.html">SportsOrganization</a></li>
<li><a href="../classes/SportsTeam.html">SportsTeam</a></li>
<li><a href="../classes/SpreadsheetDigitalDocument.html">SpreadsheetDigitalDocument</a></li>
<li><a href="../classes/StadiumOrArena.html">StadiumOrArena</a></li>
<li><a href="../classes/State.html">State</a></li>
<li><a href="../classes/StatisticalPopulation.html">StatisticalPopulation</a></li>
<li><a href="../classes/StatusEnumeration.html">StatusEnumeration</a></li>
<li><a href="../classes/SteeringPositionValue.html">SteeringPositionValue</a></li>
<li><a href="../classes/Store.html">Store</a></li>
<li><a href="../classes/StructuredValue.html">StructuredValue</a></li>
<li><a href="../classes/StupidType.html">StupidType</a></li>
<li><a href="../classes/SubscribeAction.html">SubscribeAction</a></li>
<li><a href="../classes/Substance.html">Substance</a></li>
<li><a href="../classes/SubwayStation.html">SubwayStation</a></li>
<li><a href="../classes/Suite.html">Suite</a></li>
<li><a href="../classes/SuperficialAnatomy.html">SuperficialAnatomy</a></li>
<li><a href="../classes/SurgicalProcedure.html">SurgicalProcedure</a></li>
<li><a href="../classes/SuspendAction.html">SuspendAction</a></li>
<li><a href="../classes/Synagogue.html">Synagogue</a></li>
<li><a href="../classes/Table.html">Table</a></li>
<li><a href="../classes/TakeAction.html">TakeAction</a></li>
<li><a href="../classes/Task.html">Task</a></li>
<li><a href="../classes/TattooParlor.html">TattooParlor</a></li>
<li><a href="../classes/Taxi.html">Taxi</a></li>
<li><a href="../classes/TaxiReservation.html">TaxiReservation</a></li>
<li><a href="../classes/TaxiService.html">TaxiService</a></li>
<li><a href="../classes/TaxiStand.html">TaxiStand</a></li>
<li><a href="../classes/TechArticle.html">TechArticle</a></li>
<li><a href="../classes/TelevisionChannel.html">TelevisionChannel</a></li>
<li><a href="../classes/TelevisionStation.html">TelevisionStation</a></li>
<li><a href="../classes/TennisComplex.html">TennisComplex</a></li>
<li><a href="../classes/TextDigitalDocument.html">TextDigitalDocument</a></li>
<li><a href="../classes/TheaterEvent.html">TheaterEvent</a></li>
<li><a href="../classes/TheaterGroup.html">TheaterGroup</a></li>
<li><a href="../classes/TherapeuticProcedure.html">TherapeuticProcedure</a></li>
<li><a href="../classes/Thesis.html">Thesis</a></li>
<li><a href="../classes/Thing.html">Thing</a></li>
<li><a href="../classes/this.html">this</a></li>
<li><a href="../classes/Ticket.html">Ticket</a></li>
<li><a href="../classes/TieAction.html">TieAction</a></li>
<li><a href="../classes/TipAction.html">TipAction</a></li>
<li><a href="../classes/TireShop.html">TireShop</a></li>
<li><a href="../classes/TouristAttraction.html">TouristAttraction</a></li>
<li><a href="../classes/TouristDestination.html">TouristDestination</a></li>
<li><a href="../classes/TouristInformationCenter.html">TouristInformationCenter</a></li>
<li><a href="../classes/TouristTrip.html">TouristTrip</a></li>
<li><a href="../classes/ToyStore.html">ToyStore</a></li>
<li><a href="../classes/TrackAction.html">TrackAction</a></li>
<li><a href="../classes/TradeAction.html">TradeAction</a></li>
<li><a href="../classes/TrainReservation.html">TrainReservation</a></li>
<li><a href="../classes/TrainStation.html">TrainStation</a></li>
<li><a href="../classes/TrainTrip.html">TrainTrip</a></li>
<li><a href="../classes/TransferAction.html">TransferAction</a></li>
<li><a href="../classes/TransferValueProfile.html">TransferValueProfile</a></li>
<li><a href="../classes/TravelAction.html">TravelAction</a></li>
<li><a href="../classes/TravelAgency.html">TravelAgency</a></li>
<li><a href="../classes/TreatmentIndication.html">TreatmentIndication</a></li>
<li><a href="../classes/Trip.html">Trip</a></li>
<li><a href="../classes/Triple.html">Triple</a></li>
<li><a href="../classes/TVClip.html">TVClip</a></li>
<li><a href="../classes/TVEpisode.html">TVEpisode</a></li>
<li><a href="../classes/TVSeason.html">TVSeason</a></li>
<li><a href="../classes/TVSeries.html">TVSeries</a></li>
<li><a href="../classes/TypeAndQuantityNode.html">TypeAndQuantityNode</a></li>
<li><a href="../classes/UKNonprofitType.html">UKNonprofitType</a></li>
<li><a href="../classes/UnitPriceSpecification.html">UnitPriceSpecification</a></li>
<li><a href="../classes/UnRegisterAction.html">UnRegisterAction</a></li>
<li><a href="../classes/UpdateAction.html">UpdateAction</a></li>
<li><a href="../classes/UseAction.html">UseAction</a></li>
<li><a href="../classes/UserBlocks.html">UserBlocks</a></li>
<li><a href="../classes/UserCheckins.html">UserCheckins</a></li>
<li><a href="../classes/UserComments.html">UserComments</a></li>
<li><a href="../classes/UserDownloads.html">UserDownloads</a></li>
<li><a href="../classes/UserInteraction.html">UserInteraction</a></li>
<li><a href="../classes/UserLikes.html">UserLikes</a></li>
<li><a href="../classes/UserPageVisits.html">UserPageVisits</a></li>
<li><a href="../classes/UserPlays.html">UserPlays</a></li>
<li><a href="../classes/UserPlusOnes.html">UserPlusOnes</a></li>
<li><a href="../classes/UserReview.html">UserReview</a></li>
<li><a href="../classes/UserTweets.html">UserTweets</a></li>
<li><a href="../classes/USNonprofitType.html">USNonprofitType</a></li>
<li><a href="../classes/ValueProfile.html">ValueProfile</a></li>
<li><a href="../classes/Vehicle.html">Vehicle</a></li>
<li><a href="../classes/Vein.html">Vein</a></li>
<li><a href="../classes/VerificationServiceProfile.html">VerificationServiceProfile</a></li>
<li><a href="../classes/Vessel.html">Vessel</a></li>
<li><a href="../classes/VeterinaryCare.html">VeterinaryCare</a></li>
<li><a href="../classes/VideoGallery.html">VideoGallery</a></li>
<li><a href="../classes/VideoGame.html">VideoGame</a></li>
<li><a href="../classes/VideoGameClip.html">VideoGameClip</a></li>
<li><a href="../classes/VideoGameSeries.html">VideoGameSeries</a></li>
<li><a href="../classes/VideoObject.html">VideoObject</a></li>
<li><a href="../classes/ViewAction.html">ViewAction</a></li>
<li><a href="../classes/VirtualLocation.html">VirtualLocation</a></li>
<li><a href="../classes/VisualArtsEvent.html">VisualArtsEvent</a></li>
<li><a href="../classes/VisualArtwork.html">VisualArtwork</a></li>
<li><a href="../classes/VitalSign.html">VitalSign</a></li>
<li><a href="../classes/Volcano.html">Volcano</a></li>
<li><a href="../classes/VoteAction.html">VoteAction</a></li>
<li><a href="../classes/WantAction.html">WantAction</a></li>
<li><a href="../classes/WarrantyPromise.html">WarrantyPromise</a></li>
<li><a href="../classes/WarrantyScope.html">WarrantyScope</a></li>
<li><a href="../classes/WatchAction.html">WatchAction</a></li>
<li><a href="../classes/Waterfall.html">Waterfall</a></li>
<li><a href="../classes/WearableMeasurementTypeEnumeration.html">WearableMeasurementTypeEnumeration</a></li>
<li><a href="../classes/WearableSizeGroupEnumeration.html">WearableSizeGroupEnumeration</a></li>
<li><a href="../classes/WearableSizeSystemEnumeration.html">WearableSizeSystemEnumeration</a></li>
<li><a href="../classes/WearAction.html">WearAction</a></li>
<li><a href="../classes/WebAPI.html">WebAPI</a></li>
<li><a href="../classes/WebApplication.html">WebApplication</a></li>
<li><a href="../classes/WebContent.html">WebContent</a></li>
<li><a href="../classes/WebPage.html">WebPage</a></li>
<li><a href="../classes/WebPageElement.html">WebPageElement</a></li>
<li><a href="../classes/WebSite.html">WebSite</a></li>
<li><a href="../classes/WholesaleStore.html">WholesaleStore</a></li>
<li><a href="../classes/WinAction.html">WinAction</a></li>
<li><a href="../classes/Winery.html">Winery</a></li>
<li><a href="../classes/WorkBasedProgram.html">WorkBasedProgram</a></li>
<li><a href="../classes/WorkersUnion.html">WorkersUnion</a></li>
<li><a href="../classes/WorkExperienceComponent.html">WorkExperienceComponent</a></li>
<li><a href="../classes/WorkRole.html">WorkRole</a></li>
<li><a href="../classes/WPAdBlock.html">WPAdBlock</a></li>
<li><a href="../classes/WPFooter.html">WPFooter</a></li>
<li><a href="../classes/WPHeader.html">WPHeader</a></li>
<li><a href="../classes/WPSideBar.html">WPSideBar</a></li>
<li><a href="../classes/WriteAction.html">WriteAction</a></li>
<li><a href="../classes/XPathType.html">XPathType</a></li>
<li><a href="../classes/Zoo.html">Zoo</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/com.eduworks.html">com.eduworks</a></li>
<li><a href="../modules/com.eduworks.ec.html">com.eduworks.ec</a></li>
<li><a href="../modules/org.cassproject.html">org.cassproject</a></li>
<li><a href="../modules/org.credentialengine.html">org.credentialengine</a></li>
<li><a href="../modules/org.json.ld.html">org.json.ld</a></li>
<li><a href="../modules/org.schema.html">org.schema</a></li>
<li><a href="../modules/org.w3.skos.html">org.w3.skos</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: node_modules\cassproject\src\org\schema\TechArticle.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
const schema = {};
schema.Article = require("./Article.js");
/**
* Schema.org/TechArticle
* A technical article - Example: How-to (task) topics, step-by-step, procedural troubleshooting, specifications, etc.
*
* @author schema.org
* @class TechArticle
* @module org.schema
* @extends Article
*/
module.exports = class TechArticle extends schema.Article {
/**
* Constructor, automatically sets @context and @type.
*
* @constructor
*/
constructor() {
super();
this.setContextAndType("http://schema.org/","TechArticle");
}
/**
* Schema.org/proficiencyLevel
* Proficiency needed for this content; expected values: 'Beginner', 'Expert'.
*
* @property proficiencyLevel
* @type Text
*/
proficiencyLevel;
/**
* Schema.org/dependencies
* Prerequisites needed to fulfill steps in article.
*
* @property dependencies
* @type Text
*/
dependencies;
}
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>
| {'content_hash': 'edf9e68cf94ded6d3c8c648da26d3957', 'timestamp': '', 'source': 'github', 'line_count': 1185, 'max_line_length': 146, 'avg_line_length': 91.31139240506329, 'alnum_prop': 0.4792336697349451, 'repo_name': 'Eduworks/CASS', 'id': '7c719748fca4b972e452c6d4caa895985972e696', 'size': '108204', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/files/node_modules_cassproject_src_org_schema_TechArticle.js.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '52593'}, {'name': 'HTML', 'bytes': '51035'}, {'name': 'JavaScript', 'bytes': '6444138'}]} |
class BeyondmilesController < ApplicationController
def about
end
def contact
end
end
| {'content_hash': '6209eda3fc05e7e504897c71598fc148', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 51, 'avg_line_length': 13.571428571428571, 'alnum_prop': 0.7789473684210526, 'repo_name': 'achen116/swb-aeroplan', 'id': '64b36765c9d29756019ac3bcbda782427a67dc1f', 'size': '95', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/controllers/beyondmiles_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4801'}, {'name': 'HTML', 'bytes': '17892'}, {'name': 'JavaScript', 'bytes': '921'}, {'name': 'Ruby', 'bytes': '46724'}]} |
using System.IO;
using System.Reflection;
using Castle.MonoRail.Framework;
using NUnit.Framework;
using Spark.FileSystem;
namespace Castle.MonoRail.Views.Spark.Tests.ViewComponents
{
[TestFixture]
public class ViewComponentRenderViewTests : BaseViewComponentTests
{
public override void Init()
{
base.Init();
viewComponentFactory.Registry.AddViewComponent("Widget", typeof(WidgetComponent));
}
[Test]
public void ComponentCallingRenderView()
{
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(string.Format("Home{0}ComponentCallingRenderView.spark", Path.DirectorySeparatorChar),
writer, engineContext, controller, controllerContext);
var output = writer.ToString();
Assert.IsTrue(output.Contains("This is a widget"));
}
[Test]
public void ComponentRenderViewWithParameters()
{
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(
string.Format("Home{0}ComponentRenderViewWithParameters.spark", Path.DirectorySeparatorChar), writer,
engineContext, controller, controllerContext);
var output = writer.ToString();
Assert.IsTrue(output.Contains("Mode Alpha and 123"));
Assert.IsTrue(output.Contains("Mode Beta and 456"));
}
[Test]
public void ComponentRenderViewWithContent()
{
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(string.Format("Home{0}ComponentRenderViewWithContent.spark", Path.DirectorySeparatorChar),
writer, engineContext, controller, controllerContext);
var output = writer.ToString();
Assert.IsTrue(output.Contains("Mode Delta and 789"));
Assert.IsTrue(output.Contains("<p class=\"message\">!!Delta!!</p>"));
}
[Test]
public void ComponentRenderViewFromEmbeddedResource()
{
viewComponentFactory.Registry.AddViewComponent("UseEmbeddedViews", typeof(UseEmbeddedViews));
var embeddedViewFolder = new EmbeddedViewFolder(
Assembly.Load("Castle.MonoRail.Views.Spark.Tests"),
"Castle.MonoRail.Views.Spark.Tests.EmbeddedViews");
engine.ViewFolder = engine.ViewFolder.Append(embeddedViewFolder);
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(
string.Format("Home{0}ComponentRenderViewFromEmbeddedResource.spark", Path.DirectorySeparatorChar),
writer, engineContext, controller, controllerContext);
mocks.VerifyAll();
var content = writer.ToString();
Assert.That(content.Contains("<p>This was embedded</p>"));
}
[Test]
public void ComponentRenderViewSharesOnceFlags()
{
viewComponentFactory.Registry.AddViewComponent("OnceWidget", typeof(OnceWidget));
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(
string.Format("Home{0}ComponentRenderViewSharesOnceFlags.spark", Path.DirectorySeparatorChar), writer,
engineContext, controller, controllerContext);
mocks.VerifyAll();
var content = writer.ToString();
Assert.That(content.Contains("<p>ok1</p>"));
Assert.That(content.Contains("<p>ok2</p>"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void ComponentRenderViewUsesGlobalSpark()
{
viewComponentFactory.Registry.AddViewComponent("UsesGlobalSpark", typeof(UsesGlobalSpark));
mocks.ReplayAll();
var writer = new StringWriter();
factory.Process(
string.Format("Home{0}ComponentRenderViewUsesGlobalSpark.spark", Path.DirectorySeparatorChar), writer,
engineContext, controller, controllerContext);
mocks.VerifyAll();
var content = writer.ToString();
Assert.That(content.Contains("<p>ok1</p>"));
}
[ViewComponentDetails("WidgetComponent")]
public class WidgetComponent : ViewComponent
{
[ViewComponentParam]
public string Mode { get; set; }
[ViewComponentParam]
public string ExtraData { get; set; }
public override void Render()
{
if (string.IsNullOrEmpty(Mode))
{
RenderView("default");
return;
}
PropertyBag["Mode"] = Mode;
PropertyBag["ExtraData"] = ExtraData;
RenderView("withextradata");
}
}
[ViewComponentDetails("UseEmbeddedViews")]
public class UseEmbeddedViews : ViewComponent
{
public override void Render()
{
RenderView("default");
}
}
[ViewComponentDetails("OnceWidget")]
public class OnceWidget : ViewComponent
{
public override void Render()
{
RenderView("default");
}
}
[ViewComponentDetails("UsesGlobalSpark")]
public class UsesGlobalSpark : ViewComponent
{
public override void Render()
{
RenderView("default");
}
}
}
} | {'content_hash': 'dd419861654265bc1c1d23bed0451c93', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 118, 'avg_line_length': 33.18181818181818, 'alnum_prop': 0.5621575342465753, 'repo_name': 'RobertTheGrey/spark', 'id': '51e2ec248a07fc8d2245f3caa8dbd831f57329d2', 'size': '6480', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Castle.MonoRail.Views.Spark.Tests/ViewComponents/ViewComponentRenderViewTests.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '8727'}, {'name': 'C', 'bytes': '1948'}, {'name': 'C#', 'bytes': '2303483'}, {'name': 'C++', 'bytes': '47675'}, {'name': 'CSS', 'bytes': '134890'}, {'name': 'HTML', 'bytes': '162933'}, {'name': 'Java', 'bytes': '9426'}, {'name': 'JavaScript', 'bytes': '71783'}, {'name': 'Pascal', 'bytes': '2406'}, {'name': 'Shell', 'bytes': '1999'}, {'name': 'Visual Basic', 'bytes': '22970'}, {'name': 'XSLT', 'bytes': '12347'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.8 (2)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project> | {'content_hash': '65c67542814e14f2b8e3cb2ae1a11414', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 165, 'avg_line_length': 48.361111111111114, 'alnum_prop': 0.6542217116599656, 'repo_name': 'craynafinal/libGDX_baby-trader', 'id': '9fc28d4dcc7dbdecf32b384ef2fd5470fac29b26', 'size': '1741', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/misc.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4979'}, {'name': 'Java', 'bytes': '128778'}]} |
package org.apache.ivy.plugins.resolver;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;
import org.apache.ivy.core.cache.ArtifactOrigin;
import org.apache.ivy.core.cache.RepositoryCacheManager;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.module.descriptor.DependencyDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.report.ArtifactDownloadReport;
import org.apache.ivy.core.report.DownloadReport;
import org.apache.ivy.core.resolve.DownloadOptions;
import org.apache.ivy.core.resolve.ResolveData;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.core.search.ModuleEntry;
import org.apache.ivy.core.search.OrganisationEntry;
import org.apache.ivy.core.search.RevisionEntry;
import org.apache.ivy.plugins.namespace.Namespace;
import org.apache.ivy.plugins.resolver.util.ResolvedResource;
/**
*
*/
public interface DependencyResolver {
String getName();
/**
* Should only be used by configurator
*
* @param name
* the new name of the resolver
*/
void setName(String name);
/**
* Resolve a module by id, getting its module descriptor and resolving the revision if it's a
* latest one (i.e. a revision uniquely identifying the revision of a module in the current
* environment - If this revision is not able to identify uniquely the revision of the module
* outside of the current environment, then the resolved revision must begin by ##)
*
* @throws ParseException
*/
ResolvedModuleRevision getDependency(DependencyDescriptor dd, ResolveData data)
throws ParseException;
/**
* Finds the module descriptor for the specified <tt>DependencyDescriptor</tt>.
* If this resolver can't find the module descriptor, <tt>null</tt> is returned.
*
* @param dd the dependency descriptor
* @param data the resolve data
* @return the module descriptor, or <tt>null</tt>
*/
ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data);
/**
* Download artifacts with specified DownloadOptions.
* <p>
* The resolver will always make a best effort, and do not stop when an artifact is not
* available. It rather continue to attempt to download other requested artifacts, and report
* what has been done in the returned DownloadReport.
* </p>
* <p>
* The returned DownloadReport is never <code>null</code>, and always contain an
* {@link ArtifactDownloadReport} for each requested Artifact.
* </p>
*
* @param artifacts
* an array of artifacts to download. Must not be <code>null</code>.
* @param options
* options to apply for this download. Must not be <code>null</code>.
* @return a DownloadReport with details about each Artifact download.
*/
DownloadReport download(Artifact[] artifacts, DownloadOptions options);
/**
* Download an artifact according to the given DownloadOptions.
* <p>
* This methods is an alternative to {@link #download(Artifact[], DownloadOptions)}, which
* locates and downloads a set of artifacts. This method uses an {@link ArtifactOrigin}, and as
* such is only used to materialize an already located Artifact.
* </p>
*
* @param artifact
* the location of the artifact to download. Must not be <code>null</code>.
* @param options
* options to apply for this download. Must not be <code>null</code>.
* @return a report detailing how the download has gone, is never <code>null</code>.
*/
ArtifactDownloadReport download(ArtifactOrigin artifact, DownloadOptions options);
/**
* Returns <code>true</code> if the given artifact can be located by this resolver and
* actually exist.
*
* @param artifact
* the artifact which should be tested.
* @return <code>true</code> if the given artifact can be located by this resolver and
* actually exist.
*/
boolean exists(Artifact artifact);
/**
* Locates the given artifact and returns its location if it can be located by this resolver and
* if it actually exists, or <code>null</code> in other cases.
*
* @param artifact
* the artifact which should be located
* @return the artifact location, or <code>null</code> if it can't be located by this resolver
* or doesn't exist.
*/
ArtifactOrigin locate(Artifact artifact);
void publish(Artifact artifact, File src, boolean overwrite) throws IOException;
void beginPublishTransaction(ModuleRevisionId module, boolean overwrite) throws IOException;
void abortPublishTransaction() throws IOException;
void commitPublishTransaction() throws IOException;
/**
* Reports last resolve failure as Messages
*/
void reportFailure();
/**
* Reports last artifact download failure as Messages
*
* @param art
*/
void reportFailure(Artifact art);
// listing methods, enable to know what is available from this resolver
// the listing methods must only list entries directly
// available from them, no recursion is needed as long as sub resolvers
// are registered in ivy too.
/**
* List all the values the given token can take if other tokens are set as described in the
* otherTokenValues map. For instance, if token = "revision" and the map contains
* "organisation"->"foo" "module"->"bar" The results will be the list of revisions of the module
* bar from the org foo.
* <p>
* Note that listing does not take into account namespaces, and return raw
* information without any namespace transformation. The caller is responsible for calling
* namespace transformation with the Namespace returned by {@link #getNamespace()}.
* </p>
*/
String[] listTokenValues(String token, Map otherTokenValues);
/**
* Same as {@link #listTokenValues(String, Map)} but more generic.
*
* @param tokens
* the tokens of the query
* @param criteria
* the token which have values
* @return the list of token values (Map<Strin, String>[]), must not be <code>null</code>
*/
Map[] listTokenValues(String[] tokens, Map criteria);
OrganisationEntry[] listOrganisations();
ModuleEntry[] listModules(OrganisationEntry org);
RevisionEntry[] listRevisions(ModuleEntry module);
/**
* Returns the namespace associated with this resolver.
* @return the namespace associated with this resolver.
*/
Namespace getNamespace();
void dumpSettings();
void setSettings(ResolverSettings settings);
/**
* Returns the {@link RepositoryCacheManager} used to manage the repository cache associated
* with this dependency resolver.
*
* @return the {@link RepositoryCacheManager} used to manage the repository cache associated
* with this dependency resolver.
*/
RepositoryCacheManager getRepositoryCacheManager();
}
| {'content_hash': '44aaa1b8a0df8c58ba0f387eacb9708d', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 106, 'avg_line_length': 38.38421052631579, 'alnum_prop': 0.6851775675305087, 'repo_name': 'sbt/ivy', 'id': '802344cf2e4d850c74661ee80fc8452ea8991df1', 'size': '8109', 'binary': False, 'copies': '1', 'ref': 'refs/heads/2.3.x-sbt', 'path': 'src/java/org/apache/ivy/plugins/resolver/DependencyResolver.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4371'}, {'name': 'HTML', 'bytes': '93666'}, {'name': 'Java', 'bytes': '3951769'}, {'name': 'Scala', 'bytes': '3237'}, {'name': 'XSLT', 'bytes': '72561'}]} |
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<import resource="database/Spring-Datasource.xml" />
<import resource="film/Spring-Film.xml" />
</beans> | {'content_hash': '39529d828f2833fd9fbf60f044b893d4', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 70, 'avg_line_length': 41.44444444444444, 'alnum_prop': 0.7211796246648794, 'repo_name': 'lsnare/MyFilmDB', 'id': '398a359eefaebccef6f078b9100ba08996685f87', 'size': '373', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/resources/Spring-Module.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3186'}, {'name': 'FreeMarker', 'bytes': '3503'}, {'name': 'Java', 'bytes': '54397'}, {'name': 'JavaScript', 'bytes': '471'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace WmcSoft.Canvas
{
public class CanvasRectTests
{
static ImageSharpCanvas CreateCanvas() {
return new ImageSharpCanvas(400, 200);
}
[Fact]
public void CanFillRect() {
using(var canvas = CreateCanvas()) {
canvas.FillStyle = "green";
canvas.FillRect(10, 10, 100, 100);
}
}
}
}
| {'content_hash': '87f448d5e642429ca7ff0bd106b77587', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 50, 'avg_line_length': 21.44, 'alnum_prop': 0.5839552238805971, 'repo_name': 'vjacquet/WmcSoft', 'id': 'a57cb4cfe4e6ff72c95148ec14fd449dfe747e14', 'size': '538', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'WmcSoft.Drawing/WmcSoft.Canvas.ImageSharp/CanvasRectTests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '6123726'}, {'name': 'Smalltalk', 'bytes': '11132'}]} |
package sa.com.is.utils;
import android.content.Context;
import android.util.Log;
import org.apache.james.mime4j.codec.QuotedPrintableOutputStream;
import org.apache.james.mime4j.util.MimeUtil;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Set;
import sa.com.is.Address;
import sa.com.is.Body;
import sa.com.is.Message;
import sa.com.is.MessagingException;
import sa.com.is.Multipart;
import sa.com.is.filter.Base64;
import sa.com.is.internet.MimeBodyPart;
import sa.com.is.internet.MimeMessage;
import sa.com.is.internet.MimeMessageHelper;
import sa.com.is.internet.MimeMultipart;
import sa.com.is.internet.MimeUtility;
import sa.com.is.internet.TextBody;
import sa.com.is.mailstore.BinaryMemoryBody;
import sa.com.is.message.MessageBuilder;
/**
* Created by snouto on 02/09/15.
*/
public class MimeMessageConverter {
public Message signThatMessage(Message message,Context context)
{
try
{
if(message != null &&message.isSigned())
{
MimeMessage msg = new MimeMessage();
msg.setEncrypted(message.isEncrypted());
msg.setMessageId(message.getMessageId());
msg.setSubject(message.getSubject());
msg.setReplyTo(message.getReplyTo());
msg.setServerExtra(message.getServerExtra());
//copy all headers
msg.setFrom(message.getFrom()[0]);
//copy all reciepents
addRecepients(message, msg);
//copy headers
copyHeaders(message, msg);
//msg.setBody(message.getBody());
ByteArrayOutputStream messageContents = new ByteArrayOutputStream();
ByteArrayOutputStream bodybinary = new ByteArrayOutputStream();
//OutputStream encodedOs = javax.mail.internet.MimeUtility.encode(bodybinary,MimeUtil.ENC_QUOTED_PRINTABLE);
message.getBody().writeTo(messageContents);
// encodedOs.write(messageContents.toByteArray());
MimeMessageHelper.setBody(msg, new TextBody(bodybinary.toString()));
if(MimeUtil.isQuotedPrintableEncoded(bodybinary.toString()))
{
Log.i("MimeMessageConverter","Yes it is quoted-printable");
}else
{
Log.i("MimeMessageConverter","No it is Not quoted-printable");
}
//Create a MimeMultipart of the message body
MimeMultipart msgBody = new MimeMultipart();
msgBody.setSubType("signed");
//Creating a signed MimePart
MimeBodyPart part = new MimeBodyPart();
//name="smime.p7s"
part.addHeader("Content-Type","application/pkcs7-signature;name=\"smime.p7s\"");
part.addHeader("Content-Transfer-Encoding", "base64");
//filename="smime.p7s"
part.addHeader("Content-Disposition", "attachment;filename=\"smime.p7s\"");
part.addHeader("Content-Description", "S/MIME Cryptographic Signature");
//signed Body part
msgBody.addBodyPart(new MimeBodyPart(msg.getBody()));
Body signedBody = new BinaryMemoryBody(EncryptionManager.signMessage(context, bodybinary.toByteArray()),"UTF-8");
//part.setBody(signedBody);
MimeMessageHelper.setBody(part,signedBody);
msgBody.addBodyPart(part);
MimeMessageHelper.setBody(msg,msgBody);
//finally return the message
return msg;
}else throw new Exception("Message can't be null");
}catch (Exception s)
{
Log.e("Signing",s.getMessage());
return null;
}
}
private void copyHeaders(Message source, MimeMessage target) throws Exception{
Set<String> headerNames = source.getHeaderNames();
if(headerNames != null && !headerNames.isEmpty())
{
for(String headerName :headerNames)
{
String[] headerValues = source.getHeader(headerName);
if(headerValues!= null && headerValues.length >0)
{
for(String headerValue :headerValues)
{
target.setHeader(headerName,headerValue);
}
}
}
}
}
private void addRecepients(Message source, MimeMessage target) throws Exception {
Address[] TO = source.getRecipients(Message.RecipientType.TO);
if(TO!= null &&TO.length >0)
{
target.setRecipients(Message.RecipientType.TO,TO);
}
//add CC
Address[] CC = source.getRecipients(Message.RecipientType.CC);
if(CC!=null &&CC.length >0)
{
target.setRecipients(Message.RecipientType.CC,CC);
}
//Add BCC
Address[] BCC = source.getRecipients(Message.RecipientType.BCC);
if(BCC!= null &&BCC.length >0)
{
target.setRecipients(Message.RecipientType.BCC,BCC);
}
}
}
| {'content_hash': 'be891777bf217995e5d343e3d06634f1', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 129, 'avg_line_length': 28.069148936170212, 'alnum_prop': 0.5895395110858442, 'repo_name': 'cliniome/pki', 'id': 'c3ad189bddcd9550f5adb95c3ddfb916523f37ce', 'size': '5277', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'secureClient/src/main/java/sa/com/is/utils/MimeMessageConverter.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '292'}, {'name': 'Java', 'bytes': '3479674'}, {'name': 'Shell', 'bytes': '824'}]} |
'use strict';
module.exports = function(io) {
io.on('connection', function(socket) {
});
};
| {'content_hash': '7fd04bbcbdb799bc0afab5f2fb0b8eca', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 40, 'avg_line_length': 12.375, 'alnum_prop': 0.6060606060606061, 'repo_name': 'DevelopersGuild/dgwebsite2', 'id': '5323e30ff4f9660bf15a98885a0a2d6e86679c7d', 'size': '99', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/events/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '54761'}, {'name': 'HTML', 'bytes': '59420'}, {'name': 'JavaScript', 'bytes': '69004'}, {'name': 'Rich Text Format', 'bytes': '668'}]} |
require "test/unit"
require "etc"
class TestEtc < Test::Unit::TestCase
def test_getlogin
s = Etc.getlogin
return if s == nil
assert(s.is_a?(String), "getlogin must return a String or nil")
assert_predicate(s, :valid_encoding?, "login name should be a valid string")
end
def test_passwd
Etc.passwd do |s|
assert_instance_of(String, s.name)
assert_instance_of(String, s.passwd) if s.respond_to?(:passwd)
assert_kind_of(Integer, s.uid)
assert_kind_of(Integer, s.gid)
assert_instance_of(String, s.gecos) if s.respond_to?(:gecos)
assert_instance_of(String, s.dir)
assert_instance_of(String, s.shell)
assert_kind_of(Integer, s.change) if s.respond_to?(:change)
assert_kind_of(Integer, s.quota) if s.respond_to?(:quota)
assert(s.age.is_a?(Integer) || s.age.is_a?(String)) if s.respond_to?(:age)
assert_instance_of(String, s.uclass) if s.respond_to?(:uclass)
assert_instance_of(String, s.comment) if s.respond_to?(:comment)
assert_kind_of(Integer, s.expire) if s.respond_to?(:expire)
end
Etc.passwd { assert_raise(RuntimeError) { Etc.passwd { } }; break }
end
def test_getpwuid
# password database is not unique on UID, and which entry will be
# returned by getpwuid() is not specified.
passwd = Hash.new {[]}
# on MacOSX, same entries are returned from /etc/passwd and Open
# Directory.
Etc.passwd {|s| passwd[s.uid] |= [s]}
passwd.each_pair do |uid, s|
assert_include(s, Etc.getpwuid(uid))
end
s = passwd[Process.euid]
unless s.empty?
assert_include(s, Etc.getpwuid)
end
end
def test_getpwnam
passwd = {}
Etc.passwd do |s|
passwd[s.name] ||= s unless /\A\+/ =~ s.name
end
passwd.each_value do |s|
assert_equal(s, Etc.getpwnam(s.name))
end
end
def test_passwd_with_low_level_api
a = []
Etc.passwd {|s| a << s }
b = []
Etc.setpwent
while s = Etc.getpwent
b << s
end
Etc.endpwent
assert_equal(a, b)
end
def test_group
Etc.group do |s|
assert_instance_of(String, s.name)
assert_instance_of(String, s.passwd) if s.respond_to?(:passwd)
assert_kind_of(Integer, s.gid)
end
Etc.group { assert_raise(RuntimeError) { Etc.group { } }; break }
end
def test_getgrgid
# group database is not unique on GID, and which entry will be
# returned by getgrgid() is not specified.
groups = Hash.new {[]}
# on MacOSX, same entries are returned from /etc/group and Open
# Directory.
Etc.group {|s| groups[s.gid] |= [[s.name, s.gid]]}
groups.each_pair do |gid, s|
g = Etc.getgrgid(gid)
assert_include(s, [g.name, g.gid])
end
s = groups[Process.egid]
unless s.empty?
g = Etc.getgrgid
assert_include(s, [g.name, g.gid])
end
end
def test_getgrnam
groups = Hash.new {[]}
Etc.group do |s|
groups[s.name] |= [s.gid] unless /\A\+/ =~ s.name
end
groups.each_pair do |n, s|
assert_include(s, Etc.getgrnam(n).gid)
end
end
def test_group_with_low_level_api
a = []
Etc.group {|s| a << s }
b = []
Etc.setgrent
while s = Etc.getgrent
b << s
end
Etc.endgrent
assert_equal(a, b)
end
def test_uname
begin
uname = Etc.uname
rescue NotImplementedError
return
end
assert_kind_of(Hash, uname)
[:sysname, :nodename, :release, :version, :machine].each {|sym|
assert_operator(uname, :has_key?, sym)
assert_kind_of(String, uname[sym])
}
end
def test_sysconf
begin
Etc.sysconf
rescue NotImplementedError
return
rescue ArgumentError
end
assert_kind_of(Integer, Etc.sysconf(Etc::SC_CLK_TCK))
end if defined?(Etc::SC_CLK_TCK)
def test_confstr
begin
Etc.confstr
rescue NotImplementedError
return
rescue ArgumentError
end
assert_kind_of(String, Etc.confstr(Etc::CS_PATH))
end if defined?(Etc::CS_PATH)
def test_pathconf
begin
Etc.confstr
rescue NotImplementedError
return
rescue ArgumentError
end
IO.pipe {|r, w|
val = w.pathconf(Etc::PC_PIPE_BUF)
assert(val.nil? || val.kind_of?(Integer))
}
end if defined?(Etc::PC_PIPE_BUF)
def test_nprocessors
n = Etc.nprocessors
assert_operator(1, :<=, n)
end
end
| {'content_hash': '5c72b0e1b4f1e52c2727d1f962570014', 'timestamp': '', 'source': 'github', 'line_count': 171, 'max_line_length': 80, 'avg_line_length': 25.619883040935672, 'alnum_prop': 0.6153846153846154, 'repo_name': 'pmq20/ruby-compiler', 'id': '365c27021cee14c857539e03f280094ac50c17fb', 'size': '4411', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ruby/test/etc/test_etc.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '35'}, {'name': 'Assembly', 'bytes': '545193'}, {'name': 'Awk', 'bytes': '750'}, {'name': 'Batchfile', 'bytes': '10078'}, {'name': 'C', 'bytes': '31431383'}, {'name': 'C++', 'bytes': '170471'}, {'name': 'CSS', 'bytes': '15720'}, {'name': 'Emacs Lisp', 'bytes': '122830'}, {'name': 'GDB', 'bytes': '29782'}, {'name': 'HTML', 'bytes': '22578'}, {'name': 'JavaScript', 'bytes': '18023'}, {'name': 'M4', 'bytes': '74049'}, {'name': 'Makefile', 'bytes': '320959'}, {'name': 'Perl', 'bytes': '302'}, {'name': 'Perl 6', 'bytes': '636'}, {'name': 'Python', 'bytes': '7484'}, {'name': 'Ragel', 'bytes': '24937'}, {'name': 'Roff', 'bytes': '3385688'}, {'name': 'Ruby', 'bytes': '18904964'}, {'name': 'Scheme', 'bytes': '668'}, {'name': 'Scilab', 'bytes': '745'}, {'name': 'Shell', 'bytes': '362849'}, {'name': 'TeX', 'bytes': '323102'}, {'name': 'XSLT', 'bytes': '13913'}, {'name': 'Yacc', 'bytes': '512205'}]} |
package com.jjforever.wgj.maincalendar.BLL;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.jjforever.wgj.maincalendar.AppConstants;
/**
* Created by Wgj on 2016/8/27.
* 数据库帮助类
* 本数据库中存储的时间都精确到秒,保存为integer
*/
public class DatabaseHelper extends SQLiteOpenHelper {
static SQLiteDatabase SQLiteDb;
// 数据库版本号
private static final int DATABASE_VERSION = 1;
// 数据库名
private static final String DATABASE_NAME = "MainCalendar.db";
/**
* 构造函数,调用父类SQLiteOpenHelper的构造函数
*/
// public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
// int version, DatabaseErrorHandler errorHandler)
// {
// super(context, name, factory, version, errorHandler);
// }
/**
* SQLiteOpenHelper的构造函数参数
* @param context 上下文环境
* @param name 数据库名字
* @param factory 游标工厂(可选)
* @param version 数据库模型版本号
*/
// public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
// int version)
// {
// super(context, name, factory, version);
// }
/**
* 数据库帮助类
* @param context 上下文提供器
*/
private DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// 数据库实际被创建是在getWritableDatabase()或getReadableDatabase()方法调用时
}
// 继承SQLiteOpenHelper类,必须要覆写的三个方法:onCreate(),onUpgrade(),onOpen()
/**
* 即便程序修改重新运行,只要数据库已经创建过,就不会再进入这个onCreate方法
* @param db 数据库操作对象
*/
@Override
public void onCreate(SQLiteDatabase db)
{
// 调用时间:数据库第一次创建时onCreate()方法会被调用
// onCreate方法有一个 SQLiteDatabase对象作为参数,根据需要对这个对象填充表和初始化数据
// 这个方法中主要完成创建数据库后对数据库的操作
AppConstants.DLog("DatabaseHelper onCreate");
//创建日常记录数据表
createDailyRecord(db);
// 创建闹钟记录数据库
createAlarmRecord(db);
// 创建轮班记录数据库
createShiftsWorkRecord(db);
}
/**
* 创建日常记录数据库
*/
private void createDailyRecord(SQLiteDatabase db){
// 构建创建表的SQL语句
// 当都为固定字符串常量时使用String要快速,编译器会进行优化
String createSQL = "CREATE TABLE [" + DailyRecordMng.TABLE_NAME + "] (";
createSQL += "[index] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
createSQL += "[record_time] INTEGER,";
createSQL += "[weather] INTEGER,";
createSQL += "[title] TEXT,";
createSQL += "[content] TEXT,";
createSQL += "[display] INTEGER,";
createSQL += "[create_time] INTEGER)";
// 执行创建表的SQL语句
db.execSQL(createSQL);
}
/**
* 创建闹钟记录数据表
* @param db 数据库
*/
private void createAlarmRecord(SQLiteDatabase db){
String createSQL = "CREATE TABLE [" + AlarmRecordMng.TABLE_NAME + "] (";
createSQL += "[alarm_index] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
createSQL += "[action_type] INTEGER,";
createSQL += "[alarm_time] INTEGER,";
createSQL += "[date_year] INTEGER,";
createSQL += "[date_month] INTEGER,";
createSQL += "[date_day] INTEGER,";
createSQL += "[title] TEXT,";
createSQL += "[content] TEXT,";
createSQL += "[display] INTEGER,";
createSQL += "[pause] INTEGER,";
createSQL += "[create_time] INTEGER)";
// 执行创建表的SQL语句
db.execSQL(createSQL);
}
/**
* 创建轮班记录数据库
* @param db 数据库
*/
private void createShiftsWorkRecord(SQLiteDatabase db){
// 倒班记录表
String createSQL = "CREATE TABLE [" + ShiftsWorkRecordMng.TABLE_NAME + "] (";
createSQL += "[work_index] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
createSQL += "[work_title] TEXT,";
createSQL += "[start_date] INTEGER,";
createSQL += "[work_period] INTEGER,";
createSQL += "[create_time] INTEGER)";
// 执行创建表的SQL语句
db.execSQL(createSQL);
// 倒班记录每天设置项表
createSQL = "CREATE TABLE [" + ShiftsWorkItemMng.TABLE_NAME + "] (";
createSQL += "[item_index] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
createSQL += "[work_index] INTEGER,";
createSQL += "[day_no] INTEGER,";
createSQL += "[item_title] TEXT,";
createSQL += "[start_time] INTEGER,";
createSQL += "[end_time] INTEGER)";
// 执行创建表的SQL语句
db.execSQL(createSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// 调用时间:如果DATABASE_VERSION值被改为别的数,系统发现现有数据库版本不同,即会调用onUpgrade
// onUpgrade方法的三个参数,一个 SQLiteDatabase对象,一个旧的版本号和一个新的版本号
// 这样就可以把一个数据库从旧的模型转变到新的模型
// 这个方法中主要完成更改数据库版本的操作
AppConstants.DLog("DatabaseHelper onUpgrade");
// 删除旧数据库重建数据库,测试时用,正式版不能这么用
db.execSQL("DROP TABLE IF EXISTS " + DailyRecordMng.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + AlarmRecordMng.TABLE_NAME);
onCreate(db);
// 上述做法简单来说就是,通过检查常量值来决定如何,升级时删除旧表,然后调用onCreate来创建新表
// 一般在实际项目中是不能这么做的,正确的做法是在更新数据表结构时,还要考虑用户存放于数据库中的数据不丢失
}
@Override
public void onOpen(SQLiteDatabase db)
{
super.onOpen(db);
// 每次打开数据库之后首先被执行
AppConstants.DLog("DatabaseHelper onOpen");
}
/**
* 初始化SQLite数据库
* @param context 内容提供器
*/
public static void initDatabase(Context context){
if (SQLiteDb == null) {
SQLiteDb = new DatabaseHelper(context).getWritableDatabase();
}
}
/**
* 判断是否需要初始化数据库
* @return 是否需要
*/
public static boolean isNeedInit(){
return SQLiteDb == null;
}
/**
* 关闭数据库
*/
public static void closeDatabase(){
if (SQLiteDb != null){
SQLiteDb.close();
SQLiteDb = null;
}
}
}
| {'content_hash': 'a13fe1cf42fa415ff8b6f0221fe8655c', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 95, 'avg_line_length': 28.970443349753694, 'alnum_prop': 0.6055092671314403, 'repo_name': 'mainh/MainCalendar', 'id': 'a75a6a453840a96c696dfc023eb13330023e5f40', 'size': '7159', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/jjforever/wgj/maincalendar/BLL/DatabaseHelper.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '595641'}]} |
ACCEPTED
#### According to
NUB Generator [implicit canonical]
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'f352a0a0046e63c92d2d2784aaa0d9e6', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 34, 'avg_line_length': 9.923076923076923, 'alnum_prop': 0.6976744186046512, 'repo_name': 'mdoering/backbone', 'id': '233ef50f50670394636a8fb85effaa722350f2c6', 'size': '174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum eleagnifolium/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '75577c622fb3e510ef9a0d6a2c58747a', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'c39ce519d83ab07514294a50f7a14d45d9fbc8dd', 'size': '195', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Crocus/Crocus hittiticus/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ProjectDream
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :pl
# config.action_mailer.default_url_options = {host: ENV[:host]}
end
end
| {'content_hash': '9bd1ce1c98ad412f92f200d29d9bfe16', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 99, 'avg_line_length': 42.0, 'alnum_prop': 0.7133333333333334, 'repo_name': 'frondeus/ProjectDream', 'id': '4877b1b4dda969e31c0eac8060b28c188ce45c0e', 'size': '1050', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/application.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '43837'}, {'name': 'CoffeeScript', 'bytes': '422'}, {'name': 'JavaScript', 'bytes': '732'}, {'name': 'Ruby', 'bytes': '29574'}]} |
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.external.v1_0.experiment;
import gov.nih.nci.caarray.external.v1_0.vocabulary.Term;
/**
* An Organism is a special type of Term which represents an organism from which biomaterials for a microarray
* experiment can be drawn.
*
* @author dkokotov
*/
public class Organism extends Term {
private static final long serialVersionUID = 1L;
private String commonName;
private String scientificName;
/**
* @return the common (layman) name for this organism.
*/
public String getCommonName() {
return commonName;
}
/**
* @param commonName the commonName to set
*/
public void setCommonName(String commonName) {
this.commonName = commonName;
}
/**
* @return the scientific name for this organism.
*/
public String getScientificName() {
return scientificName;
}
/**
* @param scientificName the scientificName to set
*/
public void setScientificName(String scientificName) {
this.scientificName = scientificName;
}
}
| {'content_hash': '33bb6a410cf0710962449becae37b1cd', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 110, 'avg_line_length': 28.78, 'alnum_prop': 0.5913829047949966, 'repo_name': 'NCIP/caarray', 'id': 'a2bb9a26b056bfb177d5adf5f523a15a94ec8a6c', 'size': '1439', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'software/caarray-common.jar/src/main/java/gov/nih/nci/caarray/external/v1_0/experiment/Organism.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '615'}, {'name': 'CSS', 'bytes': '126854'}, {'name': 'FreeMarker', 'bytes': '4941'}, {'name': 'Groovy', 'bytes': '4998'}, {'name': 'HTML', 'bytes': '101282'}, {'name': 'Java', 'bytes': '7360097'}, {'name': 'JavaScript', 'bytes': '1167628'}, {'name': 'Mathematica', 'bytes': '104531225'}, {'name': 'PLSQL', 'bytes': '38277'}, {'name': 'XSLT', 'bytes': '53231'}]} |
package org.opencypher.tools.io;
import java.io.Writer;
class OutputWriter extends Writer
{
final Output output;
OutputWriter( Output output )
{
this.output = output;
}
@Override
public void write( char[] cbuf, int off, int len )
{
output.append( cbuf, off, len );
}
@Override
public void write( int c )
{
output.append( (char) c );
}
@Override
public void write( char[] cbuf )
{
output.append( cbuf );
}
@Override
public void write( String str )
{
output.append( str );
}
@Override
public void write( String str, int off, int len )
{
output.append( str, off, len );
}
@Override
public Writer append( CharSequence csq )
{
output.append( csq );
return this;
}
@Override
public Writer append( CharSequence csq, int start, int end )
{
output.append( csq, start, end );
return this;
}
@Override
public Writer append( char c )
{
output.append( c );
return this;
}
@Override
public void flush()
{
output.flush();
}
@Override
public void close()
{
output.close();
}
}
| {'content_hash': '33fa9d1ba265c1a4d9f5948037165cf4', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 64, 'avg_line_length': 16.4025974025974, 'alnum_prop': 0.5352335708630246, 'repo_name': 'Mats-SX/openCypher', 'id': 'a609adc075dd040a863972b865a53c230ccdd3ef', 'size': '1940', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tools/grammar/src/main/java/org/opencypher/tools/io/OutputWriter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Gherkin', 'bytes': '417560'}]} |
using System;
using System.IO;
using System.Text;
using Apache.Http;
using Apache.Http.Entity.Mime;
using Apache.Http.Entity.Mime.Content;
using Apache.Http.Message;
using Apache.Http.Protocol;
using Sharpen;
namespace Apache.Http.Entity.Mime
{
/// <summary>Multipart/form coded HTTP entity consisting of multiple body parts.</summary>
/// <remarks>Multipart/form coded HTTP entity consisting of multiple body parts.</remarks>
/// <since>4.0</since>
public class MultipartEntity : HttpEntity
{
/// <summary>The pool of ASCII chars to be used for generating a multipart boundary.</summary>
/// <remarks>The pool of ASCII chars to be used for generating a multipart boundary.</remarks>
private static readonly char[] MultipartChars = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ToCharArray();
private readonly HttpMultipart multipart;
private readonly Header contentType;
private long length;
private volatile bool dirty;
/// <summary>Creates an instance using the specified parameters</summary>
/// <param name="mode">
/// the mode to use, may be
/// <code>null</code>
/// , in which case
/// <see cref="HttpMultipartMode.Strict">HttpMultipartMode.Strict</see>
/// is used
/// </param>
/// <param name="boundary">
/// the boundary string, may be
/// <code>null</code>
/// , in which case
/// <see cref="GenerateBoundary()">GenerateBoundary()</see>
/// is invoked to create the string
/// </param>
/// <param name="charset">
/// the character set to use, may be
/// <code>null</code>
/// , in which case
/// <see cref="MIME.DefaultCharset">MIME.DefaultCharset</see>
/// - i.e. US-ASCII - is used.
/// </param>
public MultipartEntity(HttpMultipartMode mode, string boundary, Encoding charset)
: base()
{
// @GuardedBy("dirty") // we always read dirty before accessing length
// used to decide whether to recalculate length
if (boundary == null)
{
boundary = GenerateBoundary();
}
if (mode == null)
{
mode = HttpMultipartMode.Strict;
}
this.multipart = new HttpMultipart("related", charset, boundary, mode);
this.contentType = new BasicHeader(HTTP.ContentType, GenerateContentType(boundary
, charset));
this.dirty = true;
}
/// <summary>
/// Creates an instance using the specified
/// <see cref="HttpMultipartMode">HttpMultipartMode</see>
/// mode.
/// Boundary and charset are set to
/// <code>null</code>
/// .
/// </summary>
/// <param name="mode">the desired mode</param>
public MultipartEntity(HttpMultipartMode mode) : this(mode, null, null)
{
}
/// <summary>
/// Creates an instance using mode
/// <see cref="HttpMultipartMode.Strict">HttpMultipartMode.Strict</see>
/// </summary>
public MultipartEntity() : this(HttpMultipartMode.Strict, null, null)
{
}
protected internal virtual string GenerateContentType(string boundary, Encoding charset
)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("multipart/related; boundary=");
buffer.Append(boundary);
if (charset != null)
{
buffer.Append("; charset=");
buffer.Append(charset.Name());
}
return buffer.ToString();
}
protected internal virtual string GenerateBoundary()
{
StringBuilder buffer = new StringBuilder();
Random rand = new Random();
int count = rand.Next(11) + 30;
// a random size from 30 to 40
for (int i = 0; i < count; i++)
{
buffer.Append(MultipartChars[rand.Next(MultipartChars.Length)]);
}
return buffer.ToString();
}
public virtual void AddPart(FormBodyPart bodyPart)
{
this.multipart.AddBodyPart(bodyPart);
this.dirty = true;
}
public virtual void AddPart(string name, ContentBody contentBody)
{
AddPart(new FormBodyPart(name, contentBody));
}
public virtual bool IsRepeatable()
{
foreach (FormBodyPart part in this.multipart.GetBodyParts())
{
ContentBody body = part.GetBody();
if (body.GetContentLength() < 0)
{
return false;
}
}
return true;
}
public virtual bool IsChunked()
{
return !IsRepeatable();
}
public virtual bool IsStreaming()
{
return !IsRepeatable();
}
public virtual long GetContentLength()
{
if (this.dirty)
{
this.length = this.multipart.GetTotalLength();
this.dirty = false;
}
return this.length;
}
public virtual Header GetContentType()
{
return this.contentType;
}
public virtual Header GetContentEncoding()
{
return null;
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="System.NotSupportedException"></exception>
public virtual void ConsumeContent()
{
if (IsStreaming())
{
throw new NotSupportedException("Streaming entity does not implement #consumeContent()"
);
}
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="System.NotSupportedException"></exception>
public virtual InputStream GetContent()
{
throw new NotSupportedException("Multipart form entity does not implement #getContent()"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void WriteTo(OutputStream outstream)
{
this.multipart.WriteTo(outstream);
}
}
}
| {'content_hash': '3db7d48a311285072c962c967f3dc7ed', 'timestamp': '', 'source': 'github', 'line_count': 199, 'max_line_length': 122, 'avg_line_length': 32.64824120603015, 'alnum_prop': 0.5519470524857627, 'repo_name': 'mpapp/couchbase-lite-net', 'id': '2be463469ff66d50fdca6f8306c9f6d172350a66', 'size': '8351', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/Sharpened/Http/Entity/Mime/MultipartEntity.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '132'}, {'name': 'C#', 'bytes': '4814278'}, {'name': 'Makefile', 'bytes': '663'}, {'name': 'Shell', 'bytes': '963'}]} |
typedef struct _DbusmenuMenuitem DbusmenuMenuitem;
typedef struct _DbusmenuServer DbusmenuServer;
namespace ui {
class Accelerator;
}
namespace atom {
class NativeWindowViews;
// Controls the Mac style menu bar on Unity.
//
// Unity has an Apple-like menu bar at the top of the screen that changes
// depending on the active window. In the GTK port, we had a hidden GtkMenuBar
// object in each GtkWindow which existed only to be scrapped by the
// libdbusmenu-gtk code. Since we don't have GtkWindows anymore, we need to
// interface directly with the lower level libdbusmenu-glib, which we
// opportunistically dlopen() since not everyone is running Ubuntu.
//
// This class is like the chrome's corresponding one, but it generates the menu
// from menu models instead, and it is also per-window specific.
class GlobalMenuBarX11 {
public:
explicit GlobalMenuBarX11(NativeWindowViews* window);
virtual ~GlobalMenuBarX11();
// Creates the object path for DbusmenuServer which is attached to |xid|.
static std::string GetPathForWindow(gfx::AcceleratedWidget xid);
void SetMenu(AtomMenuModel* menu_model);
bool IsServerStarted() const;
// Called by NativeWindow when it show/hides.
void OnWindowMapped();
void OnWindowUnmapped();
private:
// Creates a DbusmenuServer.
void InitServer(gfx::AcceleratedWidget xid);
// Create a menu from menu model.
void BuildMenuFromModel(AtomMenuModel* model, DbusmenuMenuitem* parent);
// Sets the accelerator for |item|.
void RegisterAccelerator(DbusmenuMenuitem* item,
const ui::Accelerator& accelerator);
CHROMEG_CALLBACK_1(GlobalMenuBarX11,
void,
OnItemActivated,
DbusmenuMenuitem*,
unsigned int);
CHROMEG_CALLBACK_0(GlobalMenuBarX11, void, OnSubMenuShow, DbusmenuMenuitem*);
NativeWindowViews* window_;
gfx::AcceleratedWidget xid_;
DbusmenuServer* server_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(GlobalMenuBarX11);
};
} // namespace atom
#endif // ATOM_BROWSER_UI_VIEWS_GLOBAL_MENU_BAR_X11_H_
| {'content_hash': '52cb0d598bf5d88005d094810814637d', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 79, 'avg_line_length': 31.803030303030305, 'alnum_prop': 0.7255836112434493, 'repo_name': 'shiftkey/electron', 'id': 'dde466c94e8297e8c629152658c844fe4d3600b4', 'size': '2546', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'atom/browser/ui/views/global_menu_bar_x11.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3717'}, {'name': 'C++', 'bytes': '2869366'}, {'name': 'CSS', 'bytes': '2379'}, {'name': 'Dockerfile', 'bytes': '513'}, {'name': 'HTML', 'bytes': '14861'}, {'name': 'JavaScript', 'bytes': '978617'}, {'name': 'Objective-C', 'bytes': '60282'}, {'name': 'Objective-C++', 'bytes': '354967'}, {'name': 'PowerShell', 'bytes': '99'}, {'name': 'Python', 'bytes': '310407'}, {'name': 'Shell', 'bytes': '13803'}]} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iskyinfor.duoduo" android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<!-- 登陆 及其个人信息 -->
<activity android:name="LoginActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ui.usercenter.MyselfInfoActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
<activity android:name=".ui.usercenter.UpdataPasswordActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".ui.usercenter.MyselfAccountActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".ui.usercenter.RushMoneyActivity" />
<activity android:name=".ui.IndexActivity"
android:launchMode="singleTask"></activity>
<!-- 同步教学 -->
<activity android:name=".ui.lesson.LessonActivity"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity android:name=".ui.lesson.LessonSearchActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.lesson.LessonPlayVideoActivity" />
<!-- 下载 -->
<activity
android:name="com.iskyinfor.duoduo.ui.downloader.DowanloadManagerActivity">
</activity>
<activity android:name=".ui.downloader.MyselfResourceActivity"
android:theme="@android:style/Theme.Dialog" />
<activity
android:name="com.iskyinfor.duoduo.ui.downloader.SettingDownloadedActivity" />
<!-- 书架 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfReadActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookshelfCommentListActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfGiftActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfManagementActivity"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfReadActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookshelfCommentListActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfGiftActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfManagementActivity"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadNotesActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadLabelActivity" />
<activity android:name=".ui.book.BookshelfReadCommentActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:name=".ui.book.BookShelfRecommendActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:name=".ui.book.BookShelfReadDirActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfReadActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookshelfCommentListActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfGiftActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.BookShelfManagementActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadNotesActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadLabelActivity" />
<activity android:name=".ui.book.BookshelfReadCommentActivity"
android:configChanges="orientation|keyboardHidden"/>
<activity android:name=".ui.book.BookShelfRecommendActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:name=".ui.book.BookShelfGiftEditActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:name=".ui.book.BookShelfRecommendEditActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadNotesActivity" />
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.book.bookshelfReadLabelActivity" />
<activity android:name=".ui.book.BookshelfReadCommentActivity"
android:configChanges="orientation|keyboardHidden"/>
<activity android:name=".ui.book.BookShelfRecommendActivity"
android:configChanges="orientation|keyboardHidden" />
<service android:name=".downloadManage.DownloadService">
<intent-filter>
<action android:name="com.iskyinfor.duoduo.downloader.START_SERVICE" />
</intent-filter>
<intent-filter>
<action android:name="com.iskyinfor.duoduo.downloader.RESTART_SERVICE" />
</intent-filter>
<intent-filter>
<action android:name="com.iskyinfor.duoduo.download.netchange.wakeup.service" />
</intent-filter>
</service>
<provider android:name=".downloadManage.provider.DbProvider"
android:authorities="com.iskyinfor.duoduo.downloader.provider">
</provider>
<!-- 书店 -->
<!-- 书店首页 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookstoreActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店购物车 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.ShoppingCartActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店收藏夹 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookFavoriteActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店书本详细信息 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.detail.BookDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店订单列表 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店书本目录 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookDirectoryActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 书店订单详细信息 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookFavoriteActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookFavoriteActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.BookDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.OrderDetailActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.shop.GivedListActivity"
android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="stateAlwaysHidden"/>
<!-- 阅读电子书界面 -->
<activity android:name="com.kang.pdfreader.MyPdfReaderActivity" android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
</activity>
<!-- 讨论园地 -->
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.talkgarden.TalkGardenActivity"/>
<activity android:configChanges="orientation|keyboardHidden"
android:name=".ui.talkgarden.UserListActivity">
</activity>
<!-- 数据测试 -->
<activity android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:name="servicedata.bookshopdataservicetest.QurryProductInfor0200020002Test" />
<!-- 数据测试 -->
</application>
<uses-sdk android:minSdkVersion="8"></uses-sdk>
<supports-screens
android:resizeable="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>
</manifest> | {'content_hash': 'e06b28d873bcbed97301c06e0b5f7930', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 125, 'avg_line_length': 50.143478260869564, 'alnum_prop': 0.7736061735888321, 'repo_name': 'zoozooll/MyExercise', 'id': '9773ce813bcf67ca11e622da999bb8992f68e96b', 'size': '11691', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DuoDuoStudy/AndroidManifest.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1495689'}, {'name': 'C#', 'bytes': '190108'}, {'name': 'C++', 'bytes': '8719269'}, {'name': 'CMake', 'bytes': '46692'}, {'name': 'CSS', 'bytes': '149067'}, {'name': 'GLSL', 'bytes': '1069'}, {'name': 'HTML', 'bytes': '5933291'}, {'name': 'Java', 'bytes': '20935928'}, {'name': 'JavaScript', 'bytes': '420263'}, {'name': 'Kotlin', 'bytes': '13567'}, {'name': 'Makefile', 'bytes': '40498'}, {'name': 'Objective-C', 'bytes': '1149532'}, {'name': 'Objective-C++', 'bytes': '248482'}, {'name': 'Python', 'bytes': '23625'}, {'name': 'RenderScript', 'bytes': '3899'}, {'name': 'Shell', 'bytes': '18962'}, {'name': 'TSQL', 'bytes': '184481'}]} |
IPython-Notebooks
=================
Sample notebooks
| {'content_hash': '646db691d99ff4d8aabd9b13b922f1e5', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 17, 'avg_line_length': 13.5, 'alnum_prop': 0.5740740740740741, 'repo_name': 'alan-wong/IPython-Notebooks', 'id': 'bd3e7d224ddd5688e4804621fe339bd4503031fe', 'size': '54', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
angular.module('ChatRoom').controller('RoomController', ['$scope', '$location', '$rootScope', '$routeParams', 'socket',
function ($scope, $location, $rootScope, $routeParams, socket) {
$scope.currentRoom = $routeParams.room;
$scope.currentUser = $routeParams.user;
$scope.users = [];
$scope.ops = [];
$scope.messageHistory = [];
$scope.privateMsgHistory = [];
$scope.topic = '';
$scope.roomTopic = '';
$scope.banned = false;
$scope.nextMessage = '';
$scope.isOp = false;
$scope.privateMessage = '';
$scope.fromUser = '';
$scope.private = false;
var joinObj = {
room: $scope.currentRoom
};
socket.emit('joinroom', joinObj, function (success, reason) {
if (!success) {
$scope.banned = true;
toastr.error('You have been banned from room ' + $scope.currentRoom);
$location.path('/rooms/' + $scope.currentUser);
}
});
$scope.options = function () {
if($scope.topic === '') {
toastr.error('You must fill in topic');
} else {
var topic = {
room: $scope.currentRoom,
topic: $scope.topic
};
socket.emit('settopic', topic);
toastr.success("Topic changed to " + $scope.topic);
$scope.topic = '';
}
};
$scope.partRoom = function () {
// redirect user to room list
$location.path('/rooms/' + $scope.currentUser);
// let server know that user has left the room
socket.emit('partroom', $scope.currentRoom);
};
$scope.sendMsg = function () {
if ($scope.nextMessage !== '') {
// only handle non-empty messages
var message = {
roomName: $scope.currentRoom,
msg: $scope.nextMessage
};
// send message to server
socket.emit('sendmsg', message);
$scope.nextMessage = '';
}
};
$scope.privateMsg = function (user) {
if($scope.nextMessage !== '') {
//only handle non-empty messages
var message = {
nick: user,
message: $scope.nextMessage
};
//send private message
socket.emit('privatemsg', message, function (sent) {
if(!sent) {
toastr.error('Could not send message');
} else {
toastr.success('\"' + $scope.nextMessage + '\" sent to ' + user);
$scope.nextMessage = '';
}
});
} else {
toastr.error("Message field cannot be empty");
}
};
/* When a room creator wants to kick a user from the room.
Parameters:an object containing the following properties: { user : "The username of the user being kicked", room: "The ID of the room"
a callback function, accepting a single boolean parameter, stating if the user could be kicked or 7not.
The server will emit the following events if the user was successfully kicked: "kicked" to the user being kicked,
and "updateusers" to the rest of the users in the room.*/
$scope.kickUser = function (user) {
//only handle non-empty kicks
var kick = {
user: user,
room: $scope.currentRoom
};
socket.emit('kick', kick, function(kicked) {
if (!kicked) {
toastr.error('Could not kick user');
}
});
};
$scope.banUser = function(user) {
var ban = {
user: user,
room: $scope.currentRoom
};
socket.emit('ban', ban, function(banned) {
if (!banned) {
toastr.error('Could not ban ' + user);
}
});
};
socket.on('recv_privatemsg', function(username, message) {
/*$scope.fromUser = username;
$scope.privateMessage = message;*/
var msg = {
nick: username,
message: message
};
toastr.info('\"' + message + '\" from ' + username, 'Private Message');
$scope.privateMsgHistory.push(msg);
});
socket.on('banned', function(room, userKicked, user) {
if ($scope.currentRoom === room && $scope.currentUser === userKicked) {
//the user in this room has been banned
//redirect to lobby
toastr.error('You have been banned from room ' + $scope.currentRoom);
$location.path('/rooms/' + $scope.currentUser);
}
});
socket.on('kicked', function (room, userKicked, user) {
if ($scope.currentRoom === room && $scope.currentUser === userKicked) {
// the user in this room has been kicked
// redirect him to the room list
toastr.warning('You have been kicked from room ' + $scope.currentRoom);
$location.path('/rooms/' + $scope.currentUser);
}
});
/* The server responds by emitting the following events: "updateusers" (to all participants in the room),
"updatetopic" (to the newly joined user, not required to handle this), "servermessage" with the first parameter
set to "join" ( to all participants in the room, informing about the newly added user). If a new room is being
created, the message "updatechat" is also emitted. */
socket.on('updateusers', function (roomName, users, ops) {
// we only want to update the users for this particular room
// and if the user is not banned
if (roomName === $scope.currentRoom && !$scope.banned) {
// empty list of users and ops
$scope.users = [];
$scope.ops = [];
// populate users and ops lists with updated information
for (var op in ops) {
$scope.ops.push(op);
}
for (var user in users) {
$scope.users.push(user);
}
if ($scope.ops.length === 0 && $scope.users.length > 0) {
// if room has no op, the first user in user list is opped (if user list is not empty)
var userOpped = $scope.users.shift();
var opObj = {
user: userOpped,
room: $scope.currentRoom
};
socket.emit('op', opObj, function (success) {
// we don't have to do anything, if user is opped the updateusers
// event will let our client know
});
}
for(var i = 0; i < $scope.ops.length; i++) {
if($scope.currentUser === $scope.ops[i]) {
$scope.isOp = true;
}
}
}
});
socket.on('updatechat', function (roomName, msgHistory) {
// we only want to update the messages for this particular room
// and if the user is not banned
if (roomName === $scope.currentRoom && !$scope.banned) {
// empty list of messages
$scope.messageHistory = msgHistory;
}
});
socket.on('updatetopic', function (roomName, topic, user) {
// we only want to update the topic for this particular room
// and if the user is not banned
if (roomName === $scope.currentRoom && !$scope.banned) {
$scope.roomTopic = topic;
}
});
$scope.$on('$destroy', function() {
// unsubscribe to socket events when site is left
socket.removeAllListeners('kicked');
socket.removeAllListeners('banned');
socket.removeAllListeners('recv_privatemsg');
socket.removeAllListeners('updateusers');
socket.removeAllListeners('updatechat');
socket.removeAllListeners('updatetopic');
});
}]); | {'content_hash': 'e3f4928c547bdb09a1438b8da336f8a7', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 134, 'avg_line_length': 30.59360730593607, 'alnum_prop': 0.6264179104477612, 'repo_name': 'MasterWebs/ChatRoom', 'id': '7e950b231ac9ea757d0196e61b1c2c408ba24c7d', 'size': '6700', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/RoomController.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '670'}, {'name': 'HTML', 'bytes': '6600'}, {'name': 'JavaScript', 'bytes': '33035'}]} |
'use strict';
angular.module('snippetModule', [
'detailSnippetModule',
'postSnippetModule'
]);
| {'content_hash': '667371ffb77541b0cdc060d563e701a3', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 33, 'avg_line_length': 17.333333333333332, 'alnum_prop': 0.6826923076923077, 'repo_name': 'ChimiDEV/SecureAngular', 'id': '78ad0882e5715852b9476447043c116d348695ee', 'size': '104', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Release/public/snippet/snippet.module.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19044'}, {'name': 'HTML', 'bytes': '46901'}, {'name': 'JavaScript', 'bytes': '112281'}]} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CenterPoint")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CenterPoint")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6b56abc2-2d18-4846-867e-98bb4ec0ea30")]
// 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")]
| {'content_hash': '250c014b2f024cdada12beed3305c079', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 38.75, 'alnum_prop': 0.7448028673835125, 'repo_name': 'yani-valeva/Programming-Fundamentals', 'id': 'b50340888418b1272f24ec312b3a18d9d79db24d', 'size': '1398', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Methods/CenterPoint/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '708821'}]} |
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
try:
from crawler.decaptcha import Entrance, DecaptchaFailure
except ImportError:
Entrance = None
from data_center.models import Course, Department
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print 'Automated decaptcha failed.'
else:
print 'crawler.decaptcha not available (requires tesseract >= 3.03).'
print 'Please provide valid ACIXSTORE and auth_num from'
print url
ACIXSTORE = raw_input('ACIXSTORE: ')
auth_num = raw_input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NCKU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
crawl_course()
crawl_dept()
# elapsed_time = time.time() - start_time
# print 'Total %.3f second used.' % elapsed_time
if len(args) == 1:
if args[0] == 'clear':
Course.objects.all().delete()
Department.objects.all().delete()
| {'content_hash': '0f7f9fa7e8aad166547ca12ab7456c3c', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 77, 'avg_line_length': 30.475, 'alnum_prop': 0.6193601312551271, 'repo_name': 'sonicyang/NCKU_Course', 'id': '7617ebe8f08f376016be955b7397eaa0917afae1', 'size': '1219', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev2', 'path': 'crawler/management/commands/crawl_course.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '101213'}, {'name': 'HTML', 'bytes': '33725'}, {'name': 'JavaScript', 'bytes': '31753'}, {'name': 'Python', 'bytes': '52973'}, {'name': 'Shell', 'bytes': '1'}]} |
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>
#include <aws/macie2/Macie2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>
#include <aws/core/utils/UUID.h>
namespace Aws
{
namespace Macie2
{
namespace Model
{
/**
*/
class AWS_MACIE2_API CreateCustomDataIdentifierRequest : public Macie2Request
{
public:
CreateCustomDataIdentifierRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "CreateCustomDataIdentifier"; }
Aws::String SerializePayload() const override;
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline const Aws::String& GetClientToken() const{ return m_clientToken; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline CreateCustomDataIdentifierRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline CreateCustomDataIdentifierRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}
/**
* <p>A unique, case-sensitive token that you provide to ensure the idempotency of
* the request.</p>
*/
inline CreateCustomDataIdentifierRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>A custom description of the custom data identifier. The description can
* contain as many as 512 characters.</p> <p>We strongly recommend that you avoid
* including any sensitive data in the description of a custom data identifier.
* Other users of your account might be able to see the identifier's description,
* depending on the actions that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline const Aws::Vector<Aws::String>& GetIgnoreWords() const{ return m_ignoreWords; }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline bool IgnoreWordsHasBeenSet() const { return m_ignoreWordsHasBeenSet; }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline void SetIgnoreWords(const Aws::Vector<Aws::String>& value) { m_ignoreWordsHasBeenSet = true; m_ignoreWords = value; }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline void SetIgnoreWords(Aws::Vector<Aws::String>&& value) { m_ignoreWordsHasBeenSet = true; m_ignoreWords = std::move(value); }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& WithIgnoreWords(const Aws::Vector<Aws::String>& value) { SetIgnoreWords(value); return *this;}
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& WithIgnoreWords(Aws::Vector<Aws::String>&& value) { SetIgnoreWords(std::move(value)); return *this;}
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddIgnoreWords(const Aws::String& value) { m_ignoreWordsHasBeenSet = true; m_ignoreWords.push_back(value); return *this; }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddIgnoreWords(Aws::String&& value) { m_ignoreWordsHasBeenSet = true; m_ignoreWords.push_back(std::move(value)); return *this; }
/**
* <p>An array that lists specific character sequences (ignore words) to exclude
* from the results. If the text matched by the regular expression is the same as
* any string in this array, Amazon Macie ignores it. The array can contain as many
* as 10 ignore words. Each ignore word can contain 4-90 characters. Ignore words
* are case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddIgnoreWords(const char* value) { m_ignoreWordsHasBeenSet = true; m_ignoreWords.push_back(value); return *this; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline const Aws::Vector<Aws::String>& GetKeywords() const{ return m_keywords; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline bool KeywordsHasBeenSet() const { return m_keywordsHasBeenSet; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline void SetKeywords(const Aws::Vector<Aws::String>& value) { m_keywordsHasBeenSet = true; m_keywords = value; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline void SetKeywords(Aws::Vector<Aws::String>&& value) { m_keywordsHasBeenSet = true; m_keywords = std::move(value); }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& WithKeywords(const Aws::Vector<Aws::String>& value) { SetKeywords(value); return *this;}
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& WithKeywords(Aws::Vector<Aws::String>&& value) { SetKeywords(std::move(value)); return *this;}
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddKeywords(const Aws::String& value) { m_keywordsHasBeenSet = true; m_keywords.push_back(value); return *this; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddKeywords(Aws::String&& value) { m_keywordsHasBeenSet = true; m_keywords.push_back(std::move(value)); return *this; }
/**
* <p>An array that lists specific character sequences (keywords), one of which
* must be within proximity (maximumMatchDistance) of the regular expression to
* match. The array can contain as many as 50 keywords. Each keyword can contain
* 3-90 characters. Keywords aren't case sensitive.</p>
*/
inline CreateCustomDataIdentifierRequest& AddKeywords(const char* value) { m_keywordsHasBeenSet = true; m_keywords.push_back(value); return *this; }
/**
* <p>The maximum number of characters that can exist between text that matches the
* regex pattern and the character sequences specified by the keywords array. Macie
* includes or excludes a result based on the proximity of a keyword to text that
* matches the regex pattern. The distance can be 1-300 characters. The default
* value is 50.</p>
*/
inline int GetMaximumMatchDistance() const{ return m_maximumMatchDistance; }
/**
* <p>The maximum number of characters that can exist between text that matches the
* regex pattern and the character sequences specified by the keywords array. Macie
* includes or excludes a result based on the proximity of a keyword to text that
* matches the regex pattern. The distance can be 1-300 characters. The default
* value is 50.</p>
*/
inline bool MaximumMatchDistanceHasBeenSet() const { return m_maximumMatchDistanceHasBeenSet; }
/**
* <p>The maximum number of characters that can exist between text that matches the
* regex pattern and the character sequences specified by the keywords array. Macie
* includes or excludes a result based on the proximity of a keyword to text that
* matches the regex pattern. The distance can be 1-300 characters. The default
* value is 50.</p>
*/
inline void SetMaximumMatchDistance(int value) { m_maximumMatchDistanceHasBeenSet = true; m_maximumMatchDistance = value; }
/**
* <p>The maximum number of characters that can exist between text that matches the
* regex pattern and the character sequences specified by the keywords array. Macie
* includes or excludes a result based on the proximity of a keyword to text that
* matches the regex pattern. The distance can be 1-300 characters. The default
* value is 50.</p>
*/
inline CreateCustomDataIdentifierRequest& WithMaximumMatchDistance(int value) { SetMaximumMatchDistance(value); return *this;}
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>A custom name for the custom data identifier. The name can contain as many as
* 128 characters.</p> <p>We strongly recommend that you avoid including any
* sensitive data in the name of a custom data identifier. Other users of your
* account might be able to see the identifier's name, depending on the actions
* that they're allowed to perform in Amazon Macie.</p>
*/
inline CreateCustomDataIdentifierRequest& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline const Aws::String& GetRegex() const{ return m_regex; }
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline bool RegexHasBeenSet() const { return m_regexHasBeenSet; }
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline void SetRegex(const Aws::String& value) { m_regexHasBeenSet = true; m_regex = value; }
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline void SetRegex(Aws::String&& value) { m_regexHasBeenSet = true; m_regex = std::move(value); }
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline void SetRegex(const char* value) { m_regexHasBeenSet = true; m_regex.assign(value); }
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline CreateCustomDataIdentifierRequest& WithRegex(const Aws::String& value) { SetRegex(value); return *this;}
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline CreateCustomDataIdentifierRequest& WithRegex(Aws::String&& value) { SetRegex(std::move(value)); return *this;}
/**
* <p>The regular expression (<i>regex</i>) that defines the pattern to match. The
* expression can contain as many as 512 characters.</p>
*/
inline CreateCustomDataIdentifierRequest& WithRegex(const char* value) { SetRegex(value); return *this;}
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>A map of key-value pairs that specifies the tags to associate with the custom
* data identifier.</p> <p>A custom data identifier can have a maximum of 50 tags.
* Each tag consists of a tag key and an associated tag value. The maximum length
* of a tag key is 128 characters. The maximum length of a tag value is 256
* characters.</p>
*/
inline CreateCustomDataIdentifierRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }
private:
Aws::String m_clientToken;
bool m_clientTokenHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
Aws::Vector<Aws::String> m_ignoreWords;
bool m_ignoreWordsHasBeenSet;
Aws::Vector<Aws::String> m_keywords;
bool m_keywordsHasBeenSet;
int m_maximumMatchDistance;
bool m_maximumMatchDistanceHasBeenSet;
Aws::String m_name;
bool m_nameHasBeenSet;
Aws::String m_regex;
bool m_regexHasBeenSet;
Aws::Map<Aws::String, Aws::String> m_tags;
bool m_tagsHasBeenSet;
};
} // namespace Model
} // namespace Macie2
} // namespace Aws
| {'content_hash': 'c8a252e0b5b8a7758cee364604c9e4f2', 'timestamp': '', 'source': 'github', 'line_count': 617, 'max_line_length': 186, 'avg_line_length': 51.680713128038896, 'alnum_prop': 0.6979960485464296, 'repo_name': 'awslabs/aws-sdk-cpp', 'id': '41b28af7790c0a484ca53bd8703215c2905b4cc0', 'size': '32006', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-macie2/include/aws/macie2/model/CreateCustomDataIdentifierRequest.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '7596'}, {'name': 'C++', 'bytes': '61740540'}, {'name': 'CMake', 'bytes': '337520'}, {'name': 'Java', 'bytes': '223122'}, {'name': 'Python', 'bytes': '47357'}]} |
<!DOCTYPE html>
<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">
<meta name="keywords" content="Concept," />
<link rel="alternate" href="/atom.xml" title="Fengrui Liu's Blog" type="application/atom+xml" />
<meta name="description" content="张量张量的概念在数学物理领域有多种定义,从计算机的角度来说: 单个的数值:Scalar 一维的数组:Vector 二维的数组:Matrix 三维及以上的数组:Tensor 在某些计算机领域(如深度学习),n维数组统称为Tensor。 张量的模展开矩阵(Tensor Unfolding) 张量的模展开矩阵,主要任务是对张量进行降维,转化为矩阵。在张量的矩阵展开过程中,是对组成张量的所有阶按交">
<meta name="keywords" content="Concept">
<meta property="og:type" content="article">
<meta property="og:title" content="张量(Tensor)">
<meta property="og:url" content="http://www.liufr.com/2017/10/31/概念/2017-10-31-张量(Tensor)/index.html">
<meta property="og:site_name" content="Fengrui Liu's Blog">
<meta property="og:description" content="张量张量的概念在数学物理领域有多种定义,从计算机的角度来说: 单个的数值:Scalar 一维的数组:Vector 二维的数组:Matrix 三维及以上的数组:Tensor 在某些计算机领域(如深度学习),n维数组统称为Tensor。 张量的模展开矩阵(Tensor Unfolding) 张量的模展开矩阵,主要任务是对张量进行降维,转化为矩阵。在张量的矩阵展开过程中,是对组成张量的所有阶按交">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1ai9wqf2j30be0933z0.jpg">
<meta property="og:image" content="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1aj1wx1pj30gx0au3zk.jpg">
<meta property="og:image" content="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1csy4khqj30k40flmyr.jpg">
<meta property="og:image" content="https://ws4.sinaimg.cn/large/006tKfTcgy1fl1cynhf5tj30fk048t8x.jpg">
<meta property="og:image" content="https://ws4.sinaimg.cn/large/006tKfTcgy1fl1d02yy9kj30fk03kt8w.jpg">
<meta property="og:image" content="https://ws1.sinaimg.cn/large/006tKfTcgy1fl1d0vgeqsj30fu02p3yn.jpg">
<meta property="og:updated_time" content="2017-10-31T05:23:50.653Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张量(Tensor)">
<meta name="twitter:description" content="张量张量的概念在数学物理领域有多种定义,从计算机的角度来说: 单个的数值:Scalar 一维的数组:Vector 二维的数组:Matrix 三维及以上的数组:Tensor 在某些计算机领域(如深度学习),n维数组统称为Tensor。 张量的模展开矩阵(Tensor Unfolding) 张量的模展开矩阵,主要任务是对张量进行降维,转化为矩阵。在张量的矩阵展开过程中,是对组成张量的所有阶按交">
<meta name="twitter:image" content="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1ai9wqf2j30be0933z0.jpg">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Muse',
version: '5.1.3',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="http://www.liufr.com/2017/10/31/概念/2017-10-31-张量(Tensor)/"/>
<title>张量(Tensor) | Fengrui Liu's Blog</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left page-post-detail">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Fengrui Liu's Blog</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-search">
<a href="javascript:;" class="popup-trigger">
<i class="menu-item-icon fa fa-search fa-fw"></i> <br />
搜索
</a>
</li>
</ul>
<div class="site-search">
<div class="popup search-popup local-search-popup">
<div class="local-search-header clearfix">
<span class="search-icon">
<i class="fa fa-search"></i>
</span>
<span class="popup-btn-close">
<i class="fa fa-times-circle"></i>
</span>
<div class="local-search-input-wrapper">
<input autocomplete="off"
placeholder="搜索..." spellcheck="false"
type="text" id="local-search-input">
</div>
</div>
<div id="local-search-result"></div>
</div>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://www.liufr.com/2017/10/31/概念/2017-10-31-张量(Tensor)/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="刘丰瑞">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.JPG">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Fengrui Liu's Blog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">张量(Tensor)</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-31T00:00:00+08:00">
2017-10-31
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/Concept/" itemprop="url" rel="index">
<span itemprop="name">Concept</span>
</a>
</span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<h3 id="张量"><a href="#张量" class="headerlink" title="张量"></a>张量</h3><p>张量的概念在数学物理领域有多种定义,从计算机的角度来说:</p>
<ul>
<li>单个的数值:Scalar</li>
<li>一维的数组:Vector</li>
<li>二维的数组:Matrix</li>
<li>三维及以上的数组:Tensor</li>
</ul>
<p><img src="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1ai9wqf2j30be0933z0.jpg" alt=""></p>
<p>在某些计算机领域(如深度学习),n维数组统称为Tensor。</p>
<p><img src="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1aj1wx1pj30gx0au3zk.jpg" alt=""></p>
<h3 id="张量的模展开矩阵-Tensor-Unfolding"><a href="#张量的模展开矩阵-Tensor-Unfolding" class="headerlink" title="张量的模展开矩阵(Tensor Unfolding)"></a>张量的模展开矩阵(Tensor Unfolding)</h3><p><img src="https://ws2.sinaimg.cn/large/006tKfTcgy1fl1csy4khqj30k40flmyr.jpg" alt=""></p>
<p>张量的模展开矩阵,主要任务是对张量进行降维,转化为矩阵。在张量的矩阵展开过程中,是对组成张量的所有阶按交错次序采样,并非简单采取某一阶的特征值再采取另一阶的特征值,这样在采集过程中实现了张量不同阶特征值之间的传递和融合。</p>
<p>例:A是一个(4×3×2)三阶张量</p>
<p>对A第一阶模展开矩阵是一个4×6矩阵:<br><img src="https://ws4.sinaimg.cn/large/006tKfTcgy1fl1cynhf5tj30fk048t8x.jpg" alt=""></p>
<p>对A的第二阶模展开矩阵是一个3×8矩阵:<br><img src="https://ws4.sinaimg.cn/large/006tKfTcgy1fl1d02yy9kj30fk03kt8w.jpg" alt=""></p>
<p>对A的第三阶模展开矩阵是一个2×12矩阵:</p>
<p><img src="https://ws1.sinaimg.cn/large/006tKfTcgy1fl1d0vgeqsj30fu02p3yn.jpg" alt=""></p>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/Concept/" rel="tag"># Concept</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/2017/10/22/Linux/2017-10-22-Linux中断和中断处理/" rel="next" title="Linux-中断和中断处理">
<i class="fa fa-chevron-left"></i> Linux-中断和中断处理
</a>
</div>
<span class="post-nav-divider"></span>
<div class="post-nav-prev post-nav-item">
<a href="/2017/11/22/概念/2017-11-22-马哈拉诺比斯距离/" rel="prev" title="马哈拉诺比斯距离(马氏距离)">
马哈拉诺比斯距离(马氏距离) <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</div>
</article>
<div class="post-spread">
</div>
</div>
</div>
<div class="comments" id="comments">
<div id="lv-container" data-id="city" data-uid="MTAyMC8zMTIyMC83NzY5"></div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
文章目录
</li>
<li class="sidebar-nav-overview" data-target="site-overview-wrap">
站点概览
</li>
</ul>
<section class="site-overview-wrap sidebar-panel">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="/images/avatar.JPG"
alt="刘丰瑞" />
<p class="site-author-name" itemprop="name">刘丰瑞</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">50</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">8</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">15</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="feed-link motion-element">
<a href="/atom.xml" rel="alternate">
<i class="fa fa-rss"></i>
RSS
</a>
</div>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/Fengrui-Liu" target="_blank" title="GitHub">
<i class="fa fa-fw fa-github"></i>GitHub</a>
</span>
<span class="links-of-author-item">
<a href="mailto:Fengrui_Liu@whu.edu.cn" target="_blank" title="E-Mail">
<i class="fa fa-fw fa-envelope"></i>E-Mail</a>
</span>
<span class="links-of-author-item">
<a href="https://plus.google.com/u/0/103950731879937187960" target="_blank" title="Google">
<i class="fa fa-fw fa-google"></i>Google</a>
</span>
<span class="links-of-author-item">
<a href="https://twitter.com/liufengrui" target="_blank" title="Twitter">
<i class="fa fa-fw fa-twitter"></i>Twitter</a>
</span>
<span class="links-of-author-item">
<a href="https://www.facebook.com/profile.php?id=100007054291326" target="_blank" title="Facebook">
<i class="fa fa-fw fa-facebook"></i>Facebook</a>
</span>
</div>
</div>
</section>
<!--noindex-->
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
<div class="post-toc">
<div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#张量"><span class="nav-number">1.</span> <span class="nav-text">张量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#张量的模展开矩阵-Tensor-Unfolding"><span class="nav-number">2.</span> <span class="nav-text">张量的模展开矩阵(Tensor Unfolding)</span></a></li></ol></div>
</div>
</section>
<!--/noindex-->
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© 2015 — <span itemprop="copyrightYear">2017</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">刘丰瑞</span>
</div>
<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
<span class="post-meta-divider">|</span>
<div class="theme-info">主题 — <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>
<script type="text/javascript">
(function(d, s) {
var j, e = d.getElementsByTagName(s)[0];
if (typeof LivereTower === 'function') { return; }
j = d.createElement(s);
j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
j.async = true;
e.parentNode.insertBefore(j, e);
})(document, 'script');
</script>
<script type="text/javascript">
// Popup Window;
var isfetched = false;
var isXml = true;
// Search DB path;
var search_path = "search.xml";
if (search_path.length === 0) {
search_path = "search.xml";
} else if (/json$/i.test(search_path)) {
isXml = false;
}
var path = "/" + search_path;
// monitor main search box;
var onPopupClose = function (e) {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
}
function proceedsearch() {
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr("autocapitalize", "none");
$localSearchInput.attr("autocorrect", "off");
$localSearchInput.focus();
}
// search function;
var searchFunc = function(path, search_id, content_id) {
'use strict';
// start loading animation
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay">' +
'<div id="search-loading-icon">' +
'<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
'</div>' +
'</div>')
.css('overflow', 'hidden');
$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');
$.ajax({
url: path,
dataType: isXml ? "xml" : "json",
async: true,
success: function(res) {
// get the contents from search data
isfetched = true;
$('.popup').detach().appendTo('.header-inner');
var datas = isXml ? $("entry", res).map(function() {
return {
title: $("title", this).text(),
content: $("content",this).text(),
url: $("url" , this).text()
};
}).get() : res;
var input = document.getElementById(search_id);
var resultContent = document.getElementById(content_id);
var inputEventFunction = function() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[\s\-]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// perform local searching
datas.forEach(function(data) {
var isMatch = false;
var hitCount = 0;
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content.trim().replace(/<[^>]+>/g,"");
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url);
var indexOfTitle = [];
var indexOfContent = [];
// only match articles with not empty titles
if(title != '') {
keywords.forEach(function(keyword) {
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({position: position, word: word});
startPosition = position + wordLen;
}
return index;
}
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
isMatch = true;
hitCount = indexOfTitle.length + indexOfContent.length;
}
}
// show search results
if (isMatch) {
// sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function (index) {
index.sort(function (itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
// merge hits into slices
function mergeIntoSlice(text, start, end, index) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length != 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({position: position, length: word.length});
var wordEnd = position + word.length;
// move to next position of hit
index.pop();
while (index.length != 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
searchTextCount += searchTextCountInSlice;
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
var slicesOfTitle = [];
if (indexOfTitle.length != 0) {
slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
}
var slicesOfContent = [];
while (indexOfContent.length != 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// cut out 100 characters
var start = position - 20;
var end = position + 80;
if(start < 0){
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if(end > content.length){
end = content.length;
}
slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
}
// sort slices in content by search text's count and hits' count
slicesOfContent.sort(function (sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// select top N slices in content
var upperBound = parseInt('1');
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
// highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function (hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
var resultItem = '';
if (slicesOfTitle.length != 0) {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
} else {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
}
slicesOfContent.forEach(function (slice) {
resultItem += "<a href='" + articleUrl + "'>" +
"<p class=\"search-result\">" + highlightKeyword(content, slice) +
"...</p>" + "</a>";
});
resultItem += "</li>";
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
})
};
if (keywords.length === 1 && keywords[0] === "") {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
} else {
resultItems.sort(function (resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class=\"search-result-list\">';
resultItems.forEach(function (result) {
searchResultList += result.item;
})
searchResultList += "</ul>";
resultContent.innerHTML = searchResultList;
}
}
if ('auto' === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// remove loading animation
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
proceedsearch();
}
});
}
// handle and trigger popup window;
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc(path, 'local-search-input', 'local-search-result');
} else {
proceedsearch();
};
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e){
e.stopPropagation();
});
$(document).on('keyup', function (event) {
var shouldDismissSearchPopup = event.which === 27 &&
$('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});
</script>
</body>
</html>
| {'content_hash': '5eb9a98bd3f11139a6179d0d815c1ffa', 'timestamp': '', 'source': 'github', 'line_count': 1151, 'max_line_length': 398, 'avg_line_length': 27.71763683753258, 'alnum_prop': 0.5068175406701564, 'repo_name': 'Fengrui-Liu/Fengrui-Liu.github.io', 'id': '0284199f4b8a7a33fe5fd0cc805689ba7649684b', 'size': '33602', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '2017/10/31/概念/2017-10-31-张量(Tensor)/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '61380'}, {'name': 'HTML', 'bytes': '3804703'}, {'name': 'JavaScript', 'bytes': '366321'}]} |
"""Utility methods for working with WSGI servers."""
import abc
import errno
import os
import signal
import sys
import time
import eventlet
from eventlet.green import socket
from eventlet.green import ssl
import eventlet.greenio
import eventlet.wsgi
import functools
from oslo_concurrency import processutils
from oslo_config import cfg
import oslo_i18n as i18n
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import importutils
from paste import deploy
import routes
import routes.middleware
import six
import webob.dec
import webob.exc
from heat.api.aws import exception as aws_exception
from heat.common import exception
from heat.common.i18n import _
from heat.common.i18n import _LE
from heat.common.i18n import _LI
from heat.common.i18n import _LW
from heat.common import serializers
LOG = logging.getLogger(__name__)
URL_LENGTH_LIMIT = 50000
api_opts = [
cfg.IPOpt('bind_host', default='0.0.0.0',
help=_('Address to bind the server. Useful when '
'selecting a particular network interface.'),
deprecated_group='DEFAULT'),
cfg.PortOpt('bind_port', default=8004,
help=_('The port on which the server will listen.'),
deprecated_group='DEFAULT'),
cfg.IntOpt('backlog', default=4096,
help=_("Number of backlog requests "
"to configure the socket with."),
deprecated_group='DEFAULT'),
cfg.StrOpt('cert_file',
help=_("Location of the SSL certificate file "
"to use for SSL mode."),
deprecated_group='DEFAULT'),
cfg.StrOpt('key_file',
help=_("Location of the SSL key file to use "
"for enabling SSL mode."),
deprecated_group='DEFAULT'),
cfg.IntOpt('workers', default=0,
help=_("Number of workers for Heat service. "
"Default value 0 means, that service will start number "
"of workers equal number of cores on server."),
deprecated_group='DEFAULT'),
cfg.IntOpt('max_header_line', default=16384,
help=_('Maximum line size of message headers to be accepted. '
'max_header_line may need to be increased when using '
'large tokens (typically those generated by the '
'Keystone v3 API with big service catalogs).')),
cfg.IntOpt('tcp_keepidle', default=600,
help=_('The value for the socket option TCP_KEEPIDLE. This is '
'the time in seconds that the connection must be idle '
'before TCP starts sending keepalive probes.')),
]
api_group = cfg.OptGroup('heat_api')
cfg.CONF.register_group(api_group)
cfg.CONF.register_opts(api_opts,
group=api_group)
api_cfn_opts = [
cfg.IPOpt('bind_host', default='0.0.0.0',
help=_('Address to bind the server. Useful when '
'selecting a particular network interface.'),
deprecated_group='DEFAULT'),
cfg.PortOpt('bind_port', default=8000,
help=_('The port on which the server will listen.'),
deprecated_group='DEFAULT'),
cfg.IntOpt('backlog', default=4096,
help=_("Number of backlog requests "
"to configure the socket with."),
deprecated_group='DEFAULT'),
cfg.StrOpt('cert_file',
help=_("Location of the SSL certificate file "
"to use for SSL mode."),
deprecated_group='DEFAULT'),
cfg.StrOpt('key_file',
help=_("Location of the SSL key file to use "
"for enabling SSL mode."),
deprecated_group='DEFAULT'),
cfg.IntOpt('workers', default=1,
help=_("Number of workers for Heat service."),
deprecated_group='DEFAULT'),
cfg.IntOpt('max_header_line', default=16384,
help=_('Maximum line size of message headers to be accepted. '
'max_header_line may need to be increased when using '
'large tokens (typically those generated by the '
'Keystone v3 API with big service catalogs).')),
cfg.IntOpt('tcp_keepidle', default=600,
help=_('The value for the socket option TCP_KEEPIDLE. This is '
'the time in seconds that the connection must be idle '
'before TCP starts sending keepalive probes.')),
]
api_cfn_group = cfg.OptGroup('heat_api_cfn')
cfg.CONF.register_group(api_cfn_group)
cfg.CONF.register_opts(api_cfn_opts,
group=api_cfn_group)
api_cw_opts = [
cfg.IPOpt('bind_host', default='0.0.0.0',
help=_('Address to bind the server. Useful when '
'selecting a particular network interface.'),
deprecated_group='DEFAULT'),
cfg.PortOpt('bind_port', default=8003,
help=_('The port on which the server will listen.'),
deprecated_group='DEFAULT'),
cfg.IntOpt('backlog', default=4096,
help=_("Number of backlog requests "
"to configure the socket with."),
deprecated_group='DEFAULT'),
cfg.StrOpt('cert_file',
help=_("Location of the SSL certificate file "
"to use for SSL mode."),
deprecated_group='DEFAULT'),
cfg.StrOpt('key_file',
help=_("Location of the SSL key file to use "
"for enabling SSL mode."),
deprecated_group='DEFAULT'),
cfg.IntOpt('workers', default=1,
help=_("Number of workers for Heat service."),
deprecated_group='DEFAULT'),
cfg.IntOpt('max_header_line', default=16384,
help=_('Maximum line size of message headers to be accepted. '
'max_header_line may need to be increased when using '
'large tokens (typically those generated by the '
'Keystone v3 API with big service catalogs.)')),
cfg.IntOpt('tcp_keepidle', default=600,
help=_('The value for the socket option TCP_KEEPIDLE. This is '
'the time in seconds that the connection must be idle '
'before TCP starts sending keepalive probes.')),
]
api_cw_group = cfg.OptGroup('heat_api_cloudwatch')
cfg.CONF.register_group(api_cw_group)
cfg.CONF.register_opts(api_cw_opts,
group=api_cw_group)
wsgi_elt_opts = [
cfg.BoolOpt('wsgi_keep_alive',
default=True,
help=_("If False, closes the client socket connection "
"explicitly.")),
cfg.IntOpt('client_socket_timeout', default=900,
help=_("Timeout for client connections' socket operations. "
"If an incoming connection is idle for this number of "
"seconds it will be closed. A value of '0' means "
"wait forever.")),
]
wsgi_elt_group = cfg.OptGroup('eventlet_opts')
cfg.CONF.register_group(wsgi_elt_group)
cfg.CONF.register_opts(wsgi_elt_opts,
group=wsgi_elt_group)
json_size_opt = cfg.IntOpt('max_json_body_size',
default=1048576,
help=_('Maximum raw byte size of JSON request body.'
' Should be larger than max_template_size.'))
cfg.CONF.register_opt(json_size_opt)
def list_opts():
yield None, [json_size_opt]
yield 'heat_api', api_opts
yield 'heat_api_cfn', api_cfn_opts
yield 'heat_api_cloudwatch', api_cw_opts
yield 'eventlet_opts', wsgi_elt_opts
def get_bind_addr(conf, default_port=None):
"""Return the host and port to bind to."""
return (conf.bind_host, conf.bind_port or default_port)
def get_socket(conf, default_port):
"""Bind socket to bind ip:port in conf.
Note: Mostly comes from Swift with a few small changes...
:param conf: a cfg.ConfigOpts object
:param default_port: port to bind to if none is specified in conf
:returns : a socket object as returned from socket.listen or
ssl.wrap_socket if conf specifies cert_file
"""
bind_addr = get_bind_addr(conf, default_port)
# TODO(jaypipes): eventlet's greened socket module does not actually
# support IPv6 in getaddrinfo(). We need to get around this in the
# future or monitor upstream for a fix
address_family = [addr[0] for addr in socket.getaddrinfo(bind_addr[0],
bind_addr[1], socket.AF_UNSPEC, socket.SOCK_STREAM)
if addr[0] in (socket.AF_INET, socket.AF_INET6)][0]
cert_file = conf.cert_file
key_file = conf.key_file
use_ssl = cert_file or key_file
if use_ssl and (not cert_file or not key_file):
raise RuntimeError(_("When running server in SSL mode, you must "
"specify both a cert_file and key_file "
"option value in your configuration file"))
sock = None
retry_until = time.time() + 30
while not sock and time.time() < retry_until:
try:
sock = eventlet.listen(bind_addr,
backlog=conf.backlog,
family=address_family)
except socket.error as err:
if err.args[0] != errno.EADDRINUSE:
raise
eventlet.sleep(0.1)
if not sock:
raise RuntimeError(_("Could not bind to %(bind_addr)s"
"after trying for 30 seconds")
% {'bind_addr': bind_addr})
return sock
class Server(object):
"""Server class to manage multiple WSGI sockets and applications."""
def __init__(self, name, conf, threads=1000):
os.umask(0o27) # ensure files are created with the correct privileges
self._logger = logging.getLogger("eventlet.wsgi.server")
self.name = name
self.threads = threads
self.children = set()
self.stale_children = set()
self.running = True
self.pgid = os.getpid()
self.conf = conf
try:
os.setpgid(self.pgid, self.pgid)
except OSError:
self.pgid = 0
def kill_children(self, *args):
"""Kills the entire process group."""
LOG.error(_LE('SIGTERM received'))
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
self.running = False
os.killpg(0, signal.SIGTERM)
def hup(self, *args):
"""Reloads configuration files with zero down time."""
LOG.error(_LE('SIGHUP received'))
signal.signal(signal.SIGHUP, signal.SIG_IGN)
raise exception.SIGHUPInterrupt
def start(self, application, default_port):
"""Run a WSGI server with the given application.
:param application: The application to run in the WSGI server
:param default_port: Port to bind to if none is specified in conf
"""
eventlet.wsgi.MAX_HEADER_LINE = self.conf.max_header_line
self.application = application
self.default_port = default_port
self.configure_socket()
self.start_wsgi()
def start_wsgi(self):
workers = self.conf.workers
# raise error if workers is incorrect value
if workers < 0:
raise ValueError("Number of workers should be more or equal '0'!")
# childs == num of cores
if workers == 0:
childs_num = processutils.get_worker_count()
# launch only one GreenPool without childs
elif workers == 1:
# Useful for profiling, test, debug etc.
self.pool = eventlet.GreenPool(size=self.threads)
self.pool.spawn_n(self._single_run, self.application, self.sock)
return
# childs equal specified value of workers
else:
childs_num = workers
LOG.info(_LI("Starting %d workers"), workers)
signal.signal(signal.SIGTERM, self.kill_children)
signal.signal(signal.SIGINT, self.kill_children)
signal.signal(signal.SIGHUP, self.hup)
while len(self.children) < childs_num:
self.run_child()
def wait_on_children(self):
while self.running:
try:
pid, status = os.wait()
if os.WIFEXITED(status) or os.WIFSIGNALED(status):
self._remove_children(pid)
self._verify_and_respawn_children(pid, status)
except OSError as err:
if err.errno not in (errno.EINTR, errno.ECHILD):
raise
except KeyboardInterrupt:
LOG.info(_LI('Caught keyboard interrupt. Exiting.'))
os.killpg(0, signal.SIGTERM)
break
except exception.SIGHUPInterrupt:
self.reload()
continue
eventlet.greenio.shutdown_safe(self.sock)
self.sock.close()
LOG.debug('Exited')
def configure_socket(self, old_conf=None, has_changed=None):
"""Ensure a socket exists and is appropriately configured.
This function is called on start up, and can also be
called in the event of a configuration reload.
When called for the first time a new socket is created.
If reloading and either bind_host or bind port have been
changed the existing socket must be closed and a new
socket opened (laws of physics).
In all other cases (bind_host/bind_port have not changed)
the existing socket is reused.
:param old_conf: Cached old configuration settings (if any)
:param has changed: callable to determine if a parameter has changed
"""
# Do we need a fresh socket?
new_sock = (old_conf is None or (
has_changed('bind_host') or
has_changed('bind_port')))
# Will we be using https?
use_ssl = not (not self.conf.cert_file or not self.conf.key_file)
# Were we using https before?
old_use_ssl = (old_conf is not None and not (
not old_conf.get('key_file') or
not old_conf.get('cert_file')))
# Do we now need to perform an SSL wrap on the socket?
wrap_sock = use_ssl is True and (old_use_ssl is False or new_sock)
# Do we now need to perform an SSL unwrap on the socket?
unwrap_sock = use_ssl is False and old_use_ssl is True
if new_sock:
self._sock = None
if old_conf is not None:
self.sock.close()
_sock = get_socket(self.conf, self.default_port)
_sock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
# sockets can hang around forever without keepalive
_sock.setsockopt(socket.SOL_SOCKET,
socket.SO_KEEPALIVE, 1)
self._sock = _sock
if wrap_sock:
self.sock = ssl.wrap_socket(self._sock,
certfile=self.conf.cert_file,
keyfile=self.conf.key_file)
if unwrap_sock:
self.sock = self._sock
if new_sock and not use_ssl:
self.sock = self._sock
# Pick up newly deployed certs
if old_conf is not None and use_ssl is True and old_use_ssl is True:
if has_changed('cert_file'):
self.sock.certfile = self.conf.cert_file
if has_changed('key_file'):
self.sock.keyfile = self.conf.key_file
if new_sock or (old_conf is not None and has_changed('tcp_keepidle')):
# This option isn't available in the OS X version of eventlet
if hasattr(socket, 'TCP_KEEPIDLE'):
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
self.conf.tcp_keepidle)
if old_conf is not None and has_changed('backlog'):
self.sock.listen(self.conf.backlog)
def _remove_children(self, pid):
if pid in self.children:
self.children.remove(pid)
LOG.info(_LI('Removed dead child %s'), pid)
elif pid in self.stale_children:
self.stale_children.remove(pid)
LOG.info(_LI('Removed stale child %s'), pid)
else:
LOG.warning(_LW('Unrecognised child %s'), pid)
def _verify_and_respawn_children(self, pid, status):
if len(self.stale_children) == 0:
LOG.debug('No stale children')
if os.WIFEXITED(status) and os.WEXITSTATUS(status) != 0:
LOG.error(_LE('Not respawning child %d, cannot '
'recover from termination'), pid)
if not self.children and not self.stale_children:
LOG.info(
_LI('All workers have terminated. Exiting'))
self.running = False
else:
if len(self.children) < self.conf.workers:
self.run_child()
def stash_conf_values(self):
"""Make a copy of some of the current global CONF's settings.
Allows determining if any of these values have changed when the config
is reloaded.
"""
conf = {}
conf['bind_host'] = self.conf.bind_host
conf['bind_port'] = self.conf.bind_port
conf['backlog'] = self.conf.backlog
conf['key_file'] = self.conf.key_file
conf['cert_file'] = self.conf.cert_file
return conf
def reload(self):
"""Reload and re-apply configuration settings.
Existing child processes are sent a SIGHUP signal
and will exit after completing existing requests.
New child processes, which will have the updated
configuration, are spawned. This allows preventing
interruption to the service.
"""
def _has_changed(old, new, param):
old = old.get(param)
new = getattr(new, param)
return (new != old)
old_conf = self.stash_conf_values()
has_changed = functools.partial(_has_changed, old_conf, self.conf)
cfg.CONF.reload_config_files()
os.killpg(self.pgid, signal.SIGHUP)
self.stale_children = self.children
self.children = set()
# Ensure any logging config changes are picked up
logging.setup(cfg.CONF, self.name)
self.configure_socket(old_conf, has_changed)
self.start_wsgi()
def wait(self):
"""Wait until all servers have completed running."""
try:
if self.children:
self.wait_on_children()
else:
self.pool.waitall()
except KeyboardInterrupt:
pass
def run_child(self):
def child_hup(*args):
"""Shuts down child processes, existing requests are handled."""
signal.signal(signal.SIGHUP, signal.SIG_IGN)
eventlet.wsgi.is_accepting = False
self.sock.close()
pid = os.fork()
if pid == 0:
signal.signal(signal.SIGHUP, child_hup)
signal.signal(signal.SIGTERM, signal.SIG_DFL)
# ignore the interrupt signal to avoid a race whereby
# a child worker receives the signal before the parent
# and is respawned unnecessarily as a result
signal.signal(signal.SIGINT, signal.SIG_IGN)
# The child has no need to stash the unwrapped
# socket, and the reference prevents a clean
# exit on sighup
self._sock = None
self.run_server()
LOG.info(_LI('Child %d exiting normally'), os.getpid())
# self.pool.waitall() is now called in wsgi's server so
# it's safe to exit here
sys.exit(0)
else:
LOG.info(_LI('Started child %s'), pid)
self.children.add(pid)
def run_server(self):
"""Run a WSGI server."""
eventlet.wsgi.HttpProtocol.default_request_version = "HTTP/1.0"
eventlet.hubs.use_hub('poll')
eventlet.patcher.monkey_patch(all=False, socket=True)
self.pool = eventlet.GreenPool(size=self.threads)
socket_timeout = cfg.CONF.eventlet_opts.client_socket_timeout or None
try:
eventlet.wsgi.server(
self.sock,
self.application,
custom_pool=self.pool,
url_length_limit=URL_LENGTH_LIMIT,
log=self._logger,
debug=cfg.CONF.debug,
keepalive=cfg.CONF.eventlet_opts.wsgi_keep_alive,
socket_timeout=socket_timeout)
except socket.error as err:
if err[0] != errno.EINVAL:
raise
self.pool.waitall()
def _single_run(self, application, sock):
"""Start a WSGI server in a new green thread."""
LOG.info(_LI("Starting single process server"))
eventlet.wsgi.server(sock, application,
custom_pool=self.pool,
url_length_limit=URL_LENGTH_LIMIT,
log=self._logger,
debug=cfg.CONF.debug)
class Middleware(object):
"""Base WSGI middleware wrapper.
These classes require an application to be initialized that will be called
next. By default the middleware will simply call its wrapped app, or you
can override __call__ to customize its behavior.
"""
def __init__(self, application):
self.application = application
def process_request(self, req):
"""Called on each request.
If this returns None, the next application down the stack will be
executed. If it returns a response then that response will be returned
and execution will stop here.
"""
return None
def process_response(self, response):
"""Do whatever you'd like to the response."""
return response
@webob.dec.wsgify
def __call__(self, req):
response = self.process_request(req)
if response:
return response
response = req.get_response(self.application)
return self.process_response(response)
class Debug(Middleware):
"""Helper class to get information about the request and response.
Helper class that can be inserted into any WSGI application chain
to get information about the request and response.
"""
@webob.dec.wsgify
def __call__(self, req):
print(("*" * 40) + " REQUEST ENVIRON")
for key, value in req.environ.items():
print(key, "=", value)
print('')
resp = req.get_response(self.application)
print(("*" * 40) + " RESPONSE HEADERS")
for (key, value) in six.iteritems(resp.headers):
print(key, "=", value)
print('')
resp.app_iter = self.print_generator(resp.app_iter)
return resp
@staticmethod
def print_generator(app_iter):
"""Prints the contents of a wrapper string iterator when iterated."""
print(("*" * 40) + " BODY")
for part in app_iter:
sys.stdout.write(part)
sys.stdout.flush()
yield part
print('')
def debug_filter(app, conf, **local_conf):
return Debug(app)
class DefaultMethodController(object):
"""Controller that handles the OPTIONS request method.
This controller handles the OPTIONS request method and any of the HTTP
methods that are not explicitly implemented by the application.
"""
def options(self, req, allowed_methods, *args, **kwargs):
"""Return a response that includes the 'Allow' header.
Return a response that includes the 'Allow' header listing the methods
that are implemented. A 204 status code is used for this response.
"""
raise webob.exc.HTTPNoContent(headers=[('Allow', allowed_methods)])
def reject(self, req, allowed_methods, *args, **kwargs):
"""Return a 405 method not allowed error.
As a convenience, the 'Allow' header with the list of implemented
methods is included in the response as well.
"""
raise webob.exc.HTTPMethodNotAllowed(
headers=[('Allow', allowed_methods)])
class Router(object):
"""WSGI middleware that maps incoming requests to WSGI apps."""
def __init__(self, mapper):
"""Create a router for the given routes.Mapper.
Each route in `mapper` must specify a 'controller', which is a
WSGI app to call. You'll probably want to specify an 'action' as
well and have your controller be a wsgi.Controller, who will route
the request to the action method.
Examples:
mapper = routes.Mapper()
sc = ServerController()
# Explicit mapping of one route to a controller+action
mapper.connect(None, "/svrlist", controller=sc, action="list")
# Actions are all implicitly defined
mapper.resource("server", "servers", controller=sc)
# Pointing to an arbitrary WSGI app. You can specify the
# {path_info:.*} parameter so the target app can be handed just that
# section of the URL.
mapper.connect(None, "/v1.0/{path_info:.*}", controller=BlogApp())
"""
self.map = mapper
self._router = routes.middleware.RoutesMiddleware(self._dispatch,
self.map)
@webob.dec.wsgify
def __call__(self, req):
"""Route the incoming request to a controller based on self.map.
If no match, return a 404.
"""
return self._router
@staticmethod
@webob.dec.wsgify
def _dispatch(req):
"""Returns controller after matching the incoming request to a route.
Called by self._router after matching the incoming request to a route
and putting the information into req.environ. Either returns 404 or the
routed WSGI app's response.
"""
match = req.environ['wsgiorg.routing_args'][1]
if not match:
return webob.exc.HTTPNotFound()
app = match['controller']
return app
class Request(webob.Request):
"""Add some OpenStack API-specific logic to the base webob.Request."""
def best_match_content_type(self):
"""Determine the requested response content-type."""
supported = ('application/json',)
bm = self.accept.best_match(supported)
return bm or 'application/json'
def get_content_type(self, allowed_content_types):
"""Determine content type of the request body."""
if "Content-Type" not in self.headers:
raise exception.InvalidContentType(content_type=None)
content_type = self.content_type
if content_type not in allowed_content_types:
raise exception.InvalidContentType(content_type=content_type)
else:
return content_type
def best_match_language(self):
"""Determines best available locale from the Accept-Language header.
:returns: the best language match or None if the 'Accept-Language'
header was not available in the request.
"""
if not self.accept_language:
return None
all_languages = i18n.get_available_languages('heat')
return self.accept_language.best_match(all_languages)
def is_json_content_type(request):
if request.method == 'GET':
try:
aws_content_type = request.params.get("ContentType")
except Exception:
aws_content_type = None
# respect aws_content_type when both available
content_type = aws_content_type or request.content_type
else:
content_type = request.content_type
# bug #1887882
# for back compatible for null or plain content type
if not content_type or content_type.startswith('text/plain'):
content_type = 'application/json'
if (content_type in ('JSON', 'application/json')
and request.body.startswith(b'{')):
return True
return False
class JSONRequestDeserializer(object):
def has_body(self, request):
"""Returns whether a Webob.Request object will possess an entity body.
:param request: Webob.Request object
"""
if (int(request.content_length or 0) > 0 and
is_json_content_type(request)):
return True
return False
def from_json(self, datastring):
try:
if len(datastring) > cfg.CONF.max_json_body_size:
msg = _('JSON body size (%(len)s bytes) exceeds maximum '
'allowed size (%(limit)s bytes).'
) % {'len': len(datastring),
'limit': cfg.CONF.max_json_body_size}
raise exception.RequestLimitExceeded(message=msg)
return jsonutils.loads(datastring)
except ValueError as ex:
raise webob.exc.HTTPBadRequest(six.text_type(ex))
def default(self, request):
if self.has_body(request):
return {'body': self.from_json(request.body)}
else:
return {}
class Resource(object):
"""WSGI app that handles (de)serialization and controller dispatch.
Reads routing information supplied by RoutesMiddleware and calls
the requested action method upon its deserializer, controller,
and serializer. Those three objects may implement any of the basic
controller action methods (create, update, show, index, delete)
along with any that may be specified in the api router. A 'default'
method may also be implemented to be used in place of any
non-implemented actions. Deserializer methods must accept a request
argument and return a dictionary. Controller methods must accept a
request argument. Additionally, they must also accept keyword
arguments that represent the keys returned by the Deserializer. They
may raise a webob.exc exception or return a dict, which will be
serialized by requested content type.
"""
def __init__(self, controller, deserializer, serializer=None):
"""Initialisation of the WSGI app.
:param controller: object that implement methods created by routes lib
:param deserializer: object that supports webob request deserialization
through controller-like actions
:param serializer: object that supports webob response serialization
through controller-like actions
"""
self.controller = controller
self.deserializer = deserializer
self.serializer = serializer
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, request):
"""WSGI method that controls (de)serialization and method dispatch."""
action_args = self.get_action_args(request.environ)
action = action_args.pop('action', None)
# From reading the boto code, and observation of real AWS api responses
# it seems that the AWS api ignores the content-type in the html header
# Instead it looks at a "ContentType" GET query parameter
# This doesn't seem to be documented in the AWS cfn API spec, but it
# would appear that the default response serialization is XML, as
# described in the API docs, but passing a query parameter of
# ContentType=JSON results in a JSON serialized response...
content_type = request.params.get("ContentType")
try:
deserialized_request = self.dispatch(self.deserializer,
action, request)
action_args.update(deserialized_request)
LOG.debug(('Calling %(controller)s : %(action)s'),
{'controller': self.controller, 'action': action})
action_result = self.dispatch(self.controller, action,
request, **action_args)
except TypeError as err:
LOG.error(_LE('Exception handling resource: %s'), err)
msg = _('The server could not comply with the request since '
'it is either malformed or otherwise incorrect.')
err = webob.exc.HTTPBadRequest(msg)
http_exc = translate_exception(err, request.best_match_language())
# NOTE(luisg): We disguise HTTP exceptions, otherwise they will be
# treated by wsgi as responses ready to be sent back and they
# won't make it into the pipeline app that serializes errors
raise exception.HTTPExceptionDisguise(http_exc)
except webob.exc.HTTPException as err:
if isinstance(err, aws_exception.HeatAPIException):
# The AWS compatible API's don't use faultwrap, so
# we want to detect the HeatAPIException subclasses
# and raise rather than wrapping in HTTPExceptionDisguise
raise
if not isinstance(err, webob.exc.HTTPError):
# Some HTTPException are actually not errors, they are
# responses ready to be sent back to the users, so we don't
# error log, disguise or translate those
raise
if isinstance(err, webob.exc.HTTPServerError):
LOG.error(
_LE("Returning %(code)s to user: %(explanation)s"),
{'code': err.code, 'explanation': err.explanation})
http_exc = translate_exception(err, request.best_match_language())
raise exception.HTTPExceptionDisguise(http_exc)
except exception.HeatException as err:
raise translate_exception(err, request.best_match_language())
except Exception as err:
log_exception(err, sys.exc_info())
raise translate_exception(err, request.best_match_language())
# Here we support either passing in a serializer or detecting it
# based on the content type.
try:
serializer = self.serializer
if serializer is None:
if content_type == "JSON":
serializer = serializers.JSONResponseSerializer()
else:
serializer = serializers.XMLResponseSerializer()
response = webob.Response(request=request)
self.dispatch(serializer, action, response, action_result)
return response
# return unserializable result (typically an exception)
except Exception:
# Here we should get API exceptions derived from HeatAPIException
# these implement get_unserialized_body(), which allow us to get
# a dict containing the unserialized error response.
# We only need to serialize for JSON content_type, as the
# exception body is pre-serialized to the default XML in the
# HeatAPIException constructor
# If we get something else here (e.g a webob.exc exception),
# this will fail, and we just return it without serializing,
# which will not conform to the expected AWS error response format
if content_type == "JSON":
try:
err_body = action_result.get_unserialized_body()
serializer.default(action_result, err_body)
except Exception:
LOG.warning(_LW("Unable to serialize exception "
"response"))
return action_result
def dispatch(self, obj, action, *args, **kwargs):
"""Find action-specific method on self and call it."""
try:
method = getattr(obj, action)
except AttributeError:
method = getattr(obj, 'default')
return method(*args, **kwargs)
def get_action_args(self, request_environment):
"""Parse dictionary created by routes library."""
try:
args = request_environment['wsgiorg.routing_args'][1].copy()
except Exception:
return {}
try:
del args['controller']
except KeyError:
pass
try:
del args['format']
except KeyError:
pass
return args
def log_exception(err, exc_info):
args = {'exc_info': exc_info} if cfg.CONF.verbose or cfg.CONF.debug else {}
LOG.error(_LE("Unexpected error occurred serving API: %s"), err,
**args)
def translate_exception(exc, locale):
"""Translates all translatable elements of the given exception."""
if isinstance(exc, exception.HeatException):
exc.message = i18n.translate(exc.message, locale)
else:
err_msg = encodeutils.exception_to_unicode(exc)
exc.message = i18n.translate(err_msg, locale)
if isinstance(exc, webob.exc.HTTPError):
exc.explanation = i18n.translate(exc.explanation, locale)
exc.detail = i18n.translate(getattr(exc, 'detail', ''), locale)
return exc
@six.add_metaclass(abc.ABCMeta)
class BasePasteFactory(object):
"""A base class for paste app and filter factories.
Sub-classes must override the KEY class attribute and provide
a __call__ method.
"""
KEY = None
def __init__(self, conf):
self.conf = conf
@abc.abstractmethod
def __call__(self, global_conf, **local_conf):
return
def _import_factory(self, local_conf):
"""Import an app/filter class.
Lookup the KEY from the PasteDeploy local conf and import the
class named there. This class can then be used as an app or
filter factory.
Note we support the <module>:<class> format.
Note also that if you do e.g.
key =
value
then ConfigParser returns a value with a leading newline, so
we strip() the value before using it.
"""
class_name = local_conf[self.KEY].replace(':', '.').strip()
return importutils.import_class(class_name)
class AppFactory(BasePasteFactory):
"""A Generic paste.deploy app factory.
This requires heat.app_factory to be set to a callable which returns a
WSGI app when invoked. The format of the name is <module>:<callable> e.g.
[app:apiv1app]
paste.app_factory = heat.common.wsgi:app_factory
heat.app_factory = heat.api.cfn.v1:API
The WSGI app constructor must accept a ConfigOpts object and a local config
dict as its two arguments.
"""
KEY = 'heat.app_factory'
def __call__(self, global_conf, **local_conf):
"""The actual paste.app_factory protocol method."""
factory = self._import_factory(local_conf)
return factory(self.conf, **local_conf)
class FilterFactory(AppFactory):
"""A Generic paste.deploy filter factory.
This requires heat.filter_factory to be set to a callable which returns a
WSGI filter when invoked. The format is <module>:<callable> e.g.
[filter:cache]
paste.filter_factory = heat.common.wsgi:filter_factory
heat.filter_factory = heat.api.middleware.cache:CacheFilter
The WSGI filter constructor must accept a WSGI app, a ConfigOpts object and
a local config dict as its three arguments.
"""
KEY = 'heat.filter_factory'
def __call__(self, global_conf, **local_conf):
"""The actual paste.filter_factory protocol method."""
factory = self._import_factory(local_conf)
def filter(app):
return factory(app, self.conf, **local_conf)
return filter
def setup_paste_factories(conf):
"""Set up the generic paste app and filter factories.
Set things up so that:
paste.app_factory = heat.common.wsgi:app_factory
and
paste.filter_factory = heat.common.wsgi:filter_factory
work correctly while loading PasteDeploy configuration.
The app factories are constructed at runtime to allow us to pass a
ConfigOpts object to the WSGI classes.
:param conf: a ConfigOpts object
"""
global app_factory, filter_factory
app_factory = AppFactory(conf)
filter_factory = FilterFactory(conf)
def teardown_paste_factories():
"""Reverse the effect of setup_paste_factories()."""
global app_factory, filter_factory
del app_factory
del filter_factory
def paste_deploy_app(paste_config_file, app_name, conf):
"""Load a WSGI app from a PasteDeploy configuration.
Use deploy.loadapp() to load the app from the PasteDeploy configuration,
ensuring that the supplied ConfigOpts object is passed to the app and
filter constructors.
:param paste_config_file: a PasteDeploy config file
:param app_name: the name of the app/pipeline to load from the file
:param conf: a ConfigOpts object to supply to the app and its filters
:returns: the WSGI app
"""
setup_paste_factories(conf)
try:
return deploy.loadapp("config:%s" % paste_config_file, name=app_name)
finally:
teardown_paste_factories()
| {'content_hash': 'a7ad67c00c9e608c70daaafd35c960ea', 'timestamp': '', 'source': 'github', 'line_count': 1072, 'max_line_length': 79, 'avg_line_length': 38.711753731343286, 'alnum_prop': 0.6018458276103038, 'repo_name': 'cwolferh/heat-scratch', 'id': '88563040749a22a108d9e68cce5b9ece965b520a', 'size': '42260', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'heat/common/wsgi.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '8338769'}, {'name': 'Shell', 'bytes': '56516'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '2ae91a47cc400e71bb1ee817095ae0af', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '5f968521d8877d37925a8461fe2a65d8ef8e4f5b', 'size': '173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Salix/Salix nepalensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
"""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.contact_log_type import ContactLogType # noqa: E501
from swagger_client.rest import ApiException
class TestContactLogType(unittest.TestCase):
"""ContactLogType unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testContactLogType(self):
"""Test ContactLogType"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.contact_log_type.ContactLogType() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| {'content_hash': 'ac41267df374d0af8f6398f7c65aee76', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 119, 'avg_line_length': 24.289473684210527, 'alnum_prop': 0.6912242686890574, 'repo_name': 'mindbody/API-Examples', 'id': '22cb7bad32359894696775042bf3b633cdc419e3', 'size': '940', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SDKs/Python/test/test_contact_log_type.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'PHP', 'bytes': '3610259'}, {'name': 'Python', 'bytes': '2338642'}, {'name': 'Ruby', 'bytes': '2284441'}, {'name': 'Shell', 'bytes': '5058'}]} |
/**
@module @ember/array
*/
import {
get,
objectAt,
alias,
PROPERTY_DID_CHANGE,
addArrayObserver,
removeArrayObserver,
replace,
CUSTOM_TAG_FOR,
arrayContentDidChange,
tagForProperty,
} from '@ember/-internals/metal';
import { isObject } from '@ember/-internals/utils';
import EmberObject from './object';
import { isArray, MutableArray } from '../mixins/array';
import { assert } from '@ember/debug';
import { combine, consumeTag, validateTag, valueForTag, tagFor } from '@glimmer/validator';
const ARRAY_OBSERVER_MAPPING = {
willChange: '_arrangedContentArrayWillChange',
didChange: '_arrangedContentArrayDidChange',
};
/**
An ArrayProxy wraps any other object that implements `Array` and/or
`MutableArray,` forwarding all requests. This makes it very useful for
a number of binding use cases or other cases where being able to swap
out the underlying array is useful.
A simple example of usage:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish'];
let ap = ArrayProxy.create({ content: A(pets) });
ap.get('firstObject'); // 'dog'
ap.set('content', ['amoeba', 'paramecium']);
ap.get('firstObject'); // 'amoeba'
```
This class can also be useful as a layer to transform the contents of
an array, as they are accessed. This can be done by overriding
`objectAtContent`:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish'];
let ap = ArrayProxy.create({
content: A(pets),
objectAtContent: function(idx) {
return this.get('content').objectAt(idx).toUpperCase();
}
});
ap.get('firstObject'); // . 'DOG'
```
When overriding this class, it is important to place the call to
`_super` *after* setting `content` so the internal observers have
a chance to fire properly:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
export default ArrayProxy.extend({
init() {
this.set('content', A(['dog', 'cat', 'fish']));
this._super(...arguments);
}
});
```
@class ArrayProxy
@extends EmberObject
@uses MutableArray
@public
*/
export default class ArrayProxy extends EmberObject {
init() {
super.init(...arguments);
/*
`this._objectsDirtyIndex` determines which indexes in the `this._objects`
cache are dirty.
If `this._objectsDirtyIndex === -1` then no indexes are dirty.
Otherwise, an index `i` is dirty if `i >= this._objectsDirtyIndex`.
Calling `objectAt` with a dirty index will cause the `this._objects`
cache to be recomputed.
*/
this._objectsDirtyIndex = 0;
this._objects = null;
this._lengthDirty = true;
this._length = 0;
this._arrangedContent = null;
this._arrangedContentIsUpdating = false;
this._arrangedContentTag = null;
this._arrangedContentRevision = null;
this._lengthTag = null;
this._arrTag = null;
}
[PROPERTY_DID_CHANGE]() {
this._revalidate();
}
[CUSTOM_TAG_FOR](key) {
if (key === '[]') {
this._revalidate();
return this._arrTag;
} else if (key === 'length') {
this._revalidate();
return this._lengthTag;
}
return tagFor(this, key);
}
willDestroy() {
this._removeArrangedContentArrayObserver();
}
/**
The content array. Must be an object that implements `Array` and/or
`MutableArray.`
@property content
@type EmberArray
@public
*/
/**
Should actually retrieve the object at the specified index from the
content. You can override this method in subclasses to transform the
content item to something new.
This method will only be called if content is non-`null`.
@method objectAtContent
@param {Number} idx The index to retrieve.
@return {Object} the value or undefined if none found
@public
*/
objectAtContent(idx) {
return objectAt(get(this, 'arrangedContent'), idx);
}
// See additional docs for `replace` from `MutableArray`:
// https://api.emberjs.com/ember/release/classes/MutableArray/methods/replace?anchor=replace
replace(idx, amt, objects) {
assert(
'Mutating an arranged ArrayProxy is not allowed',
get(this, 'arrangedContent') === get(this, 'content')
);
this.replaceContent(idx, amt, objects);
}
/**
Should actually replace the specified objects on the content array.
You can override this method in subclasses to transform the content item
into something new.
This method will only be called if content is non-`null`.
@method replaceContent
@param {Number} idx The starting index
@param {Number} amt The number of items to remove from the content.
@param {EmberArray} objects Optional array of objects to insert or null if no
objects.
@return {void}
@public
*/
replaceContent(idx, amt, objects) {
get(this, 'content').replace(idx, amt, objects);
}
// Overriding objectAt is not supported.
objectAt(idx) {
this._revalidate();
if (this._objects === null) {
this._objects = [];
}
if (this._objectsDirtyIndex !== -1 && idx >= this._objectsDirtyIndex) {
let arrangedContent = get(this, 'arrangedContent');
if (arrangedContent) {
let length = (this._objects.length = get(arrangedContent, 'length'));
for (let i = this._objectsDirtyIndex; i < length; i++) {
this._objects[i] = this.objectAtContent(i);
}
} else {
this._objects.length = 0;
}
this._objectsDirtyIndex = -1;
}
return this._objects[idx];
}
// Overriding length is not supported.
get length() {
this._revalidate();
if (this._lengthDirty) {
let arrangedContent = get(this, 'arrangedContent');
this._length = arrangedContent ? get(arrangedContent, 'length') : 0;
this._lengthDirty = false;
}
consumeTag(this._lengthTag);
return this._length;
}
set length(value) {
let length = this.length;
let removedCount = length - value;
let added;
if (removedCount === 0) {
return;
} else if (removedCount < 0) {
added = new Array(-removedCount);
removedCount = 0;
}
let content = get(this, 'content');
if (content) {
replace(content, value, removedCount, added);
this._invalidate();
}
}
_updateArrangedContentArray(arrangedContent) {
let oldLength = this._objects === null ? 0 : this._objects.length;
let newLength = arrangedContent ? get(arrangedContent, 'length') : 0;
this._removeArrangedContentArrayObserver();
this.arrayContentWillChange(0, oldLength, newLength);
this._invalidate();
this.arrayContentDidChange(0, oldLength, newLength);
this._addArrangedContentArrayObserver(arrangedContent);
}
_addArrangedContentArrayObserver(arrangedContent) {
if (arrangedContent && !arrangedContent.isDestroyed) {
assert("Can't set ArrayProxy's content to itself", arrangedContent !== this);
assert(
`ArrayProxy expects an Array or ArrayProxy, but you passed ${typeof arrangedContent}`,
isArray(arrangedContent) || arrangedContent.isDestroyed
);
addArrayObserver(arrangedContent, this, ARRAY_OBSERVER_MAPPING);
this._arrangedContent = arrangedContent;
}
}
_removeArrangedContentArrayObserver() {
if (this._arrangedContent) {
removeArrayObserver(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING);
}
}
_arrangedContentArrayWillChange() {}
_arrangedContentArrayDidChange(proxy, idx, removedCnt, addedCnt) {
this.arrayContentWillChange(idx, removedCnt, addedCnt);
let dirtyIndex = idx;
if (dirtyIndex < 0) {
let length = get(this._arrangedContent, 'length');
dirtyIndex += length + removedCnt - addedCnt;
}
if (this._objectsDirtyIndex === -1 || this._objectsDirtyIndex > dirtyIndex) {
this._objectsDirtyIndex = dirtyIndex;
}
this._lengthDirty = true;
this.arrayContentDidChange(idx, removedCnt, addedCnt);
}
_invalidate() {
this._objectsDirtyIndex = 0;
this._lengthDirty = true;
}
_revalidate() {
if (this._arrangedContentIsUpdating === true) return;
if (
this._arrangedContentTag === null ||
!validateTag(this._arrangedContentTag, this._arrangedContentRevision)
) {
let arrangedContent = this.get('arrangedContent');
if (this._arrangedContentTag === null) {
// This is the first time the proxy has been setup, only add the observer
// don't trigger any events
this._addArrangedContentArrayObserver(arrangedContent);
} else {
this._arrangedContentIsUpdating = true;
this._updateArrangedContentArray(arrangedContent);
this._arrangedContentIsUpdating = false;
}
let arrangedContentTag = (this._arrangedContentTag = tagFor(this, 'arrangedContent'));
this._arrangedContentRevision = valueForTag(this._arrangedContentTag);
if (isObject(arrangedContent)) {
this._lengthTag = combine([arrangedContentTag, tagForProperty(arrangedContent, 'length')]);
this._arrTag = combine([arrangedContentTag, tagForProperty(arrangedContent, '[]')]);
} else {
this._lengthTag = this._arrTag = arrangedContentTag;
}
}
}
}
ArrayProxy.reopen(MutableArray, {
/**
The array that the proxy pretends to be. In the default `ArrayProxy`
implementation, this and `content` are the same. Subclasses of `ArrayProxy`
can override this property to provide things like sorting and filtering.
@property arrangedContent
@public
*/
arrangedContent: alias('content'),
// Array proxies don't need to notify when they change since their `[]` tag is
// already dependent on the `[]` tag of `arrangedContent`
arrayContentDidChange(startIdx, removeAmt, addAmt) {
return arrayContentDidChange(this, startIdx, removeAmt, addAmt, false);
},
});
| {'content_hash': '35b0b92a26a97b10c91f95cabe602e90', 'timestamp': '', 'source': 'github', 'line_count': 358, 'max_line_length': 99, 'avg_line_length': 28.22905027932961, 'alnum_prop': 0.6582228379180685, 'repo_name': 'mfeckie/ember.js', 'id': '3546446f10a298f701311f1799a4ebda82b19c48', 'size': '10106', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/@ember/-internals/runtime/lib/system/array_proxy.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '9511'}, {'name': 'JavaScript', 'bytes': '3501557'}, {'name': 'Shell', 'bytes': '740'}, {'name': 'TypeScript', 'bytes': '631965'}]} |
// Copyright (c) 2018 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using Alachisoft.NCache.Common.Communication.Secure;
using System;
using System.Security.Cryptography.X509Certificates;
namespace Alachisoft.NCache.Common.Util
{
public static class CertificateStore
{
internal static X509CertificateCollection GetClientCertificates()
{
var cert = GetServerCertificate();
return cert == null ? new X509CertificateCollection() : new X509CertificateCollection(new [] { cert });
}
public static X509Certificate2 GetServerCertificate()
{
X509Certificate2 cert = null;
if ((cert = GetCertificateFromSore(new X509Store(StoreName.Root, StoreLocation.LocalMachine))) != null) return cert;
if ((cert = GetCertificateFromSore(new X509Store(StoreName.Root, StoreLocation.CurrentUser))) != null) return cert;
throw new Exception("Couldn't find the required certificate in 'Trusted Root Certificate Authorities (CAs)' store of the 'Local' and 'User' paths.");
}
public static X509Certificate2 GetCertificateFromSore(X509Store store)
{
store.Open(OpenFlags.ReadOnly);
var cert = FindCertificatByThumbprint(SslConfiguration.Thumbprint, store.Certificates);
store.Close();
return cert;
}
private static X509Certificate2 FindCertificatByThumbprint(string thumbprint, X509Certificate2Collection certificates)
{
var certificate = certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certificate.Count > 0) return certificate[0];
foreach (var cert in certificates)
if (cert.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase))
return cert;
return null;
}
}
}
| {'content_hash': '61fb94e4eefc1783a1f9f54ef12d2c44', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 161, 'avg_line_length': 43.1578947368421, 'alnum_prop': 0.6800813008130081, 'repo_name': 'Alachisoft/NCache', 'id': '1eb454e29317c0ae3c82e649225ed9b71a26ff61', 'size': '2462', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Src/NCCommon/Util/CertificateStore.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '12283536'}, {'name': 'CSS', 'bytes': '707'}, {'name': 'HTML', 'bytes': '16825'}, {'name': 'JavaScript', 'bytes': '377'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ivy-report.xsl"?>
<ivy-report version="1.0">
<info
organisation="apachecmda_frontend"
module="apachecmda_frontend$sources_javadoc_2.10"
revision="1.0-SNAPSHOT"
conf="plugin"
confs="compile, runtime, test, provided, optional, compile-internal, runtime-internal, test-internal, plugin, sources, docs, pom, scala-tool, echo-trace-compile, echo-trace-test, echo-weave, echo-sigar"
date="20160407145012"/>
<dependencies>
</dependencies>
</ivy-report>
| {'content_hash': '545c9cb65a884490a8ac5f112e00f06d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 204, 'avg_line_length': 41.46153846153846, 'alnum_prop': 0.7291280148423006, 'repo_name': 'dsarlis/SAD-Spring-2016-Project-Team4', 'id': 'a2c3dd64d46235197848cbf4b4bc07b2718a0e06', 'size': '539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ApacheCMDA-Frontend/target/resolution-cache/reports/apachecmda_frontend-apachecmda_frontend$sources_javadoc_2.10-plugin.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '270'}, {'name': 'CSS', 'bytes': '108458'}, {'name': 'HTML', 'bytes': '834216'}, {'name': 'Java', 'bytes': '426598'}, {'name': 'JavaScript', 'bytes': '3481267'}, {'name': 'Scala', 'bytes': '651187'}, {'name': 'Shell', 'bytes': '1911'}, {'name': 'XSLT', 'bytes': '86028'}]} |
package com.vgerbot.test.orm.influxdb.intergration.dao;
import com.vgerbot.orm.influxdb.InfluxDBDao;
import com.vgerbot.orm.influxdb.annotations.InfluxDBSelect;
import com.vgerbot.test.orm.influxdb.intergration.entity.CensusMeasurementUsingEnum;
import java.util.List;
public interface EnumTypeMeasurementDao extends InfluxDBDao<CensusMeasurementUsingEnum> {
@InfluxDBSelect("select * from census where scientist='lanstroth'")
List<CensusMeasurementUsingEnum> selectAll_lanstroths_data();
}
| {'content_hash': '8325495391b8e85b99c60f97ad87cea9', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 89, 'avg_line_length': 41.833333333333336, 'alnum_prop': 0.8306772908366534, 'repo_name': 'y1j2x34/spring-influxdb-orm', 'id': '87395a83c39c9f8c64855c91c5a29d0cbb9d7b53', 'size': '502', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/intergration/dao/EnumTypeMeasurementDao.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '568'}, {'name': 'Java', 'bytes': '199357'}, {'name': 'Shell', 'bytes': '274'}]} |
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="enable_ambient_temp_sensor"
android:defaultValue="false"
android:title="@string/enable_temperature_sensor_title"
android:summary="@string/enable_temperature_sensor_summary"
/>
<CheckBoxPreference
android:key="enable_sine_wave_sensor"
android:defaultValue="false"
android:title="@string/enable_sine_wave_sensor_title"
android:summary="@string/enable_sine_wave_sensor_summary"
/>
<CheckBoxPreference
android:key="dev_tools"
android:defaultValue="false"
android:title="@string/dev_tools_title"
android:summary="@string/dev_tools_summary"
/>
<CheckBoxPreference
android:key="leak_canary"
android:title="@string/dev_tools_leak_detection_title"
android:summary="@string/dev_tools_leak_detection_summary"
/>
<CheckBoxPreference
android:key="strict_mode"
android:defaultValue="false"
android:title="@string/dev_tools_strict_mode_title"
android:summary="@string/dev_tools_strict_mode_summary"
/>
<CheckBoxPreference
android:key="enable_dev_sonification_types"
android:title="@string/dev_sonification_types_title"
android:summary="@string/dev_sonification_types_summary"
android:defaultValue="false"
/>
<CheckBoxPreference
android:key="enable_third_party_sensors"
android:defaultValue="false"
android:title="@string/third_party_sensors_option_title"
android:summary="@string/third_party_sensors_option_summary"
/>
<CheckBoxPreference
android:key="use_new_manage_devices_ux"
android:defaultValue="false"
android:title="@string/use_new_manage_devices_ux_option_title"
android:summary="@string/use_new_manage_devices_ux_option_summary"
/>
<CheckBoxPreference
android:key="enable_smooth_scrolling_to_bottom"
android:defaultValue="true"
android:title="@string/enable_smooth_scrolling_on_refresh"
android:summary="@string/enable_smooth_scrolling_on_refresh_summary"
/>
<Preference
android:key="require_google_account"
android:persistent="true"
android:defaultValue="false"
android:shouldDisableView="true"
android:title="@string/require_google_account"
android:summary="@string/require_google_account_summary"
/>
<Preference
android:key="show_perf_tracker_debug"
android:title="@string/perf_tracker_debug_pref_title"
/>
</PreferenceScreen>
| {'content_hash': '4add597a95c3ff837d6e6ecf6b35309c', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 76, 'avg_line_length': 34.92631578947368, 'alnum_prop': 0.6787221217600965, 'repo_name': 'googlearchive/science-journal', 'id': '55ded2c062c8a9a2e1116fb4e1784805615b7509', 'size': '3318', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'OpenScienceJournal/whistlepunk_library/src/main/res/xml/dev_options.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '30945'}, {'name': 'Java', 'bytes': '3424733'}, {'name': 'Shell', 'bytes': '897'}, {'name': 'Starlark', 'bytes': '493'}]} |
package com.b2international.snowowl.core.domain;
import static com.google.common.collect.Lists.newArrayList;
import java.util.List;
import com.b2international.commons.exceptions.BadRequestException;
import com.b2international.index.revision.RevisionIndex;
import com.b2international.snowowl.core.RepositoryInfo;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.branch.Branch;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.repository.RepositoryRequests;
/**
* Execution context for {@link Request requests} targeting a repository.
*
* @since 4.5
*/
public interface RepositoryContext extends ServiceProvider, Bindable {
default RepositoryInfo info() {
return service(RepositoryInfo.class);
}
@Override
default DelegatingContext.Builder<? extends RepositoryContext> inject() {
return new DelegatingContext.Builder<>(RepositoryContext.class, this);
}
default BranchContext openBranch(RepositoryContext context, String path) {
return context.service(ContextConfigurer.class).configure(new RepositoryBranchContext(context, path, ensureAvailability(context, path)));
}
private Branch ensureAvailability(RepositoryContext context, String path) {
final List<String> branchesToCheck = newArrayList();
if (RevisionIndex.isBranchAtPath(path)) {
branchesToCheck.add(path.split(RevisionIndex.AT_CHAR)[0]);
} else if (RevisionIndex.isBaseRefPath(path)) {
branchesToCheck.add(path.substring(0, path.length() - 1));
} else if (RevisionIndex.isRevRangePath(path)) {
branchesToCheck.addAll(List.of(RevisionIndex.getRevisionRangePaths(path)));
} else {
branchesToCheck.add(path);
}
Branch branch = null;
for (String branchToCheck : branchesToCheck) {
branch = RepositoryRequests.branching().prepareGet(branchToCheck).build().execute(context);
if (branch.isDeleted()) {
throw new BadRequestException("Branch '%s' has been deleted and cannot accept further modifications.", branchToCheck);
}
}
return branch;
}
}
| {'content_hash': 'fa8829bbe6d729968fafaaa089efac8c', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 139, 'avg_line_length': 35.16949152542373, 'alnum_prop': 0.7797590361445783, 'repo_name': 'b2ihealthcare/snow-owl', 'id': 'b920c15ba4654964bb457eecfc3b401298116cb5', 'size': '2701', 'binary': False, 'copies': '1', 'ref': 'refs/heads/8.x', 'path': 'core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/domain/RepositoryContext.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4650'}, {'name': 'CSS', 'bytes': '672'}, {'name': 'Dockerfile', 'bytes': '2504'}, {'name': 'Groovy', 'bytes': '100933'}, {'name': 'HTML', 'bytes': '555'}, {'name': 'Java', 'bytes': '9909422'}, {'name': 'JavaScript', 'bytes': '2967'}, {'name': 'Shell', 'bytes': '37460'}]} |
var Watson = (function() {
var helpers = {
// Place your helper functions here...
};
return {
/*
* Takes the untouched input string, returns
* an array with the modified input string at position 0 and a new Sherlocked object at position 1
*/
preprocess: function(str) {
var Sherlocked = {};
// Manipulate str and Sherlocked here...
return [str, Sherlocked];
},
/*
* Takes a Sherlocked object, and returns that Sherlocked object with any desired modifications.
*/
postprocess: function(Sherlocked) {
// Manipulate Sherlocked here...
return Sherlocked;
}
};
})();
| {'content_hash': '40c0e966663d32862ee648d519e28ab3', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 100, 'avg_line_length': 18.78787878787879, 'alnum_prop': 0.6532258064516129, 'repo_name': 'mko/Sherlock', 'id': '63142b57fffc5fdd128ba7ed767152563cd527d0', 'size': '713', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'watson.js', 'mode': '33188', 'license': 'mit', 'language': []} |
require 'spec_helper'
class MMMMailgunMailer < MMMailer
mailman :mailgun
def test_mail
mail_male_mail_category("MailgunCategory1")
mail_male_mail_variables(:color => "green", :sound => "bark")
mail(:subject => "Mailgun Testing", :from => "test@example.com", :to => "test2@example.com")
end
end
module MailMaleMail
describe Mailgun do
it "should set the mailgun headers with tag and variables" do
mail = MMMMailgunMailer.test_mail
mail.header['X-Mailgun-Tag'].to_s.should == "MailgunCategory1"
mail.header['X-Mailgun-Variables'].to_s.should == "{\"color\": \"green\", \"sound\": \"bark\"}"
end
end
end
| {'content_hash': '975512d8052458eb41542e77bc2acc85', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 101, 'avg_line_length': 31.047619047619047, 'alnum_prop': 0.6671779141104295, 'repo_name': 'sportngin/mail_male_mail', 'id': 'bf8c559baf6d1db6c72389828f80408a4c6f9e03', 'size': '652', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/mail_male_mail/mailgun_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '10076'}]} |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#ifndef __HID_H
#define __HID_H
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/mod_devicetable.h> /* hid_device_id */
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/input.h>
#include <linux/semaphore.h>
#include <linux/power_supply.h>
#include <uapi/linux/hid.h>
/*
* We parse each description item into this structure. Short items data
* values are expanded to 32-bit signed int, long items contain a pointer
* into the data area.
*/
struct hid_item {
unsigned format;
__u8 size;
__u8 type;
__u8 tag;
union {
__u8 u8;
__s8 s8;
__u16 u16;
__s16 s16;
__u32 u32;
__s32 s32;
__u8 *longdata;
} data;
};
/*
* HID report item format
*/
#define HID_ITEM_FORMAT_SHORT 0
#define HID_ITEM_FORMAT_LONG 1
/*
* Special tag indicating long items
*/
#define HID_ITEM_TAG_LONG 15
/*
* HID report descriptor item type (prefix bit 2,3)
*/
#define HID_ITEM_TYPE_MAIN 0
#define HID_ITEM_TYPE_GLOBAL 1
#define HID_ITEM_TYPE_LOCAL 2
#define HID_ITEM_TYPE_RESERVED 3
/*
* HID report descriptor main item tags
*/
#define HID_MAIN_ITEM_TAG_INPUT 8
#define HID_MAIN_ITEM_TAG_OUTPUT 9
#define HID_MAIN_ITEM_TAG_FEATURE 11
#define HID_MAIN_ITEM_TAG_BEGIN_COLLECTION 10
#define HID_MAIN_ITEM_TAG_END_COLLECTION 12
/*
* HID report descriptor main item contents
*/
#define HID_MAIN_ITEM_CONSTANT 0x001
#define HID_MAIN_ITEM_VARIABLE 0x002
#define HID_MAIN_ITEM_RELATIVE 0x004
#define HID_MAIN_ITEM_WRAP 0x008
#define HID_MAIN_ITEM_NONLINEAR 0x010
#define HID_MAIN_ITEM_NO_PREFERRED 0x020
#define HID_MAIN_ITEM_NULL_STATE 0x040
#define HID_MAIN_ITEM_VOLATILE 0x080
#define HID_MAIN_ITEM_BUFFERED_BYTE 0x100
/*
* HID report descriptor collection item types
*/
#define HID_COLLECTION_PHYSICAL 0
#define HID_COLLECTION_APPLICATION 1
#define HID_COLLECTION_LOGICAL 2
/*
* HID report descriptor global item tags
*/
#define HID_GLOBAL_ITEM_TAG_USAGE_PAGE 0
#define HID_GLOBAL_ITEM_TAG_LOGICAL_MINIMUM 1
#define HID_GLOBAL_ITEM_TAG_LOGICAL_MAXIMUM 2
#define HID_GLOBAL_ITEM_TAG_PHYSICAL_MINIMUM 3
#define HID_GLOBAL_ITEM_TAG_PHYSICAL_MAXIMUM 4
#define HID_GLOBAL_ITEM_TAG_UNIT_EXPONENT 5
#define HID_GLOBAL_ITEM_TAG_UNIT 6
#define HID_GLOBAL_ITEM_TAG_REPORT_SIZE 7
#define HID_GLOBAL_ITEM_TAG_REPORT_ID 8
#define HID_GLOBAL_ITEM_TAG_REPORT_COUNT 9
#define HID_GLOBAL_ITEM_TAG_PUSH 10
#define HID_GLOBAL_ITEM_TAG_POP 11
/*
* HID report descriptor local item tags
*/
#define HID_LOCAL_ITEM_TAG_USAGE 0
#define HID_LOCAL_ITEM_TAG_USAGE_MINIMUM 1
#define HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM 2
#define HID_LOCAL_ITEM_TAG_DESIGNATOR_INDEX 3
#define HID_LOCAL_ITEM_TAG_DESIGNATOR_MINIMUM 4
#define HID_LOCAL_ITEM_TAG_DESIGNATOR_MAXIMUM 5
#define HID_LOCAL_ITEM_TAG_STRING_INDEX 7
#define HID_LOCAL_ITEM_TAG_STRING_MINIMUM 8
#define HID_LOCAL_ITEM_TAG_STRING_MAXIMUM 9
#define HID_LOCAL_ITEM_TAG_DELIMITER 10
/*
* HID usage tables
*/
#define HID_USAGE_PAGE 0xffff0000
#define HID_UP_UNDEFINED 0x00000000
#define HID_UP_GENDESK 0x00010000
#define HID_UP_SIMULATION 0x00020000
#define HID_UP_GENDEVCTRLS 0x00060000
#define HID_UP_KEYBOARD 0x00070000
#define HID_UP_LED 0x00080000
#define HID_UP_BUTTON 0x00090000
#define HID_UP_ORDINAL 0x000a0000
#define HID_UP_TELEPHONY 0x000b0000
#define HID_UP_CONSUMER 0x000c0000
#define HID_UP_DIGITIZER 0x000d0000
#define HID_UP_PID 0x000f0000
#define HID_UP_HPVENDOR 0xff7f0000
#define HID_UP_HPVENDOR2 0xff010000
#define HID_UP_MSVENDOR 0xff000000
#define HID_UP_CUSTOM 0x00ff0000
#define HID_UP_LOGIVENDOR 0xffbc0000
#define HID_UP_LNVENDOR 0xffa00000
#define HID_UP_SENSOR 0x00200000
#define HID_USAGE 0x0000ffff
#define HID_GD_POINTER 0x00010001
#define HID_GD_MOUSE 0x00010002
#define HID_GD_JOYSTICK 0x00010004
#define HID_GD_GAMEPAD 0x00010005
#define HID_GD_KEYBOARD 0x00010006
#define HID_GD_KEYPAD 0x00010007
#define HID_GD_MULTIAXIS 0x00010008
#define HID_GD_X 0x00010030
#define HID_GD_Y 0x00010031
#define HID_GD_Z 0x00010032
#define HID_GD_RX 0x00010033
#define HID_GD_RY 0x00010034
#define HID_GD_RZ 0x00010035
#define HID_GD_SLIDER 0x00010036
#define HID_GD_DIAL 0x00010037
#define HID_GD_WHEEL 0x00010038
#define HID_GD_HATSWITCH 0x00010039
#define HID_GD_BUFFER 0x0001003a
#define HID_GD_BYTECOUNT 0x0001003b
#define HID_GD_MOTION 0x0001003c
#define HID_GD_START 0x0001003d
#define HID_GD_SELECT 0x0001003e
#define HID_GD_VX 0x00010040
#define HID_GD_VY 0x00010041
#define HID_GD_VZ 0x00010042
#define HID_GD_VBRX 0x00010043
#define HID_GD_VBRY 0x00010044
#define HID_GD_VBRZ 0x00010045
#define HID_GD_VNO 0x00010046
#define HID_GD_FEATURE 0x00010047
#define HID_GD_SYSTEM_CONTROL 0x00010080
#define HID_GD_UP 0x00010090
#define HID_GD_DOWN 0x00010091
#define HID_GD_RIGHT 0x00010092
#define HID_GD_LEFT 0x00010093
#define HID_DC_BATTERYSTRENGTH 0x00060020
#define HID_CP_CONSUMER_CONTROL 0x000c0001
#define HID_DG_DIGITIZER 0x000d0001
#define HID_DG_PEN 0x000d0002
#define HID_DG_LIGHTPEN 0x000d0003
#define HID_DG_TOUCHSCREEN 0x000d0004
#define HID_DG_TOUCHPAD 0x000d0005
#define HID_DG_STYLUS 0x000d0020
#define HID_DG_PUCK 0x000d0021
#define HID_DG_FINGER 0x000d0022
#define HID_DG_TIPPRESSURE 0x000d0030
#define HID_DG_BARRELPRESSURE 0x000d0031
#define HID_DG_INRANGE 0x000d0032
#define HID_DG_TOUCH 0x000d0033
#define HID_DG_UNTOUCH 0x000d0034
#define HID_DG_TAP 0x000d0035
#define HID_DG_TABLETFUNCTIONKEY 0x000d0039
#define HID_DG_PROGRAMCHANGEKEY 0x000d003a
#define HID_DG_INVERT 0x000d003c
#define HID_DG_TIPSWITCH 0x000d0042
#define HID_DG_TIPSWITCH2 0x000d0043
#define HID_DG_BARRELSWITCH 0x000d0044
#define HID_DG_ERASER 0x000d0045
#define HID_DG_TABLETPICK 0x000d0046
#define HID_CP_CONSUMERCONTROL 0x000c0001
#define HID_CP_NUMERICKEYPAD 0x000c0002
#define HID_CP_PROGRAMMABLEBUTTONS 0x000c0003
#define HID_CP_MICROPHONE 0x000c0004
#define HID_CP_HEADPHONE 0x000c0005
#define HID_CP_GRAPHICEQUALIZER 0x000c0006
#define HID_CP_FUNCTIONBUTTONS 0x000c0036
#define HID_CP_SELECTION 0x000c0080
#define HID_CP_MEDIASELECTION 0x000c0087
#define HID_CP_SELECTDISC 0x000c00ba
#define HID_CP_PLAYBACKSPEED 0x000c00f1
#define HID_CP_PROXIMITY 0x000c0109
#define HID_CP_SPEAKERSYSTEM 0x000c0160
#define HID_CP_CHANNELLEFT 0x000c0161
#define HID_CP_CHANNELRIGHT 0x000c0162
#define HID_CP_CHANNELCENTER 0x000c0163
#define HID_CP_CHANNELFRONT 0x000c0164
#define HID_CP_CHANNELCENTERFRONT 0x000c0165
#define HID_CP_CHANNELSIDE 0x000c0166
#define HID_CP_CHANNELSURROUND 0x000c0167
#define HID_CP_CHANNELLOWFREQUENCYENHANCEMENT 0x000c0168
#define HID_CP_CHANNELTOP 0x000c0169
#define HID_CP_CHANNELUNKNOWN 0x000c016a
#define HID_CP_APPLICATIONLAUNCHBUTTONS 0x000c0180
#define HID_CP_GENERICGUIAPPLICATIONCONTROLS 0x000c0200
#define HID_DG_CONFIDENCE 0x000d0047
#define HID_DG_WIDTH 0x000d0048
#define HID_DG_HEIGHT 0x000d0049
#define HID_DG_CONTACTID 0x000d0051
#define HID_DG_INPUTMODE 0x000d0052
#define HID_DG_DEVICEINDEX 0x000d0053
#define HID_DG_CONTACTCOUNT 0x000d0054
#define HID_DG_CONTACTMAX 0x000d0055
#define HID_DG_BUTTONTYPE 0x000d0059
#define HID_DG_BARRELSWITCH2 0x000d005a
#define HID_DG_TOOLSERIALNUMBER 0x000d005b
/*
* HID report types --- Ouch! HID spec says 1 2 3!
*/
#define HID_INPUT_REPORT 0
#define HID_OUTPUT_REPORT 1
#define HID_FEATURE_REPORT 2
#define HID_REPORT_TYPES 3
/*
* HID connect requests
*/
#define HID_CONNECT_HIDINPUT 0x01
#define HID_CONNECT_HIDINPUT_FORCE 0x02
#define HID_CONNECT_HIDRAW 0x04
#define HID_CONNECT_HIDDEV 0x08
#define HID_CONNECT_HIDDEV_FORCE 0x10
#define HID_CONNECT_FF 0x20
#define HID_CONNECT_DRIVER 0x40
#define HID_CONNECT_DEFAULT (HID_CONNECT_HIDINPUT|HID_CONNECT_HIDRAW| \
HID_CONNECT_HIDDEV|HID_CONNECT_FF)
/*
* HID device quirks.
*/
/*
* Increase this if you need to configure more HID quirks at module load time
*/
#define MAX_USBHID_BOOT_QUIRKS 4
#define HID_QUIRK_INVERT 0x00000001
#define HID_QUIRK_NOTOUCH 0x00000002
#define HID_QUIRK_IGNORE 0x00000004
#define HID_QUIRK_NOGET 0x00000008
#define HID_QUIRK_HIDDEV_FORCE 0x00000010
#define HID_QUIRK_BADPAD 0x00000020
#define HID_QUIRK_MULTI_INPUT 0x00000040
#define HID_QUIRK_HIDINPUT_FORCE 0x00000080
#define HID_QUIRK_NO_EMPTY_INPUT 0x00000100
#define HID_QUIRK_NO_INIT_INPUT_REPORTS 0x00000200
#define HID_QUIRK_ALWAYS_POLL 0x00000400
#define HID_QUIRK_SKIP_OUTPUT_REPORTS 0x00010000
#define HID_QUIRK_SKIP_OUTPUT_REPORT_ID 0x00020000
#define HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP 0x00040000
#define HID_QUIRK_FULLSPEED_INTERVAL 0x10000000
#define HID_QUIRK_NO_INIT_REPORTS 0x20000000
#define HID_QUIRK_NO_IGNORE 0x40000000
#define HID_QUIRK_NO_INPUT_SYNC 0x80000000
/*
* HID device groups
*
* Note: HID_GROUP_ANY is declared in linux/mod_devicetable.h
* and has a value of 0x0000
*/
#define HID_GROUP_GENERIC 0x0001
#define HID_GROUP_MULTITOUCH 0x0002
#define HID_GROUP_SENSOR_HUB 0x0003
#define HID_GROUP_MULTITOUCH_WIN_8 0x0004
/*
* Vendor specific HID device groups
*/
#define HID_GROUP_RMI 0x0100
#define HID_GROUP_WACOM 0x0101
#define HID_GROUP_LOGITECH_DJ_DEVICE 0x0102
/*
* This is the global environment of the parser. This information is
* persistent for main-items. The global environment can be saved and
* restored with PUSH/POP statements.
*/
struct hid_global {
unsigned usage_page;
__s32 logical_minimum;
__s32 logical_maximum;
__s32 physical_minimum;
__s32 physical_maximum;
__s32 unit_exponent;
unsigned unit;
unsigned report_id;
unsigned report_size;
unsigned report_count;
};
/*
* This is the local environment. It is persistent up the next main-item.
*/
#define HID_MAX_USAGES 12288
#define HID_DEFAULT_NUM_COLLECTIONS 16
struct hid_local {
unsigned usage[HID_MAX_USAGES]; /* usage array */
unsigned collection_index[HID_MAX_USAGES]; /* collection index array */
unsigned usage_index;
unsigned usage_minimum;
unsigned delimiter_depth;
unsigned delimiter_branch;
};
/*
* This is the collection stack. We climb up the stack to determine
* application and function of each field.
*/
struct hid_collection {
unsigned type;
unsigned usage;
unsigned level;
};
struct hid_usage {
unsigned hid; /* hid usage code */
unsigned collection_index; /* index into collection array */
unsigned usage_index; /* index into usage array */
/* hidinput data */
__u16 code; /* input driver code */
__u8 type; /* input driver type */
__s8 hat_min; /* hat switch fun */
__s8 hat_max; /* ditto */
__s8 hat_dir; /* ditto */
};
struct hid_input;
struct hid_field {
unsigned physical; /* physical usage for this field */
unsigned logical; /* logical usage for this field */
unsigned application; /* application usage for this field */
struct hid_usage *usage; /* usage table for this function */
unsigned maxusage; /* maximum usage index */
unsigned flags; /* main-item flags (i.e. volatile,array,constant) */
unsigned report_offset; /* bit offset in the report */
unsigned report_size; /* size of this field in the report */
unsigned report_count; /* number of this field in the report */
unsigned report_type; /* (input,output,feature) */
__s32 *value; /* last known value(s) */
__s32 logical_minimum;
__s32 logical_maximum;
__s32 physical_minimum;
__s32 physical_maximum;
__s32 unit_exponent;
unsigned unit;
struct hid_report *report; /* associated report */
unsigned index; /* index into report->field[] */
/* hidinput data */
struct hid_input *hidinput; /* associated input structure */
__u16 dpad; /* dpad input code */
};
#define HID_MAX_FIELDS 256
struct hid_report {
struct list_head list;
unsigned id; /* id of this report */
unsigned type; /* report type */
struct hid_field *field[HID_MAX_FIELDS]; /* fields of the report */
unsigned maxfield; /* maximum valid field index */
unsigned size; /* size of the report (bits) */
struct hid_device *device; /* associated device */
};
#define HID_MAX_IDS 256
struct hid_report_enum {
unsigned numbered;
struct list_head report_list;
struct hid_report *report_id_hash[HID_MAX_IDS];
};
#define HID_MIN_BUFFER_SIZE 64 /* make sure there is at least a packet size of space */
#define HID_MAX_BUFFER_SIZE 4096 /* 4kb */
#define HID_CONTROL_FIFO_SIZE 256 /* to init devices with >100 reports */
#define HID_OUTPUT_FIFO_SIZE 64
struct hid_control_fifo {
unsigned char dir;
struct hid_report *report;
char *raw_report;
};
struct hid_output_fifo {
struct hid_report *report;
char *raw_report;
};
#define HID_CLAIMED_INPUT 1
#define HID_CLAIMED_HIDDEV 2
#define HID_CLAIMED_HIDRAW 4
#define HID_CLAIMED_DRIVER 8
#define HID_STAT_ADDED 1
#define HID_STAT_PARSED 2
struct hid_input {
struct list_head list;
struct hid_report *report;
struct input_dev *input;
};
enum hid_type {
HID_TYPE_OTHER = 0,
HID_TYPE_USBMOUSE,
HID_TYPE_USBNONE
};
struct hid_driver;
struct hid_ll_driver;
struct hid_device { /* device report descriptor */
__u8 *dev_rdesc;
unsigned dev_rsize;
__u8 *rdesc;
unsigned rsize;
struct hid_collection *collection; /* List of HID collections */
unsigned collection_size; /* Number of allocated hid_collections */
unsigned maxcollection; /* Number of parsed collections */
unsigned maxapplication; /* Number of applications */
__u16 bus; /* BUS ID */
__u16 group; /* Report group */
__u32 vendor; /* Vendor ID */
__u32 product; /* Product ID */
__u32 version; /* HID version */
enum hid_type type; /* device type (mouse, kbd, ...) */
unsigned country; /* HID country */
struct hid_report_enum report_enum[HID_REPORT_TYPES];
struct work_struct led_work; /* delayed LED worker */
struct semaphore driver_lock; /* protects the current driver, except during input */
struct semaphore driver_input_lock; /* protects the current driver */
struct device dev; /* device */
struct hid_driver *driver;
struct hid_ll_driver *ll_driver;
#ifdef CONFIG_HID_BATTERY_STRENGTH
/*
* Power supply information for HID devices which report
* battery strength. power_supply was successfully registered if
* battery is non-NULL.
*/
struct power_supply *battery;
__s32 battery_min;
__s32 battery_max;
__s32 battery_report_type;
__s32 battery_report_id;
#endif
unsigned int status; /* see STAT flags above */
unsigned claimed; /* Claimed by hidinput, hiddev? */
unsigned quirks; /* Various quirks the device can pull on us */
bool io_started; /* Protected by driver_lock. If IO has started */
struct list_head inputs; /* The list of inputs */
void *hiddev; /* The hiddev structure */
void *hidraw;
int minor; /* Hiddev minor number */
int open; /* is the device open by anyone? */
char name[128]; /* Device name */
char phys[64]; /* Device physical location */
char uniq[64]; /* Device unique identifier (serial #) */
void *driver_data;
/* temporary hid_ff handling (until moved to the drivers) */
int (*ff_init)(struct hid_device *);
/* hiddev event handler */
int (*hiddev_connect)(struct hid_device *, unsigned int);
void (*hiddev_disconnect)(struct hid_device *);
void (*hiddev_hid_event) (struct hid_device *, struct hid_field *field,
struct hid_usage *, __s32);
void (*hiddev_report_event) (struct hid_device *, struct hid_report *);
/* debugging support via debugfs */
unsigned short debug;
struct dentry *debug_dir;
struct dentry *debug_rdesc;
struct dentry *debug_events;
struct list_head debug_list;
spinlock_t debug_list_lock;
wait_queue_head_t debug_wait;
};
static inline void *hid_get_drvdata(struct hid_device *hdev)
{
return dev_get_drvdata(&hdev->dev);
}
static inline void hid_set_drvdata(struct hid_device *hdev, void *data)
{
dev_set_drvdata(&hdev->dev, data);
}
#define HID_GLOBAL_STACK_SIZE 4
#define HID_COLLECTION_STACK_SIZE 4
#define HID_SCAN_FLAG_MT_WIN_8 BIT(0)
#define HID_SCAN_FLAG_VENDOR_SPECIFIC BIT(1)
#define HID_SCAN_FLAG_GD_POINTER BIT(2)
struct hid_parser {
struct hid_global global;
struct hid_global global_stack[HID_GLOBAL_STACK_SIZE];
unsigned global_stack_ptr;
struct hid_local local;
unsigned collection_stack[HID_COLLECTION_STACK_SIZE];
unsigned collection_stack_ptr;
struct hid_device *device;
unsigned scan_flags;
};
struct hid_class_descriptor {
__u8 bDescriptorType;
__le16 wDescriptorLength;
} __attribute__ ((packed));
struct hid_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__le16 bcdHID;
__u8 bCountryCode;
__u8 bNumDescriptors;
struct hid_class_descriptor desc[1];
} __attribute__ ((packed));
#define HID_DEVICE(b, g, ven, prod) \
.bus = (b), .group = (g), .vendor = (ven), .product = (prod)
#define HID_USB_DEVICE(ven, prod) \
.bus = BUS_USB, .vendor = (ven), .product = (prod)
#define HID_BLUETOOTH_DEVICE(ven, prod) \
.bus = BUS_BLUETOOTH, .vendor = (ven), .product = (prod)
#define HID_I2C_DEVICE(ven, prod) \
.bus = BUS_I2C, .vendor = (ven), .product = (prod)
#define HID_REPORT_ID(rep) \
.report_type = (rep)
#define HID_USAGE_ID(uhid, utype, ucode) \
.usage_hid = (uhid), .usage_type = (utype), .usage_code = (ucode)
/* we don't want to catch types and codes equal to 0 */
#define HID_TERMINATOR (HID_ANY_ID - 1)
struct hid_report_id {
__u32 report_type;
};
struct hid_usage_id {
__u32 usage_hid;
__u32 usage_type;
__u32 usage_code;
};
/**
* struct hid_driver
* @name: driver name (e.g. "Footech_bar-wheel")
* @id_table: which devices is this driver for (must be non-NULL for probe
* to be called)
* @dyn_list: list of dynamically added device ids
* @dyn_lock: lock protecting @dyn_list
* @probe: new device inserted
* @remove: device removed (NULL if not a hot-plug capable driver)
* @report_table: on which reports to call raw_event (NULL means all)
* @raw_event: if report in report_table, this hook is called (NULL means nop)
* @usage_table: on which events to call event (NULL means all)
* @event: if usage in usage_table, this hook is called (NULL means nop)
* @report: this hook is called after parsing a report (NULL means nop)
* @report_fixup: called before report descriptor parsing (NULL means nop)
* @input_mapping: invoked on input registering before mapping an usage
* @input_mapped: invoked on input registering after mapping an usage
* @input_configured: invoked just before the device is registered
* @feature_mapping: invoked on feature registering
* @suspend: invoked on suspend (NULL means nop)
* @resume: invoked on resume if device was not reset (NULL means nop)
* @reset_resume: invoked on resume if device was reset (NULL means nop)
*
* probe should return -errno on error, or 0 on success. During probe,
* input will not be passed to raw_event unless hid_device_io_start is
* called.
*
* raw_event and event should return 0 on no action performed, 1 when no
* further processing should be done and negative on error
*
* input_mapping shall return a negative value to completely ignore this usage
* (e.g. doubled or invalid usage), zero to continue with parsing of this
* usage by generic code (no special handling needed) or positive to skip
* generic parsing (needed special handling which was done in the hook already)
* input_mapped shall return negative to inform the layer that this usage
* should not be considered for further processing or zero to notify that
* no processing was performed and should be done in a generic manner
* Both these functions may be NULL which means the same behavior as returning
* zero from them.
*/
struct hid_driver {
char *name;
const struct hid_device_id *id_table;
struct list_head dyn_list;
spinlock_t dyn_lock;
int (*probe)(struct hid_device *dev, const struct hid_device_id *id);
void (*remove)(struct hid_device *dev);
const struct hid_report_id *report_table;
int (*raw_event)(struct hid_device *hdev, struct hid_report *report,
u8 *data, int size);
const struct hid_usage_id *usage_table;
int (*event)(struct hid_device *hdev, struct hid_field *field,
struct hid_usage *usage, __s32 value);
void (*report)(struct hid_device *hdev, struct hid_report *report);
__u8 *(*report_fixup)(struct hid_device *hdev, __u8 *buf,
unsigned int *size);
int (*input_mapping)(struct hid_device *hdev,
struct hid_input *hidinput, struct hid_field *field,
struct hid_usage *usage, unsigned long **bit, int *max);
int (*input_mapped)(struct hid_device *hdev,
struct hid_input *hidinput, struct hid_field *field,
struct hid_usage *usage, unsigned long **bit, int *max);
int (*input_configured)(struct hid_device *hdev,
struct hid_input *hidinput);
void (*feature_mapping)(struct hid_device *hdev,
struct hid_field *field,
struct hid_usage *usage);
#ifdef CONFIG_PM
int (*suspend)(struct hid_device *hdev, pm_message_t message);
int (*resume)(struct hid_device *hdev);
int (*reset_resume)(struct hid_device *hdev);
#endif
/* private: */
struct device_driver driver;
};
/**
* hid_ll_driver - low level driver callbacks
* @start: called on probe to start the device
* @stop: called on remove
* @open: called by input layer on open
* @close: called by input layer on close
* @parse: this method is called only once to parse the device data,
* shouldn't allocate anything to not leak memory
* @request: send report request to device (e.g. feature report)
* @wait: wait for buffered io to complete (send/recv reports)
* @raw_request: send raw report request to device (e.g. feature report)
* @output_report: send output report to device
* @idle: send idle request to device
*/
struct hid_ll_driver {
int (*start)(struct hid_device *hdev);
void (*stop)(struct hid_device *hdev);
int (*open)(struct hid_device *hdev);
void (*close)(struct hid_device *hdev);
int (*power)(struct hid_device *hdev, int level);
int (*parse)(struct hid_device *hdev);
void (*request)(struct hid_device *hdev,
struct hid_report *report, int reqtype);
int (*wait)(struct hid_device *hdev);
int (*raw_request) (struct hid_device *hdev, unsigned char reportnum,
__u8 *buf, size_t len, unsigned char rtype,
int reqtype);
int (*output_report) (struct hid_device *hdev, __u8 *buf, size_t len);
int (*idle)(struct hid_device *hdev, int report, int idle, int reqtype);
};
#define PM_HINT_FULLON 1<<5
#define PM_HINT_NORMAL 1<<1
/* Applications from HID Usage Tables 4/8/99 Version 1.1 */
/* We ignore a few input applications that are not widely used */
#define IS_INPUT_APPLICATION(a) (((a >= 0x00010000) && (a <= 0x00010008)) || (a == 0x00010080) || (a == 0x000c0001) || ((a >= 0x000d0002) && (a <= 0x000d0006)))
/* HID core API */
extern int hid_debug;
extern bool hid_ignore(struct hid_device *);
extern int hid_add_device(struct hid_device *);
extern void hid_destroy_device(struct hid_device *);
extern int __must_check __hid_register_driver(struct hid_driver *,
struct module *, const char *mod_name);
/* use a define to avoid include chaining to get THIS_MODULE & friends */
#define hid_register_driver(driver) \
__hid_register_driver(driver, THIS_MODULE, KBUILD_MODNAME)
extern void hid_unregister_driver(struct hid_driver *);
/**
* module_hid_driver() - Helper macro for registering a HID driver
* @__hid_driver: hid_driver struct
*
* Helper macro for HID drivers which do not do anything special in module
* init/exit. This eliminates a lot of boilerplate. Each module may only
* use this macro once, and calling it replaces module_init() and module_exit()
*/
#define module_hid_driver(__hid_driver) \
module_driver(__hid_driver, hid_register_driver, \
hid_unregister_driver)
extern void hidinput_hid_event(struct hid_device *, struct hid_field *, struct hid_usage *, __s32);
extern void hidinput_report_event(struct hid_device *hid, struct hid_report *report);
extern int hidinput_connect(struct hid_device *hid, unsigned int force);
extern void hidinput_disconnect(struct hid_device *);
int hid_set_field(struct hid_field *, unsigned, __s32);
int hid_input_report(struct hid_device *, int type, u8 *, int, int);
int hidinput_find_field(struct hid_device *hid, unsigned int type, unsigned int code, struct hid_field **field);
struct hid_field *hidinput_get_led_field(struct hid_device *hid);
unsigned int hidinput_count_leds(struct hid_device *hid);
__s32 hidinput_calc_abs_res(const struct hid_field *field, __u16 code);
void hid_output_report(struct hid_report *report, __u8 *data);
void __hid_request(struct hid_device *hid, struct hid_report *rep, int reqtype);
u8 *hid_alloc_report_buf(struct hid_report *report, gfp_t flags);
struct hid_device *hid_allocate_device(void);
struct hid_report *hid_register_report(struct hid_device *device, unsigned type, unsigned id);
int hid_parse_report(struct hid_device *hid, __u8 *start, unsigned size);
struct hid_report *hid_validate_values(struct hid_device *hid,
unsigned int type, unsigned int id,
unsigned int field_index,
unsigned int report_counts);
int hid_open_report(struct hid_device *device);
int hid_check_keys_pressed(struct hid_device *hid);
int hid_connect(struct hid_device *hid, unsigned int connect_mask);
void hid_disconnect(struct hid_device *hid);
const struct hid_device_id *hid_match_id(struct hid_device *hdev,
const struct hid_device_id *id);
s32 hid_snto32(__u32 value, unsigned n);
__u32 hid_field_extract(const struct hid_device *hid, __u8 *report,
unsigned offset, unsigned n);
/**
* hid_device_io_start - enable HID input during probe, remove
*
* @hid - the device
*
* This should only be called during probe or remove and only be
* called by the thread calling probe or remove. It will allow
* incoming packets to be delivered to the driver.
*/
static inline void hid_device_io_start(struct hid_device *hid) {
if (hid->io_started) {
dev_warn(&hid->dev, "io already started");
return;
}
hid->io_started = true;
up(&hid->driver_input_lock);
}
/**
* hid_device_io_stop - disable HID input during probe, remove
*
* @hid - the device
*
* Should only be called after hid_device_io_start. It will prevent
* incoming packets from going to the driver for the duration of
* probe, remove. If called during probe, packets will still go to the
* driver after probe is complete. This function should only be called
* by the thread calling probe or remove.
*/
static inline void hid_device_io_stop(struct hid_device *hid) {
if (!hid->io_started) {
dev_warn(&hid->dev, "io already stopped");
return;
}
hid->io_started = false;
down(&hid->driver_input_lock);
}
/**
* hid_map_usage - map usage input bits
*
* @hidinput: hidinput which we are interested in
* @usage: usage to fill in
* @bit: pointer to input->{}bit (out parameter)
* @max: maximal valid usage->code to consider later (out parameter)
* @type: input event type (EV_KEY, EV_REL, ...)
* @c: code which corresponds to this usage and type
*/
static inline void hid_map_usage(struct hid_input *hidinput,
struct hid_usage *usage, unsigned long **bit, int *max,
__u8 type, __u16 c)
{
struct input_dev *input = hidinput->input;
usage->type = type;
usage->code = c;
switch (type) {
case EV_ABS:
*bit = input->absbit;
*max = ABS_MAX;
break;
case EV_REL:
*bit = input->relbit;
*max = REL_MAX;
break;
case EV_KEY:
*bit = input->keybit;
*max = KEY_MAX;
break;
case EV_LED:
*bit = input->ledbit;
*max = LED_MAX;
break;
}
}
/**
* hid_map_usage_clear - map usage input bits and clear the input bit
*
* The same as hid_map_usage, except the @c bit is also cleared in supported
* bits (@bit).
*/
static inline void hid_map_usage_clear(struct hid_input *hidinput,
struct hid_usage *usage, unsigned long **bit, int *max,
__u8 type, __u16 c)
{
hid_map_usage(hidinput, usage, bit, max, type, c);
clear_bit(c, *bit);
}
/**
* hid_parse - parse HW reports
*
* @hdev: hid device
*
* Call this from probe after you set up the device (if needed). Your
* report_fixup will be called (if non-NULL) after reading raw report from
* device before passing it to hid layer for real parsing.
*/
static inline int __must_check hid_parse(struct hid_device *hdev)
{
return hid_open_report(hdev);
}
/**
* hid_hw_start - start underlaying HW
*
* @hdev: hid device
* @connect_mask: which outputs to connect, see HID_CONNECT_*
*
* Call this in probe function *after* hid_parse. This will setup HW buffers
* and start the device (if not deffered to device open). hid_hw_stop must be
* called if this was successful.
*/
static inline int __must_check hid_hw_start(struct hid_device *hdev,
unsigned int connect_mask)
{
int ret = hdev->ll_driver->start(hdev);
if (ret || !connect_mask)
return ret;
ret = hid_connect(hdev, connect_mask);
if (ret)
hdev->ll_driver->stop(hdev);
return ret;
}
/**
* hid_hw_stop - stop underlaying HW
*
* @hdev: hid device
*
* This is usually called from remove function or from probe when something
* failed and hid_hw_start was called already.
*/
static inline void hid_hw_stop(struct hid_device *hdev)
{
hid_disconnect(hdev);
hdev->ll_driver->stop(hdev);
}
/**
* hid_hw_open - signal underlaying HW to start delivering events
*
* @hdev: hid device
*
* Tell underlying HW to start delivering events from the device.
* This function should be called sometime after successful call
* to hid_hiw_start().
*/
static inline int __must_check hid_hw_open(struct hid_device *hdev)
{
return hdev->ll_driver->open(hdev);
}
/**
* hid_hw_close - signal underlaying HW to stop delivering events
*
* @hdev: hid device
*
* This function indicates that we are not interested in the events
* from this device anymore. Delivery of events may or may not stop,
* depending on the number of users still outstanding.
*/
static inline void hid_hw_close(struct hid_device *hdev)
{
hdev->ll_driver->close(hdev);
}
/**
* hid_hw_power - requests underlying HW to go into given power mode
*
* @hdev: hid device
* @level: requested power level (one of %PM_HINT_* defines)
*
* This function requests underlying hardware to enter requested power
* mode.
*/
static inline int hid_hw_power(struct hid_device *hdev, int level)
{
return hdev->ll_driver->power ? hdev->ll_driver->power(hdev, level) : 0;
}
/**
* hid_hw_request - send report request to device
*
* @hdev: hid device
* @report: report to send
* @reqtype: hid request type
*/
static inline void hid_hw_request(struct hid_device *hdev,
struct hid_report *report, int reqtype)
{
if (hdev->ll_driver->request)
return hdev->ll_driver->request(hdev, report, reqtype);
__hid_request(hdev, report, reqtype);
}
/**
* hid_hw_raw_request - send report request to device
*
* @hdev: hid device
* @reportnum: report ID
* @buf: in/out data to transfer
* @len: length of buf
* @rtype: HID report type
* @reqtype: HID_REQ_GET_REPORT or HID_REQ_SET_REPORT
*
* @return: count of data transfered, negative if error
*
* Same behavior as hid_hw_request, but with raw buffers instead.
*/
static inline int hid_hw_raw_request(struct hid_device *hdev,
unsigned char reportnum, __u8 *buf,
size_t len, unsigned char rtype, int reqtype)
{
if (len < 1 || len > HID_MAX_BUFFER_SIZE || !buf)
return -EINVAL;
return hdev->ll_driver->raw_request(hdev, reportnum, buf, len,
rtype, reqtype);
}
/**
* hid_hw_output_report - send output report to device
*
* @hdev: hid device
* @buf: raw data to transfer
* @len: length of buf
*
* @return: count of data transfered, negative if error
*/
static inline int hid_hw_output_report(struct hid_device *hdev, __u8 *buf,
size_t len)
{
if (len < 1 || len > HID_MAX_BUFFER_SIZE || !buf)
return -EINVAL;
if (hdev->ll_driver->output_report)
return hdev->ll_driver->output_report(hdev, buf, len);
return -ENOSYS;
}
/**
* hid_hw_idle - send idle request to device
*
* @hdev: hid device
* @report: report to control
* @idle: idle state
* @reqtype: hid request type
*/
static inline int hid_hw_idle(struct hid_device *hdev, int report, int idle,
int reqtype)
{
if (hdev->ll_driver->idle)
return hdev->ll_driver->idle(hdev, report, idle, reqtype);
return 0;
}
/**
* hid_hw_wait - wait for buffered io to complete
*
* @hdev: hid device
*/
static inline void hid_hw_wait(struct hid_device *hdev)
{
if (hdev->ll_driver->wait)
hdev->ll_driver->wait(hdev);
}
/**
* hid_report_len - calculate the report length
*
* @report: the report we want to know the length
*/
static inline int hid_report_len(struct hid_report *report)
{
/* equivalent to DIV_ROUND_UP(report->size, 8) + !!(report->id > 0) */
return ((report->size - 1) >> 3) + 1 + (report->id > 0);
}
int hid_report_raw_event(struct hid_device *hid, int type, u8 *data, int size,
int interrupt);
/* HID quirks API */
u32 usbhid_lookup_quirk(const u16 idVendor, const u16 idProduct);
int usbhid_quirks_init(char **quirks_param);
void usbhid_quirks_exit(void);
#ifdef CONFIG_HID_PID
int hid_pidff_init(struct hid_device *hid);
#else
#define hid_pidff_init NULL
#endif
#define dbg_hid(format, arg...) \
do { \
if (hid_debug) \
printk(KERN_DEBUG "%s: " format, __FILE__, ##arg); \
} while (0)
#define hid_printk(level, hid, fmt, arg...) \
dev_printk(level, &(hid)->dev, fmt, ##arg)
#define hid_emerg(hid, fmt, arg...) \
dev_emerg(&(hid)->dev, fmt, ##arg)
#define hid_crit(hid, fmt, arg...) \
dev_crit(&(hid)->dev, fmt, ##arg)
#define hid_alert(hid, fmt, arg...) \
dev_alert(&(hid)->dev, fmt, ##arg)
#define hid_err(hid, fmt, arg...) \
dev_err(&(hid)->dev, fmt, ##arg)
#define hid_notice(hid, fmt, arg...) \
dev_notice(&(hid)->dev, fmt, ##arg)
#define hid_warn(hid, fmt, arg...) \
dev_warn(&(hid)->dev, fmt, ##arg)
#define hid_info(hid, fmt, arg...) \
dev_info(&(hid)->dev, fmt, ##arg)
#define hid_dbg(hid, fmt, arg...) \
dev_dbg(&(hid)->dev, fmt, ##arg)
#endif
| {'content_hash': '3d768fbe83205c9f26ec96565e90e59b', 'timestamp': '', 'source': 'github', 'line_count': 1142, 'max_line_length': 160, 'avg_line_length': 30.643607705779335, 'alnum_prop': 0.7093870552936133, 'repo_name': 'KristFoundation/Programs', 'id': '251a1d382e2325a17e0acb169d6e111589cf7444', 'size': '35119', 'binary': False, 'copies': '136', 'ref': 'refs/heads/master', 'path': 'luaide/include/linux/hid.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '10201036'}, {'name': 'Awk', 'bytes': '30879'}, {'name': 'C', 'bytes': '539626448'}, {'name': 'C++', 'bytes': '3413466'}, {'name': 'Clojure', 'bytes': '1570'}, {'name': 'Cucumber', 'bytes': '4809'}, {'name': 'Groff', 'bytes': '46837'}, {'name': 'Lex', 'bytes': '55541'}, {'name': 'Lua', 'bytes': '59745'}, {'name': 'Makefile', 'bytes': '1601043'}, {'name': 'Objective-C', 'bytes': '521706'}, {'name': 'Perl', 'bytes': '730609'}, {'name': 'Perl6', 'bytes': '3783'}, {'name': 'Python', 'bytes': '296036'}, {'name': 'Shell', 'bytes': '357961'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '12797'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '115572'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="maven" version="1.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="java" version="1.8"/>
<installed facet="jst.web" version="3.1"/>
</faceted-project>
| {'content_hash': 'd96132a21f3456addbb70886d522437b', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 49, 'avg_line_length': 37.0, 'alnum_prop': 0.6385135135135135, 'repo_name': 'smallyaohailu/jeesite', 'id': '8c93fd7b92e727738638dfedd45f5fda30738371', 'size': '296', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.settings/org.eclipse.wst.common.project.facet.core.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '54451'}, {'name': 'HTML', 'bytes': '87972'}, {'name': 'Java', 'bytes': '1586964'}, {'name': 'JavaScript', 'bytes': '1787004'}]} |
#include "paging.h"
const struct page_table* p4_table = 0xfffffffffffff000;
static int64_t read_tlb() {
int64_t val;
asm volatile ("mov %%cr3, %0" : "=r"(val));
return val;
}
static void write_tlb(int64_t val) {
asm volatile ("mov %0, %%cr3" : : "r"(val));
}
static void flush_tlb() {
write_tlb(read_tlb());
}
static void invalidate_page(intptr_t addr) {
asm volatile("invlpg (%0)"
:
: "r"(addr)
: "memory");
}
static void enable_no_exec() {
asm volatile("push %%rcx\n"
"mov $0xC0000080, %%ecx\n"
"rdmsr\n"
"or $0x800, %%eax\n"
"wrmsr\n"
"pop %%rcx"
:
:
: "%ecx");
}
/*
Bit Name Full Name Description
0 PE Protected Mode Enable If 1, system is in protected mode, else system is in real mode
1 MP Monitor co-processor Controls interaction of WAIT/FWAIT instructions with TS flag in CR0
2 EM Emulation If set, no x87 floating point unit present, if clear, x87 FPU present
3 TS Task switched Allows saving x87 task context upon a task switch only after x87 instruction used
4 ET Extension type On the 386, it allowed to specify whether the external math coprocessor was an 80287 or 80387
5 NE Numeric error Enable internal x87 floating point error reporting when set, else enables PC style x87 error detection
16 WP Write protect When set, the CPU can't write to read-only pages when privilege level is 0
18 AM Alignment mask Alignment check enabled if AM set, AC flag (in EFLAGS register) set, and privilege level is 3
29 NW Not-write through Globally enables/disable write-through caching
30 CD Cache disable Globally enables/disable the memory cache
31 PG Paging If 1, enable paging and use the CR3 register, else disable paging
*/
enum cr0_bits {
cr0_protected_mode_enable = 1,
cr0_monitor_co_processor = 1 << 1,
cr0_emulation = 1 << 2,
cr0_task_switched = 1 << 3,
cr0_extension_type = 1 << 4,
cr0_numeric_error = 1 << 5,
cr0_write_protect = 1 << 16,
cr0_alignment_mask = 1 << 18,
cr0_not_write_through = 1 << 29,
cr0_cache_disable = 1 << 30,
cr0_paging = 1 << 31
};
/*
Bit Name Full Name Description
0 VME Virtual 8086 Mode Extensions If set, enables support for the virtual interrupt flag (VIF) in virtual-8086 mode.
1 PVI Protected-mode Virtual Interrupts If set, enables support for the virtual interrupt flag (VIF) in protected mode.
2 TSD Time Stamp Disable If set, RDTSC instruction can only be executed when in ring 0, otherwise RDTSC can be used at any privilege level.
3 DE Debugging Extensions If set, enables debug register based breaks on I/O space access
4 PSE Page Size Extension If unset, page size is 4 KiB, else page size is increased to 4 MiB (if PAE is enabled or the processor is in Long Mode this bit is ignored[1]).
5 PAE Physical Address Extension If set, changes page table layout to translate 32-bit virtual addresses into extended 36-bit physical addresses.
6 MCE Machine Check Exception If set, enables machine check interrupts to occur.
7 PGE Page Global Enabled If set, address translations (PDE or PTE records) may be shared between address spaces.
8 PCE Performance-Monitoring Counter enable If set, RDPMC can be executed at any privilege level, else RDPMC can only be used in ring 0.
9 OSFXSR Operating system support for FXSAVE and FXRSTOR instructions If set, enables SSE instructions and fast FPU save & restore
10 OSXMMEXCPT Operating System Support for Unmasked SIMD Floating-Point Exceptions If set, enables unmasked SSE exceptions.
13 VMXE Virtual Machine Extensions Enable see Intel VT-x
14 SMXE Safer Mode Extensions Enable see Trusted Execution Technology (TXT)
16 FSGSBASE Enables the instructions RDFSBASE, RDGSBASE, WRFSBASE, and WRGSBASE.
17 PCIDE PCID Enable If set, enables process-context identifiers (PCIDs).
18 OSXSAVE XSAVE and Processor Extended States Enable
20 SMEP[2] Supervisor Mode Execution Protection Enable If set, execution of code in a higher ring generates a fault
21 SMAP Supervisor Mode Access Protection Enable If set, access of data in a higher ring generates a fault[3]
22 PKE Protection Key Enable See Intel® 64 and IA-32 Architectures Software Developer’s Manual
*/
enum cr4_bits {
cr4_vme = 1,
cr4_pvi = 1 << 1,
cr4_tsd = 1 << 2,
cr4_de = 1 << 3,
cr4_pse = 1 << 4,
cr4_pae = 1 << 5,
cr4_mce = 1 << 6,
cr4_pge = 1 << 7,
cr4_pce = 1 << 8,
cr4_osfxsr = 1 << 9,
cr4_osxmmecpt = 1 << 10,
cr4_vmxe = 1 << 13,
cr4_smxe = 1 << 14,
cr4_fsgsbase = 1 << 15,
cr4_pcide = 1 << 17,
cr4_osxsave = 1 << 18,
cr4_smep = 1 << 20,
cr4_smap = 1 << 21,
cr4_pke = 1 << 22
};
/*
Bit Purpose
0 SCE (System Call Extensions)
1–7 Reserved
8 LME (Long Mode Enable)
9 Reserved
10 LMA (Long Mode Active)
11 NXE (No-Execute Enable)
12 SVME (Secure Virtual Machine Enable)
13 LMSLE (Long Mode Segment Limit Enable)
14 FFXSR (Fast FXSAVE/FXRSTOR)
15 TCE (Translation Cache Extension)
16–63 Reserved
*/
const uint32_t ia32_msfr = 0xC0000080;
enum efer_bits {
efer_sce = 1,
efer_lme = 1 << 8,
efer_lma = 1 << 10,
efer_nxe = 1 << 11,
efer_svme = 1 << 12,
efer_lmsle = 1 << 13,
efer_ffxsr = 1 << 14,
efer_tce = 1 << 15
};
static uint64_t read_efer(uint32_t msr) {
uint32_t low, high;
asm volatile("mov %2, %%ecx\n"
"rdmsr\n"
"mov %%eax, %0\n"
"mov %%edx, %1\n"
: "=r"(low), "=r"(high)
: "r"(msr)
: "%ecx", "%rax", "%rdx");
return low | (high << 32);
}
static void write_efer(uint64_t val, uint32_t msr) {
uint32_t low = val & 0xffffffff;
uint32_t high = val >> 32;
asm volatile("mov %0, %%ecx\n"
"mov %1, %%eax\n"
"mov %2, %%edx\n"
"wrmsr\n"
:
: "r"(msr), "r"(low), "r"(high)
: "%ecx", "%rax", "%rdx");
}
static int64_t read_cr0() {
int64_t val;
asm volatile ("mov %%cr0, %0" : "=r"(val));
return val;
}
static void write_cr0(int64_t val) {
asm volatile ("mov %0, %%cr0" : : "r"(val));
}
static int64_t read_cr4() {
int64_t val;
asm volatile ("mov %%cr4, %0" : "=r"(val));
return val;
}
static void write_cr4(int64_t val) {
asm volatile ("mov %0, %%cr0" : : "r"(val));
}
static enable_write_protect() {
write_cr0(read_cr0() | cr0_write_protect);
}
void set_unused(struct page_table_entry* entry) {
entry->entry = 0x0;
}
void init_page_table(struct page_table* table) {
for(int i=0; i<PAGE_TABLE_ENTRY_COUNT; ++i) {
set_unused(&table->entries[i]);
}
}
struct page_table* descened_page_table(struct page_table *table, size_t index) {
if(index >= 512) {
return NULL;
}
if(table->entries[index].entry & (present_bit | !huge_bit)) {
return (struct page_table*)( ((uintptr_t)table->entries << 9) | (index << 12) );
}
return NULL;
}
void set_page_table_entry(struct page_table_entry *entry, struct frame *frame, uintptr_t flags) {
//assert that the frame is aligned to 4096 bytes
assert(((!physical_addr_mask) & get_frame_start_addr(frame)) == 0);
entry->entry = (get_frame_start_addr(frame) & physical_addr_mask) | flags;
}
/* Return 0 if success. 1 if frame is not present in memory.
*
*/
int get_physical_frame(struct page_table_entry *entry, struct frame *f) {
if(entry->entry & present_bit) {
get_frame_for_addr(f, entry->entry & physical_addr_mask);
return 0;
}
return -1;
}
void get_page_for_vaddr(virtual_addr_t vaddr, struct page* p) {
assert(vaddr < 0x0000800000000000 || vaddr >= 0xffff800000000000);
p->number = vaddr / PAGE_SIZE;
}
uint16_t get_p4_index(struct page* p) {
return (p->number >> 27) & 0777;
}
uint16_t get_p3_index(struct page* p) {
return (p->number >> 18) & 0777;
}
uint16_t get_p2_index(struct page* p) {
return (p->number >> 9) & 0777;
}
uint16_t get_p1_index(struct page* p) {
return p->number & 0777;
}
int translate_page(struct page *page, struct frame *frame) {
struct page_table* table = p4_table;
table = descened_page_table(table, get_p4_index(page));
if(table->entries[get_p3_index(page)].entry & huge_bit) {
//todo
}
table = descened_page_table(table, get_p3_index(page));
if(table->entries[get_p2_index(page)].entry & huge_bit) {
//todo
if(0 != get_physical_frame(&table->entries[get_p2_index(page)], frame))
return -1;
frame->number += get_p1_index(page);
return 0;
}
table = descened_page_table(table, get_p2_index(page));
return get_physical_frame(&table->entries[get_p1_index(page)], frame);
}
physical_addr_t translate(virtual_addr_t vaddr) {
struct page page;
struct frame f;
get_page_for_vaddr(vaddr, &page);
translate_page(&page, &f);
return (f.number * PAGE_SIZE) + (vaddr % PAGE_SIZE);
}
struct page_table* get_next_page_table_or_create(struct page_table* table, uint16_t index) {
struct page_table* tbl = descened_page_table(table, index);
if(tbl == NULL) {
struct frame frame;
int success = allocate_frame(&frame);
if(success == 0) {
set_page_table_entry(&table->entries[index], &frame, present_bit | writeable_bit);
flush_tlb();
}
}
return descened_page_table(table, index);
}
void map_page_to_frame(struct page *page, struct frame *frame, uintptr_t flags) {
struct page_table* p3_table = get_next_page_table_or_create(p4_table, get_p4_index(page));
struct page_table* p2_table = get_next_page_table_or_create(p3_table, get_p3_index(page));
struct page_table* p1_table = get_next_page_table_or_create(p2_table, get_p2_index(page));
//make sure unused here!
set_page_table_entry(&p1_table->entries[get_p1_index(page)], frame, present_bit | flags);
}
void map_page(struct page *page, uintptr_t flags) {
struct frame frame;
int success = allocate_frame(&frame);
map_page_to_frame(page, &frame, flags);
}
void identity_map_page(struct frame *frame, uintptr_t flags) {
struct page p;
get_page_for_vaddr(get_frame_start_addr(frame), &p);
map_page_to_frame(&p, frame, flags);
}
void unmap_page(struct page *page) {
struct page_table* table = p4_table;
table = descened_page_table(table, get_p4_index(page));
table = descened_page_table(table, get_p3_index(page));
table = descened_page_table(table, get_p2_index(page));
set_unused(&table->entries[get_p1_index(page)]);
struct frame frame;
get_physical_frame(&table->entries[get_p1_index(page)], &frame);
deallocate_frame(&frame);
flush_tlb();
}
static intptr_t get_p4_table_phys_addr() {
return read_tlb();
}
void remap_kernel() {
enable_no_exec();
//enable_write_protect(); //currently breaks as it makes stack unwritable
struct page page;
page.number = 0xdeadbeef;
struct frame new_p4_frame;
int success = allocate_frame(&new_p4_frame);
map_page_to_frame(&page, &new_p4_frame, present_bit | writeable_bit);
struct page old_p4_page;
old_p4_page.number = 0xdddd0000;
struct frame old_p4_frame;
get_frame_for_addr(&old_p4_frame, (uintptr_t)read_tlb());
terminal_printf("Old page addr: %#zx\n", old_p4_frame.number);
map_page_to_frame(&old_p4_page, &old_p4_frame, present_bit | writeable_bit);
flush_tlb();
struct page_table *old_p4_table = old_p4_page.number * PAGE_SIZE;
init_page_table(page.number*PAGE_SIZE);
terminal_printf("CR3 = %#zx\n", read_tlb());
terminal_printf("Old p4 entry[511] %#zX\n", p4_table->entries[511]);
terminal_printf("Old p4 entry[511] %#zX\n", old_p4_table->entries[511]);
terminal_printf("New p4 frame addr %#zX\n", get_frame_start_addr(&new_p4_frame));
set_page_table_entry(page.number*PAGE_SIZE + (8 * 511), &new_p4_frame, present_bit | writeable_bit);
set_page_table_entry(&p4_table->entries[511], &new_p4_frame, present_bit | writeable_bit);
terminal_printf("new p4 entry[511] %#zX\n", p4_table->entries[511]);
flush_tlb();
for(int i=0; i<data.elf_symbols->num; ++i) {
struct multiboot_elf_section_header* section = &data.elf_symbols->sectionheaders[i];
if(!elf_section_is_allocated(section)) {
continue;
}
uintptr_t addr = section->sh_addr;
uintptr_t end_addr = section->sh_addr + section->sh_size - 1;
assert(addr % PAGE_SIZE == 0);
assert(addr <= end_addr);
uintptr_t flags = present_bit;
if(!elf_section_is_exectuable(section)) {
flags |= no_exec_bit;
}
if(elf_section_is_writable(section)) {
flags |= writeable_bit;
}
terminal_printf("Addr: %#zx\tFlags : %#zX\n", addr, flags);
while(addr < end_addr) {
struct frame frame;
get_frame_for_addr(&frame, addr);
addr += PAGE_SIZE;
identity_map_page(&frame, flags);
}
}
//id map the vga buffer
struct frame vga_frame;
get_frame_for_addr(&vga_frame, 0xb8000);
identity_map_page(&vga_frame, writeable_bit | present_bit | no_exec_bit);
//id map the multiboot structure
for(intptr_t mboot_addr = (intptr_t)data.start; mboot_addr <= data.start + data.start->total_size; mboot_addr += PAGE_SIZE) {
struct frame mboot_frame;
get_frame_for_addr(&mboot_frame, mboot_addr);
identity_map_page(&mboot_frame, present_bit | no_exec_bit);
}
terminal_printf("New kernel page tables set up.\n");
//restore old p4
set_page_table_entry(&old_p4_table->entries[511], &old_p4_frame, present_bit | writeable_bit);
flush_tlb();
terminal_printf("Old p4 entry[511] %#zX\n", p4_table->entries[511]);
unmap_page(&old_p4_page);
write_tlb(new_p4_frame.number*PAGE_SIZE);
flush_tlb();
//create guard page from old p4 frame
struct page guard_page;
guard_page.number = old_p4_frame.number;
unmap_page(&guard_page);
terminal_printf("End of remap.\n");
}
/* From http://git.qemu.org/?p=qemu.git;a=blob;f=target/i386/monitor.c
47 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
48 " %c%c%c%c%c%c%c%c%c\n",
49 addr,
50 pte & mask,
51 pte & PG_NX_MASK ? 'X' : '-',
52 pte & PG_GLOBAL_MASK ? 'G' : '-',
53 pte & PG_PSE_MASK ? 'P' : '-',
54 pte & PG_DIRTY_MASK ? 'D' : '-',
55 pte & PG_ACCESSED_MASK ? 'A' : '-',
56 pte & PG_PCD_MASK ? 'C' : '-',
57 pte & PG_PWT_MASK ? 'T' : '-',
58 pte & PG_USER_MASK ? 'U' : '-',
59 pte & PG_RW_MASK ? 'W' : '-');
*/ | {'content_hash': 'e5c566fb1580fe57c2719ae46eba0184', 'timestamp': '', 'source': 'github', 'line_count': 458, 'max_line_length': 169, 'avg_line_length': 32.80567685589519, 'alnum_prop': 0.6181031613976705, 'repo_name': 'RichardHScott/os_c', 'id': '4fb7d53e0e95d152be9cbc45fd895ee38283294b', 'size': '15032', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/paging.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '10068'}, {'name': 'Batchfile', 'bytes': '172'}, {'name': 'C', 'bytes': '74588'}, {'name': 'Makefile', 'bytes': '1426'}]} |
package de.uni_hildesheim.sse.qmApp.commands;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.ProgressIndicator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import de.uni_hildesheim.sse.qmApp.dialogs.Dialogs;
import de.uni_hildesheim.sse.qmApp.dialogs.DialogsUtil;
import de.uni_hildesheim.sse.qmApp.model.Location;
import de.uni_hildesheim.sse.qmApp.model.Reasoning;
import de.uni_hildesheim.sse.qmApp.model.Utils;
import de.uni_hildesheim.sse.qmApp.model.VariabilityModel;
import de.uni_hildesheim.sse.qmApp.model.Utils.ConfigurationProperties;
import de.uni_hildesheim.sse.repositoryConnector.IRepositoryConnector;
import de.uni_hildesheim.sse.repositoryConnector.UserContext;
import de.uni_hildesheim.sse.repositoryConnector.svnConnector.SVNConnector;
import de.uni_hildesheim.sse.repositoryConnector.svnConnector.ConnectorException;
import de.uni_hildesheim.sse.repositoryConnector.svnConnector.RepositoryEventHandler;
/**
* The handler for the "commit model" command.
*
* @author Holger Eichelberger, Aike Sass
*/
public class CommitModel extends AbstractHandler {
private static final String EXCEPTION_TITLE = "Connector Exception";
private IRepositoryConnector repositoryConnector;
private ProgressIndicator progress;
private Display display;
private Shell shell;
/**
* Creates the instantiate command.
*/
public CommitModel() {
repositoryConnector = new SVNConnector();
if (UserContext.INSTANCE.getUsername() == null) {
setBaseEnabled(false);
} else {
repositoryConnector.setRepositoryURL(ConfigurationProperties.REPOSITORY_URL.getValue());
try {
repositoryConnector.authenticate(UserContext.INSTANCE.getUsername(),
UserContext.INSTANCE.getPassword());
} catch (ConnectorException e) {
Dialogs.showErrorDialog(EXCEPTION_TITLE, e.getMessage());
}
setBaseEnabled(true);
}
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
HandlerUtils.saveDirty(true);
if (Reasoning.reasonOn(VariabilityModel.Definition.TOP_LEVEL, false)) {
new Thread(new ModelUpdate()).start();
}
return null;
}
/**
* Implements the model update running in parallel to the user interface so
* that user interface updates can happen.
*
* @author Sass
*/
private class ModelUpdate implements Runnable, RepositoryEventHandler {
/**
* Creates a model updater.
*/
private ModelUpdate() {
repositoryConnector.setCommitEventHandler(this);
display = PlatformUI.getWorkbench().getDisplay();
shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setSize(300, 100);
shell.setText("Commiting");
shell.setLocation(DialogsUtil.getXPosition(shell, display), DialogsUtil.getYPosition(shell, display));
progress = new ProgressIndicator(shell, SWT.HORIZONTAL);
progress.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
try {
if (repositoryConnector.getChangesCount(Location.getModelLocationFile(), false) > 0) {
shell.open();
} else {
MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK | SWT.CANCEL);
dialog.setText("Info");
dialog.setMessage("There are no changes in your workspace.");
dialog.open();
}
} catch (ConnectorException e) {
Dialogs.showErrorDialog(EXCEPTION_TITLE, e.getMessage());
}
}
@Override
public void progress(final double status) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
progress.worked(status);
}
});
}
@Override
public void completed() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
progress.done();
shell.dispose();
}
});
}
@Override
public void run() {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
progress.beginTask(repositoryConnector.getChangesCount(Location.getModelLocationFile(), false));
} catch (ConnectorException e) {
Dialogs.showErrorDialog(EXCEPTION_TITLE, e.getMessage());
}
}
});
boolean conflicts;
try {
conflicts = repositoryConnector.storeModel(Utils.getDestinationFileForModel());
if (conflicts) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
try {
repositoryConnector.updateModel(Utils.getDestinationFileForModel());
repositoryConnector.resolveConflicts(Utils.getDestinationFileForModel(), false);
MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
dialog.setText("Info");
dialog.setMessage("There were some conflicts. Local changes were overwritten.");
int messageBox = dialog.open();
switch (messageBox) {
case SWT.OK:
completed();
break;
default:
// TODO
break;
}
} catch (ConnectorException e) {
Dialogs.showErrorDialog(EXCEPTION_TITLE, e.getMessage());
}
}
});
}
} catch (ConnectorException e) {
Dialogs.showErrorDialog(EXCEPTION_TITLE, e.getMessage());
}
}
}
}
| {'content_hash': 'ed2194630efc4fcb19829801f86bd01d', 'timestamp': '', 'source': 'github', 'line_count': 178, 'max_line_length': 120, 'avg_line_length': 38.60112359550562, 'alnum_prop': 0.5722602241304031, 'repo_name': 'QualiMaster/QM-IConf', 'id': '72e9667a2adfdd00211c13a600ee2d3b631c31bd', 'size': '6871', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'QualiMasterApplication/src/de/uni_hildesheim/sse/qmApp/commands/CommitModel.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2941'}, {'name': 'HTML', 'bytes': '3071'}, {'name': 'Java', 'bytes': '2591289'}]} |
package org.bdgenomics.adam.ds.feature
import org.bdgenomics.formats.avro.{ Dbxref, Feature, OntologyTerm, Strand }
import scala.collection.JavaConversions._
import scala.collection.mutable.{ ArrayBuffer, HashMap, MutableList }
import scala.math.{ max, min }
/**
* Utility methods on features and related classes.
*/
private[feature] object Features {
/**
* Parse a strand from the specified string.
*
* @param s string to parse
* @return a strand parsed from the specified string, or None if the stand
* is unspecified or incorrectly specified
*/
def toStrand(s: String): Option[Strand] = {
s.trim match {
case "+" => Some(Strand.FORWARD)
case "-" => Some(Strand.REVERSE)
case "." => Some(Strand.INDEPENDENT)
case "?" => Some(Strand.UNKNOWN)
case _ => None
}
}
/**
* Convert the specified strand to its string value.
*
* @param strand strand to convert
* @param emptyUnknown If true, returns an empty string if we fall through the
* match. Else, returns the unknown string.
* @return the specified strand converted to its string value
*/
def asString(strand: Strand, emptyUnknown: Boolean = false): String = {
strand match {
case Strand.FORWARD => "+"
case Strand.REVERSE => "-"
case Strand.INDEPENDENT => "."
case Strand.UNKNOWN => "?"
case _ => {
if (emptyUnknown) {
""
} else {
"?"
}
}
}
}
/**
* Parse a database cross reference from the specified string.
*
* @param s string to parse
* @return a database cross reference parsed from the specified string, or None if
* the database cross reference is unspecified or incorrectly specified
*/
def toDbxref(s: String): Option[Dbxref] = {
val i = s.indexOf(':')
if (i >= 0) {
Some(new Dbxref(s.substring(0, i), s.substring(i)))
} else {
None
}
}
/**
* Convert the specified database cross reference to its string value.
*
* @param dbxref database cross reference to convert
* @return the specified database cross reference converted to its string value
*/
def asString(dbxref: Dbxref): String = {
dbxref.getDb + ":" + dbxref.getAccession
}
/**
* Parse an ontology term from the specified string.
*
* @param s string to parse
* @return an ontology term parsed from the specified string, or None if
* the ontology term is unspecified or incorrectly specified
*/
def toOntologyTerm(s: String): Option[OntologyTerm] = {
val i = s.indexOf(':')
if (i >= 0) {
Some(new OntologyTerm(s.substring(0, i), s.substring(i)))
} else {
None
}
}
/**
* Convert the specified ontology term to its string value.
*
* @param ontologyTerm ontology term to convert
* @return the specified ontology term converted to its string value
*/
def asString(ontologyTerm: OntologyTerm): String = {
ontologyTerm.getDb + ":" + ontologyTerm.getAccession
}
/**
* Assign values for various feature fields from a sequence of attribute key value pairs.
*
* @param attributes sequence of attribute key value pairs
* @param f feature builder
* @return the specified feature builder
*/
def assignAttributes(attributes: Seq[(String, String)], f: Feature.Builder): Feature.Builder = {
// initialize empty builder list fields
val aliases = new MutableList[String]()
val notes = new MutableList[String]()
val parentIds = new MutableList[String]()
val dbxrefs = new MutableList[Dbxref]()
val ontologyTerms = new MutableList[OntologyTerm]()
// set id, name, target, gap, derivesFrom, and isCircular
// and populate aliases, notes, parentIds, dbxrefs, and ontologyTerms
// from attributes if specified
val remaining = new HashMap[String, String]
attributes.foreach(entry =>
entry._1 match {
// reserved keys in GFF3 specification
case "ID" => f.setFeatureId(entry._2)
case "Name" => f.setName(entry._2)
case "Target" => f.setTarget(entry._2)
case "Gap" => f.setGap(entry._2)
case "Derives_from" => f.setDerivesFrom(entry._2)
case "Is_circular" => f.setCircular(entry._2.toBoolean)
// sampleId information
case "sampleId" => f.setSampleId(entry._2)
case "Alias" => aliases += entry._2
case "Note" => notes += entry._2
case "Parent" => parentIds += entry._2
case "Dbxref" => toDbxref(entry._2).foreach(dbxrefs += _)
case "Ontology_term" => toOntologyTerm(entry._2).foreach(ontologyTerms += _)
// commonly used keys in GTF/GFF2, e.g. via Ensembl
case "gene_id" => f.setGeneId(entry._2)
case "transcript_id" => f.setTranscriptId(entry._2)
case "exon_id" => f.setExonId(entry._2)
case "protein_id" => f.setProteinId(entry._2)
// unrecognized key, save to attributes
case _ => remaining += entry
}
)
// set list fields if non-empty
if (aliases.nonEmpty) f.setAliases(aliases)
if (notes.nonEmpty) f.setNotes(notes)
if (parentIds.nonEmpty) f.setParentIds(parentIds)
if (dbxrefs.nonEmpty) f.setDbxrefs(dbxrefs)
if (ontologyTerms.nonEmpty) f.setOntologyTerms(ontologyTerms)
// set remaining attributes if non-empty;
// any duplicate keys are lost at this point, last one in wins
if (remaining.nonEmpty) f.setAttributes(remaining)
f
}
/**
* Gather values from various feature fields into a sequence of attribute key value pairs.
*
* @param feature feature to gather values from
* @return values from various feature fields gathered into a sequence of attribute key value pairs
*/
def gatherAttributes(feature: Feature): Seq[(String, String)] = {
val attrs = new ArrayBuffer[(String, String)]
def addBooleanTuple(b: java.lang.Boolean) = {
attrs += Tuple2("Is_circular", b.toString)
}
Option(feature.getFeatureId).foreach(attrs += Tuple2("ID", _))
Option(feature.getName).foreach(attrs += Tuple2("Name", _))
Option(feature.getTarget).foreach(attrs += Tuple2("Target", _))
Option(feature.getGap).foreach(attrs += Tuple2("Gap", _))
Option(feature.getDerivesFrom).foreach(attrs += Tuple2("Derives_from", _))
Option(feature.getCircular).foreach(addBooleanTuple)
Option(feature.getGeneId).foreach(attrs += Tuple2("gene_id", _))
Option(feature.getTranscriptId).foreach(attrs += Tuple2("transcript_id", _))
Option(feature.getExonId).foreach(attrs += Tuple2("exon_id", _))
Option(feature.getProteinId).foreach(attrs += Tuple2("protein_id", _))
Option(feature.getSampleId).foreach(attrs += Tuple2("sampleId", _))
for (alias <- feature.getAliases) attrs += Tuple2("Alias", alias)
for (note <- feature.getNotes) attrs += Tuple2("Note", note)
for (parentId <- feature.getParentIds) attrs += Tuple2("Parent", parentId)
for (dbxref <- feature.getDbxrefs) attrs += Tuple2("Dbxref", asString(dbxref))
for (ontologyTerm <- feature.getOntologyTerms) attrs += Tuple2("Ontology_term", asString(ontologyTerm))
attrs ++= feature.getAttributes.toSeq
}
/**
* Build a name for the specified feature considering its attributes. Used when
* writing out to lossy feature formats such as BED, NarrowPeak, and IntervalList.
*
* @param feature feature
* @return a name for the specified feature considering its attributes
*/
def nameOf(feature: Feature): String = {
Option(feature.getName).foreach(return _)
Option(feature.getFeatureId).foreach(return _)
feature.getFeatureType match {
case "exon" | "SO:0000147" => Option(feature.getExonId).foreach(return _)
case "transcript" | "SO:0000673" => Option(feature.getTranscriptId).foreach(return _)
case "gene" | "SO:0000704" => Option(feature.getGeneId).foreach(return _)
case s: String => Option(s).foreach(return _)
case null =>
}
"sequence_feature"
}
/**
* Format the feature score as double floating point values
* with "." as missing value.
*
* @param score Feature score to format.
* @return Return the specified feature score formatted as
* double floating point values with "." as missing value.
*/
def formatScore(score: java.lang.Double): String = {
Option(score).fold(".")(_.toString)
}
/**
* Interpolate the feature score to integer values between 0 and 1000,
* with missing value as specified.
*
* @param score Feature score to interpolate.
* @param minimumScore Minimum score, interpolated to 0.
* @param maximumScore Maximum score, interpolated to 1000.
* @param missingValue Value to use if score is not specified.
* @return Return the specified feature score interpolated to integer values
* between 0 and 1000, with missing value as specified.
*/
def interpolateScore(score: java.lang.Double,
minimumScore: Double,
maximumScore: Double,
missingValue: Int): Int = {
def constrain(v: Double, min: Double, max: Double): Double = {
if (v < min) {
min
} else if (v > max) {
max
} else {
v
}
}
def interp(value: Double,
sourceMin: Double,
sourceMax: Double,
targetMin: Double,
targetMax: Double): Double = {
val v = max(min(sourceMax, value), sourceMin)
targetMin + (targetMax - targetMin) * ((v - sourceMin) / (sourceMax - sourceMin))
}
Option(score).fold(missingValue)(interp(_, minimumScore, maximumScore, 0, 1000).toInt)
}
}
| {'content_hash': '4c6a3f4fca4ad11d5e8482d854241a98', 'timestamp': '', 'source': 'github', 'line_count': 269, 'max_line_length': 107, 'avg_line_length': 36.58364312267658, 'alnum_prop': 0.6350980591403312, 'repo_name': 'heuermh/adam', 'id': '3fdca67eb8a5b1b1e69e4b4e2574e608ac01ade6', 'size': '10634', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'adam-core/src/main/scala/org/bdgenomics/adam/ds/feature/Features.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '55385'}, {'name': 'Makefile', 'bytes': '4025'}, {'name': 'Python', 'bytes': '140113'}, {'name': 'R', 'bytes': '101505'}, {'name': 'Scala', 'bytes': '2306680'}, {'name': 'Shell', 'bytes': '16324'}]} |
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest import exceptions
from tempest import test
class TokensV3TestJSON(base.BaseIdentityV3AdminTest):
_interface = 'json'
@test.attr(type='smoke')
def test_tokens(self):
# Valid user's token is authenticated
# Create a User
u_name = data_utils.rand_name('user-')
u_desc = '%s-description' % u_name
u_email = '%s@testmail.tm' % u_name
u_password = data_utils.rand_name('pass-')
_, user = self.client.create_user(
u_name, description=u_desc, password=u_password,
email=u_email)
self.addCleanup(self.client.delete_user, user['id'])
# Perform Authentication
resp, body = self.token.auth(user['id'], u_password)
self.assertEqual(201, resp.status)
subject_token = resp['x-subject-token']
# Perform GET Token
_, token_details = self.client.get_token(subject_token)
self.assertEqual(resp['x-subject-token'], subject_token)
self.assertEqual(token_details['user']['id'], user['id'])
self.assertEqual(token_details['user']['name'], u_name)
# Perform Delete Token
self.client.delete_token(subject_token)
self.assertRaises(exceptions.NotFound, self.client.get_token,
subject_token)
@test.skip_because(bug="1351026")
@test.attr(type='gate')
def test_rescope_token(self):
"""Rescope a token.
An unscoped token can be requested, that token can be used to request a
scoped token. The scoped token can be revoked, and the original token
used to get a token in a different project.
"""
# Create a user.
user_name = data_utils.rand_name(name='user-')
user_password = data_utils.rand_name(name='pass-')
_, user = self.client.create_user(user_name, password=user_password)
self.addCleanup(self.client.delete_user, user['id'])
# Create a couple projects
project1_name = data_utils.rand_name(name='project-')
_, project1 = self.client.create_project(project1_name)
self.addCleanup(self.client.delete_project, project1['id'])
project2_name = data_utils.rand_name(name='project-')
_, project2 = self.client.create_project(project2_name)
self.addCleanup(self.client.delete_project, project2['id'])
# Create a role
role_name = data_utils.rand_name(name='role-')
_, role = self.client.create_role(role_name)
self.addCleanup(self.client.delete_role, role['id'])
# Grant the user the role on both projects.
self.client.assign_user_role(project1['id'], user['id'],
role['id'])
self.client.assign_user_role(project2['id'], user['id'],
role['id'])
# Get an unscoped token.
resp, token_auth = self.token.auth(user=user['id'],
password=user_password)
self.assertEqual(201, resp.status)
token_id = resp['x-subject-token']
orig_expires_at = token_auth['token']['expires_at']
orig_issued_at = token_auth['token']['issued_at']
orig_user = token_auth['token']['user']
self.assertIsInstance(token_auth['token']['expires_at'], unicode)
self.assertIsInstance(token_auth['token']['issued_at'], unicode)
self.assertEqual(['password'], token_auth['token']['methods'])
self.assertEqual(user['id'], token_auth['token']['user']['id'])
self.assertEqual(user['name'], token_auth['token']['user']['name'])
self.assertEqual('default',
token_auth['token']['user']['domain']['id'])
self.assertEqual('Default',
token_auth['token']['user']['domain']['name'])
self.assertNotIn('catalog', token_auth['token'])
self.assertNotIn('project', token_auth['token'])
self.assertNotIn('roles', token_auth['token'])
# Use the unscoped token to get a scoped token.
resp, token_auth = self.token.auth(token=token_id,
tenant=project1_name,
domain='Default')
token1_id = resp['x-subject-token']
self.assertEqual(201, resp.status)
self.assertEqual(orig_expires_at, token_auth['token']['expires_at'],
'Expiration time should match original token')
self.assertIsInstance(token_auth['token']['issued_at'], unicode)
self.assertNotEqual(orig_issued_at, token_auth['token']['issued_at'])
self.assertEqual(set(['password', 'token']),
set(token_auth['token']['methods']))
self.assertEqual(orig_user, token_auth['token']['user'],
'User should match original token')
self.assertIsInstance(token_auth['token']['catalog'], list)
self.assertEqual(project1['id'],
token_auth['token']['project']['id'])
self.assertEqual(project1['name'],
token_auth['token']['project']['name'])
self.assertEqual('default',
token_auth['token']['project']['domain']['id'])
self.assertEqual('Default',
token_auth['token']['project']['domain']['name'])
self.assertEqual(1, len(token_auth['token']['roles']))
self.assertEqual(role['id'], token_auth['token']['roles'][0]['id'])
self.assertEqual(role['name'], token_auth['token']['roles'][0]['name'])
# Revoke the unscoped token.
self.client.delete_token(token1_id)
# Now get another scoped token using the unscoped token.
resp, token_auth = self.token.auth(token=token_id,
tenant=project2_name,
domain='Default')
self.assertEqual(201, resp.status)
self.assertEqual(project2['id'],
token_auth['token']['project']['id'])
self.assertEqual(project2['name'],
token_auth['token']['project']['name'])
class TokensV3TestXML(TokensV3TestJSON):
_interface = 'xml'
| {'content_hash': '1606e2d3a7d34db4a0ac49b4ebbb33d7', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 79, 'avg_line_length': 44.858156028368796, 'alnum_prop': 0.5753359683794467, 'repo_name': 'Mirantis/tempest', 'id': 'bd08614b566b84542a550714702c4fbf48ad015d', 'size': '6961', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tempest/api/identity/admin/v3/test_tokens.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '3297127'}, {'name': 'Shell', 'bytes': '8663'}]} |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from crawler import views
from searcher import views
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'searcher.views.search', name='search'),
url(r'^(?P<page>[0-9]+)/$', 'searcher.views.search', name='search'),
url(r'^video/(?P<video_id>[-\w]+)/$', 'searcher.views.video_by_id',name='video'),
url(r'^crawl/', 'crawler.views.crawl', name='crawl'),
) | {'content_hash': '81056386d375159a01301db3c9b3ec98', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 85, 'avg_line_length': 40.583333333333336, 'alnum_prop': 0.6570841889117043, 'repo_name': 'nazeehshoura/crawler', 'id': '6f19ba7c8d29ea4728677c6f828085c4aad9bcb8', 'size': '487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'search_engine/urls.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '41725'}, {'name': 'HTML', 'bytes': '6070'}, {'name': 'JavaScript', 'bytes': '77499'}, {'name': 'Python', 'bytes': '13976'}]} |
require 'spec_helper'
describe Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference do
before do
@fixtures_path = File.expand_path('../../fixtures', __FILE__)
end
it "parse the file correctly" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/teste_class_and_args.rb")
dependencies, methods = parser.parse(file_content)
first_parsed_class = methods[0]
expect(first_parsed_class.class_name).to eql("Teste")
expect(first_parsed_class.method_calls.count).to eql(7)
method_calls = first_parsed_class.method_calls
expect(method_calls[2].class_name).to eql("C::D")
expect(method_calls[2].method_name).to eql(:some_method)
expect(method_calls[2].params[0]).to eql(:param1)
end
it "parse the file correctly 2" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/teste_class_and_args2.rb")
dependencies, methods = parser.parse(file_content)
expect(dependencies.size).to be_eql(2)
expect(methods.size).to be_eql(1)
method = methods[0]
expect(method.method_name).to be_eql(:initialize)
method_calls = method.method_calls
expect(method_calls.size).to be_eql(3)
expect(method_calls[0].method_name).to be_eql(:is_a?)
expect(method_calls[0].params).to include("ActionView::LookupContext")
expect(method_calls[1].method_name).to be_eql(:new)
expect(method_calls[1].params).to include(:context)
expect(method_calls[2].method_name).to be_eql(:new)
expect(method_calls[2].params).to include("ActionView::LookupContext")
end
it "parse the file correctly 3" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/rails_action_view_class_teste.rb")
dependencies, methods = parser.parse(file_content)
expect(dependencies.first.dependencies).to include("Helpers")
expect(dependencies[8].dependencies).to include("ActiveSupport::InheritableOptions")
expect(dependencies[8].dependencies).to include("ActionView::LookupContext")
expect(dependencies[8].dependencies).to include("ActionView::Renderer")
end
it "parse the file correctly 4" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/rails_active_record_class.rb")
dependencies, methods = parser.parse(file_content)
end
it "parse the file correclty 5" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/homebrew_bottles_class.rb")
dependencies, methods = parser.parse(file_content)
expect(dependencies.last.dependencies).to include("MacOS::Version")
end
it "parse the file correclty 6" do
parser = Archruby::Ruby::TypeInference::Ruby::ParserForTypeinference.new
file_content = File.read("#{@fixtures_path}/homebrew_brew_teste.rb")
dependencies, methods = parser.parse(file_content)
end
end
| {'content_hash': '8346c5ba64c4be3ec87e5e6fdd82ec57', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 88, 'avg_line_length': 44.55072463768116, 'alnum_prop': 0.7205595315549772, 'repo_name': 'sergiotp/archruby', 'id': '7c0fa15438c7150fd4a6f3c0138162633b370806', 'size': '3074', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/ruby/type_inference/ruby/parser_for_typeinference_spec.rb', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1484'}, {'name': 'HTML', 'bytes': '4249'}, {'name': 'JavaScript', 'bytes': '664'}, {'name': 'Ruby', 'bytes': '216445'}]} |
using Highcharts4Net.Library.Helpers;
namespace Highcharts4Net.Library.Options
{
/// <summary>
/// Options for the dial or arrow pointer of the gauge.
/// </summary>
public class PlotOptionsGaugeDial
{
/// <summary>
/// The background or fill color of the gauge's dial.
/// Default: black
/// </summary>
//[JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)]
public ColorOrGradient BackgroundColor { get; set; }
/// <summary>
/// The length of the dial's base part, relative to the total radius or length of the dial.
/// Default: 70%
/// </summary>
public string BaseLength { get; set; }
/// <summary>
/// The pixel width of the base of the gauge dial. The base is the part closest to the pivot, defined by baseLength.
/// Default: 3
/// </summary>
public HighchartsDataPoint? BaseWidth { get; set; }
/// <summary>
/// The border color or stroke of the gauge's dial. By default, the borderWidth is 0, so this must be set in addition to a custom border color.
/// Default: silver
/// </summary>
public ColorOrGradient BorderColor { get; set; }
/// <summary>
/// The width of the gauge dial border in pixels.
/// Default: 0
/// </summary>
public HighchartsDataPoint? BorderWidth { get; set; }
/// <summary>
/// The radius or length of the dial, in percentages relative to the radius of the gauge itself.
/// Default: 80%
/// </summary>
public string Radius { get; set; }
/// <summary>
/// The length of the dial's rear end, the part that extends out on the other side of the pivot. Relative to the dial's length.
/// Default: 10%
/// </summary>
public string RearLength { get; set; }
/// <summary>
/// The width of the top of the dial, closest to the perimeter. The pivot narrows in from the base to the top.
/// Default: 1
/// </summary>
public HighchartsDataPoint? TopWidth { get; set; }
}
} | {'content_hash': 'b98e7fa8b06169084548d9eecfe5b765', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 145, 'avg_line_length': 30.41269841269841, 'alnum_prop': 0.6664926931106472, 'repo_name': 'davcs86/Highcharts4Net', 'id': '8c5d5e71e087029b74d1f5091298090358672b19', 'size': '1916', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Highcharts4Net/Library/Options/PlotOptionsGaugeDial.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1311879'}, {'name': 'JavaScript', 'bytes': '1215'}]} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.apache.hadoop.hbase.shaded.com.google.protobuf;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.Descriptors.EnumDescriptor;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.Descriptors.EnumValueDescriptor;
/**
* Interface of useful methods added to all enums generated by the protocol
* compiler.
*/
public interface ProtocolMessageEnum extends Internal.EnumLite {
/**
* Return the value's numeric value as defined in the .proto file.
*/
@Override
int getNumber();
/**
* Return the value's descriptor, which contains information such as
* value name, number, and type.
*/
EnumValueDescriptor getValueDescriptor();
/**
* Return the enum type's descriptor, which contains information
* about each defined value, etc.
*/
EnumDescriptor getDescriptorForType();
}
| {'content_hash': '29ea87c21ac76743d429a14ab1af2d55', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 90, 'avg_line_length': 42.30508474576271, 'alnum_prop': 0.7616185897435898, 'repo_name': 'gustavoanatoly/hbase', 'id': '7b40fbef86c7b36fec05a99390be3fe0f48f093d', 'size': '2496', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'hbase-protocol-shaded/src/main/java/org/apache/hadoop/hbase/shaded/com/google/protobuf/ProtocolMessageEnum.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '351'}, {'name': 'Batchfile', 'bytes': '23942'}, {'name': 'C', 'bytes': '28534'}, {'name': 'C++', 'bytes': '56085'}, {'name': 'CMake', 'bytes': '13186'}, {'name': 'CSS', 'bytes': '35785'}, {'name': 'HTML', 'bytes': '15644'}, {'name': 'Java', 'bytes': '31160752'}, {'name': 'JavaScript', 'bytes': '2694'}, {'name': 'Makefile', 'bytes': '1359'}, {'name': 'PHP', 'bytes': '8385'}, {'name': 'Perl', 'bytes': '383739'}, {'name': 'Protocol Buffer', 'bytes': '262179'}, {'name': 'Python', 'bytes': '87467'}, {'name': 'Ruby', 'bytes': '481475'}, {'name': 'Scala', 'bytes': '439837'}, {'name': 'Shell', 'bytes': '175165'}, {'name': 'Thrift', 'bytes': '41474'}, {'name': 'XSLT', 'bytes': '6764'}]} |
<?php
App::uses('CtkNode', 'Ctk.Lib');
App::uses('CtkContent', 'Ctk.Lib');
App::uses('CtkEvent', 'Ctk.Lib');
/**
* Abstract class representing a base element in HTML.
*
* @package Ctk.Factory
*/
abstract class HtmlElement extends CtkNode {
/**
* The template to use for this object.
*
* @var string The name of the template.
*/
protected $_template = 'element';
/**
* The configuration parameters used by the template for this object.
*
* @var array The template configuration parameters.
*/
protected $_params = array(
'accesskey' => null,
'attributes' => null,
'class' => null,
'contenteditable' => null,
'contextmenu' => null,
'dir' => null,
'draggable' => null,
'dropzone' => null,
'events' => null,
'hidden' => null,
'lang' => null,
'spellcheck' => null,
'style' => null,
'tabindex' => null,
'title' => null,
'buffer' => null
);
/**
* The type of element this object represents.
*
* @var string The element type.
*/
protected $_nodeType = 'element';
/**
* The collection of attributes for the HTML element.
*
* @var array The element attributes.
*/
protected $_attributes = array();
/**
* Determines if a given attribute has been set.
*
* @param string $name Name of the attribute.
* @return boolean
*/
final public function hasAttribute($name) {
return isset($this->_attributes[strtolower($name)]);
}
/**
* Returns an attribute set on the element.
*
* @param string $name Name of the attribute.
* @return mixed
* @throws CakeException if attribute has not been previously set.
*/
final public function getAttribute($name) {
if ($this->hasAttribute($name)) {
return $this->_attributes[strtolower($name)];
}
throw new CakeException(sprintf('Unknown attribute: %s', $name));
}
/**
* Sets an attribute on the element.
*
* @param string $name Name of the attribute.
* @param mixed $value Value of the attribute.
* @return HtmlElement
*/
final public function setAttribute($name, $value = null) {
$this->_attributes[strtolower($name)] = $value;
return $this;
}
/**
* Removes a previously set attribute from the element.
*
* @param string $name Name of the attribute.
* @return HtmlElement
*/
final public function removeAttribute($name) {
unset($this->_attributes[strtolower($name)]);
return $this;
}
/**
* Removes all attributes previously set on the element.
*
* @return HtmlElement
*/
final public function clearAttributes() {
$this->_attributes = array();
return $this;
}
/**
* Gets the content for the attributes for the template.
*
* @param array $params The params to create as attributes if a value is set.
* @return string
*/
final public function parseAttributes($params = array()) {
$content = '';
$params = array_merge(array('accesskey', 'contenteditable', 'contextmenu', 'dir', 'draggable', 'dropzone', 'events', 'hidden', 'lang', 'spellcheck', 'style', 'tabindex', 'title'), $params);
if ($this->__isset('attributes') && is_array($this->attributes)) {
foreach ($this->attributes as $name => $value) {
$content .= ' ' . $name . '="' . htmlentities($value) . '"';
}
}
foreach ($params as $name) {
if (isset($this->$name)) {
$content .= ' ' . $name . '="' . htmlentities($this->$name) . '"';
}
}
foreach ($this->_attributes as $name => $value) {
if ($name !== 'class') {
$content .= ' ' . $name . '="' . htmlentities($value) . '"';
}
}
return $content;
}
/**
* Gets the content for the class attribute for the template.
*
* @return string
*/
final public function parseClass() {
$content = ' class="html-element html-' . $this->getType();
if ($this->__isset('class')) {
$content .= ' ' . $this->__get('class');
}
if ($this->hasAttribute('class')) {
$content .= ' ' . $this->_attributes['class'];
}
return $content . '"';
}
/**
* Gets the content for the events for the template.
*
* @return string
*/
final public function parseEvents() {
$listeners = array();
$events = $this->getEvents();
if ($this->hasEvents()) {
foreach ($events as $type => $objects) {
foreach ($objects as $event) {
$listeners[] = $this->JsFactory->Listener(array(
'node' => $this,
'type' => $type,
'code' => $event
));
}
}
}
if (isset($this->events)) {
if ($this->allowsEvents()) {
foreach ($this->events as $type => $event) {
$listeners[] = $this->JsFactory->Listener(array(
'node' => $this,
'type' => $type,
'code' => $event
));
}
}
}
if (count($listeners) > 0) {
$factory = $this->getFactory();
$buffer = (isset($factory->settings['buffer']))? $factory->settings['buffer'] : $this->buffer;
if (!empty($buffer)) {
$view = $factory->getView();
$view->append((is_string($buffer))? $buffer : 'script', new CtkContent($view, '<script type="text/javascript">' . implode('', $listeners) . '</script>'));
} else {
return '<script type="text/javascript">' . implode('', $listeners) . '</script>';
}
}
return '';
}
}
| {'content_hash': 'beb3dfb4a2071c77ff98160d837c4e38', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 191, 'avg_line_length': 24.862068965517242, 'alnum_prop': 0.6084802853180107, 'repo_name': 'jameswatts/cake-toolkit', 'id': 'a9ca025cd2b646db12924b3001ab590ec70bfedb', 'size': '5615', 'binary': False, 'copies': '1', 'ref': 'refs/heads/beta', 'path': 'View/Factory/Html/Objects/HtmlElement.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '368003'}]} |
category: posts
draft: false
title: Pages Full of Links to Cool Things
date: 2021-03-24 22:22:38
tags:
- technology
- web
- lists
- resources
- nostalgia
---
[Terra](https://marijn.uk/linkroll/), [Gossip's Web](https://gossipsweb.net/), and [Marijn's Linkroll](https://marijn.uk/linkroll/) remind my (oldass) self of a more innocent time when one would 'surf the internet', come by a list of links another human being liked, and discover all sorts of strange and wacky handmade things. I think I'm saying I really miss how _fun_ [something like Geocities](https://neocities.org/) was.
God [this is really happening](/misc/o/old-man-cloud.png)...
**Update**
[Blogsurf.io](https://blogsurf.io/) is another blog aggregator managed by a human being.
| {'content_hash': '7f848d68414a1c9961fc1c98bf10592e', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 426, 'avg_line_length': 35.13636363636363, 'alnum_prop': 0.7128072445019404, 'repo_name': 'afreeorange/log', 'id': '6150e3845b41521aa98e3d8a52f03642ee2be3f7', 'size': '777', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'posts/2021/pages-full-of-links-to-cool-things.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '19499'}, {'name': 'Python', 'bytes': '13478'}, {'name': 'Shell', 'bytes': '852'}]} |
"""
test_sv.py -- Test cases for Simple VIVO
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2015 (c) Michael Conlon"
__license__ = "New BSD license"
__version__ = "1.00"
def run_tests(tests):
"""
Run a series of tests. Produce timing for each
:return: dictionary of test timings keyed by test id.
"""
from datetime import datetime
from subprocess import call
test_timings = {}
for test_id in tests:
start = datetime.now()
try:
rc = call(tests[test_id], shell=True)
except OSError as error_thing:
rc = str(error_thing)
end = datetime.now()
elapsed = (end - start).total_seconds()
test_timings[test_id] = [rc, elapsed]
return test_timings
def main():
"""
Run tests, print results
:return: None
"""
tests = {
# "summarize": "python ../sv.py -a summarize",
# "serialize": "python ../sv.py -a serialize",
# "update": "python ../sv.py -a update",
# "get": "python ../sv.py -a get -s get.txt",
# "help": "python ../sv.py -h",
# "test": "python ../sv.py -a test",
# "config not found": "python ../sv.py -a update -c data/cfg_not_found.cfg",
# "file not found": "python ../sv.py -a update -c data/file_not_found.cfg",
"invalid access": "python ../sv.py -a test -c data/invalid_access.cfg",
# "invalid JSON": "python ../sv.py -a update -d data/grant_invalid_def.json",
# "awards get": "cd ../examples/awards; python ../../sv.py -a get -s get.txt",
# "awards update": "cd ../examples/awards; python ../../sv.py -a update",
# "concepts get": "cd ../examples/concepts; python ../../sv.py -a get -s get.txt",
# "concepts update": "cd ../examples/concepts; python ../../sv.py -a update",
# "courses get": "cd ../examples/courses; python ../../sv.py -c sv_courses.cfg -a get -s get.txt",
# "courses update": "cd ../examples/courses; python ../../sv.py -c sv_courses.cfg -a update",
# "teaching get": "cd ../examples/courses; python ../../sv.py -a get -s get.txt",
# "teaching update": "cd ../examples/courses; python ../../sv.py -a update",
# "dates get": "cd ../examples/dates; python ../../sv.py -a get -s get.txt",
# "dates update": "cd ../examples/dates; python ../../sv.py -a update",
# "education get": "cd ../examples/education; python ../../sv.py -a get -s get.txt",
# "education update": "cd ../examples/education; python ../../sv.py -a update",
# "grants get": "cd ../examples/grants; python ../../sv.py -a get -s get.txt",
# "grants update": "cd ../examples/grants; python ../../sv.py -a update",
# "journals get": "cd ../examples/journals; python ../../sv.py -a get -s get.txt",
# "journals update": "cd ../examples/journals; python ../../sv.py -a update",
# "locations get": "cd ../examples/locations; python ../../sv.py -a get -s get.txt",
# "locations update": "cd ../examples/locations; python ../../sv.py -a update",
# "orgs get": "cd ../examples/orgs; python ../../sv.py -a get -s get.txt",
# "orgs update": "cd ../examples/orgs; python ../../sv.py -a update",
# "people get": "cd ../examples/people; python ../../sv.py -a get -s get.txt",
# "people update": "cd ../examples/people; python ../../sv.py -a update",
# "positions get": "cd ../examples/positions; python ../../sv.py -a get -s get.txt",
# "positions update": "cd ../examples/positions; python ../../sv.py -a update"
}
test_results = run_tests(tests)
for testid in sorted(test_results):
print testid.rjust(20), test_results[testid][0], "\t", test_results[testid][1]
if __name__ == "__main__":
main()
| {'content_hash': '52b06c2fe4110b0a546618e3e96a25ef', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 106, 'avg_line_length': 48.278481012658226, 'alnum_prop': 0.557420031463031, 'repo_name': 'indera/vivo-pump', 'id': '17265f763351feb5c3b1b542fb138593bb665264', 'size': '3851', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/test_sv.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Makefile', 'bytes': '1398'}, {'name': 'Python', 'bytes': '266337'}, {'name': 'TeX', 'bytes': '945852'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '5ff16b7e10371c2c5ee1f00c176bd37f', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '0906de68faf371bac784be53c4945fd2c7b3454c', 'size': '185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Cyperus/Cyperus seemannianus/ Syn. Cyperus upoluensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |