text
stringlengths 2
1.04M
| meta
dict |
|---|---|
package com.baidu.oped.apm.bootstrap.interceptor.group;
import com.baidu.oped.apm.bootstrap.interceptor.AfterInterceptor5;
import com.baidu.oped.apm.bootstrap.interceptor.AroundInterceptor5;
import com.baidu.oped.apm.bootstrap.interceptor.BeforeInterceptor5;
import com.baidu.oped.apm.bootstrap.logging.PLogger;
import com.baidu.oped.apm.bootstrap.logging.PLoggerFactory;
/**
* @author emeroad
*/
public class GroupedInterceptor5 implements AroundInterceptor5 {
private final PLogger logger = PLoggerFactory.getLogger(getClass());
private final boolean debugEnabled = logger.isDebugEnabled();
private final BeforeInterceptor5 before;
private final AfterInterceptor5 after;
private final InterceptorGroup group;
private final ExecutionPolicy policy;
public GroupedInterceptor5(BeforeInterceptor5 before, AfterInterceptor5 after, InterceptorGroup group, ExecutionPolicy policy) {
this.before = before;
this.after = after;
this.group = group;
this.policy = policy;
}
@Override
public void before(Object target, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4) {
InterceptorGroupInvocation transaction = group.getCurrentInvocation();
if (transaction.tryEnter(policy)) {
if (before != null) {
before.before(target, arg0, arg1, arg2, arg3, arg4);
}
} else {
if (debugEnabled) {
logger.debug("tryBefore() returns false: interceptorGroupTransaction: {}, executionPoint: {}. Skip interceptor {}", new Object[] {transaction, policy, before == null ? null : before.getClass()} );
}
}
}
@Override
public void after(Object target, Object arg0, Object arg1, Object arg2, Object arg3, Object arg4, Object result, Throwable throwable) {
InterceptorGroupInvocation transaction = group.getCurrentInvocation();
if (transaction.canLeave(policy)) {
if (after != null) {
after.after(target, arg0, arg1, arg2, arg3, arg4, result, throwable);
}
transaction.leave(policy);
} else {
if (debugEnabled) {
logger.debug("tryAfter() returns false: interceptorGroupTransaction: {}, executionPoint: {}. Skip interceptor {}", new Object[] {transaction, policy, after == null ? null : after.getClass()} );
}
}
}
}
|
{
"content_hash": "cf9cdd70a2b61535f9682e18900a08f6",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 212,
"avg_line_length": 40.916666666666664,
"alnum_prop": 0.6659877800407332,
"repo_name": "masonmei/java-agent",
"id": "4cc59ec3ce03cc5bf705a98cc580a74b34f7b7e7",
"size": "3049",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bootstrap-core/src/main/java/com/baidu/oped/apm/bootstrap/interceptor/group/GroupedInterceptor5.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "198"
},
{
"name": "Groovy",
"bytes": "1380"
},
{
"name": "Java",
"bytes": "4208633"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Shell",
"bytes": "548"
},
{
"name": "Thrift",
"bytes": "6834"
}
],
"symlink_target": ""
}
|
// @flow
import React, { useCallback } from 'react';
import { Image, View } from 'react-native';
import { useSelector } from 'react-redux';
import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { isGifEnabled } from '../../../gifs/functions';
import { navigate } from '../../../mobile/navigation/components/conference/ConferenceNavigationContainerRef';
import { screen } from '../../../mobile/navigation/routes';
import { REACTIONS } from '../../constants';
import RaiseHandButton from './RaiseHandButton';
import ReactionButton from './ReactionButton';
/**
* The type of the React {@code Component} props of {@link ReactionMenu}.
*/
type Props = {
/**
* Used to close the overflow menu after raise hand is clicked.
*/
onCancel: Function,
/**
* Whether or not it's displayed in the overflow menu.
*/
overflowMenu: boolean
};
/**
* Animated reaction emoji.
*
* @returns {ReactElement}
*/
function ReactionMenu({
onCancel,
overflowMenu
}: Props) {
const _styles = useSelector(state => ColorSchemeRegistry.get(state, 'Toolbox'));
const gifEnabled = useSelector(isGifEnabled);
const openGifMenu = useCallback(() => {
navigate(screen.conference.gifsMenu);
onCancel();
}, []);
return (
<View style = { overflowMenu ? _styles.overflowReactionMenu : _styles.reactionMenu }>
<View style = { _styles.reactionRow }>
{
Object.keys(REACTIONS).map(key => (
<ReactionButton
key = { key }
reaction = { key }
styles = { _styles.reactionButton } />
))
}
{
gifEnabled && (
<ReactionButton
onClick = { openGifMenu }
styles = { _styles.reactionButton }>
<Image
height = { 22 }
source = { require('../../../../../images/GIPHY_icon.png') } />
</ReactionButton>
)
}
</View>
<RaiseHandButton onCancel = { onCancel } />
</View>
);
}
export default ReactionMenu;
|
{
"content_hash": "25adc087f890529b140f7f1d8ad240ba",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 109,
"avg_line_length": 30.584415584415584,
"alnum_prop": 0.5146496815286624,
"repo_name": "jitsi/jitsi-meet",
"id": "cc88ce4371a30c68435fc8eac38e4a1cebe46874",
"size": "2355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "react/features/reactions/components/native/ReactionMenu.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "829"
},
{
"name": "HTML",
"bytes": "20408"
},
{
"name": "Java",
"bytes": "232895"
},
{
"name": "JavaScript",
"bytes": "2550511"
},
{
"name": "Lua",
"bytes": "301404"
},
{
"name": "Makefile",
"bytes": "4160"
},
{
"name": "Objective-C",
"bytes": "154389"
},
{
"name": "Ruby",
"bytes": "7816"
},
{
"name": "SCSS",
"bytes": "152946"
},
{
"name": "Shell",
"bytes": "36422"
},
{
"name": "Starlark",
"bytes": "152"
},
{
"name": "Swift",
"bytes": "50411"
},
{
"name": "TypeScript",
"bytes": "2866536"
}
],
"symlink_target": ""
}
|
package EquationEditor.Tree;
/**
* Superclass for all different Math objects of the tree to inherit fields/methods from
* @author Alex Billingsley
*/
public class MathObject implements java.io.Serializable {
private String name;
private int id;
private MathObject parent = null;
/** Creates a new instance of MathObject */
public MathObject(int id, String name) {
this.name=name;
this.id=id;
}
/** Returns the field <code>name</code>
* @return The string <code>name</code>
*/
public String getName() {
return name;
}
public int getID() {
return id;
}
/** Sets the field <code>parent</code> from the parameter
* @param parent the <code>MathObject</code> to set as the <code>parent</code>
*/
public void setParent(MathObject parent) {
this.parent = parent;
}
/** Returns the field <code>parent</code>
* @return The field <code>parent</code> of type <code>MathObject</code>
*/
public MathObject getParent() {
return parent;
}
}
|
{
"content_hash": "b6fb0b8d5d472e08b230152bc24cbb4c",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 87,
"avg_line_length": 21.53846153846154,
"alnum_prop": 0.6035714285714285,
"repo_name": "HamdaBinteAjmal/PROFET",
"id": "6dcb3906047d5fa20655f20252ce943798d4f48c",
"size": "1816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EquationEditor/Tree/MathObject.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Common Lisp",
"bytes": "1058187"
},
{
"name": "HTML",
"bytes": "803"
},
{
"name": "Java",
"bytes": "677593"
},
{
"name": "NewLisp",
"bytes": "2382"
}
],
"symlink_target": ""
}
|
import numpy as np
import time
#from dpLoadh5 import dpLoadh5
from dpFRAG import dpFRAG
# labeled chunks
#chunk_range_beg = 17,19,2, 17,23,1, 22,23,1, 22,18,1, 22,23,2, 19,22,2
chunk = [17,19,2]
size = [128,128,128]
offset = [0,0,0]
has_ECS = True
#username = 'watkinspv'
username = 'patilra'
# Input supervoxel labels (hdf5)
labelfile = '/Data/' + username + '/full_datasets/neon_sixfold/mbfergus32/huge_supervoxels.h5'
label_subgroups = ['with_background','0.99999000']
# Input probability data (hdf5)
probfile = '/Data/' + username + '/full_datasets/neon_sixfold/mbfergus32/huge_probs.h5'
# Input segmented labels (hdf5)
gtfile = '/Data/datasets/labels/gt/M0007_33_labels_briggmankl_watkinspv_39x35x7chunks_Forder.h5'
gt_dataset = 'labels'
# Input raw EM data
rawfile = '/Data/datasets/raw/M0007_33_39x35x7chunks_Forder.h5'
raw_dataset = 'data_mag1'
# Output agglomerated labels
outfile = '/Data/' + username + '/tmp_agglo_out.h5'
# Input probability augmented data
probaugfile = ''
#probaugfile = '/Data/' + username + '/full_datasets/neon_sixfold/mbfergus32/huge_probs.h5'
# Input raw EM augmented data
rawaugfile = ''
#rawaugfile = '/Data/datasets/raw/M0007_33_39x35x7chunks_Forder_aug.h5'
# output raw supervoxels (with empty labels removed)
rawout = '/home/' + username + ('/Downloads/svox_%dx%dx%d.raw' % tuple(size))
feature_set = 'minimal'
progressBar = True
verbose = True
# use getFeatures=False to only get the RAG (wihtout boundary voxels or features)
getFeatures = False
# instantiate frag and load data
frag = dpFRAG.makeBothFRAG(labelfile, chunk, size, offset,
[probfile, probaugfile], [rawfile, rawaugfile],
raw_dataset, gtfile, outfile, label_subgroups, ['training','thr'],
progressBar=progressBar, feature_set=feature_set, has_ECS=has_ECS,
verbose=verbose)
# hack to save raveled indices of overlap in context of whole volume (including boundary)
# boundary size is saved in frag.eperim
frag.ovlp_attrs += ['ovlp_cur_dilate']
# create graph
frag.createFRAG(features=getFeatures)
# just to use same name for RAG networkx object as was in driver-cpu.py (from gala example.py)
g_train = frag.FRAG
# save adjacency matrix
print('Exporting adjacency matrix'); t=time.time()
import networkx as nx
am=nx.to_numpy_matrix(g_train)
#np.savetxt("tmp-adjacency_matrix-cpu.txt",am, fmt="%d", delimiter='')
print(am.dtype, am.shape)
fn = 'tmp-adjacency-matrix-cpu-%dx%d-%s.raw' % (am.shape[0], am.shape[1], str(am.dtype))
am.tofile(fn)
am2 = np.fromfile(fn, dtype=np.float64).reshape(am.shape)
print(am2.dtype, am2.shape)
print('\tdone in %.4f s' % (time.time() - t))
# dump supervoxels
frag.supervoxels_noperim.transpose((2,1,0)).tofile(rawout)
if getFeatures:
print('Outputting boundary voxels'); t=time.time()
fout = open("tmp-boundary_pixel_indices-cpu.txt","w")
edges = g_train.edges()
edges.sort()
for edge in edges:
fout.write("(%d, %d): "%(edge[0],edge[1]))
#for b in g_train[edge[0]][edge[1]]['boundary']:
# fout.write("%d "%b)
boundary_subs = np.transpose(np.nonzero(g_train[edge[0]][edge[1]]['ovlp_attrs']['ovlp_cur_dilate']))
start_sub = np.array([x.start for x in g_train[edge[0]][edge[1]]['ovlp_attrs']['aobnd']])
#global_subs_padded = boundary_subs + start_sub
#global_inds = np.ravel_multi_index(global_subs_padded.T.reshape(3,-1), frag.supervoxels.shape)
#for b in global_inds:
# fout.write("%d "%b)
global_subs_unpadded = boundary_subs + start_sub - frag.eperim
for b in range(global_subs_unpadded.shape[0]):
fout.write("(%d,%d,%d) " % tuple(global_subs_unpadded[b,:].tolist()))
fout.write("\n")
fout.close()
print('\tdone in %.4f s' % (time.time() - t))
|
{
"content_hash": "17bff9341a586016f34b091600d137db",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 109,
"avg_line_length": 37.728155339805824,
"alnum_prop": 0.6623777663407102,
"repo_name": "elhuhdron/emdrp",
"id": "8a37ce260ecc647533ef07e228f2dc4e70d24082",
"size": "3923",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "emdrp/emdrp/scripts/driver-cpu-FRAG.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37754"
},
{
"name": "C++",
"bytes": "154981"
},
{
"name": "Cuda",
"bytes": "1363813"
},
{
"name": "MATLAB",
"bytes": "325043"
},
{
"name": "Makefile",
"bytes": "21180"
},
{
"name": "Python",
"bytes": "1382623"
},
{
"name": "Shell",
"bytes": "198347"
}
],
"symlink_target": ""
}
|
<?xml version='1.0' encoding='utf-8'?>
<osi xmlns='urn:cfg.svc.als.osi.itu.iso'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='urn:cfg.svc.als.osi.itu.iso cfg.xsd'>
<asap>
<jndi>
<!--
This jndi element specifies directories where are defined the
ApplicationEntityInformation (APT and AEQ) from either the ldap element
for a LDAP server, either from the file element for a local jndi file system directory.
From the applicationEntity or the applicationProcess entry is fetched the
corresponding mandatory presentationAddress attribute on the initiator side.
From the applicationEntity or the applicationProcess entry is fetched the
corresponding mandatory javaClassName attribute on the responder side.
When both file and ldap element are present, the ldap element has
precedence over the file element and the DN is looked for only from this ldap
element. The file element is mainly used at the installation time for running
the ASAPEcho demo application but it could be used also meantime until the ldap
be properly configured.
-->
<!--
<ldap>
<server host='localhost' port='389'>
<root dn='cn=Directory Manager' pwd='pippo' />
<base dn='' />
</server>
</ldap>
-->
<!--
The ASAPEcho application's Distinguished Name is:
countryName=fr
organizationName=kampbell
organizationalUnitName=osi
organizationalUnitName=demos
commonName=ASAPEcho
which corresponds to the jndi file system based directory file
$INSTALLDIR/cfg/countryName=fr/organizationName=kampbell/organizationalUnitName=osi/organizationalUnitName=demos/commonName=ASAPEcho
The commonName=ASAPEcho file contains one mandatory attributes as property:
presentationAddress=#512///localTCP=localhost. Since the ASAPEcho application
is a specific ASE above the PSAP layer, its javaClassName is given by the psap
service element of this configuration file. For a User Service Element
above the ASAP layer, the mandatory attribute javaClassName should be provided
-->
<file url='file:///${installer:INSTALLATION_PATH}'>
<base dn='cfg/jndi' />
</file>
</jndi>
</asap>
<psap>
<service entity='asap' selector='#1' class='ALS::ASAP::PROV::Provider' library='asap'/>
<service entity='echo' selector='#128' class='com.pac.osi.demo.echo.PSAPEchoServer' />
<service entity='sink' selector='#129' class='com.pac.osi.demo.echo.PSAPEchoServer' />
<service entity='echo' selector='#1024' class='com.pac.osi.demo.echo.RoSAPEchoServer' />
</psap>
<ssap>
<service entity='psap' selector='#1' class='ALS::PSAP::PROV::Provider' library='psap'/>
<service entity='rts' selector='#2' class='com.pac.osi.rtsap.RtSAP' />
<service entity='ros' selector='#3' class='com.pac.osi.rosap.RoSAP' />
<service entity='echo' selector='#128' class='ALS::SSAP::EchoServer' library='SSAPEchoServer'/>
<service entity='sink' selector='#129' class='ALS::SSAP::EchoServer' library='SSAPEchoServer'/>
</ssap>
<tsap>
<service entity='ssap' selector='#1' class='ALS::SSAP::PROV::Provider' library='ssap'/>
<service entity='echo' selector='#128' class='ALS::TSAP::EchoServer' library='TSAPEchoServer'/>
<service entity='sink' selector='#129' class='ALS::TSAP::EchoServer' library='TSAPEchoServer'/>
</tsap>
<addr>
<macros>
<!--
macros used in presentation address definition as specified in RFC1278
A string encoding of Presentation Address" from S.E Hardcastle-Kille.
###############################################################################
#
# Syntax:
#
# <macro> <string>
#
# Each token is separated by LWSP, though double-quotes may be
# used to prevent separation
#
###############################################################################
# standard macros, defined in "A string encoding of Presentation Address"
Int-X25(80) TELEX+00728722+X.25(80)+01+
Janet TELEX+00728722+X.25(80)+02+
Internet-RFC-1006 TELEX+00728722+RFC-1006+03+
# ISODE standard macros
X25(80) TELEX+00728722+X.25(80)+
TCP TELEX+00728722+RFC-1006+
# Interim Community Names
realNS NS+
Int-X25 X25(80)=01+
# Janet X25(80)=02+
Internet TCP=03+
localTCP TCP=05+
localHost localTCP=127.0.0.1+
IXI X25(80)=06+
NSAP NS+
# US GOSIP v2 Addresses
us NS+47000580
nsfnet us=ffff00
psinet us=fffc00
# UK CONS addresses
UKNS DCC+826+d
JanetNS UKNS=11000
-->
<macro name='X25(80)' value='TELEX+00728722+X.25(80)+'/>
<macro name='TCP' value='TELEX+00728722+RFC-1006+'/>
<macro name='Int-X25(80)' value='TELEX+00728722+X.25(80)+01+'/>
<macro name='Janet' value='X25(80)=02+'/>
<macro name='realNS' value='NS+'/>
<macro name='Int-X25' value='X25(80)=01+'/>
<macro name='Internet' value='TCP=03+'/>
<macro name='localTCP' value='TCP=05+'/>
<macro name='localhost' value='localTCP=127.0.0.1+'/>
<macro name='IXI' value='X25(80)=06+'/>
<macro name='NSAP' value='NS+'/>
</macros>
</addr>
</osi>
|
{
"content_hash": "84a870e2390e0f894410672a9980645e",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 133,
"avg_line_length": 39.54744525547445,
"alnum_prop": 0.6288298265042451,
"repo_name": "Kampbell/ISODE",
"id": "72ece13062ce741e333a572fecb6fdce86072004",
"size": "5418",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "isode++/code/iso/itu/osi/demo/AEI.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "27"
},
{
"name": "C",
"bytes": "15682"
},
{
"name": "C++",
"bytes": "7251635"
},
{
"name": "COBOL",
"bytes": "4269"
},
{
"name": "Groff",
"bytes": "18533"
},
{
"name": "Java",
"bytes": "117590"
}
],
"symlink_target": ""
}
|
package me.learn.personal.month2;
/**
*
* Title 191 : Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
*
* @author bramanarayan
* @date May 28, 2020
*/
public class CountSetBits {
public static void main(String args[]) {
CountSetBits solution = new CountSetBits();
solution.hammingWeight(1000);
solution.hammingWeight(1);
solution.hammingWeight(2);
solution.hammingWeight(7);
}
/**
*
* An Integer in Java has 32 bits, e.g. 00101000011110010100001000011010. To
* count the 1s in the Integer representation we put the input int n in bit AND
* with 1 (that is represented as 00000000000000000000000000000001, and if this
* operation result is 1, that means that the last bit of the input integer is
* 1. Thus we add it to the 1s count.
*
* ones = ones + (n & 1);
*
* Then we shift the input Integer by one on the right, to check for the next
* bit.
*
* n = n>>>1;
*
* We need to use bit shifting unsigned operation >>> (while >> depends on sign
* extension)
*
* We keep doing this until the input Integer is 0.
*
* In Java we need to put attention on the fact that the maximum integer is
* 2147483647. Integer type in Java is signed and there is no unsigned int. So
* the input 2147483648 is represented in Java as -2147483648 (in java int type
* has a cyclic representation, that means
* Integer.MAX_VALUE+1==Integer.MIN_VALUE). This force us to use
*
* n!=0
*
* in the while condition and we cannot use
*
* n>0
*
* because the input 2147483648 would correspond to -2147483648 in java and the
* code would not enter the while if the condition is n>0 for n=2147483648.
*/
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count = count + (n & 1);
n = n >>> 1;
}
System.out.println(count);
return count;
}
}
|
{
"content_hash": "908b510182d8352db76d1462e28e47f0",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 139,
"avg_line_length": 27.84,
"alnum_prop": 0.6867816091954023,
"repo_name": "balajiboggaram/algorithms",
"id": "fb2f0e3ac21e7f695a5b429aad8c1b0456fa1ab7",
"size": "2088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/me/learn/personal/month2/CountSetBits.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "20090"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>izf: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.0 / izf - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
izf
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-28 20:25:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-28 20:25:49 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/izf"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/IZF"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: Intuitionistic set theory" "keyword: pointed graphs" "keyword: type theory" "keyword: intuitionistic choice operator" "keyword: set theory" "keyword: Zermelo-Fraenkel" "category: Mathematics/Logic/Set theory" "date: 2003-02" ]
authors: [ "Alexandre Miquel <Alexandre.Miquel@pps.jussieu.fr> [http://www.pps.jussieu.fr/~miquel]" ]
bug-reports: "https://github.com/coq-contribs/izf/issues"
dev-repo: "git+https://github.com/coq-contribs/izf.git"
synopsis: "Intuitionistic Zermelo-Fraenkel Set Theory in Coq"
description: """
This development contains the set-as-pointed-graph
interpretation of Intuitionistic Zermelo Frankel set theory in system
F_omega.2++ (F_omega + one extra universe + intuitionistic choice
operator), which is described in chapter 9 of the author's PhD
thesis (for IZ) and in the author's CSL'03 paper (for the extension
IZ -> IZF)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/izf/archive/v8.7.0.tar.gz"
checksum: "md5=956fb32afa3d43bb5ffac725cfa1d81d"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-izf.8.7.0 coq.8.11.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.0).
The following dependencies couldn't be met:
- coq-izf -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-izf.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
{
"content_hash": "8ea2c07bc79ad71ea15054709c7f6318",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 324,
"avg_line_length": 43.035714285714285,
"alnum_prop": 0.55283540802213,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "b2610c5e464a597564067b5fcaa627a59f26b765",
"size": "7255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.11.0/izf/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
@class DBSHARINGSharedLinkPolicy;
@class DBTEAMLOGSharedFolderChangeLinkPolicyDetails;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `SharedFolderChangeLinkPolicyDetails` struct.
///
/// Changed who can access shared folder via link.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGSharedFolderChangeLinkPolicyDetails : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// New shared folder link policy.
@property (nonatomic, readonly) DBSHARINGSharedLinkPolicy *dNewValue;
/// Previous shared folder link policy. Might be missing due to historical data
/// gap.
@property (nonatomic, readonly, nullable) DBSHARINGSharedLinkPolicy *previousValue;
#pragma mark - Constructors
///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param dNewValue New shared folder link policy.
/// @param previousValue Previous shared folder link policy. Might be missing
/// due to historical data gap.
///
/// @return An initialized instance.
///
- (instancetype)initWithDNewValue:(DBSHARINGSharedLinkPolicy *)dNewValue
previousValue:(nullable DBSHARINGSharedLinkPolicy *)previousValue;
///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
/// @param dNewValue New shared folder link policy.
///
/// @return An initialized instance.
///
- (instancetype)initWithDNewValue:(DBSHARINGSharedLinkPolicy *)dNewValue;
- (instancetype)init NS_UNAVAILABLE;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `SharedFolderChangeLinkPolicyDetails`
/// struct.
///
@interface DBTEAMLOGSharedFolderChangeLinkPolicyDetailsSerializer : NSObject
///
/// Serializes `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` instances.
///
/// @param instance An instance of the
/// `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGSharedFolderChangeLinkPolicyDetails *)instance;
///
/// Deserializes `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` API object.
///
/// @return An instantiation of the
/// `DBTEAMLOGSharedFolderChangeLinkPolicyDetails` object.
///
+ (DBTEAMLOGSharedFolderChangeLinkPolicyDetails *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
|
{
"content_hash": "f5889287eb9113f37784ebdaa8118fd1",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 110,
"avg_line_length": 30.852272727272727,
"alnum_prop": 0.7712707182320442,
"repo_name": "dropbox/dropbox-sdk-obj-c",
"id": "1f39876061aed7ecd82d242bc6738f33d82f67c9",
"size": "2901",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGSharedFolderChangeLinkPolicyDetails.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1288"
},
{
"name": "CSS",
"bytes": "6608"
},
{
"name": "Objective-C",
"bytes": "18903013"
},
{
"name": "Python",
"bytes": "7087"
},
{
"name": "Ruby",
"bytes": "1819"
},
{
"name": "Shell",
"bytes": "4527"
}
],
"symlink_target": ""
}
|
from jmessage import users
from jmessage import common
from conf import *
import time
import json
jmessage=common.JMessage(app_key,master_secret)
groups=jmessage.create_groups()
response=groups.get_group_members("10184277")
time.sleep(2)
print (response.content)
|
{
"content_hash": "7b4b8abd1c42c177d656c7fcf726bfe6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 20.384615384615383,
"alnum_prop": 0.8075471698113208,
"repo_name": "jpush/jmessage-api-python-client",
"id": "f8662fec075d664fe185e647c3242503b6d6d9ea",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/groups/get_group_members.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "18615"
}
],
"symlink_target": ""
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved
// Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved..
#pragma once
#include "CoreMinimal.h"
#include "UObject/CoreOnline.h"
#include "OnlineSubsystemB3atZTypes.h"
#include "OnlineDelegateMacros.h"
/**
* Delegate used when the user query request has completed
*
* @param LocalUserNum the controller number of the associated user that made the request
* @param bWasSuccessful true if the async action completed without error, false if there was an error
* @param UserIds list of user ids that were queried
* @param ErrorStr string representing the error condition
*/
DECLARE_MULTICAST_DELEGATE_FourParams(FOnQueryUserInfoComplete, int32, bool, const TArray< TSharedRef<const FUniqueNetId> >&, const FString&);
typedef FOnQueryUserInfoComplete::FDelegate FOnQueryUserInfoCompleteDelegate;
struct FExternalIdQueryOptions
{
FExternalIdQueryOptions()
: bLookupByDisplayName(false) {}
FString AuthType;
bool bLookupByDisplayName; // Lookup by external display name as opposed to external id
};
/**
* Interface class for obtaining online User info
*/
class IOnlineUser
{
public:
/**
* Starts an async task that queries/reads the info for a list of users
*
* @param LocalUserNum the user requesting the query
* @param UserIds list of users to read info about
*
* @return true if the read request was started successfully, false otherwise
*/
virtual bool QueryUserInfo(int32 LocalUserNum, const TArray<TSharedRef<const FUniqueNetId> >& UserIds) = 0;
/**
* Delegate used when the user query request has completed
*
* @param LocalUserNum the controller number of the associated user that made the request
* @param bWasSuccessful true if the async action completed without error, false if there was an error
* @param UserIds list of user ids that were queried
* @param ErrorStr string representing the error condition
*/
DEFINE_ONLINE_PLAYER_DELEGATE_THREE_PARAM(MAX_LOCAL_PLAYERS, OnQueryUserInfoComplete, bool, const TArray< TSharedRef<const FUniqueNetId> >&, const FString&);
/**
* Obtains the cached list of online user info
*
* @param LocalUserNum the local user that queried for online user data
* @param OutUsers [out] array that receives the copied data
*
* @return true if user info was found
*/
virtual bool GetAllUserInfo(int32 LocalUserNum, TArray< TSharedRef<class FB3atZOnlineUser> >& OutUsers) = 0;
/**
* Get the cached user entry for a specific user id if found
*
* @param LocalUserNum the local user that queried for online user data
* @param UserId id to use for finding the cached online user
*
* @return user info or null ptr if not found
*/
virtual TSharedPtr<FB3atZOnlineUser> GetUserInfo(int32 LocalUserNum, const class FUniqueNetId& UserId) = 0;
/**
* Called when done querying for a UserId mapping from a requested display name
*
* @param bWasSuccessful true if server was contacted and a valid result received
* @param UserId user id initiating the request
* @param DisplayNameOrEmail the name string that was being queried
* @param FoundUserId the user id matched for the passed name string
* @param Error string representing the error condition
*/
DECLARE_DELEGATE_FiveParams(FOnQueryUserMappingComplete, bool /*bWasSuccessful*/, const FUniqueNetId& /*UserId*/, const FString& /*DisplayNameOrEmail*/, const FUniqueNetId& /*FoundUserId*/, const FString& /*Error*/);
/**
* Contacts server to obtain a user id from an arbitrary user-entered name string, eg. display name
*
* @param UserId id of the user that is requesting the name string lookup
* @param DisplayNameOrEmail a string of a display name or email to attempt to map to a user id
*
* @return true if the operation was started successfully
*/
virtual bool QueryUserIdMapping(const FUniqueNetId& UserId, const FString& DisplayNameOrEmail, const FOnQueryUserMappingComplete& Delegate = FOnQueryUserMappingComplete()) = 0;
/**
* Called when done querying for UserId mappings from external ids
*
* @param bWasSuccessful true if server was contacted and a valid result received
* @param UserId user id initiating the request
* @param QueryOptions Options specifying how to treat the External IDs and other query-related settings
* @param ExternalIds array of external ids to attempt to map to user ids
* @param Error string representing the error condition
*/
DECLARE_DELEGATE_FiveParams(FOnQueryExternalIdMappingsComplete, bool /*bWasSuccessful*/, const FUniqueNetId& /*UserId*/, const FExternalIdQueryOptions& /*QueryOptions*/, const TArray<FString>& /*ExternalIds*/, const FString& /*Error*/);
/**
* Contacts server to obtain user ids from external ids
*
* @param UserId id of the user that is requesting the name string lookup
* @param QueryOptions Options specifying how to treat the External IDs and other query-related settings
* @param ExternalIds array of external ids to attempt to map to user ids
*
* @return true if the operation was started successfully
*/
virtual bool QueryExternalIdMappings(const FUniqueNetId& UserId, const FExternalIdQueryOptions& QueryOptions, const TArray<FString>& ExternalIds, const FOnQueryExternalIdMappingsComplete& Delegate = FOnQueryExternalIdMappingsComplete()) = 0;
/**
* Get the cached user ids for the specified external ids
*
* @param QueryOptions Options specifying how to treat the External IDs and other query-related settings
* @param ExternalIds array of external ids to map to user ids
* @param OutIds array of user ids that map to the specified external ids (can contain null entries)
*/
virtual void GetExternalIdMappings(const FExternalIdQueryOptions& QueryOptions, const TArray<FString>& ExternalIds, TArray<TSharedPtr<const FUniqueNetId>>& OutIds) = 0;
/**
* Get the cached user id for the specified external id
*
* @param QueryOptions Options specifying how to treat the External IDs and other query-related settings
* @param ExternalId external id to obtain user id for
* @return user info or null ptr if not found
*/
virtual TSharedPtr<const FUniqueNetId> GetExternalIdMapping(const FExternalIdQueryOptions& QueryOptions, const FString& ExternalId) = 0;
};
|
{
"content_hash": "27afe9150296dea0a3855916da2dea6a",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 242,
"avg_line_length": 44.72142857142857,
"alnum_prop": 0.7660118191982112,
"repo_name": "philippbb/OnlineSubsytemB3atZPlugin",
"id": "0dc58a3a85cb289b8369e18b2d513490c9782b0e",
"size": "6261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OnlineSubsystemB3atZ/Source/Public/Interfaces/OnlineUserInterface.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "391382"
},
{
"name": "C#",
"bytes": "2914"
},
{
"name": "C++",
"bytes": "1363564"
}
],
"symlink_target": ""
}
|
package com.jonathancolt.nicity.core.lang;
/*
* #%L
* nicity-core
* %%
* Copyright (C) 2013 Jonathan Colt
* %%
* 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.
* #L%
*/
/**
*
* @author Administrator
*/
public class IntBits {
private int masks;
/**
*
*/
public IntBits() {
}
/**
*
* @param _masks
*/
public IntBits(int _masks) {
masks = _masks;
}
/**
*
* @param _masks
*/
public void setMask(int _masks) {
masks = _masks;
}
/**
*
* @param _addBit
*/
public void addBit(int _addBit) {
addMask(_addBit);
}
/**
*
* @param _addMask
*/
public void addMask(int _addMask) {
masks |= _addMask;
}
/**
*
* @param _removeBit
*/
public void removeBit(int _removeBit) {
removeMask(_removeBit);
}
/**
*
* @param _removeMask
*/
public void removeMask(int _removeMask) {
masks &= ~_removeMask;
}
/**
*
* @param _toggleMask
*/
public void toggleMask(int _toggleMask) {
if (hasMask(_toggleMask)) {
removeMask(_toggleMask);
}
else {
addMask(_toggleMask);
}
}
/**
*
* @param _removeMask
* @param _addMask
*/
public void replaceMask(int _removeMask, int _addMask) {
removeMask(_removeMask);
addMask(_addMask);
}
/**
*
* @return
*/
public int getMask() {
return masks;
}
/**
*
* @param _hasBit
* @return
*/
public boolean hasBit(int _hasBit) {
return hasMask(_hasBit);
}
/**
*
* @param _hasMask
* @return
*/
public boolean hasMask(int _hasMask) {
return (masks & _hasMask) == _hasMask;
}
@Override
public int hashCode() {
return masks;
}
@Override
public boolean equals(Object _instance) {
if (_instance == this) {
return true;
}
if (_instance instanceof IntBits) {
IntBits ibm = (IntBits) _instance;
return (ibm.masks == masks);
}
if (_instance instanceof Integer) {
return masks == (Integer) _instance;
}
return false;
}
@Override
public String toString() {
return Integer.toBinaryString(masks);
}
}
|
{
"content_hash": "056377dd583fcb73e7d2f5957d15b931",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 75,
"avg_line_length": 18.696202531645568,
"alnum_prop": 0.523696682464455,
"repo_name": "jnthnclt/nicity",
"id": "0f520772ba61e56379cae6592cf7af1af26926f5",
"size": "3610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nicity-core/src/main/java/com/jonathancolt/nicity/core/lang/IntBits.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26281"
},
{
"name": "Java",
"bytes": "3596700"
},
{
"name": "Ruby",
"bytes": "80"
}
],
"symlink_target": ""
}
|
<?xml version="1.0"?>
<!-- The COPYRIGHT file at the top level of
this repository contains the full copyright notices and license terms. -->
<form string="Payment Profile" col="4">
<label name="active" />
<field name="active" />
<label name="sequence" />
<field name="sequence" />
<separator string="Party Details" id="party_details" colspan="4" />
<label name="party" />
<field name="party" />
<label name="name" />
<field name="name" />
<newline />
<label name="address" />
<field name="address" />
<separator string="Gateway" id="gateway" colspan="4"/>
<label name="gateway"/>
<field name="gateway"/>
<separator string="Card Details" id="card_details" colspan="4" />
<label name="provider_reference"/>
<field name="provider_reference"/>
<label name="last_4_digits"/>
<field name="last_4_digits"/>
<newline />
<label name="expiry_month"/>
<field name="expiry_month"/>
<label name="expiry_year"/>
<field name="expiry_year"/>
</form>
|
{
"content_hash": "1b282f3a4080ac74fb7486e437130cae",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 74,
"avg_line_length": 34.46666666666667,
"alnum_prop": 0.6150870406189555,
"repo_name": "fulfilio/trytond-payment-gateway",
"id": "5c6c8e8df3e6d84fec4265cf3115bcce2a9f759f",
"size": "1034",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "view/payment_profile_form.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "71263"
}
],
"symlink_target": ""
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractSByte()
{
var test = new SimpleBinaryOpTest__SubtractSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSByte testClass)
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleBinaryOpTest__SubtractSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Subtract(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(pClsVar1)),
Sse2.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractSByte();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractSByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(&test._fld1)),
Sse2.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((sbyte)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((sbyte)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
{
"content_hash": "6b2800c0c897f55589c4a07130d5b324",
"timestamp": "",
"source": "github",
"line_count": 585,
"max_line_length": 187,
"avg_line_length": 41.873504273504274,
"alnum_prop": 0.5709503592423253,
"repo_name": "wtgodbe/coreclr",
"id": "7ed23e3346e47c0092229cb8e08e0153ca21dbd6",
"size": "24496",
"binary": false,
"copies": "42",
"ref": "refs/heads/master",
"path": "tests/src/JIT/HardwareIntrinsics/X86/Sse2/Subtract.SByte.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "976648"
},
{
"name": "Awk",
"bytes": "6904"
},
{
"name": "Batchfile",
"bytes": "167893"
},
{
"name": "C",
"bytes": "4862319"
},
{
"name": "C#",
"bytes": "154822068"
},
{
"name": "C++",
"bytes": "64306017"
},
{
"name": "CMake",
"bytes": "723128"
},
{
"name": "M4",
"bytes": "15214"
},
{
"name": "Makefile",
"bytes": "46117"
},
{
"name": "Objective-C",
"bytes": "14116"
},
{
"name": "Perl",
"bytes": "23653"
},
{
"name": "PowerShell",
"bytes": "132755"
},
{
"name": "Python",
"bytes": "480080"
},
{
"name": "Roff",
"bytes": "672227"
},
{
"name": "Scala",
"bytes": "4102"
},
{
"name": "Shell",
"bytes": "513230"
},
{
"name": "Smalltalk",
"bytes": "635930"
},
{
"name": "SuperCollider",
"bytes": "650"
},
{
"name": "TeX",
"bytes": "126781"
},
{
"name": "XSLT",
"bytes": "1016"
},
{
"name": "Yacc",
"bytes": "157492"
}
],
"symlink_target": ""
}
|
package org.devacfr.maven.skins.reflow.context;
import javax.annotation.Nonnull;
import org.devacfr.maven.skins.reflow.ISkinConfig;
/**
* @author Christophe Friederich
* @since 2.3
*/
public class BodyContext extends Context<BodyContext> {
/**
* Default constructor.
*
* @param config
* a config (can not be {@code null}).
*/
public BodyContext(final @Nonnull ISkinConfig config) {
super(config, ContextType.body);
}
@Override
protected void initialize(@Nonnull final ISkinConfig config) {
// not use all default context initializations.
}
@Override
protected String onPreRender(final @Nonnull ISkinConfig skinConfig, final @Nonnull String bodyContent) {
return bodyContent;
}
}
|
{
"content_hash": "ed8012e6f09fb0c2ba30d340e1dad7cb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 106,
"avg_line_length": 22.029411764705884,
"alnum_prop": 0.7022696929238985,
"repo_name": "devacfr/reflow-maven-skin",
"id": "63a5d3a4d734cfe5076141628f8a58175195626b",
"size": "1354",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "reflow-velocity-tools/src/main/java/org/devacfr/maven/skins/reflow/context/BodyContext.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "941"
},
{
"name": "CSS",
"bytes": "22231"
},
{
"name": "HTML",
"bytes": "58307"
},
{
"name": "Java",
"bytes": "346879"
},
{
"name": "JavaScript",
"bytes": "12386"
},
{
"name": "Shell",
"bytes": "14140"
}
],
"symlink_target": ""
}
|
var method = Custom.prototype;
/**
* Constructeur
*/
function Custom(params) {
this._customFunction = null;
this.parseParams(params);
}
/**
* Parse param for get parameters
*/
method.parseParams = function(params){
if("custom_function" in params)
this._customFunction=params["custom_function"];
};
// Retourne le resultar formatter
method.getResult = function() {
return this._customFunction();
};
module.exports = Custom;
|
{
"content_hash": "9f762f673afe588b117844d1a5655cf7",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 49,
"avg_line_length": 17.153846153846153,
"alnum_prop": 0.6973094170403588,
"repo_name": "Kaenn/Geko",
"id": "7a6c13b553fea82bbdca77a9a31ca8eeca4f6405",
"size": "446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "old/modules_old/API/controler/requester/Custom.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2259"
},
{
"name": "HTML",
"bytes": "9937"
},
{
"name": "JavaScript",
"bytes": "330958"
},
{
"name": "Smarty",
"bytes": "197"
}
],
"symlink_target": ""
}
|
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using com.amazon.device.iap.cpt.json;
namespace com.amazon.device.iap.cpt
{
public sealed class GetUserDataResponse : Jsonable
{
public string RequestId{get;set;}
public AmazonUserData AmazonUserData{get;set;}
public string Status{get;set;}
public string ToJson()
{
try
{
Dictionary<string, object> toJson = this.GetObjectDictionary();
return Json.Serialize(toJson);
}
catch(System.ApplicationException ex)
{
throw new AmazonException("Error encountered while Jsoning", ex);
}
}
public override Dictionary<string, object> GetObjectDictionary()
{
try
{
Dictionary<string, object> objectDictionary = new Dictionary<string, object>();
objectDictionary.Add("requestId", RequestId);
objectDictionary.Add("amazonUserData", (AmazonUserData != null) ? AmazonUserData.GetObjectDictionary() : null);
objectDictionary.Add("status", Status);
return objectDictionary;
}
catch(System.ApplicationException ex)
{
throw new AmazonException("Error encountered while getting object dictionary", ex);
}
}
public static GetUserDataResponse CreateFromDictionary(Dictionary<string, object> jsonMap)
{
try
{
if (jsonMap == null)
{
return null;
}
var request = new GetUserDataResponse();
if(jsonMap.ContainsKey("requestId"))
{
request.RequestId = (string) jsonMap["requestId"];
}
if(jsonMap.ContainsKey("amazonUserData"))
{
request.AmazonUserData = AmazonUserData.CreateFromDictionary(jsonMap["amazonUserData"] as Dictionary<string, object>);
}
if(jsonMap.ContainsKey("status"))
{
request.Status = (string) jsonMap["status"];
}
return request;
}
catch (System.ApplicationException ex)
{
throw new AmazonException("Error encountered while creating Object from dicionary", ex);
}
}
public static GetUserDataResponse CreateFromJson(string jsonMessage)
{
try
{
Dictionary<string, object> jsonMap = Json.Deserialize(jsonMessage) as Dictionary<string, object>;
Jsonable.CheckForErrors(jsonMap);
return CreateFromDictionary(jsonMap);
}
catch(System.ApplicationException ex)
{
throw new AmazonException("Error encountered while UnJsoning", ex);
}
}
public static Dictionary<string, GetUserDataResponse> MapFromJson(Dictionary<string, object> jsonMap)
{
Dictionary<string, GetUserDataResponse> result = new Dictionary<string, GetUserDataResponse>();
foreach (var entry in jsonMap)
{
GetUserDataResponse value = CreateFromDictionary(entry.Value as Dictionary<string, object>);
result.Add(entry.Key, value);
}
return result;
}
public static List<GetUserDataResponse> ListFromJson(List<object> array)
{
List<GetUserDataResponse> result = new List<GetUserDataResponse>();
foreach (var e in array)
{
result.Add(CreateFromDictionary(e as Dictionary<string, object>));
}
return result;
}
}
}
|
{
"content_hash": "215eab5dd2019eaf8e8bf233a310d1b0",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 139,
"avg_line_length": 33.82644628099174,
"alnum_prop": 0.535304177864647,
"repo_name": "EJBQ/Bae-Zeus-X",
"id": "b3abd918512856c174a3ffe73eb90ca7d02f46f8",
"size": "4664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Plugins/Amazon/AmazonIapV2/Source/GetUserDataResponse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "855076"
},
{
"name": "JavaScript",
"bytes": "1791"
},
{
"name": "Objective-C",
"bytes": "1309"
}
],
"symlink_target": ""
}
|
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/AGEFlagIcons/AGEFlagIcons.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/AGEFlagIcons/AGEFlagIcons.framework"
fi
|
{
"content_hash": "0dc6620b5b70f7230f34716ead996129",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 209,
"avg_line_length": 40.166666666666664,
"alnum_prop": 0.6381742738589211,
"repo_name": "alexanderedge/AGEFlagIcons",
"id": "8e2f9c1b1992f381b140fe8d13321e69423fd13b",
"size": "3625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/Pods/Target Support Files/Pods-AGEFlagIcons_Example/Pods-AGEFlagIcons_Example-frameworks.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "7596"
},
{
"name": "Ruby",
"bytes": "1433"
},
{
"name": "Shell",
"bytes": "17273"
}
],
"symlink_target": ""
}
|
"use strict";
define(['app', 'scripts/webitel/utils', 'modules/widget/widgetModel', 'modules/calendar/calendarModel', 'modules/queueCallback/queueCallbackModel', 'modules/widget/widgetDefaultValues', 'modules/callflows/public/publicModel'], function (app, utils) {
app.controller("WidgetCtrl", ['$scope', '$http', '$modal', '$routeParams', '$filter',
'$location', '$route', 'notifi', '$confirm', 'webitel', 'TableSearch', '$timeout', '$rootScope', 'WidgetModel', 'CalendarModel', 'QueueCallbackModel', 'WidgetDefault', 'CallflowPublicModel',
function ($scope, $http, $modal, $routeParams, $filter, $location, $route, notifi, $confirm, webitel, TableSearch,
$timeout, $rootScope, WidgetModel, CalendarModel, QueueCallbackModel, WidgetDefault, CallflowPublicModel) {
$scope.canDelete = true || webitel.connection.session.checkResource('widget', 'd');
$scope.canUpdate = true || webitel.connection.session.checkResource('widget', 'u');
$scope.canCreate = true || webitel.connection.session.checkResource('widget', 'c');
$scope.viewMode = !$scope.canUpdate;
$scope.rowCollection = [];
$scope.displayedCollection = [];
$scope.isLoading = false;
$scope.isReviewMode = false;
$scope.domain = webitel.domain();
$scope.horisontal = {
pos: "left",
x: 0
};
$scope.vertical = {
pos: "bottom",
y: 0
};
$scope.canDelete = true || webitel.connection.session.checkResource('widget', 'd');
$scope.canUpdate = true || webitel.connection.session.checkResource('widget', 'u');
$scope.canCreate = true || webitel.connection.session.checkResource('widget', 'c');
$scope.viewMode = !$scope.canUpdate;
$scope.changePanel = function (panelStatistic) {
$scope.panelStatistic = !!panelStatistic;
};
$scope.query = TableSearch.get('domains');
$scope.$watch("query", function (newVal) {
TableSearch.set(newVal, 'domains');
});
$scope.calendar={};
$scope.country = {};
$scope.validate = {};
$scope.blackIp = {};
$scope.callflow = {};
function onCopied() {
return notifi.info("Copy", 1000);
}
function onCopiedFail(err) {
return notifi.error(err, 5000);
}
$scope.script = angular.copy(WidgetDefault.script);
$scope.widget = angular.copy(WidgetDefault.widget);
$scope.widget.config.lang = angular.copy(WidgetDefault.en_lang);
$scope.fontFamilies = angular.copy(WidgetDefault.fontFamilies);
$scope.languages = angular.copy(WidgetDefault.languages);
$scope.calendars = [];
$scope.queues = [];
$scope.publics = [];
$scope.onCopied = onCopied;
$scope.onCopiedFail = onCopiedFail;
$scope.reloadData = reloadData;
$scope.closePage = closePage;
$scope.create = create;
$scope.save = save;
$scope.edit = edit;
$scope.removeItem = removeItem;
$scope.addCountry = addCountry;
$scope.deleteCountry = deleteCountry;
$scope.addValidate = addValidate;
$scope.deleteValidate = deleteValidate;
$scope.addToBlacklist = addToBlacklist;
$scope.deleteFromBlacklist = deleteFromBlacklist;
$scope.changeLanguage = changeLanguage;
$scope.getCalendar = getCalendar;
$scope.reviewButton = reviewButton;
$scope.initCallbacks = initCallbacks;
$scope.initCalendars = initCalendars;
$scope.initCallflows = initCallflows;
$scope.initCountries = initCountries;
$scope.regenerateButton = regenerateButton;
var changeDomainEvent = $rootScope.$on('webitel:changeDomain', function (e, domainName) {
$scope.domain = domainName;
closePage();
});
$scope.$on('$destroy', function () {
if($scope.isReviewMode){
var button = angular.element(document.getElementById('callMeContent'));
button.remove();
}
changeDomainEvent();
});
function changeLanguage(){
if($scope.widget.language === "ru"){
$scope.widget.config.lang = angular.copy(WidgetDefault.ru_lang);
}
if($scope.widget.language === "ua"){
$scope.widget.config.lang = angular.copy(WidgetDefault.ua_lang);
}
if($scope.widget.language === "en"){
$scope.widget.config.lang = angular.copy(WidgetDefault.en_lang);
}
}
$scope.$watch("callflow", function (newVal) {
if(newVal.value){
var val = newVal.value;
if(($scope.widget.callflow_id!=val.id && $scope.widget.config.destinationNumber!=val.number) ||
($scope.widget.callflow_id==val.id && $scope.widget.config.destinationNumber!=val.number) ||
($scope.widget.callflow_id!=val.id && $scope.widget.config.destinationNumber==val.number)){
$scope.widget.callflow_id = val.id;
$scope.widget.config.destinationNumber = val.number;
}
}
}, true);
$scope.$watchCollection("horisontal", function (newVal) {
if(newVal.x!==null){
if(newVal.pos=='left'){
delete $scope.widget.config.css.buttonPosition.right;
$scope.widget.config.css.buttonPosition.left = newVal.x.toString()+"px";
}
else{
delete $scope.widget.config.css.buttonPosition.left;
$scope.widget.config.css.buttonPosition.right = newVal.x.toString()+"px";
}
}
});
$scope.$watchCollection("vertical", function (newVal) {
if(newVal.y!==null){
if(newVal.pos=='top'){
delete $scope.widget.config.css.buttonPosition.bottom;
$scope.widget.config.css.buttonPosition.top = newVal.y.toString()+"px";
}
else{
delete $scope.widget.config.css.buttonPosition.top;
$scope.widget.config.css.buttonPosition.bottom = newVal.y.toString()+"px";
}
}
});
$scope.$watch('domain', function(domainName) {
$scope.domain = domainName;
reloadData();
}, true);
$scope.$watch('widget', function(newValue, oldValue) {
if ($scope.isReviewMode){
var config = angular.copy($scope.widget.config);
callMeButtonGenerate(config);
}
if ($scope.widget._new)
return $scope.isEdit = $scope.isNew = true;
return $scope.isEdit = !!oldValue.id;
}, true);
$scope.cancel = function () {
$scope.widget = angular.copy($scope.oldWidget);
disableEditMode();
};
function disableEditMode () {
$timeout(function () {
$scope.isEdit = false;
}, 0);
}
function regenerateButton(){
getCalendar(save);
}
function reviewButton() {
if(!$scope.isReviewMode){
window.WebitelCallbackId = $scope.widget.id;
window.WebitelCallbackHost = $scope.widget._widgetBaseUri;
window.WebitelCallbackDomain = $scope.widget.domain;
$scope.isReviewMode = true;
var gcw = document.createElement('script'); gcw.type = 'text/javascript'; gcw.async = true;
gcw.src = WebitelCallbackHost+'/widget.client.js';//'./modules/widget/widget.client.js';
var sn = document.getElementsByTagName('script')[0]; sn.parentNode.insertBefore(gcw, sn);
}
else{
$scope.isReviewMode = false;
var button = angular.element(document.getElementById('callMeContent'));
button.remove();
}
}
function addCountry(){
if($scope.country.value){
$scope.widget.config.showInCountry.countries.push(angular.copy($scope.country.value));
$scope.country={};
}
}
function deleteCountry(index){
$scope.widget.config.showInCountry.countries.splice(index, 1);
}
function addValidate(){
if($scope.validate.value){
$scope.widget.config.validateNumbers.push(angular.copy($scope.validate.value));
$scope.validate={};
}
}
function deleteValidate(index){
$scope.widget.config.validateNumbers.splice(index, 1);
}
function addToBlacklist(){
if($scope.blackIp.value){
if(!$scope.widget.blacklist)$scope.widget.blacklist=[];
$scope.widget.blacklist.push(angular.copy($scope.blackIp.value));
$scope.blackIp={};
}
}
function deleteFromBlacklist(index){
$scope.widget.blacklist.splice(index, 1);
}
function removeItem(row) {
$confirm({text: 'Are you sure you want to delete ' + row.name + ' ?'}, { templateUrl: 'views/confirm.html' })
.then(function() {
WidgetModel.remove(row.id, $scope.domain, function (err) {
if (err)
return notifi.error(err, 5000);
reloadData();
});
});
}
function getCalendar(cb) {
CalendarModel.item($scope.domain, $scope.widget.config.calendar.id, function(err, item) {
if (err) {
return notifi.error(err, 5000);
}
$scope.widget.config.calendar.accept = item.accept;
$scope.widget.config.calendar.timezone = item.timeZone.id;
var arr = [];
item.except.forEach(function(i){
var date = new Date(i.date);
if(i.repeat==1){
arr.push({
date: (date.getUTCMonth()+1)+"-" + date.getUTCDate(),
repeat: i.repeat
});
}
else{
arr.push({
date: date.getUTCFullYear()+"-"+(date.getUTCMonth()+1)+"-" + date.getUTCDate(),
repeat: i.repeat
});
}
});
$scope.widget.config.calendar.except = arr;
if(cb)cb();
});
}
function initCallbacks(){
var col = encodeURIComponent(JSON.stringify({
name: 1,
id: 1
}));
QueueCallbackModel.list({
columns: col,
limit: 5000,
page: 1,
domain: $scope.domain
}, function (err, res) {
$scope.isLoading = false;
if (err)
return notifi.error(err, 5000);
var arr = [];
angular.forEach(res.data || res.info, function(item) {
arr.push(item);
});
$scope.queues = arr;
});
}
function initCalendars(){
CalendarModel.list($scope.domain, function (err, res) {
if (err)
return notifi.error(err, 5000);
var c = [];
var data = res.data;
angular.forEach(data, function (v) {
c.push({
"id": v._id,
"name": v.name
});
});
$scope.calendars = c;
});
}
function initCallflows(){
CallflowPublicModel.list($scope.domain, function (err, res) {
if (err)
return notifi.error(err, 5000);
var arr = [];
angular.forEach(res, function(item) {
item.destination_number.map(function(i){
arr=arr.concat({ id: item.id, number:i})
})
});
$scope.publics = arr;
});
}
function initCountries() {
$http.get('./modules/widget/countries.json').success(function(data) {
$scope.countries = data;
});
}
function create() {
initCountries();
$scope.widget._new = true;
};
function save() {
var cb = function (err, res) {
if (err)
return notifi.error(err, 5000);
if ($scope.widget._new) {
return $location.path('/widget/' + res.data[0] + '/edit');
} else {
$scope.widget.__time = Date.now();
return edit();
};
};
if ($scope.widget._new) {
WidgetModel.add(angular.copy($scope.widget), $scope.domain, cb);
} else {
WidgetModel.update($scope.widget, $scope.widget.id, $scope.domain, cb);
}
}
function edit () {
initCountries();
var id = $routeParams.id;
var domain = $routeParams.domain;
WidgetModel.item(id, domain, function(err, item) {
if (err) {
return notifi.error(err, 5000);
};
$scope.oldWidget = angular.copy(item);
$scope.widget = item;
$scope.callflow.value ={
id: $scope.widget.callflow_id,
number: $scope.widget.config.destinationNumber
};
if(item.config.css.buttonPosition.bottom){
$scope.vertical.pos= 'bottom' ;
$scope.vertical.y = parseInt(item.config.css.buttonPosition.bottom);
}
else{
$scope.vertical.pos= 'top' ;
$scope.vertical.y = parseInt(item.config.css.buttonPosition.top);
}
if(item.config.css.buttonPosition.left){
$scope.horisontal.pos= 'left' ;
$scope.horisontal.x = parseInt(item.config.css.buttonPosition.left);
}
else{
$scope.horisontal.pos= 'right' ;
$scope.horisontal.x = parseInt(item.config.css.buttonPosition.right);
}
$scope.script = $scope.script.replace("##ID##", id).replace(/##HOST##/g,$scope.widget._widgetBaseUri).replace("##DOMAIN##",$scope.domain);
disableEditMode();
})
}
function closePage() {
$location.path('/widget');
}
function reloadData () {
if ($location.$$path != '/widget')
return 0;
if (!$scope.domain)
return $scope.rowCollection = [];
$scope.isLoading = true;
var col = encodeURIComponent(JSON.stringify({
name: 1,
description: 1,
id: 1
}));
WidgetModel.list({
columns: col,
limit: 5000,
page: 1,
domain: $scope.domain
}, function (err, res) {
$scope.isLoading = false;
if (err)
return notifi.error(err, 5000);
var arr = [];
angular.forEach(res.data, function(item) {
arr.push(item);
});
$scope.rowCollection = arr;
});
}
$scope.init = function init () {
if (!!$route.current.method) {
return $scope[$route.current.method]();
}
reloadData();
}();
}])
});
|
{
"content_hash": "aec67b69ce1a62685c480fba85862ccb",
"timestamp": "",
"source": "github",
"line_count": 439,
"max_line_length": 250,
"avg_line_length": 40.70159453302961,
"alnum_prop": 0.4532124468323259,
"repo_name": "webitel/web-client",
"id": "ba19e952647e5d56a06545e9cdae4f4c0a0149d7",
"size": "17868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/widget/widget.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "330314"
},
{
"name": "Dockerfile",
"bytes": "1054"
},
{
"name": "HTML",
"bytes": "702158"
},
{
"name": "JavaScript",
"bytes": "1313808"
},
{
"name": "Shell",
"bytes": "2686"
}
],
"symlink_target": ""
}
|
author: elliott
layout: post
title: "23rd class - Contributing, Commit access, and advanced git"
---
## Announcements
* Pygame hacking - questions?
* Project proposal - questions?
* Personal workflows
## Contribtuing guidelines
If you want people to contribute to your project it helps to have contributor guidelines. Not too restrictive and not too lax. THis helps people know that work they spend on a pull request is unlikely to be wasted by not being what you want.
We've all been contribtuing to the class website and today we'll formalize our contributor guidelines, Gettting Started, and any other documentation our project needs to be complete. To do this, we'll need examples of other projects that have done this well or poorly to emulate or avoid.
## Group exercise
Pick one of the following to research as a group for about 15 minutes. Be prepared to give some examples and what you liked or disliked about them, and a sketch of what you think We should have for this class. Get feedback, then work on that section of the README or create a new file and submit a pull request! This is a group activity, but the pull request will come from one person. Here are things that mature projects should have:
* Contributor guideslines
* Getting started
* License
* Diversity statement
* Developer reference materials
Some of these may not be appropriate for our class, so as you research them and recommend something, it's OK to recommend that we not do anything. But you should still provide examples so we know what a good one looks like.
## Advanced Git
Pro Git is the best git reference out there. The section on [re-writing history](http://git-scm.com/book/en/Git-Tools-Rewriting-History) is what we'll go over today if there's time. `git commit --amend` and `git rebase -i` will be useful for you during projects.
|
{
"content_hash": "1c3c66d523bf42223a4ab5f24b713364",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 439,
"avg_line_length": 59.58064516129032,
"alnum_prop": 0.7758527341635084,
"repo_name": "gerbal/Song-of-560",
"id": "56654c395a9f7af1e01b02d12ba88af536867a3d",
"size": "1851",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_posts/elliott/2013-11-13-23.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39177"
},
{
"name": "JavaScript",
"bytes": "678908"
},
{
"name": "Python",
"bytes": "149070"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.criminalintent" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".CrimeListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CrimeActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
|
{
"content_hash": "8783b740eb949dacb10a9aeb87aa275a",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 76,
"avg_line_length": 31.958333333333332,
"alnum_prop": 0.5984354628422425,
"repo_name": "yijia1992/criminalintent",
"id": "4b2e777f7b45029e85d1cf905735a0f9fa67bae3",
"size": "767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6868"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TestMySkills.WebAPI.Areas.HelpPage.ModelDescriptions;
using TestMySkills.WebAPI.Areas.HelpPage.Models;
namespace TestMySkills.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => string.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(
HelpPageApiModel apiModel,
ApiParameterDescription apiParameter,
ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(string.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
{
"content_hash": "6daf5e6581d2d9b8da817292657d35d2",
"timestamp": "",
"source": "github",
"line_count": 470,
"max_line_length": 196,
"avg_line_length": 52.38297872340426,
"alnum_prop": 0.6100324939073923,
"repo_name": "encounter12/TestMySkills",
"id": "b8d4e87aaf10df0334e22e9a2d2db6e0e48ad8f1",
"size": "24620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/TestMySkills.WebAPI/Areas/HelpPage/HelpPageConfigurationExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "114"
},
{
"name": "C#",
"bytes": "230431"
},
{
"name": "CSS",
"bytes": "3646"
},
{
"name": "HTML",
"bytes": "7272"
},
{
"name": "JavaScript",
"bytes": "37457"
}
],
"symlink_target": ""
}
|
0.9
------------------------------------------------
* Removed `FieldName`, the relic of the old ages
* `(@=)`, `@==`, `@!?` and `lasso` now take `Proxy` instead of `FieldName`. Those who are using `mkField` need to replace the operands with proxies (OverloadedLabels is recommended).
* Supported aeson 1.x
* Introduced `IsLabel` flag which toggles the presence of optics `OverloadedLabels`. By disabling it, this package can now coexist with other users of the `IsLabel` class, such as `generic-lens` and `relational-query`.
0.8.3
------------------------------------------------
* `Comp` is now a pattern synonym for `Compose`
* Added missing `liftTyped` implementations
* Supported aeson-2.0
0.8.1
------------------------------------------------
* Added `DefaultOrdered` and `Incremental` instances to `:&`
* Added an `Incremental` instance to `Field`
0.8
------------------------------------------------
* Removed `Associate`, `AssocKey`, `AssocValue`, `ValueIs`, `KeyIs`, `KeyValue`, `proxyAssocKey`, `proxyAssocValue`, `stringAssokKey`, `xlb`, `:*`, `:|`
* Reverted deprecation of `Data.Extensible.Tangle`
0.7.1
------------------------------------------------
* Removed `vector` and `prettyprinter` orphans
* Deprecated `Data.Extensible.Tangle`; use [tangle](https://hackage.haskell.org/package/tangle)
* `parseJSON` gives more informative failure messages on failure
* Supported `barbies ^>= 2`
0.7
-------------------------------------------------
* Moved `Data.Extensible.Effect` into new `extensible-skeleton` package
* Instances for barbies and cassava are now optional
* Deprecated 訊
0.6.1
-------------------------------------------------
* Added `fromNullable`
* Added `xlb`
* Added a `HasField` instance for `RecordOf`
* Removed `deriveIsRecord`
* Supported GHC 8.8
0.6
-------------------------------------------------
* Added a MonadCont instance for Eff
* `(:*)` and `(:|)` are deprecated in favour of `(:&)` and `(:*)` where their
type parameters are flipped
* Flipped the type parameters of `BitProd` and `TangleT`
* Added `itemKey`, `hmapWithIndexWith`, `hfoldMapWith`, `hfoldMapWithIndexWith`,
`hfoldrWithIndexWith`, `hfoldlWithIndexWith`, `hrepeatWith`, `htabulateWith`,
and `hgenerateWith`
0.5.1
-------------------------------------------------
* Split `Data.Extensible.HList` and `Data.Extensible.Internal` to the
`membership` package
* `AssocKey`, `AssocValue`, `ValueIs`, `KeyValue` and their related combinators
are deprecated. Use ones from `membership`
* `IsRecord` now has a generic default implementation
* Deprecated `deriveIsRecord`
0.5
-------------------------------------------------
* GHC older than 8.4 is no longer supported
* Removed `Const'`
* `Data.Extensible.Plain` is no longer exported from `Data.Extensible`
* Added `wrap` and `unwrap` to `Wrapper`
* Added `(=<:)`
0.4.10.1
-------------------------------------------------
* Fixed build on GHC 8.6
0.4.10
-------------------------------------------------
* Added a `MonadResource`, `MonadThrow`, and `MonadCatch` instances for `Eff`
* `Proxy` and `KnownSymbol` are now reexported from `Data.Extensible`
0.4.9
-------------------------------------------------
* Generalised the `MonadIO` instance for `Eff` to `(MonadIO m, Associate "IO" m xs) => MonadIO (Eff xs)`
* Added `And :: (k -> Constraint) -> (k -> Constraint) -> k -> Constraint`
* Added `Semigroup` and `Monoid` instances for `Const'`
* Added `stringAssocKey :: (IsString a, KnownSymbol (AssocKey kv)) => proxy kv -> a`
* Added a `Wrapper` instance for `Either e`
* Added instances of `Pretty` and `Lift`
* Added `hmapWithIndexFor`
0.4.8
-------------------------------------------------
* Changed the `FromJSON` instance for `Record` to call `parseJSON Null` for missing fields
* Added `FromJSON` and `ToJSON` instances for `Nullable (Field h) :* xs`
0.4.7.2
-------------------------------------------------
* Added cassava's `ToNamedRecord`, `ToRecord`, `FromNamedRecord` and `FromRecord` instances
* Added `KeyIs` and `ValueIs`
* Added `FromJSON` and `ToJSON` instances for `(:*)`
0.4.7.1
-------------------------------------------------
* Fixed weird CPP errors on macOS 10.13.2 (#18)
* Added `optFlag`, `optLastArg`, and `optionOptArg`
0.4.7
-------------------------------------------------
* Made various optimisations to improve the compilation time
* Added trivial instances for `FromBits`
* Generalised the API of `Data.Extensible.GetOpt`
0.4.6
-------------------------------------------------
* New module `Data.Extensible.GetOpt`
* Added `fromBitProd`
* Added `Hashable` instances for `:*`, `:|`, `BitProd`, `Membership`, and various wrappers
* Added an `Unbox` instance for `:*`
* Added `hfoldlWithIndex` and `hfoldlWithIndexFor`
0.4.5
-------------------------------------------------
* Added `nothingEff`
* Added `happend`
* Added `Arbitrary` instances for `:*`, `:|`, and wrappers
* Added `Data.Extensible.Bits`
0.4.4
-------------------------------------------------
* Added `contEff` and `runContEff`
* Added `castEff`
* Added `evalStateEff`
* Added `Semigroup` and `Monoid` instances for `Match`, `Comp`, `Prod`
* Added `evalStateDef`, `execStateDef`, and `execWriterDef`
* Added `mkFieldAs`
* Added a `Bounded` instance for `:*`
0.4.3
-------------------------------------------------
* Added `WrappedPointer`
* Added `NFData` and `Generic` instances for `Comp`
* Added a `Semigroup` instance for `h :* xs` and `Membership xs x`
* Added `Prod`
* Added `peelEff0`
* Changed the `IsLabel` instance so that a function is always inferred as an optic
* `Data.Extensible.Class` now exports `compareMembership`
* Renamed `runMembership` to `leadership`
0.4.2
-------------------------------------------------
* Made `newFrom` strict
* `pieceAt` for `(:*)` is now strict
* Added `(<!)`
* Added `peelEff1`, `peelAction0`, `execStateEff`, `execWriterEff`
* Added atomic operations for `Struct`
* Added constrained variants of folds
0.4.1
--------------------------------------------------
* Added `hforce`
* Added an `NFData` instance for `(:*)` and `:|`
* Added a rule to fuse a chain of product updates
* Added a `Monoid` instance for `TangleT`
* Added `(@==)`
* `#foo` can now be overloaded as `FieldOptic "foo"`
0.4
---------------------------------------------------
* Added `Data.Extensible.Struct`
* Changed the representation of `(:*)` to use `SmallArray`
* Removed `(<:*)`. `hhead`, `htail`, `huncons`, `(*++*)`, `htrans`
* New functions: `hfoldrWithIndex`, `hrepeat`, `hrepeatFor`, `haccumMap`,
`haccum`, `hpartition`, `henumerate`, `hlength`, `hcount`
* Added various derived instances for `Field`
* Added `liftField`, `liftField2`
* Added `Wrapper` instances for `Maybe` and `[]`
* Added `>:` as a synonym for `:>`
* `Data.Extensible.Effect`
* Refined the API
* Added `Data.Extensible.Effect.Default`
* Added `Data.Extensible.Tangle`
* Added `record`
* Type inference aids
0.3.7.1
----------------------------------------------------
* `pieceAt` for `(:*)` is now index-preserving
* Removed `sector`, `sectorAt`, `picked`
0.3.7
-----------------------------------------------------
* Support GHC 8.0
* Added a `Monoid` instance for `Field`
* Added `Data.Extensible.Record`
* Added `Enum` and `Bounded` instances for `Proxy :| xs`
* Removed `Data.Extensible.Union`
0.3.6
-----------------------------------------------------
* Added `(@:>)`
* Added `(!-!!)`, `nihility`, `squash`
0.3.5
-----------------------------------------------------
* Added `Data.Extensible.Effect`
* Added `decEffects`
0.3.4
-----------------------------------------------------
* Added `Data.Extensible.Wrapper`
* Added `itemAt`, `item`, `itemAssoc`
* Safe Haskell
* Generalized `Field`
0.3.3
-----------------------------------------------------
* Renamed `sectorAt`, `sector`, `sectorAssoc` to `pieceAt`, `piece`, `pieceAssoc`, respectively
* `picked` is now subsumed by `piece`
* `mkField` yields more generalized optics
* Renamed `UnionAt` to `EmbedAt`
* Removed `clause`; Use `piece . _Match`
* Removed `record`; Use `piece . _K0`
* Added `htraverseWithIndex`
* Renamed `ord` to `mkMembership`
* Fixed the `Show` instance of `:|`
* Added `Variant`
0.3.2
-----------------------------------------------------
* Added `Associate` class and combinators around it
* `Data.Extensible.Record` now lets values be independent from keys
* `mkField` requires 1 argument
* Added `Data.Extensible.Union`, partially taking `elevator`'s functionality
* Removed old `Data.Extensible.Union` and `Data.Extensible.League`
* Removed `(<?!)`
0.3.1
-----------------------------------------------------
* Removed `Reifiable`
* Now `library` yields desired dictionaries
* Added `remember`
* Added `strike` and `strikeAt`
0.3
-----------------------------------------------------
* Renamed `generate` to `htabulate`
* Renamed `generateA` to `hgenerate`
* Renamed `generateFor` to `htabulateFor`
* Renamed `generateForA` to `hgenerateFor`
* Renamed `htabulate` to `hmapWithIndex`
* Added `(<@=>)`
* Added `Comp`
* Fixed badly-specialized `htraverse`
* Added `hsequence`, `hdistribute`, `hcollect`
* Added `hindex`
0.2.10
-----------------------------------------------------
* Optimized `sector` (~2x)
0.2.9
-----------------------------------------------------
* Renamed `(<?~)` to `(<?!$)`
* Renamed `(<$?~)` to `(<?!~)`
* Refactored `Data.Extensible.Dictionary`
* Supported serialization/deserialization of products using `binary`
0.2.8
-----------------------------------------------------
* Improved performance considerably
0.2.7
-----------------------------------------------------
* Added `accessing`
* Added `decFields` and `decFieldsDeriving`
* Renamed `Position` to `Membership`
0.2.6
-----------------------------------------------------
* Right-associated `(++)`
* Added `htrans`
* Added `recordType`
* Made Eq, Ord, Show instances for Position more reasonable
0.2.5
-----------------------------------------------------
* Added `(<:)`
* Re-exported `Data.Extensible.Record`, `Data.Extensible.Union`, `Data.Extensible.League`
* Brushed instances up
* Added `subset`
* Added `Data.Extensible.Internal.HList` and combinators
0.2.4
------------------------------------------------------
* Corrected the definition of `Half`
* Added `coinclusion`, `wrench`, `retrench` along with `Nullable`
* Added `htabulate`
0.2.3
-------------------------------------------------------
* Corrected the behavior of `Generate` and `Forall`
* Made type errors more readable
* Added `(*++*)`
* Fixed the accidental miscall of `getUnion`
0.2.2
--------------------------------------------------------
* Added `recordAt`
* Added `ord`
* Re-added `K1`
* Toggled INLINE pragmas
0.2.1
--------------------------------------------------------
* Added `hhead` and `htail`
* Changed the definition of `Union` to use coyoneda style
0.2
--------------------------------------------------------
* Split modules up
* Flipped `Position`
* Added several combinators
|
{
"content_hash": "be52dcca4be17fd85e6b8de6934548e8",
"timestamp": "",
"source": "github",
"line_count": 325,
"max_line_length": 218,
"avg_line_length": 33.72615384615385,
"alnum_prop": 0.5546939147887966,
"repo_name": "fumieval/extensible",
"id": "042f41c1ba5e4aea6b3ea1d2f711e25e5b7b4501",
"size": "10963",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "122872"
}
],
"symlink_target": ""
}
|
namespace extensions::webauthn_proxy {
namespace {
std::string Base64UrlEncode(base::span<const uint8_t> input) {
// Byte strings, which appear in the WebAuthn IDL as ArrayBuffer or
// ByteSource, are base64url-encoded without trailing '=' padding.
std::string output;
base::Base64UrlEncode(
base::StringPiece(reinterpret_cast<const char*>(input.data()),
input.size()),
base::Base64UrlEncodePolicy::OMIT_PADDING, &output);
return output;
}
bool Base64UrlDecode(base::StringPiece input, std::string* output) {
return base::Base64UrlDecode(
input, base::Base64UrlDecodePolicy::DISALLOW_PADDING, output);
}
// Base64url-decodes the value of `key` from `dict`. Returns `nullopt` if the
// key isn't present or decoding failed.
absl::optional<std::string> Base64UrlDecodeStringKey(const base::Value& dict,
const std::string& key) {
const std::string* b64url_data = dict.FindStringKey(key);
if (!b64url_data) {
return absl::nullopt;
}
std::string decoded;
if (!Base64UrlDecode(*b64url_data, &decoded)) {
return absl::nullopt;
}
return decoded;
}
// Like `Base64UrlDecodeStringKey()` attempts to find and base64-decode the
// value of `key` in `dict`. However, the value may also be of
// `base::Value::Type::NONE`. Returns true on success and the decoded result if
// the value was a string. Returns `{false, absl::nullopt}` if the key wasn't
// found or if decoding the string failed.
//
// This is useful for extracting attributes that are defined as nullable
// ArrayBuffers in the WebIDL since the JS `null` value maps to
// `base::Value::Type::NONE`.
std::tuple<bool, absl::optional<std::string>> Base64UrlDecodeNullableStringKey(
const base::Value& dict,
const std::string& key) {
const base::Value* value = dict.FindKey(key);
if (!value || (!value->is_string() && !value->is_none())) {
return {false, absl::nullopt};
}
if (value->is_none()) {
return {true, absl::nullopt};
}
DCHECK(value->is_string());
const std::string* b64url_data = dict.FindStringKey(key);
if (!b64url_data) {
return {false, absl::nullopt};
}
std::string decoded;
if (!Base64UrlDecode(*b64url_data, &decoded)) {
return {false, absl::nullopt};
}
return {true, decoded};
}
std::vector<uint8_t> ToByteVector(const std::string& in) {
const uint8_t* in_ptr = reinterpret_cast<const uint8_t*>(in.data());
return std::vector<uint8_t>(in_ptr, in_ptr + in.size());
}
base::Value ToValue(const device::PublicKeyCredentialRpEntity& relying_party) {
base::Value::Dict value;
value.Set("id", relying_party.id);
// `PublicKeyCredentialEntity.name` is required in the IDL but optional on the
// mojo struct.
value.Set("name", relying_party.name.value_or(""));
return base::Value(std::move(value));
}
base::Value ToValue(const device::PublicKeyCredentialUserEntity& user) {
base::Value::Dict value;
value.Set("id", Base64UrlEncode(user.id));
// `PublicKeyCredentialEntity.name` is required in the IDL but optional on the
// mojo struct.
value.Set("name", user.name.value_or(""));
if (user.display_name) {
value.Set("displayName", *user.display_name);
}
return base::Value(std::move(value));
}
base::Value ToValue(
const device::PublicKeyCredentialParams::CredentialInfo& params) {
base::Value::Dict value;
switch (params.type) {
case device::CredentialType::kPublicKey:
value.Set("type", device::kPublicKey);
}
value.Set("alg", params.algorithm);
return base::Value(std::move(value));
}
base::Value ToValue(const device::PublicKeyCredentialDescriptor& descriptor) {
base::Value::Dict value;
switch (descriptor.credential_type) {
case device::CredentialType::kPublicKey:
value.Set("type", device::kPublicKey);
}
value.Set("id", Base64UrlEncode(descriptor.id));
base::Value::List transports;
for (const device::FidoTransportProtocol& transport : descriptor.transports) {
transports.Append(ToString(transport));
}
if (!transports.empty()) {
value.Set("transports", std::move(transports));
}
return base::Value(std::move(value));
}
base::Value ToValue(
const device::AuthenticatorAttachment& authenticator_attachment) {
switch (authenticator_attachment) {
case device::AuthenticatorAttachment::kCrossPlatform:
return base::Value("cross-platform");
case device::AuthenticatorAttachment::kPlatform:
return base::Value("platform");
case device::AuthenticatorAttachment::kAny:
// Any maps to the key being omitted, not a null value.
NOTREACHED();
return base::Value("invalid");
}
}
base::Value ToValue(
const device::ResidentKeyRequirement& resident_key_requirement) {
switch (resident_key_requirement) {
case device::ResidentKeyRequirement::kDiscouraged:
return base::Value("discouraged");
case device::ResidentKeyRequirement::kPreferred:
return base::Value("preferred");
case device::ResidentKeyRequirement::kRequired:
return base::Value("required");
}
}
base::Value ToValue(
const device::UserVerificationRequirement& user_verification_requirement) {
switch (user_verification_requirement) {
case device::UserVerificationRequirement::kDiscouraged:
return base::Value("discouraged");
case device::UserVerificationRequirement::kPreferred:
return base::Value("preferred");
case device::UserVerificationRequirement::kRequired:
return base::Value("required");
}
}
base::Value ToValue(
const device::AuthenticatorSelectionCriteria& authenticator_selection) {
base::Value::Dict value;
absl::optional<std::string> attachment;
if (authenticator_selection.authenticator_attachment !=
device::AuthenticatorAttachment::kAny) {
value.Set("authenticatorAttachment",
ToValue(authenticator_selection.authenticator_attachment));
}
value.Set("residentKey", ToValue(authenticator_selection.resident_key));
value.Set("userVerification",
ToValue(authenticator_selection.user_verification_requirement));
return base::Value(std::move(value));
}
base::Value ToValue(const device::AttestationConveyancePreference&
attestation_conveyance_preference) {
switch (attestation_conveyance_preference) {
case device::AttestationConveyancePreference::kNone:
return base::Value("none");
case device::AttestationConveyancePreference::kIndirect:
return base::Value("indirect");
case device::AttestationConveyancePreference::kDirect:
return base::Value("direct");
case device::AttestationConveyancePreference::kEnterpriseApprovedByBrowser:
case device::AttestationConveyancePreference::
kEnterpriseIfRPListedOnAuthenticator:
return base::Value("enterprise");
}
}
base::Value ToValue(const blink::mojom::RemoteDesktopClientOverride&
remote_desktop_client_override) {
base::Value::Dict value;
value.Set("origin", remote_desktop_client_override.origin.Serialize());
value.Set("sameOriginWithAncestors",
remote_desktop_client_override.same_origin_with_ancestors);
return base::Value(std::move(value));
}
base::Value ToValue(const blink::mojom::ProtectionPolicy policy) {
switch (policy) {
case blink::mojom::ProtectionPolicy::UNSPECIFIED:
NOTREACHED();
return base::Value("invalid");
case blink::mojom::ProtectionPolicy::NONE:
return base::Value("userVerificationOptional");
case blink::mojom::ProtectionPolicy::UV_OR_CRED_ID_REQUIRED:
return base::Value("userVerificationOptionalWithCredentialIDList");
case blink::mojom::ProtectionPolicy::UV_REQUIRED:
return base::Value("userVerificationRequired");
}
}
base::Value ToValue(const device::LargeBlobSupport large_blob) {
switch (large_blob) {
case device::LargeBlobSupport::kNotRequested:
NOTREACHED();
return base::Value("invalid");
case device::LargeBlobSupport::kRequired:
return base::Value("required");
case device::LargeBlobSupport::kPreferred:
return base::Value("preferred");
}
}
base::Value ToValue(const device::CableDiscoveryData& cable_authentication) {
base::Value::Dict value;
switch (cable_authentication.version) {
case device::CableDiscoveryData::Version::INVALID:
NOTREACHED();
break;
case device::CableDiscoveryData::Version::V1:
value.Set("version", 1);
value.Set("clientEid",
Base64UrlEncode(cable_authentication.v1->client_eid));
value.Set("authenticatorEid",
Base64UrlEncode(cable_authentication.v1->authenticator_eid));
value.Set("sessionPreKey",
Base64UrlEncode(cable_authentication.v1->session_pre_key));
break;
case device::CableDiscoveryData::Version::V2:
value.Set("version", 2);
value.Set("clientEid",
Base64UrlEncode(cable_authentication.v2->experiments));
value.Set("authenticatorEid", "");
value.Set("sessionPreKey",
Base64UrlEncode(cable_authentication.v2->server_link_data));
break;
}
return base::Value(std::move(value));
}
absl::optional<device::FidoTransportProtocol> FidoTransportProtocolFromValue(
const base::Value& value) {
if (!value.is_string()) {
return absl::nullopt;
}
return device::ConvertToFidoTransportProtocol(value.GetString());
}
absl::optional<device::AuthenticatorAttachment>
NullableAuthenticatorAttachmentFromValue(const base::Value& value) {
if (!value.is_none() && !value.is_string()) {
return absl::nullopt;
}
if (value.is_none()) {
// PublicKeyCredential.authenticatorAttachment can be `null`, which is
// equivalent to `AuthenticatorAttachment::kAny`.
return device::AuthenticatorAttachment::kAny;
}
const std::string& attachment_name = value.GetString();
if (attachment_name == "platform") {
return device::AuthenticatorAttachment::kPlatform;
} else if (attachment_name == "cross-platform") {
return device::AuthenticatorAttachment::kCrossPlatform;
}
return absl::nullopt;
}
} // namespace
base::Value ToValue(
const blink::mojom::PublicKeyCredentialCreationOptionsPtr& options) {
base::Value::Dict value;
value.Set("rp", ToValue(options->relying_party));
value.Set("user", ToValue(options->user));
value.Set("challenge", Base64UrlEncode(options->challenge));
base::Value::List public_key_parameters;
for (const device::PublicKeyCredentialParams::CredentialInfo& params :
options->public_key_parameters) {
public_key_parameters.Append(ToValue(params));
}
value.Set("pubKeyCredParams", std::move(public_key_parameters));
base::Value::List exclude_credentials;
for (const device::PublicKeyCredentialDescriptor& descriptor :
options->exclude_credentials) {
exclude_credentials.Append(ToValue(descriptor));
}
value.Set("excludeCredentials", std::move(exclude_credentials));
if (options->authenticator_selection) {
value.Set("authenticatorSelection",
ToValue(*options->authenticator_selection));
}
value.Set("attestation", ToValue(options->attestation));
base::Value::Dict& extensions =
value.Set("extensions", base::Value::Dict())->GetDict();
if (options->hmac_create_secret) {
extensions.Set("hmacCreateSecret", true);
}
if (options->protection_policy !=
blink::mojom::ProtectionPolicy::UNSPECIFIED) {
extensions.Set("credentialProtectionPolicy",
ToValue(options->protection_policy));
extensions.Set("enforceCredentialProtectionPolicy",
options->enforce_protection_policy);
}
if (options->appid_exclude) {
extensions.Set("appIdExclude", *options->appid_exclude);
}
if (options->cred_props) {
extensions.Set("credProps", true);
}
if (options->large_blob_enable != device::LargeBlobSupport::kNotRequested) {
base::Value::Dict large_blob_value;
large_blob_value.Set("support", ToValue(options->large_blob_enable));
extensions.Set("largeBlob", std::move(large_blob_value));
}
DCHECK(!options->is_payment_credential_creation);
if (options->cred_blob) {
extensions.Set("credBlob", Base64UrlEncode(*options->cred_blob));
}
if (options->google_legacy_app_id_support) {
extensions.Set("googleLegacyAppidSupport", true);
}
if (options->min_pin_length_requested) {
extensions.Set("minPinLength", true);
}
if (options->remote_desktop_client_override) {
extensions.Set("remoteDesktopClientOverride",
ToValue(*options->remote_desktop_client_override));
}
DCHECK(!options->prf_enable);
return base::Value(std::move(value));
}
base::Value ToValue(
const blink::mojom::PublicKeyCredentialRequestOptionsPtr& options) {
base::Value::Dict value;
value.Set("challenge", Base64UrlEncode(options->challenge));
value.Set("rpId", options->relying_party_id);
base::Value::List allow_credentials;
for (const device::PublicKeyCredentialDescriptor& descriptor :
options->allow_credentials) {
allow_credentials.Append(ToValue(descriptor));
}
value.Set("allowCredentials", std::move(allow_credentials));
value.Set("userVerification", ToValue(options->user_verification));
base::Value::Dict& extensions =
value.Set("extensions", base::Value::Dict())->GetDict();
if (options->appid) {
extensions.Set("appid", *options->appid);
}
base::Value::List cable_authentication_data;
for (const device::CableDiscoveryData& cable :
options->cable_authentication_data) {
cable_authentication_data.Append(ToValue(cable));
}
if (!cable_authentication_data.empty()) {
extensions.Set("cableAuthentication", std::move(cable_authentication_data));
}
if (options->get_cred_blob) {
extensions.Set("getCredBlob", true);
}
if (options->large_blob_read || options->large_blob_write) {
base::Value::Dict large_blob_value;
if (options->large_blob_read) {
large_blob_value.Set("read", true);
}
if (options->large_blob_write) {
large_blob_value.Set("write",
Base64UrlEncode(*options->large_blob_write));
}
extensions.Set("largeBlob", std::move(large_blob_value));
}
if (options->remote_desktop_client_override) {
extensions.Set("remoteDesktopClientOverride",
ToValue(*options->remote_desktop_client_override));
}
DCHECK(!options->prf);
return base::Value(std::move(value));
}
std::pair<blink::mojom::MakeCredentialAuthenticatorResponsePtr, std::string>
MakeCredentialResponseFromValue(const base::Value& value) {
if (!value.is_dict()) {
return {nullptr, "value is not a dict"};
}
const std::string* type = value.FindStringKey("type");
if (!type || *type != device::kPublicKey) {
return {nullptr, "invalid type"};
}
auto response = blink::mojom::MakeCredentialAuthenticatorResponse::New();
response->info = blink::mojom::CommonCredentialInfo::New();
const std::string* id = value.FindStringKey("id");
if (!id) {
return {nullptr, "invalid id"};
}
response->info->id = *id;
absl::optional<std::string> raw_id = Base64UrlDecodeStringKey(value, "rawId");
if (!raw_id) {
return {nullptr, "invalid rawId"};
}
response->info->raw_id = ToByteVector(*raw_id);
const base::Value* authenticator_attachment_value =
value.FindKey("authenticatorAttachment");
if (!authenticator_attachment_value) {
return {nullptr, "invalid authenticatorAttachment"};
}
absl::optional<device::AuthenticatorAttachment> authenticator_attachment =
NullableAuthenticatorAttachmentFromValue(*authenticator_attachment_value);
if (!authenticator_attachment) {
return {nullptr, "invalid authenticatorAttachment"};
}
response->authenticator_attachment = *authenticator_attachment;
const base::Value* attestation_response = value.FindDictKey("response");
if (!attestation_response) {
return {nullptr, "invalid response"};
}
absl::optional<std::string> authenticator_data =
Base64UrlDecodeStringKey(*attestation_response, "authenticatorData");
if (!authenticator_data) {
return {nullptr, "invalid authenticatorData"};
}
response->info->authenticator_data = ToByteVector(*authenticator_data);
absl::optional<std::string> attestation_object =
Base64UrlDecodeStringKey(*attestation_response, "attestationObject");
if (!attestation_object) {
return {nullptr, "invalid attestationObject"};
}
response->attestation_object = ToByteVector(*attestation_object);
absl::optional<std::string> client_data_json =
Base64UrlDecodeStringKey(*attestation_response, "clientDataJSON");
if (!client_data_json) {
return {nullptr, "invalid clientDataJSON"};
}
response->info->client_data_json = ToByteVector(*client_data_json);
// publicKey is required but nullable.
auto [ok, opt_public_key] =
Base64UrlDecodeNullableStringKey(*attestation_response, "publicKey");
if (!ok) {
return {nullptr, "invalid publicKey"};
}
if (opt_public_key) {
response->public_key_der = ToByteVector(*opt_public_key);
}
absl::optional<int> public_key_algorithm =
attestation_response->FindIntKey("publicKeyAlgorithm");
if (!public_key_algorithm) {
return {nullptr, "invalid publicKeyAlgorithm"};
}
response->public_key_algo = *public_key_algorithm;
const base::Value* transports =
attestation_response->FindListKey("transports");
if (!transports) {
return {nullptr, "invalid transports"};
}
for (const base::Value& transport_name : transports->GetList()) {
absl::optional<device::FidoTransportProtocol> transport =
FidoTransportProtocolFromValue(transport_name);
if (!transport) {
return {nullptr, "invalid transports"};
}
response->transports.push_back(*transport);
}
const base::Value* client_extension_results =
value.FindDictKey("clientExtensionResults");
if (!client_extension_results) {
return {nullptr, "invalid clientExtensionResults"};
}
absl::optional<bool> cred_blob =
client_extension_results->FindBoolKey("credBlob");
if (cred_blob) {
response->echo_cred_blob = true;
response->cred_blob = *cred_blob;
}
const base::Value* cred_props =
client_extension_results->FindDictKey("credProps");
if (cred_props) {
response->echo_cred_props = true;
absl::optional<bool> rk = cred_props->FindBoolKey("rk");
if (rk) {
response->has_cred_props_rk = true;
response->cred_props_rk = *rk;
}
}
const absl::optional<bool> hmac_create_secret =
client_extension_results->FindBoolKey("hmacCreateSecret");
if (hmac_create_secret) {
response->echo_hmac_create_secret = true;
response->hmac_create_secret = *hmac_create_secret;
}
const base::Value* large_blob =
client_extension_results->FindDictKey("largeBlob");
if (large_blob) {
response->echo_large_blob = true;
const absl::optional<bool> supported = large_blob->FindBoolKey("supported");
if (!supported) {
return {nullptr, "invalid largeBlob extension"};
}
response->supports_large_blob = *supported;
}
return {std::move(response), ""};
}
std::pair<blink::mojom::GetAssertionAuthenticatorResponsePtr, std::string>
GetAssertionResponseFromValue(const base::Value& value) {
if (!value.is_dict()) {
return {nullptr, "value is not a dict"};
}
const std::string* type = value.FindStringKey("type");
if (!type || *type != device::kPublicKey) {
return {nullptr, "invalid type"};
}
auto response = blink::mojom::GetAssertionAuthenticatorResponse::New();
response->info = blink::mojom::CommonCredentialInfo::New();
const std::string* id = value.FindStringKey("id");
if (!id) {
return {nullptr, "invalid id"};
}
response->info->id = *id;
absl::optional<std::string> raw_id = Base64UrlDecodeStringKey(value, "rawId");
if (!raw_id) {
return {nullptr, "invalid rawId"};
}
response->info->raw_id = ToByteVector(*raw_id);
const base::Value* authenticator_attachment_value =
value.FindKey("authenticatorAttachment");
if (!authenticator_attachment_value) {
return {nullptr, "invalid authenticatorAttachment"};
}
absl::optional<device::AuthenticatorAttachment> authenticator_attachment =
NullableAuthenticatorAttachmentFromValue(*authenticator_attachment_value);
if (!authenticator_attachment) {
return {nullptr, "invalid authenticatorAttachment"};
}
response->authenticator_attachment = *authenticator_attachment;
const base::Value* assertion_response = value.FindDictKey("response");
if (!assertion_response) {
return {nullptr, "invalid response"};
}
absl::optional<std::string> client_data_json =
Base64UrlDecodeStringKey(*assertion_response, "clientDataJSON");
if (!client_data_json) {
return {nullptr, "invalid clientDataJSON"};
}
response->info->client_data_json = ToByteVector(*client_data_json);
absl::optional<std::string> authenticator_data =
Base64UrlDecodeStringKey(*assertion_response, "authenticatorData");
if (!authenticator_data) {
return {nullptr, "invalid authenticatorData"};
}
response->info->authenticator_data = ToByteVector(*authenticator_data);
absl::optional<std::string> signature =
Base64UrlDecodeStringKey(*assertion_response, "signature");
if (!signature) {
return {nullptr, "invalid signature"};
}
response->signature = ToByteVector(*signature);
// userHandle is non-optional but nullable.
auto [ok, opt_user_handle] =
Base64UrlDecodeNullableStringKey(*assertion_response, "userHandle");
if (!ok) {
return {nullptr, "invalid userHandle"};
}
if (opt_user_handle) {
response->user_handle = ToByteVector(*opt_user_handle);
}
const base::Value* client_extension_results =
value.FindDictKey("clientExtensionResults");
if (!client_extension_results) {
return {nullptr, "invalid clientExtensionResults"};
}
const absl::optional<bool> app_id =
client_extension_results->FindBoolKey("appid");
if (app_id) {
response->echo_appid_extension = true;
response->appid_extension = *app_id;
}
if (client_extension_results->FindKey("getCredBlob")) {
absl::optional<std::string> cred_blob =
Base64UrlDecodeStringKey(*client_extension_results, "getCredBlob");
if (!cred_blob) {
return {nullptr, "invalid credBlob extension"};
}
response->get_cred_blob = ToByteVector(*cred_blob);
}
const base::Value* large_blob =
client_extension_results->FindDictKey("largeBlob");
if (large_blob) {
response->echo_large_blob = true;
if (large_blob->FindStringKey("blob")) {
absl::optional<std::string> blob =
Base64UrlDecodeStringKey(*large_blob, "blob");
if (!blob) {
return {nullptr, "invalid largeBlob extension"};
}
response->large_blob = ToByteVector(*blob);
}
const absl::optional<bool> written = large_blob->FindBoolKey("written");
if (written) {
response->echo_large_blob_written = true;
response->large_blob_written = *written;
}
}
return {std::move(response), ""};
}
} // namespace extensions::webauthn_proxy
|
{
"content_hash": "d96c96270586b19b9c783d6771ec6789",
"timestamp": "",
"source": "github",
"line_count": 664,
"max_line_length": 80,
"avg_line_length": 34.95331325301205,
"alnum_prop": 0.6930070231375759,
"repo_name": "nwjs/chromium.src",
"id": "7665e92950ce096afa14086e6dd4dd7e48dacd7e",
"size": "24147",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "chrome/browser/extensions/api/web_authentication_proxy/value_conversions.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
from thesaurus import fullfil_thesaurus_db
from extract_names import extract_names
from cache import name_genders, university_locations, university_types
import os, sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
from model.teseo_model import University
from model.dbconnection import dbconfig
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import mysql.connector
if __name__ == '__main__':
# Get names and surnames for people
print "Extracting names..."
extract_names()
# Fullfil people tables with gender
print "\n\nGetting genders..."
config = dbconfig
engine = create_engine('mysql://%s:%s@%s/%s?charset=utf8' % (config['user'], config['password'], config['host'], dbconfig['database']))
Session = sessionmaker(bind=engine)
session = Session()
cnx = mysql.connector.connect(**config)
update_cnx = mysql.connector.connect(**config)
cursor_pers = cnx.cursor()
cursor_update_pers = update_cnx.cursor()
cursor_pers.execute("SELECT id, first_name FROM person WHERE first_name <> '' ")
for pers in cursor_pers:
pers_id = pers[0]
pers_name = pers[1].encode('utf-8').split()[0]
if pers_name in name_genders and name_genders[pers_name] and name_genders[pers_name] != 'None':
sys.stdout.write('%s - %s \r' % (pers_id, name_genders[pers_name]))
sys.stdout.flush()
cursor_update_pers.execute("UPDATE person SET gender='%s' WHERE id=%s" % (name_genders[pers_name], pers_id))
cursor_pers.close()
cursor_update_pers.close()
# Generate the full hierarchy of unesco descriptors with codes
print "\n\nGenerating Unesco hierarchy..."
fullfil_thesaurus_db()
# Fulfill university tables with locations
print "\n\nGetting university locations and type (private-public)..."
for uni, location in university_locations.items():
uni_db = session.query(University).filter(University.name == uni).first()
if not uni_db:
uni_db = University(name=uni)
uni_db.location = location
uni_db.private = university_types[uni] == 'private'
session.add(uni_db)
session.commit()
|
{
"content_hash": "a119c87faed53434314c2528636a3352",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 139,
"avg_line_length": 38.189655172413794,
"alnum_prop": 0.6690744920993228,
"repo_name": "OpenDataDayBilbao/teseo2014",
"id": "41a347649a3c4ff695c51a183f3af032e203666e",
"size": "2215",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "data/update_db.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "48886"
},
{
"name": "HTML",
"bytes": "227949"
},
{
"name": "JavaScript",
"bytes": "360395"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "140298"
}
],
"symlink_target": ""
}
|
<?php
namespace Google\Service\Gmail;
class PopSettings extends \Google\Model
{
/**
* @var string
*/
public $accessWindow;
/**
* @var string
*/
public $disposition;
/**
* @param string
*/
public function setAccessWindow($accessWindow)
{
$this->accessWindow = $accessWindow;
}
/**
* @return string
*/
public function getAccessWindow()
{
return $this->accessWindow;
}
/**
* @param string
*/
public function setDisposition($disposition)
{
$this->disposition = $disposition;
}
/**
* @return string
*/
public function getDisposition()
{
return $this->disposition;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PopSettings::class, 'Google_Service_Gmail_PopSettings');
|
{
"content_hash": "855348decfdc182ce4c39e2c78837c92",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 81,
"avg_line_length": 16.895833333333332,
"alnum_prop": 0.6387176325524044,
"repo_name": "googleapis/google-api-php-client-services",
"id": "c22f927af10890c54b3ae63d3f5d3592b1b386b5",
"size": "1401",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "src/Gmail/PopSettings.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "55414116"
},
{
"name": "Python",
"bytes": "427325"
},
{
"name": "Shell",
"bytes": "787"
}
],
"symlink_target": ""
}
|
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.ServiceModel;
namespace ACorns.WCF.DynamicClientProxy.Internal
{
/// <summary>
/// Use a bit of reflection and code emiting to emit a nice proxy class that inherits from ClientBase<TInterface>, TInterface.
/// The emited class follows the recommended ClientBase pattern.
/// </summary>
/// <typeparam name="TInterface"></typeparam>
internal class WCFProxyClassBuilder<TInterface>
: AbstractClassBuilder<TInterface> where TInterface : class
{
public WCFProxyClassBuilder()
: base(typeof (ClientBase<TInterface>))
{
}
/// <summary>
/// Generate the contents of the method. This will generate:
///
/// ....
/// return Channel.MethodName(params);
/// ...
///
/// </summary>
/// <param name="method"></param>
/// <param name="parameterTypes"></param>
/// <param name="iLGenerator"></param>
protected override void GenerateMethodImpl(MethodInfo method, Type[] parameterTypes, ILGenerator iLGenerator)
{
iLGenerator.Emit(OpCodes.Ldarg_0); // this
// Get the details Property of the ClientBase
MethodInfo channelProperty = GetMethodFromBaseClass("get_Channel");
// Get the channel: "base.Channel<TInterface>."
iLGenerator.EmitCall(OpCodes.Call, channelProperty, null);
// Prepare the parameters for the call
ParameterInfo[] parameters = method.GetParameters();
for (int index = 0; index < parameterTypes.Length; index++)
{
iLGenerator.Emit(OpCodes.Ldarg, (((short) index) + 1));
}
// Call the Channel via the interface
iLGenerator.Emit(OpCodes.Callvirt, method);
// Thanks, all done
iLGenerator.Emit(OpCodes.Ret);
}
}
}
|
{
"content_hash": "31610622abf92dd0dfbdacc9868a7fe0",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 127,
"avg_line_length": 30.8,
"alnum_prop": 0.7030696576151122,
"repo_name": "SSEHUB/EASyProducer",
"id": "4cb449e368e2cf011bec8848639e3946405dda20",
"size": "1694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Plugins/EASy-Producer/ScenariosTest/testdata/real/INDENICA/PL_WMS_Platform/WMSsolution/ACorns.WCF.DynamicClientProxy/Internal/WCFProxyClassBuilder.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "1184"
},
{
"name": "Batchfile",
"bytes": "6836"
},
{
"name": "GAP",
"bytes": "2073949"
},
{
"name": "HTML",
"bytes": "112226"
},
{
"name": "Java",
"bytes": "30149700"
},
{
"name": "Shell",
"bytes": "2416"
},
{
"name": "Velocity Template Language",
"bytes": "231811"
},
{
"name": "Xtend",
"bytes": "2141"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XK_igrave` constant in crate `x11_dl`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XK_igrave">
<title>x11_dl::keysym::XK_igrave - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a></p><script>window.sidebarCurrent = {name: 'XK_igrave', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a>::<wbr><a class='constant' href=''>XK_igrave</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-3450' class='srclink' href='../../src/x11_dl/keysym.rs.html#349' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XK_igrave: <a class='type' href='../../libc/types/os/arch/c95/type.c_uint.html' title='libc::types::os::arch::c95::c_uint'>c_uint</a><code> = </code><code>0x0ec</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "x11_dl";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
{
"content_hash": "7ea41b1831ba17a142e6178d538763ec",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 240,
"avg_line_length": 37.584158415841586,
"alnum_prop": 0.5226554267650158,
"repo_name": "mcanders/bevy",
"id": "26ba251759dc3e895547e55f66c206e173715bcb",
"size": "3796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/x11_dl/keysym/constant.XK_Igrave (Case Conflict).html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "316751"
}
],
"symlink_target": ""
}
|
package com.huawei.esdk.fusioncompute.demo.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
import com.huawei.esdk.fusioncompute.local.model.PageList;
import com.huawei.esdk.fusioncompute.local.model.cluster.ClusterBasicInfo;
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
import com.huawei.esdk.fusioncompute.local.model.host.Host;
import com.huawei.esdk.fusioncompute.local.model.host.QueryHostListReq;
/**
* “查询VDC”请求处理类
* @author dWX213051
* @see
* @since eSDK Cloud V100R003C50
*/
public class QueryClusterAndHostServlet extends HttpServlet
{
/**
* 序列化版本标识
*/
private static final long serialVersionUID = 190954570327110271L;
/**
* log日志对象
*/
private static final Logger LOGGER = Logger
.getLogger(QueryClusterAndHostServlet.class);
/**
* gson,用于转换String和json之间的转换
*/
private Gson gson = new Gson();
@Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
@Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//设置request的编码
request.setCharacterEncoding("UTF-8");
// 获取需要调用的方法名
String methodName = request.getParameter("method");
String resp = "";
if ("queryClusterAndHost".equals(methodName))
{
// 查询VDC
resp = queryPortGroups(request);
}
//设置response的编码
response.setContentType("application/json;charset=UTF-8");
// 输出流
PrintWriter pw = response.getWriter();
pw.print(resp);
pw.close();
}
/**
* 查VDC信息
*
* @param request
* HttpServletRequest对象
* @return json格式的字符串
* @see
* @since eSDK Cloud V100R003C50
*/
public String queryPortGroups(HttpServletRequest request)
{
// 定义返回结果
String response = null;
String userName = ParametersUtils.userName;
String password = ParametersUtils.password;
// 鉴权
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
if (!"00000000".equals(loginResp.getErrorCode()))
{
LOGGER.error("Failed to Login FC System!");
return gson.toJson(loginResp);
}
LOGGER.info("Login Success!");
LOGGER.info("Begin to query PortGroups information.");
String siteUri = request.getParameter("siteUri");
String tag = "";
String name = "";
Integer limit = 50;
Integer offset = 0;
QueryHostListReq req = new QueryHostListReq();
req.setLimit(limit);
req.setOffset(offset);
FCSDKResponse<PageList<Host>> hostResp = ServiceManageFactory.getHostResource().queryHostList(siteUri, req);
FCSDKResponse<List<ClusterBasicInfo>> clusResp = ServiceManageFactory.getClusterResource().queryClusters(siteUri, tag, name);
// 根据接口返回数据生成JSON字符串,以便于页面展示
response = gson.toJson(hostResp) + "||" + gson.toJson(clusResp);
LOGGER.info("Finish to query PortGroups, response is : " + response);
return response;
}
}
|
{
"content_hash": "a380b1959cfa8fbbfa8ed630a83594a6",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 133,
"avg_line_length": 29.12686567164179,
"alnum_prop": 0.6553932872149628,
"repo_name": "eSDK/esdk_cloud_fc_cli",
"id": "5c1b396c8a7f214a3d7d7f94a6332fe559f19cf3",
"size": "4095",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/demo/FC/eSDK_FC_1.3_Native_Demo_BS_JAVA/src/com/huawei/esdk/fusioncompute/demo/servlet/QueryClusterAndHostServlet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "364780"
},
{
"name": "CSS",
"bytes": "43856"
},
{
"name": "HTML",
"bytes": "231161"
},
{
"name": "Java",
"bytes": "1649173"
},
{
"name": "JavaScript",
"bytes": "303462"
}
],
"symlink_target": ""
}
|
package com.glipka.easyReactJS.reactBootstrap
import scala.scalajs.js
import scala.scalajs.js._
import com.glipka.easyReactJS.react._
import ReactBootstrap._
@js.native trait LabelProps extends HTMLProps[Label] with js.Any{
var bsSize: Sizes = js.native
var bsStyle: String = js.native
}
@js.native
class Label(props: LabelProps) extends Component[LabelProps, Any](props) with js.Any {
}
|
{
"content_hash": "105d6d97eb1ef89082acd0472105e972",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 86,
"avg_line_length": 24.8125,
"alnum_prop": 0.7732997481108312,
"repo_name": "glipka/Easy-React-With-ScalaJS",
"id": "8c67cafbe148b851404a2b166a87e9fb923d730e",
"size": "980",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/glipka/easyReactJS/reactBootstrap/Label.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "478"
},
{
"name": "HTML",
"bytes": "1141"
},
{
"name": "Scala",
"bytes": "660804"
}
],
"symlink_target": ""
}
|
require 'spec_helper'
describe JasmineParser::FileParser do
before(:each) do
@suite = JasmineParser::JasmineSuite.new
@parser = JasmineParser::FileParser.new(@suite)
end
describe "parsing command" do
it "should not accept strings for file name input" do
expect {@parser.parse "foo"}.to raise_error JasmineParser::WrongArgumentTypeForFileParser
end
it "should not accept files that do not exist" do
expect {@parser.parse ["foo"]}.to raise_error JasmineParser::FileDoesNotExistError
end
it "should parse existing file" do
@parser.parse ["spec/fixture/spec/example_spec.js"]
end
end
describe "suite object" do
before(:each) do
@parser.parse ["spec/fixture/spec/example_spec.js"]
end
it "should contain children" do
@suite.spec_files.size.should == 1
end
end
end
|
{
"content_hash": "55226ec320e3096d879767fe49cea0c1",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 95,
"avg_line_length": 22.63157894736842,
"alnum_prop": 0.6883720930232559,
"repo_name": "dimacus/jasmine-parser",
"id": "91203d19cb2cbfe387ac739da6489a477146ca01",
"size": "2386",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/file_parser_spec.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package org.kiji.schema;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.ApiStability;
import org.kiji.schema.util.KijiNameValidator;
/**
* URI that uniquely identifies a Kiji instance, table, column(s).
* Use <em>kiji://.env/default/</em> for the default Kiji instance URI.
*
* <p>
* KijiURI objects can be constructed directly from parsing a URI string:
* </p>
* <pre><code>
* final KijiURI uri = KijiURI.newBuilder("kiji://.env/default/mytable/col").build();
* </code></pre>
*
* <p>
* Alternately, KijiURI objects can be constructed from components by using the builder:
* </p>
* <pre><code>
* final KijiURI uri = KijiURI.newBuilder()
* .withInstanceName("default")
* .withTableName("mytable")
* .addColumnName(new KijiColumnName(col))
* .build();
* </code></pre>
*
* Valid URI forms look like:
* <li> "kiji://zkHost"
* <li> "kiji://zkHost/instance"
* <li> "kiji://zkHost/instance/table"
* <li> "kiji://zkHost:zkPort/instance/table"
* <li> "kiji://zkHost1,zkHost2/instance/table"
* <li> "kiji://(zkHost1,zkHost2):zkPort/instance/table"
* <li> "kiji://zkHost/instance/table/col"
* <li> "kiji://zkHost/instance/table/col1,col2"
* <li> "kiji://.env/instance/table"
* <li> "kiji://.unset/instance/table"
*/
@ApiAudience.Public
@ApiStability.Stable
public final class KijiURI {
/** URI/URL scheme used to fully qualify a Kiji table. */
public static final String KIJI_SCHEME = "kiji";
/** String to specify an unset KijiURI field. */
public static final String UNSET_URI_STRING = ".unset";
/** String to specify a value through the local environment. */
public static final String ENV_URI_STRING = ".env";
/** Default Zookeeper port. */
public static final int DEFAULT_ZOOKEEPER_CLIENT_PORT = 2181;
/** ZooKeeper quorum configured from the local environment.*/
private static final ImmutableList<String> ENV_ZOOKEEPER_QUORUM;
/** ZooKeeper client port configured from the local environment. */
private static final int ENV_ZOOKEEPER_CLIENT_PORT;
/**
* Resolves the local environment ZooKeeper parameters.
*
* Local environment refers to the hbase-site.xml configuration file available on the classpath.
*/
static {
Configuration conf = HBaseConfiguration.create();
ENV_ZOOKEEPER_QUORUM = ImmutableList.copyOf(conf.get(HConstants.ZOOKEEPER_QUORUM).split(","));
ENV_ZOOKEEPER_CLIENT_PORT =
conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, DEFAULT_ZOOKEEPER_CLIENT_PORT);
}
/** Pattern matching "(host1,host2,host3):port". */
public static final Pattern RE_AUTHORITY_GROUP = Pattern.compile("\\(([^)]+)\\):(\\d+)");
/**
* Ordered list of Zookeeper quorum host names or IP addresses.
* Preserves user ordering. Never null.
*/
private final ImmutableList<String> mZookeeperQuorum;
/** Normalized (sorted) version of mZookeeperQuorum. Never null. */
private final ImmutableList<String> mZookeeperQuorumNormalized;
/** Zookeeper client port number. */
private final int mZookeeperClientPort;
/** Kiji instance name. Null means unset. */
private final String mInstanceName;
/** Kiji table name. Null means unset. */
private final String mTableName;
/** Kiji column names. Never null. Empty means unset. Preserves user ordering. */
private final ImmutableList<KijiColumnName> mColumnNames;
/** Normalized version of mColumnNames. Never null. */
private final ImmutableList<KijiColumnName> mColumnNamesNormalized;
/**
* Constructs a new KijiURI with the given parameters.
*
* @param zookeeperQuorum Zookeeper quorum.
* @param zookeeperClientPort Zookeeper client port.
* @param instanceName Instance name.
* @param tableName Table name.
* @param columnNames Column names.
* @throws KijiURIException If the parameters are invalid.
*/
private KijiURI(
Iterable<String> zookeeperQuorum,
int zookeeperClientPort,
String instanceName,
String tableName,
Iterable<KijiColumnName> columnNames) {
mZookeeperQuorum = ImmutableList.copyOf(zookeeperQuorum);
mZookeeperQuorumNormalized = ImmutableSortedSet.copyOf(mZookeeperQuorum).asList();
mZookeeperClientPort = zookeeperClientPort;
mInstanceName =
((null == instanceName) || !instanceName.equals(UNSET_URI_STRING)) ? instanceName : null;
mTableName = ((null == tableName) || !tableName.equals(UNSET_URI_STRING)) ? tableName : null;
mColumnNames = ImmutableList.copyOf(columnNames);
mColumnNamesNormalized = ImmutableSortedSet.copyOf(mColumnNames).asList();
validateNames();
}
/**
* Constructs a URI that fully qualifies a Kiji table.
*
* @param uri Kiji URI
* @throws KijiURIException if the URI is invalid.
*/
private KijiURI(URI uri) {
if (!uri.getScheme().equals(KIJI_SCHEME)) {
throw new KijiURIException(uri.toString(), "URI scheme must be '" + KIJI_SCHEME + "'");
}
final AuthorityParser parser = new AuthorityParser(uri);
mZookeeperQuorum = parser.getZookeeperQuorum();
mZookeeperQuorumNormalized = ImmutableSortedSet.copyOf(mZookeeperQuorum).asList();
mZookeeperClientPort = parser.getZookeeperClientPort();
final String[] path = new File(uri.getPath()).toString().split("/");
if (path.length > 4) {
throw new KijiURIException(uri.toString(),
"Invalid path, expecting '/kiji-instance/table-name/(column1, column2, ...)'");
}
Preconditions.checkState((path.length == 0) || path[0].isEmpty());
// Instance name:
if (path.length >= 2) {
mInstanceName = (path[1].equals(UNSET_URI_STRING)) ? null: path[1];
} else {
mInstanceName = null;
}
// Table name:
if (path.length >= 3) {
mTableName = (path[2].equals(UNSET_URI_STRING)) ? null : path[2];
} else {
mTableName = null;
}
// Columns:
final ImmutableList.Builder<KijiColumnName> builder = ImmutableList.builder();
if (path.length >= 4) {
if (!path[3].equals(UNSET_URI_STRING)) {
String[] split = path[3].split(",");
for (String name : split) {
builder.add(new KijiColumnName(name));
}
}
}
mColumnNames = builder.build();
mColumnNamesNormalized = ImmutableSortedSet.copyOf(mColumnNames).asList();
validateNames();
}
/**
* Builder class for constructing KijiURIs.
*/
public static final class KijiURIBuilder {
/**
* Zookeeper quorum: comma-separated list of Zookeeper host names or IP addresses.
* Preserves user ordering.
*/
private ImmutableList<String> mZookeeperQuorum;
/** Zookeeper client port number. */
private int mZookeeperClientPort;
/** Kiji instance name. Null means unset. */
private String mInstanceName;
/** Kiji table name. Null means unset. */
private String mTableName;
/** Kiji column names. Never null. Empty means unset. Preserves user ordering. */
private ImmutableList<KijiColumnName> mColumnNames;
/**
* Constructs a new builder for KijiURIs.
*
* @param zookeeperQuorum The initial zookeeper quorum.
* @param zookeeperClientPort The initial zookeeper client port.
* @param instanceName The initial instance name.
* @param tableName The initial table name.
* @param columnNames The initial column names.
*/
private KijiURIBuilder(
Iterable<String> zookeeperQuorum,
int zookeeperClientPort,
String instanceName,
String tableName,
Iterable<KijiColumnName> columnNames) {
mZookeeperQuorum = ImmutableList.copyOf(zookeeperQuorum);
mZookeeperClientPort = zookeeperClientPort;
mInstanceName =
((null == instanceName) || !instanceName.equals(UNSET_URI_STRING)) ? instanceName : null;
mTableName = ((null == tableName) || !tableName.equals(UNSET_URI_STRING)) ? tableName : null;
mColumnNames = ImmutableList.copyOf(columnNames);
}
/**
* Constructs a new builder for KijiURIs with default values.
* See {@link KijiURI#newBuilder()} for specific values.
*/
private KijiURIBuilder() {
mZookeeperQuorum = ENV_ZOOKEEPER_QUORUM;
mZookeeperClientPort = ENV_ZOOKEEPER_CLIENT_PORT;
mInstanceName = KConstants.DEFAULT_INSTANCE_NAME;
mTableName = UNSET_URI_STRING;
ImmutableList.Builder<KijiColumnName> columnBuilder = ImmutableList.builder();
mColumnNames = columnBuilder.build();
}
/**
* Configures the KijiURI with Zookeeper Quorum.
*
* @param zookeeperQuorum The zookeeper quorum.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withZookeeperQuorum(String[] zookeeperQuorum) {
mZookeeperQuorum = ImmutableList.copyOf(zookeeperQuorum);
return this;
}
/**
* Configures the KijiURI with the Zookeeper client port.
*
* @param zookeeperClientPort The port.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withZookeeperClientPort(int zookeeperClientPort) {
mZookeeperClientPort = zookeeperClientPort;
return this;
}
/**
* Configures the KijiURI with the Kiji instance name.
*
* @param instanceName The Kiji instance name.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withInstanceName(String instanceName) {
mInstanceName = instanceName;
return this;
}
/**
* Configures the KijiURI with the Kiji table name.
*
* @param tableName The Kiji table name.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withTableName(String tableName) {
mTableName = tableName;
return this;
}
/**
* Configures the KijiURI with the Kiji column names.
*
* @param columnNames The Kiji column names to configure.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withColumnNames(Collection<String> columnNames) {
ImmutableList.Builder<KijiColumnName> builder = ImmutableList.builder();
for (String column : columnNames) {
builder.add(new KijiColumnName(column));
}
mColumnNames = builder.build();
return this;
}
/**
* Adds the column names to the Kiji URI column names.
*
* @param columnNames The Kiji column names to add.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder addColumnNames(Collection<KijiColumnName> columnNames) {
ImmutableList.Builder<KijiColumnName> builder = ImmutableList.builder();
builder.addAll(mColumnNames).addAll(columnNames);
mColumnNames = builder.build();
return this;
}
/**
* Adds the column name to the Kiji URI column names.
*
* @param columnName The Kiji column name to add.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder addColumnName(KijiColumnName columnName) {
ImmutableList.Builder<KijiColumnName> builder = ImmutableList.builder();
builder.addAll(mColumnNames).add(columnName);
mColumnNames = builder.build();
return this;
}
/**
* Configures the KijiURI with the Kiji column names.
*
* @param columnNames The Kiji column names.
* @return This builder instance so you may chain configuration method calls.
*/
public KijiURIBuilder withColumnNames(Iterable<KijiColumnName> columnNames) {
mColumnNames = ImmutableList.copyOf(columnNames);
return this;
}
/**
* Builds the configured KijiURI.
*
* @return A KijiURI.
* @throws KijiURIException If the KijiURI was configured improperly.
*/
public KijiURI build() {
return new KijiURI(
mZookeeperQuorum,
mZookeeperClientPort,
mInstanceName,
mTableName,
mColumnNames);
}
}
/**
* Private class for parsing the authority portion of a KijiURI.
*/
private static class AuthorityParser {
private final ImmutableList<String> mZookeeperQuorum;
private final int mZookeeperClientPort;
/**
* Constructs an AuthorityParser.
*
* @param uri The uri whose authority is to be parsed.
* @throws KijiURIException If the authority is invalid.
*/
public AuthorityParser(URI uri) {
String authority = uri.getAuthority();
if (null == authority) {
throw new KijiURIException(uri.toString(), "HBase address missing.");
}
if (authority.equals(ENV_URI_STRING)) {
mZookeeperQuorum = ENV_ZOOKEEPER_QUORUM;
mZookeeperClientPort = ENV_ZOOKEEPER_CLIENT_PORT;
return;
}
final Matcher zkMatcher = RE_AUTHORITY_GROUP.matcher(authority);
if (zkMatcher.matches()) {
mZookeeperQuorum = ImmutableList.copyOf(zkMatcher.group(1).split(","));
mZookeeperClientPort = Integer.parseInt(zkMatcher.group(2));
} else {
final String[] splits = authority.split(":");
switch (splits.length) {
case 1:
mZookeeperQuorum = ImmutableList.copyOf(authority.split(","));
mZookeeperClientPort = DEFAULT_ZOOKEEPER_CLIENT_PORT;
break;
case 2:
if (splits[0].contains(",")) {
throw new KijiURIException(uri.toString(),
"Multiple zookeeper hosts must be parenthesized.");
} else {
mZookeeperQuorum = ImmutableList.of(splits[0]);
}
mZookeeperClientPort = Integer.parseInt(splits[1]);
break;
default:
throw new KijiURIException(uri.toString(),
"Invalid address, expecting 'zookeeper-quorum[:zookeeper-client-port]'");
}
}
}
/**
* Gets the zookeeper quorum.
*
* @return The zookeeper quorum.
*/
public ImmutableList<String> getZookeeperQuorum() {
return mZookeeperQuorum;
}
/**
* Gets the zookeeper client port.
*
* @return The zookeeper client port.
*/
public int getZookeeperClientPort() {
return mZookeeperClientPort;
}
}
/**
* Gets a builder configured with default Kiji URI fields.
*
* More precisely, the following defaults are initialized:
* <ul>
* <li>The Zookeeper quorum and client port is taken from the Hadoop <tt>Configuration</tt></li>
* <li>The Kiji instance name is set to <tt>KConstants.DEFAULT_INSTANCE_NAME</tt>
* (<tt>"default"</tt>).</li>
* <li>The table name and column names are explicitly left unset.</li>
* </ul>
*
* @return A builder configured with this Kiji URI.
*/
public static KijiURIBuilder newBuilder() {
return new KijiURIBuilder();
}
/**
* Gets a builder configured with a Kiji URI.
*
* @param uri The Kiji URI to configure the builder from.
* @return A builder configured with uri.
*/
public static KijiURIBuilder newBuilder(KijiURI uri) {
return new KijiURIBuilder(uri.getZookeeperQuorumOrdered(),
uri.getZookeeperClientPort(),
uri.getInstance(),
uri.getTable(),
uri.getColumnsOrdered());
}
/**
* Gets a builder configured with the Kiji URI.
*
* <p> The String parameter can be a relative URI (with a specified instance), in which
* case it is automatically normalized relative to DEFAULT_HBASE_URI.
*
* @param uri String specification of a Kiji URI.
* @return A builder configured with uri.
* @throws KijiURIException If the uri is invalid.
*/
public static KijiURIBuilder newBuilder(String uri) {
if (!uri.startsWith("kiji://")) {
uri = String.format("%s/%s/", KConstants.DEFAULT_HBASE_URI, uri);
}
try {
return newBuilder(new KijiURI(new URI(uri)));
} catch (URISyntaxException exn) {
throw new KijiURIException(uri, exn.getMessage());
}
}
/**
* Resolve the path relative to this KijiURI. Returns a new instance.
*
* @param path The path to resolve.
* @return The resolved KijiURI.
* @throws KijiURIException If this KijiURI is malformed.
*/
public KijiURI resolve(String path) {
try {
// Without the "./", URI will assume a path containing a colon
// is a new URI, for example "family:column".
URI uri = new URI(toString()).resolve(String.format("./%s", path));
return new KijiURI(uri);
} catch (URISyntaxException e) {
throw new RuntimeException(
String.format("KijiURI was incorrectly constructed (should never happen): %s",
this.toString()));
} catch (IllegalArgumentException e) {
throw new KijiURIException(this.toString(),
String.format("Path can not be resolved: %s", path));
}
}
/**
* Returns the set of Zookeeper quorum hosts (names or IPs).
*
* <p> Host names or IP addresses are de-duplicated and sorted. </p>
*
* @return the set of Zookeeper quorum hosts (names or IPs).
* Never null.
*/
public ImmutableList<String> getZookeeperQuorum() {
return mZookeeperQuorumNormalized;
}
/**
* Returns the original user-specified list of Zookeeper quorum hosts.
*
* <p> Host names are exactly as specified by the user. </p>
*
* @return the original user-specified list of Zookeeper quorum hosts.
* Never null.
*/
public ImmutableList<String> getZookeeperQuorumOrdered() {
return mZookeeperQuorum;
}
/** @return Zookeeper client port. */
public int getZookeeperClientPort() {
return mZookeeperClientPort;
}
/**
* Returns the name of the Kiji instance specified by this URI, if any.
*
* @return the name of the Kiji instance specified by this URI.
* Null means unspecified (ie. this URI does not target a Kiji instance).
*/
public String getInstance() {
return mInstanceName;
}
/**
* Returns the name of the Kiji table specified by this URI, if any.
*
* @return the name of the Kiji table specified by this URI.
* Null means unspecified (ie. this URI does not target a Kiji table).
*/
public String getTable() {
return mTableName;
}
/** @return Kiji columns (comma-separated list of Kiji column names), normalized. Never null. */
public ImmutableList<KijiColumnName> getColumns() {
return mColumnNamesNormalized;
}
/** @return Kiji columns (comma-separated list of Kiji column names), ordered. Never null. */
public Collection<KijiColumnName> getColumnsOrdered() {
return mColumnNames;
}
/** {@inheritDoc} */
@Override
public String toString() {
return toString(false);
}
/**
* Returns a string representation of this URI that preserves ordering of lists in fields,
* such as the Zookeeper quorum and Kiji columns.
*
* @return An order-preserving string representation of this URI.
*/
public String toOrderedString() {
return toString(true);
}
/**
* Returns a string representation of this URI.
*
* @param preserveOrdering Whether to preserve ordering of lsits in fields.
* @return A string reprresentation of this URI.
*/
private String toString(boolean preserveOrdering) {
// Remove trailing unset fields.
if (!mColumnNames.isEmpty()) {
return toStringCol(preserveOrdering);
} else if (mTableName != null) {
return toStringTable(preserveOrdering);
} else if (mInstanceName != null) {
return toStringInstance(preserveOrdering);
} else {
return toStringAuthority(preserveOrdering);
}
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return toString().hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
return object.getClass() == this.getClass() && object.toString().equals(this.toString());
}
/**
* Validates the names used in the URI.
*
* @throws KijiURIException if there is an invalid name in this URI.
*/
private void validateNames() {
if ((mInstanceName != null) && !KijiNameValidator.isValidKijiName(mInstanceName)) {
throw new KijiURIException(String.format(
"Invalid Kiji URI: '%s' is not a valid Kiji instance name.", mInstanceName));
}
if ((mTableName != null) && !KijiNameValidator.isValidLayoutName(mTableName)) {
throw new KijiURIException(String.format(
"Invalid Kiji URI: '%s' is not a valid Kiji table name.", mTableName));
}
}
/**
* Formats the full KijiURI up to the authority, preserving order.
*
* @param preserveOrdering Whether to preserve ordering.
* @return Representation of this KijiURI up to the authority.
*/
private String toStringAuthority(boolean preserveOrdering) {
String zkQuorum;
ImmutableList<String> zookeeperQuorum =
preserveOrdering ? mZookeeperQuorum : mZookeeperQuorumNormalized;
if (null == zookeeperQuorum) {
zkQuorum = UNSET_URI_STRING;
} else {
if (zookeeperQuorum.size() == 1) {
zkQuorum = zookeeperQuorum.get(0);
} else {
zkQuorum = String.format("(%s)", Joiner.on(",").join(zookeeperQuorum));
}
}
return String.format("%s://%s:%s/",
KIJI_SCHEME,
zkQuorum,
mZookeeperClientPort);
}
/**
* Formats the full KijiURI up to the instance.
*
* @param preserveOrdering Whether to preserve ordering.
* @return Representation of this KijiURI up to the instance.
*/
private String toStringInstance(boolean preserveOrdering) {
return String.format("%s%s/",
toStringAuthority(preserveOrdering),
(null == mInstanceName) ? UNSET_URI_STRING : mInstanceName);
}
/**
* Formats the full KijiURI up to the table.
*
* @param preserveOrdering Whether to preserve ordering.
* @return Representation of this KijiURI up to the table.
*/
private String toStringTable(boolean preserveOrdering) {
return String.format("%s%s/",
toStringInstance(preserveOrdering),
(null == mTableName) ? UNSET_URI_STRING : mTableName);
}
/**
* Formats the full KijiURI up to the column.
*
* @param preserveOrdering Whether to preserve ordering.
* @return Representation of this KijiURI up to the table.
*/
private String toStringCol(boolean preserveOrdering) {
String columnField;
ImmutableList<KijiColumnName> columns =
preserveOrdering ? mColumnNames : mColumnNamesNormalized;
if (columns.isEmpty()) {
columnField = UNSET_URI_STRING;
} else {
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (KijiColumnName column : columns) {
builder.add(column.getName());
}
ImmutableList<String> strColumns = builder.build();
if (strColumns.size() == 1) {
columnField = strColumns.get(0);
} else {
columnField = Joiner.on(",").join(strColumns);
}
}
try {
// SCHEMA-6. URI Encode column names using RFC-2396.
final URI columnsEncoded = new URI(KIJI_SCHEME, columnField, null);
return String.format("%s%s/",
toStringTable(preserveOrdering),
columnsEncoded.getRawSchemeSpecificPart());
} catch (URISyntaxException e) {
throw new KijiURIException(e.getMessage());
}
}
}
|
{
"content_hash": "590480db03642e575daf1ce74468e9c5",
"timestamp": "",
"source": "github",
"line_count": 725,
"max_line_length": 100,
"avg_line_length": 33.11724137931034,
"alnum_prop": 0.6675551853394419,
"repo_name": "zenoss/kiji-schema",
"id": "8e7d46e75119459411d06cd07269c865f953b71c",
"size": "24726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kiji-schema/src/main/java/org/kiji/schema/KijiURI.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
layout: post
title: Happy birthday - Marcus inside (www.marcusoft.net)
date: 2007-10-29T11:38:00.001Z
author: Marcus Hammarberg
tags:
- Marcus private
modified_time: 2007-10-29T11:51:37.275Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-2496410496021557951
blogger_orig_url: http://www.marcusoft.net/2007/10/happy-birthday-marcus-inside.html
---
Today i have had this blog for a whole year. I never thought that it
would evolve to this. Here are some interesting (?) facts and statics.
- First - i was wrong of course - the first posting was actually on
2006-10-24 but i have only have had statics since 2006-10-29.
- Total number of posts: 270. Which average to 0.73 post a day.
- 39 people has commented these posting
- 7404 pages has been served to 1667 different visitors
- Top content is the sketch [Mor i
skutan](http://marcushammarberg.blogspot.com/2007/08/mor-i-skutan.html)
with 168 hits
- Best visitor day was 2007-10-15 with 98 different visitors
- I've changed the layout for the blog 4 times (if i remember
correctly)
- 2007-08-27 was another important date in the history of the blog
since the URL and name was changed into the current
[marcusoft.net](http://www.marcusoft.net/)
So - there you have it - happy birthday
[marcusoft.net](http://www.marcusoft.net/)
|
{
"content_hash": "df68d734c0a855da1ab5af99165ea546",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 84,
"avg_line_length": 43.666666666666664,
"alnum_prop": 0.7519083969465649,
"repo_name": "marcusoftnet/marcusoftnet.github.io",
"id": "3b665bc1c1eaf2ed24b3c26ca61b32e665bbeeaf",
"size": "1314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2007-10-29-happy-birthday-marcus-inside.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10246"
},
{
"name": "SCSS",
"bytes": "85197"
},
{
"name": "Shell",
"bytes": "2397"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hammer-tactics: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / hammer-tactics - 1.3+8.11</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hammer-tactics
<small>
1.3+8.11
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-31 19:42:23 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-31 19:42:23 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.12.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.1 Official release 4.12.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/lukaszcz/coqhammer"
dev-repo: "git+https://github.com/lukaszcz/coqhammer.git"
bug-reports: "https://github.com/lukaszcz/coqhammer/issues"
license: "LGPL-2.1-only"
synopsis: "Reconstruction tactics for the hammer for Coq"
description: """
Collection of tactics that are used by the hammer for Coq
to reconstruct proofs found by automated theorem provers. When the hammer
has been successfully applied to a project, only this package needs
to be installed; the hammer plugin is not required.
"""
build: [make "-j%{jobs}%" {ocaml:version >= "4.06"} "tactics"]
install: [
[make "install-tactics"]
[make "test-tactics"] {with-test}
]
depends: [
"ocaml"
"coq" {>= "8.11" & < "8.12~"}
]
conflicts: [
"coq-hammer" {!= version}
]
tags: [
"keyword:automation"
"keyword:hammer"
"keyword:tactics"
"logpath:Hammer.Tactics"
"date:2020-07-28"
]
authors: [
"Lukasz Czajka <lukaszcz@mimuw.edu.pl>"
]
url {
src: "https://github.com/lukaszcz/coqhammer/archive/refs/tags/v1.3-coq8.11.tar.gz"
checksum: "sha512=f50e39145b772c38cc19b1be7d1d66bd3b1bee6cb685ea897165eaa89fa0b5a746e4ec97a774429ccf2cf9bd10d272331d1b4e2a4b9247080df4ef7fb9600a1d"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hammer-tactics.1.3+8.11 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-hammer-tactics -> coq < 8.12~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer-tactics.1.3+8.11</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
{
"content_hash": "68976ac93cc9f899ec50f10d59e2cf9d",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 159,
"avg_line_length": 41.28333333333333,
"alnum_prop": 0.5560489839860046,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "534318f688dc7bd4bc607df3bb022ae086ecf52d",
"size": "7456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.12.1-2.0.8/released/8.13.1/hammer-tactics/1.3+8.11.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
"""
ffs.formats
"""
import collections
import csv
import six
from six.moves import StringIO
WriterType = csv.writer(StringIO()).__class__
ReaderType = csv.reader(StringIO()).__class__
class CSV(object):
"""
The Quantum CSV file operates like both a csv.reader and a csv.writer,
until we observe you doing something with it that lets us know what it
is.
If you try to iterate through it, the CSV collapses into a reader.
If you try to writerow() it, the CSV collapses into a writer.
If HEADER is True, we consume the frist row, and use it to generate a
namedtuple based on the fieldnames, returning rows as an instance of this
class.
"""
# !!! add strip= True
def __init__(self, path, delimiter=',', header=False):
self.path = path
self.delimiter = delimiter
self.header = header
self.resolved = None
self.fh = None
self.rowklass = None
# Later we should figure out what to do with writers with headers?
if header:
self._resolve_reader()
self._generate_rowklass()
def __repr__(self):
rpr = '<{0} CSV {1}>'.format('Unresolved', self.path)
return rpr
def __enter__(self):
"""
Pass and return self
"""
return self
def __exit__(self, msg, exc, tb):
if self.fh:
self._close()
def _close(self):
"""
Close whatever it is we want to close.
Return: None
Exceptions: None
"""
self.fh.close()
def _resolve_reader(self):
"""
Resolve SELF to a Reader
Return: None
Exceptions: None
"""
self.fh = self.path.fs.open(self.path, 'rU')
self.resolved = csv.reader(self.fh, delimiter=self.delimiter)
def _resolve_writer(self):
"""
Resolve SELF to a Writer
Return: None
Exceptions: None
"""
self.fh = self.path.fs.open(self.path, 'w')
self.resolved = csv.writer(self.fh, delimiter=self.delimiter)
def _generate_rowklass(self):
"""
Create a namedtuple based on the frist row of the CSV.
Store this at self.rowklass
Return: None
Exceptions: None
"""
header = six.next(self.resolved)
clean = []
for h in header:
underscoreless = h.strip().lower().replace(' ', '_').replace('.', '_')
specialless = underscoreless.replace('(', '').replace(')', '').replace('?', '').replace('-', '')
if specialless == '':
clean.append(specialless)
continue
try:
num = int(specialless[0])
numbers = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
numless = numbers[num] + specialless[1:]
cleaned = numless
except ValueError:
cleaned = specialless
more = 1
while cleaned in clean:
more += 1
cleaned += str(more)
clean.append(cleaned)
for i, v in enumerate(clean):
if v == '':
clean[i] = 'field_' + str(i)
self.rowklass = collections.namedtuple('RowKlass', clean)
def __iter__(self):
"""
If we are unresolved, resolve to a reader, and return an Iterable.
If we are resolved, raise TypeError
Return: iterable
Exceptions: TypeError
"""
if not self.resolved:
self._resolve_reader()
if isinstance(self.resolved, WriterType):
raise TypeError('Writer is not iterable')
def gen():
for row in self.resolved:
if self.header and self.rowklass:
row = self.rowklass(*row)
yield row
return gen()
@property
def line_num(self):
"""
If we're unresolved, resolve to a reader then, pass through.
If we're resolved to a reader, pass through.
If we're resolved to a writer, raise AttributeError
Return: None
Exceptions: AttributeError
"""
if not self.resolved:
self._resolve_reader()
if isinstance(self.resolved, WriterType):
raise AttributeError('CSV Writer object has no attribute line_num')
return self.resolved.line_num
def next(self):
"""
If we're unresolved, resolve to a reader then, pass through.
If we're resolved to a reader, pass through.
If we're resolved to a writer, raise AttributeError
Return: list[str]
Exceptions: AttributeError
"""
if not self.resolved:
self._resolve_reader()
if isinstance(self.resolved, WriterType):
raise AttributeError('CSV Writer object has no attribute next')
row = self.resolved.next()
if self.header and self.rowklass:
row = self.rowklass(*row)
return row
def writerow(self, row):
"""
Construct and write a CSV record from a sequence of fields.
Non-string elements will be converted to a string.
Arguments:
- `row`: iterable
Return: None
Exceptions: None
"""
if not self.resolved:
self._resolve_writer()
if isinstance(self.resolved, ReaderType):
raise AttributeError('Object CSV has no attribute writerow')
self.resolved.writerow(row)
def writerows(self, row):
"""
Construct and write a CSV record from a sequence of sequences
Non-string elements will be converted to a string.
Arguments:
- `row`: iterable of iterables
Return: None
Exceptions: None
"""
if not self.resolved:
self._resolve_writer()
if isinstance(self.resolved, ReaderType):
raise AttributeError('Object CSV has no attribute writerows')
self._resolve_writer()
self.resolved.writerows(row)
|
{
"content_hash": "ce1cee1c641dfaaaa04330dff89af75e",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 108,
"avg_line_length": 28.564814814814813,
"alnum_prop": 0.5542949756888168,
"repo_name": "davidmiller/ffs",
"id": "852ac0233cee90a220b9954ccd6157c2a8e90d75",
"size": "6170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ffs/formats.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "231181"
},
{
"name": "Ruby",
"bytes": "605"
}
],
"symlink_target": ""
}
|
#import "NSObject.h"
#import "DVTInvalidation-Protocol.h"
@class DVTStackBacktrace, IDEBotExecution, IDEBotSCMDefinition, IDEXcodeServer, NSArray, NSDate, NSDictionary, NSMutableArray, NSMutableDictionary, NSString, NSURL;
@interface IDEBot : NSObject <DVTInvalidation>
{
NSMutableArray *_botExecutions;
NSMutableDictionary *_botExecutionsByGUID;
BOOL _alwaysBuildFromClean;
BOOL _performsAnalyzeAction;
BOOL _performsTestAction;
BOOL _performsArchiveAction;
BOOL _enabled;
BOOL _pollsForCommits;
BOOL _expectsCommitTriggers;
BOOL _notifiesCommittersOnSuccess;
BOOL _notifiesCommittersOnFailure;
BOOL _isFetchingBotExecutions;
IDEXcodeServer *_server;
NSString *_GUID;
NSURL *_botURL;
NSString *_name;
NSString *_botDescription;
IDEBotSCMDefinition *_scmDefinition;
NSString *_schemeName;
unsigned long long _scheduleType;
unsigned long long _periodType;
long long _dayOfWeek;
NSDate *_timeOfDayDate;
long long _minuteOfHour;
NSArray *_additionalEmailsToNotifyOnSuccess;
NSArray *_additionalEmailsToNotifyOnFailure;
long long _destinationSelectionType;
NSArray *_specificDestinationGUIDs;
NSDictionary *_extendedAttributesDictionary;
unsigned long long _maximumNumberOfLocalBotExecutions;
unsigned long long _totalBotExecutionCount;
IDEBotExecution *_lastBotExecution;
IDEBotExecution *_lastCompletedBotExecution;
unsigned long long _lastUpdateGeneration;
long long _botRevision;
NSMutableDictionary *_deferredBotExecutionUpdates;
NSMutableDictionary *_deferredBotExecutionDeletes;
}
+ (BOOL)automaticallyNotifiesObserversOfLastCompletedBotExecution;
+ (BOOL)automaticallyNotifiesObserversOfLastBotExecution;
+ (id)botWithURL:(id)arg1;
+ (id)botURLForBotWithGUID:(id)arg1 server:(id)arg2;
+ (id)_strongURLToWeakBotMap;
+ (void)initialize;
@property(retain, nonatomic) NSMutableDictionary *deferredBotExecutionDeletes; // @synthesize deferredBotExecutionDeletes=_deferredBotExecutionDeletes;
@property(retain, nonatomic) NSMutableDictionary *deferredBotExecutionUpdates; // @synthesize deferredBotExecutionUpdates=_deferredBotExecutionUpdates;
@property(nonatomic) BOOL isFetchingBotExecutions; // @synthesize isFetchingBotExecutions=_isFetchingBotExecutions;
@property(nonatomic) long long botRevision; // @synthesize botRevision=_botRevision;
@property(nonatomic) unsigned long long lastUpdateGeneration; // @synthesize lastUpdateGeneration=_lastUpdateGeneration;
@property(retain, nonatomic) IDEBotExecution *lastCompletedBotExecution; // @synthesize lastCompletedBotExecution=_lastCompletedBotExecution;
@property(retain, nonatomic) IDEBotExecution *lastBotExecution; // @synthesize lastBotExecution=_lastBotExecution;
@property(nonatomic) unsigned long long totalBotExecutionCount; // @synthesize totalBotExecutionCount=_totalBotExecutionCount;
@property(readonly, nonatomic) NSArray *botExecutions; // @synthesize botExecutions=_botExecutions;
@property(nonatomic) unsigned long long maximumNumberOfLocalBotExecutions; // @synthesize maximumNumberOfLocalBotExecutions=_maximumNumberOfLocalBotExecutions;
@property(copy, nonatomic) NSDictionary *extendedAttributesDictionary; // @synthesize extendedAttributesDictionary=_extendedAttributesDictionary;
@property(copy, nonatomic) NSArray *specificDestinationGUIDs; // @synthesize specificDestinationGUIDs=_specificDestinationGUIDs;
@property(nonatomic) long long destinationSelectionType; // @synthesize destinationSelectionType=_destinationSelectionType;
@property(copy, nonatomic) NSArray *additionalEmailsToNotifyOnFailure; // @synthesize additionalEmailsToNotifyOnFailure=_additionalEmailsToNotifyOnFailure;
@property(nonatomic) BOOL notifiesCommittersOnFailure; // @synthesize notifiesCommittersOnFailure=_notifiesCommittersOnFailure;
@property(copy, nonatomic) NSArray *additionalEmailsToNotifyOnSuccess; // @synthesize additionalEmailsToNotifyOnSuccess=_additionalEmailsToNotifyOnSuccess;
@property(nonatomic) BOOL notifiesCommittersOnSuccess; // @synthesize notifiesCommittersOnSuccess=_notifiesCommittersOnSuccess;
@property(nonatomic) BOOL expectsCommitTriggers; // @synthesize expectsCommitTriggers=_expectsCommitTriggers;
@property(nonatomic) BOOL pollsForCommits; // @synthesize pollsForCommits=_pollsForCommits;
@property(nonatomic) long long minuteOfHour; // @synthesize minuteOfHour=_minuteOfHour;
@property(retain, nonatomic) NSDate *timeOfDayDate; // @synthesize timeOfDayDate=_timeOfDayDate;
@property(nonatomic) long long dayOfWeek; // @synthesize dayOfWeek=_dayOfWeek;
@property(nonatomic) unsigned long long periodType; // @synthesize periodType=_periodType;
@property(nonatomic) unsigned long long scheduleType; // @synthesize scheduleType=_scheduleType;
@property(nonatomic) BOOL enabled; // @synthesize enabled=_enabled;
@property(nonatomic) BOOL performsArchiveAction; // @synthesize performsArchiveAction=_performsArchiveAction;
@property(nonatomic) BOOL performsTestAction; // @synthesize performsTestAction=_performsTestAction;
@property(nonatomic) BOOL performsAnalyzeAction; // @synthesize performsAnalyzeAction=_performsAnalyzeAction;
@property(nonatomic) BOOL alwaysBuildFromClean; // @synthesize alwaysBuildFromClean=_alwaysBuildFromClean;
@property(retain, nonatomic) NSString *schemeName; // @synthesize schemeName=_schemeName;
@property(retain, nonatomic) IDEBotSCMDefinition *scmDefinition; // @synthesize scmDefinition=_scmDefinition;
@property(retain, nonatomic) NSString *botDescription; // @synthesize botDescription=_botDescription;
@property(retain, nonatomic) NSString *name; // @synthesize name=_name;
@property(readonly, nonatomic) NSURL *botURL; // @synthesize botURL=_botURL;
@property(readonly, nonatomic) NSString *GUID; // @synthesize GUID=_GUID;
@property(retain, nonatomic) IDEXcodeServer *server; // @synthesize server=_server;
- (void).cxx_destruct;
- (void)_fetchExecutionCount;
- (void)_fetchNotifyEmails;
- (void)_fetchSchedule;
- (void)enableBotWithCompletionBlock:(id)arg1;
- (void)disableBotWithCompletionBlock:(id)arg1;
- (void)startCleanBotExecutionWithCompletionBlock:(id)arg1;
- (void)startBotExecutionWithCompletionBlock:(id)arg1;
- (void)botExecutionForGUID:(id)arg1 integrationNumber:(unsigned long long)arg2 fetchIfNecessary:(BOOL)arg3 withCompletionBlock:(id)arg4;
- (id)_botExecutionForGUID:(id)arg1;
- (void)fetchBotExecutionsInRange:(struct _NSRange)arg1 withCompletionBlock:(id)arg2;
- (void)fetchBotExecutionsWithCompletionBlock:(id)arg1;
- (void)loadMoreBotExecutionsWithCompletionBlock:(id)arg1;
- (void)botRunGUIDDeleted:(id)arg1 botGUID:(id)arg2;
- (void)botRunModified:(id)arg1;
- (id)fullDescription;
- (id)_scheduleTypeDescriptionString;
- (id)description;
- (void)updateWithDictionary:(id)arg1 updateGeneration:(unsigned long long)arg2;
- (id)propertyListRepresentation;
- (void)primitiveInvalidate;
- (void)_didChangeBotExecutions;
- (void)_willChangeBotExections;
- (void)_updateLastBotExecutions;
- (id)initWithPropertyListRepresentation:(id)arg1 server:(id)arg2;
- (id)initWithServer:(id)arg1 GUID:(id)arg2;
- (void)_botCommonInit;
// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly, nonatomic, getter=isValid) BOOL valid;
@end
|
{
"content_hash": "9136d995f917220f0081bc6df419dc2a",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 164,
"avg_line_length": 58.214285714285715,
"alnum_prop": 0.8141785957736878,
"repo_name": "liyong03/YLCleaner",
"id": "ee1909c831de0406a3fba6df2014519c102eeab3",
"size": "7475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "YLCleaner/Xcode-RuntimeHeaders/IDEFoundation/IDEBot.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "158958"
},
{
"name": "C++",
"bytes": "612673"
},
{
"name": "Objective-C",
"bytes": "10594281"
},
{
"name": "Ruby",
"bytes": "675"
}
],
"symlink_target": ""
}
|
CustomNetworkAccessManager::CustomNetworkAccessManager(QObject *parent) : QNetworkAccessManager(parent)
{
m_userAgent = " Mozilla/5.0 (Linux; U; Jolla; Sailfish; Mobile; rv:20.0) Gecko/20.0 Firefox/20.0 DevConf 0.2+";
}
|
{
"content_hash": "fe10d4a95330a747968c0c9b8c3f89b0",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 115,
"avg_line_length": 56,
"alnum_prop": 0.75,
"repo_name": "jmlich/devconf-sailfish",
"id": "c405974f24d44a4506f564f21309fb8312ae49a0",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/customnetworkaccessmanager.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "10458"
},
{
"name": "JavaScript",
"bytes": "8176"
},
{
"name": "Python",
"bytes": "433"
},
{
"name": "QML",
"bytes": "79739"
},
{
"name": "QMake",
"bytes": "2139"
},
{
"name": "Shell",
"bytes": "1344"
}
],
"symlink_target": ""
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.vjia.transcardqueryer;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int app_launcher=0x7f020000;
public static final int badatong=0x7f020001;
public static final int bg_1=0x7f020002;
public static final int bg_2=0x7f020003;
public static final int bg_3=0x7f020004;
public static final int bg_4=0x7f020005;
public static final int bg_5=0x7f020006;
public static final int button_background=0x7f020007;
public static final int button_blue=0x7f020008;
public static final int button_gray=0x7f020009;
public static final int button_green=0x7f02000a;
public static final int button_red=0x7f02000b;
public static final int buttons=0x7f02000c;
public static final int clear_button_background=0x7f02000d;
public static final int footer_background=0x7f02000e;
public static final int header_background=0x7f02000f;
public static final int ic_launcher=0x7f020010;
public static final int proxy=0x7f020011;
public static final int watermark=0x7f020012;
}
public static final class id {
public static final int action_settings=0x7f08000c;
public static final int button_clear=0x7f080009;
public static final int button_query=0x7f080008;
public static final int edittext_cardno=0x7f080007;
public static final int edittext_cardtype=0x7f080004;
public static final int left_image_of_cardno=0x7f080005;
public static final int left_image_of_cardtype=0x7f080002;
public static final int linear_layout_body=0x7f080001;
public static final int linear_layout_footer=0x7f08000a;
public static final int linear_layout_header=0x7f080000;
public static final int textview_card_money=0x7f08000b;
public static final int textview_cardno=0x7f080006;
public static final int textview_cardtype=0x7f080003;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int activity_query_result=0x7f030001;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_intro=0x7f050003;
public static final int app_name=0x7f050000;
public static final int cart_no_str=0x7f050007;
public static final int cart_type_str=0x7f050006;
public static final int clear_cardno=0x7f050004;
public static final int edittext_cardtype_str=0x7f050008;
public static final int hello_world=0x7f050002;
public static final int query_card=0x7f050005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
|
{
"content_hash": "c5578d8edffa14fc5c562df5a0470071",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 82,
"avg_line_length": 43.61904761904762,
"alnum_prop": 0.6973799126637554,
"repo_name": "RyanTech/firstcodeandroid",
"id": "999a647cdbcd4b3a07c6284d8a4f0ebb6074251e",
"size": "4580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "TranscardQueryer/gen/com/vjia/transcardqueryer/R.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "167953"
},
{
"name": "Java",
"bytes": "273972"
},
{
"name": "Objective-J",
"bytes": "11260"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content=""/>
<meta name="author" content=""/>
<link rel="icon" href="/favicon.ico"/>
<title>绿·硒邮寄</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="/webjarslocator/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="webjarslocator/bootstrap-daterangepicker/daterangepicker.css">
<link href="css/dashboard.css" rel="stylesheet"/>
<link rel="stylesheet" href="css/rolelist.css"/>
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]>
<script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="business">
<nav class="navbar navbar-inverse navbar-fixed-top" ng-controller="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#/">绿·硒邮寄
<small><var>v1.0.1</var></small>
</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul id="navloginBar" class="nav navbar-nav navbar-right" role="tablist" ng-show="!authenticated">
<li><a href="#/login">登陆</a></li>
</ul>
<ul id="navUserBar" class="nav navbar-nav navbar-right" ng-show="authenticated">
<li><p class="navbar-text">欢迎 <a href="#/customer" class="navbar-link">{{user.name}}</a></p></li>
<li><a href="" data-toggle="modal" data-target="#changModal">设置密码</a></li>
<li><a href="#/customer">修改资料</a></li>
<li><a href="" ng-click="logout()">注销</a></li>
<li><a>帮助</a></li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-md-2 sidebar" ng-show="authenticated">
<ul class="nav nav-pills nav-stacked">
<li class="active"><a>导航菜单</a></li>
<li ng-Tree ng-repeat="child in menus | orderBy:orderId">
<a href="" class="dropdown-toggle " id="dropdownMenu1"
data-toggle="dropdown" aria-expanded="true">{{child.menuName}}
<i class="glyphicon glyphicon glyphicon-triangle-bottom"></i></a>
<ul class="nav-tabs nav-stacked">
<li style="padding-left: 10px" role="{{subChild.authority}}"
ng-repeat="subChild in child.subMenus">
<a role="{{subChild.authority}}" tabindex="-1" href="#{{subChild.url}}">{{subChild.menuName}}</a>
</li>
</ul>
</li>
</ul>
</div>
<div ng-view class="col-md-10 col-md-offset-2 main">
</div>
</div>
</div>
</div>
<!-- chang password form
================================================== -->
<div ng-controller="changPwsCtl" class="modal fade bs-example-modal-sm" id="changModal" tabindex="-1" role="dialog"
aria-labelledby="changModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<form name="changForm" class="modal-content" role="form" ng-submit="chang()">
<input name='{"amount":100,"routingNumber":"evilsRoutingNumber","account":"evilsAccountNumber", "ignore_me":"'
value='test"}' type='hidden'>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="ModalLabel">修改密码</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger" ng-show="error">
密码修改失败,错误信息:<p id="changpwdErrorMessage"></p>
</div>
<div class="form-group" ng-class="{ 'has-error' : changForm.oldpassword.$invalid}">
<input type="password" class="form-control" id="oldpassword" name="oldpassword" placeholder="旧密码"
required="required" autofocus="autofocus" ng-model="credentials.oldpassword"/>
<p ng-show="changForm.oldpassword.$invalid" class="help-block">旧密码为必填项</p>
</div>
<div class="form-group"
ng-class="{ 'has-error' : changForm.password.$invalid && !changForm.password.$pristine }">
<input type="password" class="form-control" id="password" name="password" placeholder="新密码"
required="required" ng-minlength="8" ng-maxlength="25" ng-model="credentials.password"/>
<p ng-show="changForm.password.$invalid && !changForm.password.$pristine" class="help-block">
新密码为必填项</p>
</div>
<div class="form-group" ng-class="{'has-error' : credentials.password!=credentials.confirmpassword }">
<input type="password" class="form-control" id="confirmpassword" name="confirmpassword"
placeholder="确认密码" required="required" ng-model="credentials.confirmpassword"/>
<p ng-show="credentials.password!=credentials.confirmpassword" class="help-block">新密码和确认密码不相同</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="submit" class="btn btn-primary" ng-disabled="changForm.$invalid">保存</button>
</div>
</form>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/js/ie10-viewport-bug-workaround.js"></script>
<script type="text/javascript" src="webjars/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="webjarslocator/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="webjarslocator/angularjs/angular.min.js"></script>
<script type="text/javascript" src="webjarslocator/angularjs/angular-route.min.js"></script>
<script type="text/javascript" src="webjarslocator/angularjs/angular-cookies.min.js"></script>
<script type="text/javascript" src="webjarslocator/angularjs/angular-messages.min.js"></script>
<script type="text/javascript" src="webjarslocator/angularjs/i18n/angular-locale_zh-cn.js"></script>
<script type="text/javascript" src="webjarslocator/momentjs/min/moment.min.js"></script>
<script type="text/javascript" src="webjarslocator/bootstrap-daterangepicker/daterangepicker.js"></script>
<script type="text/javascript" src="js/business.js"></script>
<script type="text/javascript" src="js/account.js"></script>
<script type="text/javascript" src="js/goodsapp.js"></script>
</body>
</html>
|
{
"content_hash": "75fbf473763ce1bb135ba46b82bdc9f8",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 125,
"avg_line_length": 54.08510638297872,
"alnum_prop": 0.5726462103330711,
"repo_name": "DongpoAlex/business",
"id": "73204221f70f7172bdd75b1a661da97862ffb946",
"size": "7790",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/public/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3599"
},
{
"name": "HTML",
"bytes": "89357"
},
{
"name": "Java",
"bytes": "88130"
},
{
"name": "JavaScript",
"bytes": "51575"
},
{
"name": "SQLPL",
"bytes": "5227"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">XingAPI Sample</string>
<string name="btn_login">OAuth Login</string>
</resources>
|
{
"content_hash": "13131da2667ff0fc0e79b9fa0ba7f422",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 51,
"avg_line_length": 21.125,
"alnum_prop": 0.6627218934911243,
"repo_name": "hdodenhof/xing-android-sdk",
"id": "cc2c7c78fbfd5f1b52f2c8ff8603098a60b96e9f",
"size": "169",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sample/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "89385"
}
],
"symlink_target": ""
}
|
<?php
/**
* @namespace
*/
namespace Zend\Search\Lucene\Search\Highlighter;
/**
* @category Zend
* @package Zend_Search_Lucene
* @subpackage Search
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface HighlighterInterface
{
/**
* Set document for highlighting.
*
* @param Zend_Search_Lucene_Document_Html $document
*/
public function setDocument(\Zend\Search\Lucene\Document\Html $document);
/**
* Get document for highlighting.
*
* @return Zend_Search_Lucene_Document_Html $document
*/
public function getDocument();
/**
* Highlight specified words (method is invoked once per subquery)
*
* @param string|array $words Words to highlight. They could be organized using the array or string.
*/
public function highlight($words);
}
|
{
"content_hash": "b320a6f8643fcc6fb3890e357ba296cb",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 105,
"avg_line_length": 25.13157894736842,
"alnum_prop": 0.6596858638743456,
"repo_name": "FbN/Zend-Framework-Namespaced-",
"id": "b7d13f2fd78a583e8d5a567c101e3874109fca17",
"size": "1727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Zend/Search/Lucene/Search/Highlighter/HighlighterInterface.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "14877183"
}
],
"symlink_target": ""
}
|
package voldemort.store;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import voldemort.utils.ClosableIterator;
import voldemort.utils.Pair;
import voldemort.versioning.Occurred;
import voldemort.versioning.Versioned;
public class AbstractStorageEngine<K, V, T> extends AbstractStore<K, V, T> implements
StorageEngine<K, V, T> {
public AbstractStorageEngine(String name) {
super(name);
}
@Override
public ClosableIterator<Pair<K, Versioned<V>>> entries() {
return null;
}
@Override
public ClosableIterator<K> keys() {
return null;
}
@Override
public ClosableIterator<Pair<K, Versioned<V>>> entries(int partitionId) {
return null;
}
@Override
public ClosableIterator<K> keys(int partitionId) {
return null;
}
@Override
public void truncate() {}
@Override
public boolean isPartitionAware() {
return false;
}
@Override
public boolean isPartitionScanSupported() {
return false;
}
@Override
public boolean beginBatchModifications() {
return false;
}
@Override
public List<Versioned<V>> multiVersionPut(K key, List<Versioned<V>> values) {
throw new UnsupportedOperationException("multiVersionPut is not supported for "
+ this.getClass().getName());
}
@Override
public boolean endBatchModifications() {
return false;
}
/**
* Computes the final list of versions to be stored, on top of what is
* currently being stored. Final list is valsInStorage modified in place
*
*
* @param valuesInStorage list of versions currently in storage
* @param multiPutValues list of new versions being written to storage
* @return list of versions from multiPutVals that were rejected as obsolete
*/
protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage,
List<Versioned<V>> multiPutValues) {
List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size());
// Go over all the values and determine whether the version is
// acceptable
for(Versioned<V> value: multiPutValues) {
Iterator<Versioned<V>> iter = valuesInStorage.iterator();
boolean obsolete = false;
// Compare the current version with a set of accepted versions
while(iter.hasNext()) {
Versioned<V> curr = iter.next();
Occurred occurred = value.getVersion().compare(curr.getVersion());
if(occurred == Occurred.BEFORE) {
obsolete = true;
break;
} else if(occurred == Occurred.AFTER) {
iter.remove();
}
}
if(obsolete) {
// add to return value if obsolete
obsoleteVals.add(value);
} else {
// else update the set of accepted versions
valuesInStorage.add(value);
}
}
return obsoleteVals;
}
}
|
{
"content_hash": "a40971d9e9f2fc47ba27904b7318d841",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 105,
"avg_line_length": 30.55140186915888,
"alnum_prop": 0.5965126950137657,
"repo_name": "medallia/voldemort",
"id": "4ba9aefcf9ca12f507cf2e7d9ddb6bc6ec5cc912",
"size": "3269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/voldemort/store/AbstractStorageEngine.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "205381"
},
{
"name": "CSS",
"bytes": "1078"
},
{
"name": "Java",
"bytes": "6820367"
},
{
"name": "JavaScript",
"bytes": "0"
},
{
"name": "Python",
"bytes": "85605"
},
{
"name": "Ruby",
"bytes": "52094"
},
{
"name": "Scala",
"bytes": "6561"
},
{
"name": "Shell",
"bytes": "88510"
}
],
"symlink_target": ""
}
|
% CorrelIntro -- Info about CorrelDemo
%
% The files in this directory can reproduce the figures in the paper
% ``Wavelet Threshold Estimators for Data with Correlated Noise"
% by I.M. Johnstone and B.W. Silverman.
%
%
% From the abstract: Wavelet threshold estimators for data with
% stationary correlated noise are constructed by applying a
% level-dependent soft threshold to the coefficients in the wavelet
% transform. A variety of threshold choices are proposed, including one
% based on an unbiased estimate of mean squared error. The practical
% performance of the method is demonstrated on examples, including data
% from a neurophysiological context. The theoretical properties of the
% estimators are investigated by comparing them with an ideal but
% unattainable `benchmark', that can be considered in the wavelet
% context as the risk obtained by ideal spatial adaptivity, and more
% generally is obtained by the use of an `oracle' that provides
% information not actually available in the data. It is shown that the
% level-dependent threshold estimator performs well relative to the
% benchmark risk, and that its minimax behaviour cannot be improved upon
% in order of magnitude by any other estimator. The wavelet domain
% structure of both short and long range dependent noise is considered,
% and in both cases it is shown that the estimators have near-optimal
% behaviour simultaneously in a wide range of function classes, adapting
% automatically to the regularity properties of the underlying model.
% The proofs of the main results are obtained by considering a more
% general multivariate normal decision-theoretic problem.
%
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail wavelab@stat.stanford.edu
|
{
"content_hash": "5901e37f61c4fb3a5aa93fdecc4087ad",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 72,
"avg_line_length": 47.625,
"alnum_prop": 0.7674540682414698,
"repo_name": "linhvannguyen/PhDworks",
"id": "bcb95f4978a4200d686d9c11bb148ae791d02c15",
"size": "1905",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "codes/missingfuncs/Wavelab850/Papers/Correl/CorrelIntro.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11203"
},
{
"name": "C",
"bytes": "1007620"
},
{
"name": "C++",
"bytes": "1012443"
},
{
"name": "CSS",
"bytes": "14933"
},
{
"name": "HTML",
"bytes": "1357543"
},
{
"name": "Java",
"bytes": "1833"
},
{
"name": "Jupyter Notebook",
"bytes": "415227"
},
{
"name": "M",
"bytes": "68479"
},
{
"name": "Makefile",
"bytes": "3007"
},
{
"name": "Matlab",
"bytes": "5625827"
},
{
"name": "Objective-C",
"bytes": "606"
},
{
"name": "Python",
"bytes": "32885"
},
{
"name": "Scheme",
"bytes": "6"
},
{
"name": "Shell",
"bytes": "124887"
},
{
"name": "TeX",
"bytes": "932814"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/SonghayCore/assets/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/SonghayCore/assets/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/SonghayCore/assets/favicons/favicon-16x16.png">
<link rel="manifest" href="/SonghayCore/assets/favicons/site.webmanifest">
<link rel="shortcut icon" type="image/png" href="/SonghayCore/assets/favicons/favicon.ico"/>
<link rel="mask-icon" href="/SonghayCore/assets/favicons/safari-pinned-tab.svg" color="#e9ecef">
<meta name="msapplication-config" content="/SonghayCore/assets/favicons/browserconfig.xml" />
<meta name="msapplication-TileColor" content="#e9ecef">
<meta name="theme-color" content="#e9ecef">
<link href="/SonghayCore/assets/bootstrap/bootstrap.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;700&family=Roboto+Slab:wght@400;700&family=Roboto:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&display=swap" rel="stylesheet" data-no-mirror>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.26.0/themes/prism.css">
<link href="/SonghayCore/assets/css/theme.css" rel="stylesheet" />
<link href="/SonghayCore/assets/css/styles.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/a1cad7ed9a.js" crossorigin="anonymous" data-no-mirror></script>
<script src="https://cdn.jsdelivr.net/npm/mermaid@8.4.8/dist/mermaid.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.1/dist/svg-pan-zoom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.26.0/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.26.0/plugins/autoloader/prism-autoloader.min.js" data-no-mirror></script>
<script src="https://cdn.jsdelivr.net/npm/quicklink@2.0.0/dist/quicklink.umd.js"></script>
<title>SonghayCore - August(int, int)</title>
</head>
<body class="d-flex flex-column">
<div class="flex-grow-1 d-flex flex-column">
<div class="bg-nav">
<div class="container-xl py-3">
<div class="row">
<div class="offset-lg-2 col-12 col-lg-8 px-0">
<nav class="navbar navbar-expand-md navbar-light align-items-start">
<a class="navbar-brand" href="/">
<span class="text-primary">SonghayCore</span>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapse-topnav" aria-controls="collapse-topnav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div id="collapse-topnav" class="collapse navbar-collapse flex-wrap">
<ul class="navbar-nav mr-auto">
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/SonghayCore/latest">API</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
</div>
<div class="flex-grow-1 d-flex flex-column">
<!-- Titlebar -->
<div id="titlebar" class="py-4">
<div class="container-xl">
<div class="row">
<div class="offset-lg-2 col-12 col-lg-8 px-3 px-lg-0 w-100 d-flex flex-wrap align-items-end">
<div class="flex-grow-1">
<div class="breadcrumbs d-flex flex-column flex-md-row text-break">
<span><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions">DateTimeExtensions</a>.</span>
</div>
<div class="text-white m-0 text-break title">
<div>August<wbr>(int, <wbr>int)<wbr> <small>Method</small></div>
</div>
</div>
<div class="navbar navbar-expand-md navbar-dark p-0">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#left-sidebar" aria-controls="left-sidebar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Under title -->
<div id="undertitle">
<div class="container-xl">
<div class="row">
<div class="col-md-3 col-lg-2">
</div>
<div class="col-md-9 col-lg-8 bg-white">
</div>
<div class="col-lg-2 d-none d-lg-block">
</div>
</div>
</div>
</div>
<!-- Body -->
<div class="flex-grow-1 d-flex flex-column">
<div class="container-xl flex-grow-1 d-flex flex-column">
<div class="row flex-grow-1 align-items-stretch">
<div class="col-md-3 col-lg-2 p-md-0 m-md-0 bg-body">
<div id="left-sidebar" class="sidebar collapse px-0 px-md-3 pt-3">
<div class="sidebar-root">
<div class="sidebar-root bg-white mb-3 page-box font-size-sm">
<div class="sidebar-nav-item sidebar-header mb-0 pb-0">Namespace</div>
<div class="sidebar-nav-item font-weight-normal mt-0 pt-0"><a href="/SonghayCore/latest/Songhay.Extensions">Songhay<wbr>.Extensions</a></div>
<div class="sidebar-nav-item sidebar-header mb-0 pb-0">Type</div>
<div class="sidebar-nav-item font-weight-normal mt-0 pt-0"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions">DateTimeExtensions</a></div>
</div>
<div class="sidebar-nav-item sidebar-header">Method Members</div>
<div class="sidebar-nav-children">
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/BF6E7102">April<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item active"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/8B068147">August<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/79CFB48B">December<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/D08FF8FA">February<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/1FECAE5C">GetNextWeekday<wbr>(DateTime, <wbr>DayOfWeek)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/4BF2E64F">January<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/D2F3995F">July<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/D68CB189">June<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/9EA6721E">March<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/1180C1FD">May<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/BDBA2887">November<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/BEC5F0E9">October<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/3B61666F">September<wbr>(int, <wbr>int)<wbr></a></div>
<div class="sidebar-nav-item"><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions/C6A0E732">ToPrettyDate<wbr>(DateTime)<wbr></a></div>
</div>
</div>
</div>
</div>
<div id="content" class="col-md-9 col-lg-8 p-4 pt-md-0 bg-white">
<div class="lead mb-3">
Returns a DateTime representing the specified day in August
in the specified year.
</div>
<div class="p-3 bg-light page-box container small">
<dl class="dl-horizontal">
<dt>Namespace</dt>
<dd><a href="/SonghayCore/latest/Songhay.Extensions">Songhay<wbr>.Extensions</a></dd>
<dt>Containing Type</dt>
<dd><a href="/SonghayCore/latest/Songhay.Extensions/DateTimeExtensions">DateTimeExtensions</a></dd>
</dl>
</div>
<h1 id="Syntax">Syntax</h1>
<pre class="language-csharp"><code class="language-csharp">public static DateTime August(this int day, int year)</code></pre>
<h1 id="Parameters">Parameters</h1>
<div class="table-responsive">
<table class="table table-api table-striped table-hover three-cols">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>day</td>
<td>int</td>
<td></td>
</tr>
<tr>
<td>year</td>
<td>int</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<h1 id="ReturnValue">Return Value</h1>
<div class="table-responsive">
<table class="table table-api table-striped table-hover two-cols">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>DateTime</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-lg-2 p-md-0 m-md-0 bg-body">
<div id="right-sidebar" class="sidebar px-0 px-md-3 pt-3">
<div class="sidebar-root">
<div class="sidebar-nav-item sidebar-header">On This Page</div>
<div class="sidebar-nav-children">
<div class="sidebar-nav-item"><a href="#Syntax">Syntax</a></div>
<div class="sidebar-nav-item"><a href="#Parameters">Parameters</a></div>
<div class="sidebar-nav-item"><a href="#ReturnValue">Return Value</a></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div id="footer" class="p-3 text-white">
<div class="container-xl">
<div class="row">
<div class="offset-lg-2 col-12 col-lg-8">
<div class="pt-2 font-size-sm text-muted text-center">
Generated By <a class="text-muted" href="https://statiq.dev">Statiq</a>
</div>
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script>
$(document).ready(function() {
quicklink.listen();
// Bootstrap tooltips
$('[data-toggle="tooltip"]').tooltip();
// Keeps the sidebars in view on wider viewports
let left = null;
let leftParent = null;
let right = null;
let rightParent = null;
function stickSidebars()
{
if (left == null) {
left = $('#left-sidebar');
right = $('#right-sidebar');
}
if (left.length) {
if (window.innerWidth >= 768) {
if (leftParent == null) {
leftParent = left.parent()[0];
}
if (leftParent) {
let leftRect = leftParent.getBoundingClientRect();
stickSidebar(left, leftRect);
}
} else {
left.css('position', 'relative');
if (left.css('bottom') != 0) {
left.css('bottom', '0');
}
}
}
if (right.length) {
if (window.innerWidth >= 768) {
if (rightParent == null) {
rightParent = right.parent()[0];
}
if (rightParent) {
let rightRect = rightParent.getBoundingClientRect();
stickSidebar(right, rightRect);
}
} else {
right.css('position', 'relative');
if (right.css('bottom') != 0) {
right.css('bottom', '0');
}
}
}
}
function stickSidebar(sidebar, rect) {
// Bottom
if (rect.bottom > window.innerHeight) {
sidebar.css('bottom', rect.bottom - window.innerHeight + "px");
} else {
sidebar.css('bottom', 0);
}
// Top
if (rect.top < 0) {
sidebar.css('position', 'sticky');
} else {
sidebar.css('position', 'absolute');
}
}
$(window).on("load", function() {
stickSidebars();
});
$(window).scroll(function() {
stickSidebars();
});
$(window).resize(function() {
stickSidebars();
})
// Mermaid diagrams
mermaid.initialize(
{
flowchart:
{
useMaxWidth: false
},
startOnLoad: false,
cloneCssStyles: false
});
mermaid.init(undefined, ".mermaid");
// Remove the max-width setting that Mermaid sets
var mermaidSvg = $('.mermaid svg');
mermaidSvg.addClass('img-fluid');
mermaidSvg.css('max-width', '');
// Make it scrollable
var target = document.querySelector(".mermaid svg");
if(target !== null)
{
var panZoom = window.panZoom = svgPanZoom(target, {
zoomEnabled: true,
controlIconsEnabled: true,
fit: true,
center: true,
maxZoom: 20,
zoomScaleSensitivity: 0.6
});
// Do the reset once right away to fit the diagram
panZoom.resize();
panZoom.fit();
panZoom.center();
$(window).resize(function(){
panZoom.resize();
panZoom.fit();
panZoom.center();
});
}
});
</script>
</body>
</html>
|
{
"content_hash": "efecf5779f187f5dd766fb33b36f333c",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 232,
"avg_line_length": 44.01020408163265,
"alnum_prop": 0.5019128217018317,
"repo_name": "BryanWilhite/SonghayCore",
"id": "93950455212336677ec914c2d096f9c15355eb09",
"size": "17252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/latest/Songhay.Extensions/DateTimeExtensions/8b068147.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "752650"
}
],
"symlink_target": ""
}
|
Ext.define("e4e.dc.command.DcRpcFilterCommand", {
extend : "e4e.dc.command.AbstractDcAsyncCommand",
dcApiMethod : e4e.dc.DcCommandFactory.RPC_FILTER,
/**
* Call a service on the data-source filter.
*
* @param serviceName:
* The name of the data-source service to be executed.
* @param options:
* Specifications regarding the execution of this task. Command
* specific attributes: Attributes of specs:
* <li> namr: Name of the server-side RPC </li>
* <li> modal: Boolean flag to show a progress bar during the
* execution of the request to block user interaction.
* <li> context: object with variables you may need in your
* callbacks
* <li> callbacks: Object specifying callback functions to be
* invoked Attributes of callbacks :
* <li>successFn: Callback to execute on successful execution</li>
* <li>successScope: scope of the successFn</li>
* <li>silentSuccess: do not fire the
* afterDoServiceFilterSuccess event</li>
* <li>failureFn: callback to execute on failure</li>
* <li>failureScope: scope of the failureFn</li>
* <li>silentFailure: do not fire the
* <code>afterDoServiceFailure</code> event</li>
* The arguments passed to these functions are described in the
* afterDoServiceFilterSuccess() and
* afterDoServiceFilterFailure() methods which actually invoke
* them.
*
*/
onExecute : function(options) {
var dc = this.dc;
var serviceName = options.name;
var s = options || {};
var p = {
data : Ext.encode(dc.filter.data)
};
if (dc.params != null) {
p["params"] = Ext.encode(dc.params.data);
}
p[Main.requestParam.SERVICE_NAME_PARAM] = serviceName;
p["rpcType"] = "filter";
if (s.modal) {
Main.working();
}
Ext.Ajax.request({
url : Main.dsAPI(dc.dsName, "json").service,
method : "POST",
params : p,
success : this.onAjaxSuccess,
failure : this.onAjaxFailure,
scope : this,
options : options
});
}
/**
* Method called after a successful execution of the service. Successful
* means that server returns a 200 status code and the success attribute in
* the returning json is set to true. It first invokes the task specific
* callback then fires the associated event. Both type of callback methods (
* the one specified in callbacks and the handler of the fired event) will
* be passed the data-control instance (this) followed by the arguments of
* this method. If you need a certain callback to be executed each time,
* attach an event listener to the fired event.
*
* @param response:
* the server response object as received from the ajax request
* @param serviceName:
* the name of service which has been executed.
* @param specs:
* Specifications regarding the execution of this task.
* @See doService()
*
*/
,
onAjaxSuccess : function(response, options) {
try {
Ext.Msg.hide();
} catch (e) {
}
var o = options.options || {}, name = o.name, s = o || {};
var dc = this.dc;
var r = Ext.decode(response.responseText);
if (r.success) {
// filter
this._updateModel(dc.filter, r.data, {targetType:"filter"});
// params
if (r.params) {
this._updateModel(dc.params, r.params, {targetType:"params"});
}
}
if (s.callbacks && s.callbacks.successFn) {
s.callbacks.successFn.call(s.callbacks.successScope || dc, dc,
response, name, options);
}
if (!(s.callbacks && s.callbacks.silentSuccess === true)) {
dc.fireEvent("afterDoServiceFilterSuccess", dc, response, name,
options);
}
}
/**
* Method called when execution of the service fails. Failure means that
* server returns anything except a 200 class status code or the success
* attribute in the returning json is set to false. It first invokes the
* task specific callback then fires the associated event. Both type of
* callback methods ( the one specified in callbacks and the handler of the
* fired event) will be passed the data-control instance (this) followed by
* the arguments of this method. If you need a certain callback to be
* executed each time, attach an event listener to the fired event.
*
* @param response:
* the server response object as received from the ajax request
* @param serviceName:
* the name of service which has been executed.
* @param specs:
* Specifications regarding the execution of this task.
* @See doService()
*/
,
onAjaxFailure : function(response, options) {
try {
Ext.Msg.hide();
} catch (e) {
}
var o = options.options || {}, serviceName = o.name, s = o || {};
var dc = this.dc;
Main.serverMessage(response.responseText);
if (s.callbacks && s.callbacks.failureFn) {
s.callbacks.failureFn.call(s.callbacks.failureScope || dc, dc,
response, serviceName, options);
}
if (!(s.callbacks && s.callbacks.silentFailure === true)) {
dc.fireEvent("afterDoServiceFilterFailure", dc, response, name,
options);
}
}
});
|
{
"content_hash": "969ae4b7cc96beee0d710269d876ce5f",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 78,
"avg_line_length": 35.04026845637584,
"alnum_prop": 0.6470024899444551,
"repo_name": "seava/seava.lib.e4e",
"id": "0465c0eb08e509d7da38e923d499d2afd5da15bd",
"size": "5344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "seava.e4e.impl/src/main/resources/webapp/js/e4e/dc/command/DcRpcFilterCommand.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2751623"
},
{
"name": "JavaScript",
"bytes": "5469014"
}
],
"symlink_target": ""
}
|
import {
Store,
AnyAction,
Reducer,
Middleware,
StoreEnhancer,
Unsubscribe,
createStore,
applyMiddleware,
compose,
Dispatch,
} from 'redux';
import { NgZone } from '@angular/core';
import { BehaviorSubject, Observable, Observer } from 'rxjs';
import { distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
import { NgRedux } from './ng-redux';
import {
Selector,
PathSelector,
Comparator,
resolveToFunctionSelector,
} from './selectors';
import { assert } from '../utils/assert';
import { SubStore } from './sub-store';
import { enableFractalReducers } from './fractal-reducer-map';
import { ObservableStore } from './observable-store';
/** @hidden */
export class RootStore<RootState> extends NgRedux<RootState> {
private _store: Store<RootState> | undefined = undefined;
private _store$: BehaviorSubject<RootState>;
constructor(private ngZone: NgZone) {
super();
NgRedux.instance = this;
this._store$ = new BehaviorSubject<RootState | undefined>(undefined).pipe(
filter(n => n !== undefined),
switchMap(observableStore => observableStore as any)
// TODO: fix this? needing to explicitly cast this is wrong
) as BehaviorSubject<RootState>;
}
configureStore = (
rootReducer: Reducer<RootState, AnyAction>,
initState: RootState,
middleware: Middleware[] = [],
enhancers: StoreEnhancer<RootState>[] = []
): void => {
assert(!this._store, 'Store already configured!');
// Variable-arity compose in typescript FTW.
this.setStore(
compose.apply(null, [applyMiddleware(...middleware), ...enhancers])(
createStore
)(enableFractalReducers(rootReducer), initState)
);
};
provideStore = (store: Store<RootState>) => {
assert(!this._store, 'Store already configured!');
this.setStore(store);
};
getState = (): RootState => this._store!.getState();
subscribe = (listener: () => void): Unsubscribe =>
this._store!.subscribe(listener);
replaceReducer = (nextReducer: Reducer<RootState, AnyAction>): void => {
this._store!.replaceReducer(nextReducer);
};
dispatch: Dispatch<AnyAction> = <A extends AnyAction>(action: A): A => {
assert(
!!this._store,
'Dispatch failed: did you forget to configure your store? ' +
'https://github.com/angular-redux/@angular-redux/core/blob/master/' +
'README.md#quick-start'
);
if (!NgZone.isInAngularZone()) {
return this.ngZone.run(() => this._store!.dispatch(action));
} else {
return this._store!.dispatch(action);
}
};
select = <SelectedType>(
selector?: Selector<RootState, SelectedType>,
comparator?: Comparator
): Observable<SelectedType> =>
this._store$.pipe(
distinctUntilChanged(),
map(resolveToFunctionSelector(selector)),
distinctUntilChanged(comparator)
);
configureSubStore = <SubState>(
basePath: PathSelector,
localReducer: Reducer<SubState, AnyAction>
): ObservableStore<SubState> =>
new SubStore<SubState>(this, basePath, localReducer);
private setStore(store: Store<RootState>) {
this._store = store;
const storeServable = this.storeToObservable(store);
this._store$.next(storeServable as any);
}
private storeToObservable = (
store: Store<RootState>
): Observable<RootState> =>
new Observable<RootState>((observer: Observer<RootState>) => {
observer.next(store.getState());
const unsubscribeFromRedux = store.subscribe(() =>
observer.next(store.getState())
);
return () => {
unsubscribeFromRedux();
observer.complete();
};
});
}
|
{
"content_hash": "0501b718cf2d6b25f5aad8bf0fec1642",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 78,
"avg_line_length": 29.272,
"alnum_prop": 0.6630226837933861,
"repo_name": "angular-redux/store",
"id": "74ad9e14cf3b9736fc80331f56252f46df1ad7f8",
"size": "3659",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/components/root-store.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1236"
},
{
"name": "TypeScript",
"bytes": "82403"
}
],
"symlink_target": ""
}
|
package net.technolords.micro.command;
import org.apache.camel.Exchange;
import net.technolords.micro.model.ResponseContext;
public interface Command {
String CONFIG = "config";
String LOG = "log";
String RESET = "reset";
String STATS = "stats";
String STOP = "stop";
String getId();
ResponseContext executeCommand(Exchange exchange);
}
|
{
"content_hash": "4109587ffd52f63b503b258aec982af6",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 54,
"avg_line_length": 23.0625,
"alnum_prop": 0.7046070460704607,
"repo_name": "Technolords/microservice-mock",
"id": "db479cd8ac9827ffdc488845c1fd0793f5b18ab0",
"size": "369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/technolords/micro/command/Command.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "274"
},
{
"name": "Java",
"bytes": "193350"
}
],
"symlink_target": ""
}
|
.class public Lcom/android/camera/ui/FocusIndicatorRotateLayout;
.super Lcom/android/camera/ui/RotateLayout;
.source "FocusIndicatorRotateLayout.java"
# interfaces
.implements Lcom/android/camera/ui/FocusIndicator;
# annotations
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Lcom/android/camera/ui/FocusIndicatorRotateLayout$1;,
Lcom/android/camera/ui/FocusIndicatorRotateLayout$Disappear;,
Lcom/android/camera/ui/FocusIndicatorRotateLayout$EndAction;
}
.end annotation
# instance fields
.field private mBlockFocus:Z
.field private mDisappear:Ljava/lang/Runnable;
.field private mEndAction:Ljava/lang/Runnable;
.field private mFocusScale:Landroid/view/animation/Animation;
.field private mState:I
# direct methods
.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.locals 2
.parameter "context"
.parameter "attrs"
.prologue
const/4 v1, 0x0
.line 55
invoke-direct {p0, p1, p2}, Lcom/android/camera/ui/RotateLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.line 43
new-instance v0, Lcom/android/camera/ui/FocusIndicatorRotateLayout$Disappear;
invoke-direct {v0, p0, v1}, Lcom/android/camera/ui/FocusIndicatorRotateLayout$Disappear;-><init>(Lcom/android/camera/ui/FocusIndicatorRotateLayout;Lcom/android/camera/ui/FocusIndicatorRotateLayout$1;)V
iput-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
.line 44
new-instance v0, Lcom/android/camera/ui/FocusIndicatorRotateLayout$EndAction;
invoke-direct {v0, p0, v1}, Lcom/android/camera/ui/FocusIndicatorRotateLayout$EndAction;-><init>(Lcom/android/camera/ui/FocusIndicatorRotateLayout;Lcom/android/camera/ui/FocusIndicatorRotateLayout$1;)V
iput-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mEndAction:Ljava/lang/Runnable;
.line 48
iput-object v1, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mFocusScale:Landroid/view/animation/Animation;
.line 49
const/4 v0, 0x0
iput-boolean v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mBlockFocus:Z
.line 56
const v0, 0x7f050008
invoke-static {p1, v0}, Landroid/view/animation/AnimationUtils;->loadAnimation(Landroid/content/Context;I)Landroid/view/animation/Animation;
move-result-object v0
iput-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mFocusScale:Landroid/view/animation/Animation;
.line 60
return-void
.end method
.method static synthetic access$200(Lcom/android/camera/ui/FocusIndicatorRotateLayout;)Ljava/lang/Runnable;
.locals 1
.parameter "x0"
.prologue
.line 34
iget-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
return-object v0
.end method
.method static synthetic access$302(Lcom/android/camera/ui/FocusIndicatorRotateLayout;I)I
.locals 0
.parameter "x0"
.parameter "x1"
.prologue
.line 34
iput p1, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mState:I
return p1
.end method
.method private setDrawable(I)V
.locals 2
.parameter "resid"
.prologue
.line 79
iget-object v0, p0, Lcom/android/camera/ui/RotateLayout;->mChild:Landroid/view/View;
invoke-virtual {p0}, Landroid/view/View;->getResources()Landroid/content/res/Resources;
move-result-object v1
invoke-virtual {v1, p1}, Landroid/content/res/Resources;->getDrawable(I)Landroid/graphics/drawable/Drawable;
move-result-object v1
invoke-virtual {v0, v1}, Landroid/view/View;->setBackgroundDrawable(Landroid/graphics/drawable/Drawable;)V
.line 80
return-void
.end method
.method private setDrawable(Landroid/graphics/drawable/Drawable;)V
.locals 1
.parameter "drawable"
.prologue
.line 82
iget-object v0, p0, Lcom/android/camera/ui/RotateLayout;->mChild:Landroid/view/View;
invoke-virtual {v0, p1}, Landroid/view/View;->setBackgroundDrawable(Landroid/graphics/drawable/Drawable;)V
.line 83
return-void
.end method
# virtual methods
.method public clear()V
.locals 2
.prologue
const/high16 v1, 0x3f80
.line 153
invoke-virtual {p0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;
move-result-object v0
invoke-virtual {v0}, Landroid/view/ViewPropertyAnimator;->cancel()V
.line 154
iget-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
invoke-virtual {p0, v0}, Landroid/view/View;->removeCallbacks(Ljava/lang/Runnable;)Z
.line 155
iget-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
invoke-interface {v0}, Ljava/lang/Runnable;->run()V
.line 156
invoke-virtual {p0, v1}, Landroid/view/View;->setScaleX(F)V
.line 157
invoke-virtual {p0, v1}, Landroid/view/View;->setScaleY(F)V
.line 158
invoke-virtual {p0}, Landroid/view/View;->invalidate()V
.line 159
return-void
.end method
.method public setBlockFocus(Z)V
.locals 0
.parameter "blocked"
.prologue
.line 133
iput-boolean p1, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mBlockFocus:Z
.line 134
if-eqz p1, :cond_0
.line 135
invoke-virtual {p0}, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->clear()V
.line 139
:goto_0
return-void
.line 137
:cond_0
invoke-virtual {p0}, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->showStart()V
goto :goto_0
.end method
.method public showFail(Z)V
.locals 1
.parameter "timeout"
.prologue
.line 120
iget-boolean v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mBlockFocus:Z
if-eqz v0, :cond_0
.line 131
:goto_0
return-void
.line 124
:cond_0
const v0, 0x7f0200f4
invoke-direct {p0, v0}, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->setDrawable(I)V
.line 129
const/4 v0, 0x2
iput v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mState:I
goto :goto_0
.end method
.method public showStart()V
.locals 1
.prologue
.line 86
iget-boolean v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mBlockFocus:Z
if-eqz v0, :cond_0
.line 96
:goto_0
return-void
.line 90
:cond_0
const v0, 0x7f0200f6
invoke-direct {p0, v0}, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->setDrawable(I)V
.line 93
iget-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mFocusScale:Landroid/view/animation/Animation;
invoke-virtual {p0, v0}, Landroid/view/View;->startAnimation(Landroid/view/animation/Animation;)V
.line 94
const/4 v0, 0x1
iput v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mState:I
goto :goto_0
.end method
.method public showSuccess(Z)V
.locals 4
.parameter "timeout"
.prologue
.line 100
iget-boolean v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mBlockFocus:Z
if-eqz v0, :cond_0
.line 116
:goto_0
return-void
.line 104
:cond_0
const v0, 0x7f0200f5
invoke-direct {p0, v0}, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->setDrawable(I)V
.line 106
iget-object v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
invoke-virtual {p0, v0}, Landroid/view/View;->removeCallbacks(Ljava/lang/Runnable;)Z
.line 107
invoke-virtual {p0}, Landroid/view/View;->getHandler()Landroid/os/Handler;
move-result-object v0
if-eqz v0, :cond_1
.line 108
invoke-virtual {p0}, Landroid/view/View;->getHandler()Landroid/os/Handler;
move-result-object v0
iget-object v1, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mDisappear:Ljava/lang/Runnable;
const-wide/16 v2, 0x1f4
invoke-virtual {v0, v1, v2, v3}, Landroid/os/Handler;->postDelayed(Ljava/lang/Runnable;J)Z
.line 114
:cond_1
const/4 v0, 0x2
iput v0, p0, Lcom/android/camera/ui/FocusIndicatorRotateLayout;->mState:I
goto :goto_0
.end method
|
{
"content_hash": "38b706bb7cdce94bff7245efbf79c546",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 205,
"avg_line_length": 26.529032258064515,
"alnum_prop": 0.7205739299610895,
"repo_name": "baidurom/devices-Coolpad8720L",
"id": "f82f7801ef6f6a39df2e48a967a0127f1027a706",
"size": "8224",
"binary": false,
"copies": "1",
"ref": "refs/heads/coron-4.3",
"path": "CP_Gallery3D/smali/com/android/camera/ui/FocusIndicatorRotateLayout.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "13619"
},
{
"name": "Shell",
"bytes": "1917"
}
],
"symlink_target": ""
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array('session');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('form');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
|
{
"content_hash": "55821df4f76f46a6262b718d37e98e6d",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 77,
"avg_line_length": 29.925925925925927,
"alnum_prop": 0.47599009900990097,
"repo_name": "metalcodeifsp/class_clock_modulo_2",
"id": "ba56154eda26f1568b68ae3f4a6d62b3e08e1079",
"size": "4040",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/config/autoload.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39022"
},
{
"name": "HTML",
"bytes": "8481464"
},
{
"name": "JavaScript",
"bytes": "56666"
},
{
"name": "PHP",
"bytes": "6815453"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Thu Aug 07 18:51:31 PDT 2014 -->
<title>H-Index</title>
<meta name="date" content="2014-08-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="H-Index";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-6.html">Prev Letter</a></li>
<li><a href="index-8.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-7.html" target="_top">Frames</a></li>
<li><a href="index-7.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">D</a> <a href="index-4.html">E</a> <a href="index-5.html">F</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> <a href="index-20.html">X</a> <a href="index-21.html">Y</a> <a href="index-22.html">Z</a> <a name="_H_">
<!-- -->
</a>
<h2 class="title">H</h2>
<dl>
<dt><span class="strong"><a href="../j3dio/obj/ObjFace.html#hasNorms()">hasNorms()</a></span> - Method in class j3dio.obj.<a href="../j3dio/obj/ObjFace.html" title="class in j3dio.obj">ObjFace</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../j3dio/obj/ObjFace.html#hasTextures()">hasTextures()</a></span> - Method in class j3dio.obj.<a href="../j3dio/obj/ObjFace.html" title="class in j3dio.obj">ObjFace</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../j3dio/stl/StlModel.html#header">header</a></span> - Variable in class j3dio.stl.<a href="../j3dio/stl/StlModel.html" title="class in j3dio.stl">StlModel</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">D</a> <a href="index-4.html">E</a> <a href="index-5.html">F</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> <a href="index-20.html">X</a> <a href="index-21.html">Y</a> <a href="index-22.html">Z</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-6.html">Prev Letter</a></li>
<li><a href="index-8.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-7.html" target="_top">Frames</a></li>
<li><a href="index-7.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"content_hash": "005a404f3a76d47281c88a9979736820",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 805,
"avg_line_length": 45.32258064516129,
"alnum_prop": 0.6215302491103203,
"repo_name": "FracturedRetina/FracturedRetina.github.io",
"id": "5004207ed3d874c5e55d2e7135a434f33c5ffeef",
"size": "5620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "j3dio/doc/doc_v4.1.2-beta/index-files/index-7.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100817"
},
{
"name": "HTML",
"bytes": "4441646"
},
{
"name": "JavaScript",
"bytes": "758"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Wed Feb 26 19:24:06 PST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.ctc.wstx.util.StringUtil (Woodstox 6.1.0 API)</title>
<meta name="date" content="2020-02-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.ctc.wstx.util.StringUtil (Woodstox 6.1.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/ctc/wstx/util/StringUtil.html" title="class in com.ctc.wstx.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/ctc/wstx/util/class-use/StringUtil.html" target="_top">Frames</a></li>
<li><a href="StringUtil.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.ctc.wstx.util.StringUtil" class="title">Uses of Class<br>com.ctc.wstx.util.StringUtil</h2>
</div>
<div class="classUseContainer">No usage of com.ctc.wstx.util.StringUtil</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/ctc/wstx/util/StringUtil.html" title="class in com.ctc.wstx.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/ctc/wstx/util/class-use/StringUtil.html" target="_top">Frames</a></li>
<li><a href="StringUtil.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://fasterxml.com">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"content_hash": "aaa5c2d529f6dfb9ef0a3d431b8bebae",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 128,
"avg_line_length": 35.77777777777778,
"alnum_prop": 0.6062555456965395,
"repo_name": "FasterXML/woodstox",
"id": "4ff9cb8d15fbee4cf71e7c195834b0ffbb352521",
"size": "4508",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadoc/6.1/com/ctc/wstx/util/class-use/StringUtil.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2475"
},
{
"name": "Java",
"bytes": "3239858"
}
],
"symlink_target": ""
}
|
package uk.org.rbc1b.roms.security;
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
/**
* @author oliver.elder.esq
*/
public class RomsPermissionEvaluatorTest {
// CHECKSTYLE:OFF
private RomsPermissionEvaluator evaluator;
private MockAuthentication authentication;
@Before
public void setUp() {
evaluator = new RomsPermissionEvaluator();
authentication = new MockAuthentication(1, "testname", "passwd");
authentication.addAuthority(Application.ATTENDANCE, AccessLevel.DELETE, AccessLevel.DELETE);
authentication.addAuthority(Application.CIRCUIT, AccessLevel.EDIT, AccessLevel.DELETE);
authentication.addAuthority(Application.CONG, AccessLevel.ADD, AccessLevel.DELETE);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidPermission() {
evaluator.hasPermission(authentication, "AuthC", "Invalid");
}
@Test(expected = IllegalArgumentException.class)
public void testValidPermissionTargetNotFound() {
evaluator.hasPermission(authentication, "AuthUnknown", "READ");
}
@Test
public void testValidPermissionDenied() {
assertEquals(false, evaluator.hasPermission(authentication, Application.CIRCUIT.name(), "ADD"));
}
@Test
public void testValidPermissionAllowed() {
assertEquals(true, evaluator.hasPermission(authentication, Application.CONG.name(), "ADD"));
assertEquals(true, evaluator.hasPermission(authentication, Application.ATTENDANCE.name(), "ADD"));
}
private class MockAuthentication implements Authentication {
private static final long serialVersionUID = 1L;
private final Map<Application, ROMSGrantedAuthority> authorities = new HashMap<Application, ROMSGrantedAuthority>();
private final Integer userId;
private final String password;
private final String userName;
private MockAuthentication(Integer userId, String userName, String password) {
this.userId = userId;
this.userName = userName;
this.password = password;
}
private void addAuthority(Application application, AccessLevel departmentLevel, AccessLevel nonDepartmentLevel) {
ROMSGrantedAuthority authority = new ROMSGrantedAuthority();
authority.setApplication(application);
authority.setDepartmentLevelAccess(departmentLevel);
authority.setNonDepartmentLevelAccess(nonDepartmentLevel);
authorities.put(application, authority);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities.values();
}
@Override
public Object getCredentials() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getDetails() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getPrincipal() {
return new ROMSUserDetails() {
private static final long serialVersionUID = 1L;
@Override
public ROMSGrantedAuthority findAuthority(Application application) {
return authorities.get(application);
}
@Override
public Integer getUserId() {
return userId;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
// do nothing
}
@Override
public String getName() {
return userName;
}
}
}
|
{
"content_hash": "297f80283ea99b8ecd61197c5fdb151e",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 124,
"avg_line_length": 32.506410256410255,
"alnum_prop": 0.6121080654703215,
"repo_name": "RBC1B/ROMS",
"id": "e1f4a38ef1291ad9c72d68a6406b9507eff92acd",
"size": "6199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/uk/org/rbc1b/roms/security/RomsPermissionEvaluatorTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18428"
},
{
"name": "FreeMarker",
"bytes": "27951"
},
{
"name": "Java",
"bytes": "1436534"
},
{
"name": "JavaScript",
"bytes": "187547"
},
{
"name": "PLSQL",
"bytes": "276"
},
{
"name": "Shell",
"bytes": "1388"
}
],
"symlink_target": ""
}
|
# Теория компиляторов для неофитов
## Лабораторная работа №3: "Лексер"
[Содержание](../tutorial/content.md)
[Лекция: Лексический анализатор](../tutorial/lexer.md)
-------
В этой работе мы реализуем конечные автоматы, регулярные выражения и лексер.
Необходимая теория изложена в лекции по ссылке вверху.
Полный исходный код находится в папке проектов: [projects/regexp](../projects/regexp).
Проект целиком реализует компиляцию регулярных выражений,
сейчас нас будут интересовать только некоторые классы из пакетов
`terminal`, `fsa` и `lexer`.
Начнем с реализации конечного автомата.
Создадим интерфейс [fsa.IFSA]](../projects/regexp/src/main/java/fsa/IFSA.java)
недетерминированного конечного автомата, декларирующего все необходимые функции
для запуска готового конечного автомата и просмотра его состояния.
```java
public interface IFSA<T, F> {
```
Конечный автомат состоит из некоторого числа состояний,
переходы между состояниями маркируются метками,
состояния также могут быть помечены, такие состояния считаются остановочными.
Конкретный вид состояния не важен для его работы,
поэтому мы не включаем его в интерфейс.
Метки переходов будут определяться алфавитом разбираемого языка,
в качестве которого можно выбрать ASCII, UNICODE,
или еще что-то, поэтому мы не будем ограничивать себя
одним типом, а введем параметр `T`, который будет задавать тип меток.
Маркеры остановочных состояний также могут быть разными,
например, это может быть перечисление или функция, задающая семантическое
действие, поэтому маркеры остановочных состояний параметризуем
типом `F`.
Первый метод, который мы включим в интерфейс, будет перезапусать автомат,
т.е. переводить его в стартовое состояние, что нужно для многократного
использования автомата.
```java
void reset();
```
Следующий метод выполняет переход из текущего состояния по данной метке `label`.
Если такой переход в автомате возможен, то метод вернет `true`, и автомат
перейдет в новое состояние, в противном случае метод вернет `false`
и состояние автомата не изменится.
Интерфейс допускает работу с недетерминированными автоматами,
в этом случае текущих состояний может быть несколько и
переход осущесталяется сразу во все состояния, в которые возможен переход.
```java
boolean makeTransition(T label);
```
Теперь обратимся к остановочным состояниям.
Мы разрешим состояниям иметь несколько маркеров, которые могут, например,
помечать, какую из лексем удалось свернуть.
Определим функцию, которая будет возвращать все маркеры текущего состояия.
Спрячем реализацию хранилища маркеров за интерфейсом `java.lang.Iterable`
и будем действовать подобным образом далее.
```java
Iterable<F> getMarkers();
```
Наконец, создадим метод, который послужит примером использования
интерфейса.
Метод будет возвращать `true`, если строка `string` порождается автоматом
и `false` в противном случае.
Приведем реализацию по умолчанию, которая будет перезапускать автомат,
затем выполнять переходы до тех пор, пока есть символы в строке,
а в конце проверит, является ли состояние остановочным.
```java
default boolean match(Iterable<T> string) {
this.reset();
for(T label: string)
if(!this.makeTransition(label)) return false;
return this.getMarkers().iterator().hasNext();
};
}
```
Если автомат детерминированный, то он может иметь не более
одного маркера на состояние, в этом случае создание коллекции
маркеров нерационально использует ресурсы и не исключает возможность
возвращение некорректного значения.
Поэтому для детерминированного автомата мы создадим интерфейс
[fsa.IDFA]](../projects/regexp/src/main/java/fsa/IDFA.java),
который добавляет к `fsa.IFSA` одну функцию,
возвращающую единственный маркер состояния.
```java
public interface IDFA<T, F> extends IFSA<T, F> {
F getMarker();
}
```
Любая реализация интерфейса должна удовлетворять следующим условиям:
1. Eсли состояние не остановочное, то `getMarker` возвращает `null`,
а `getMarkers` возвращает пустую коллекцию.
1. Если `getMarker` возвращает маркер `m`, то `getMarkers` должно
возвращать коллекцию из одного только `m`.
Перед тем, как мы перейдем к реализации интерфейсов,
создадим класс [fsa.State]](../projects/regexp/src/main/java/fsa/State.java),
который будет хранить состояние автомата.
Состояний конечное состояние, больше мы ничего про состояния не знаем,
поэтому будем просто нумеровать их целыми числами.
Мы хотим гарантировать, что обьект состояния всегда
соответствует некоторому состоянию, поэтому запретим пользователям самим
создавать обьекты состояния, их должен создавать только сам автомат.
```java
public class State {
private int id;
State(int id);
```
Однако иметь доступ к номеру состояния удобно для отладки и ускорения некоторых операций.
Создадим метод, который возвращает номер состояния.
```java
public int getId() { return this.id; }
```
Также переопределим операции сравнения и хэш-функции,
так чтобы сравнивались номера состояний.
```java
@Override public int hashCode() { return this.id; }
@Override public boolean equals(Object obj) {
if(obj==null) return false;
if(this.getClass()!=obj.getClass()) return false;
State state=(State)obj;
return this.id==state.id;
};
```
Наконец, пусть строкове представление класса выводим номер состояния:
```java
@Override public String toString() { return String.valueOf(this.id); };
}
```
Мы почти готовы к реализации конечного автомата,
однако перед тем, как начать, давайте подумаем как автомат будет
использоваться.
Определенный нами интерфейс позволяет делать переходы по
символам алфавита, что ествественно, так как символы алфавита
мы читаем из разбираемой строки.
Однако при составлении автомата перечислять все символы
перехода может быть как неудобно, так и расточительно.
Действительно, `Unicode` определяет более 100000 символов,
и если мы хотим создать переход по всем символам, кроме
нескольких, то создание перехода для каждого символа
представляется крайне нерациональным.
Вместо этого лучше задавать классы символов, по которым делается переход.
Тогда переходы, допустимые из текущего состояния,
можно хранить в виде квази ассоциативного массива,
ключами в котором будут классы, а извлекать элементы массива
можно по отдельным символам, представителям классов.
Если в качестве классов использовать сами символы, то новая коллекция
должна быть идентична `java.util.Map`.
Зададим интерфейс [terminal.IPredicateMap](../projects/regexp/src/main/java/terminal/IPredicateMap.java)
такой коллекции.
```java
public interface IPredicateMap<P extends ICharSet<K,P>,K,V, SELF extends IPredicateMap<P,K,V,SELF>> {
```
Здесь параметр `P` задает тип для класса символов,
параметр `K` задает тип для одного символа,
параметр `V` задает тип хранимого в коллекции массива.
Параметр `SELF` содержит тип самой коллекции, и используется для создания
экземпляров коллекции.
Зададим метод, который будет возвращать пустую коллекцию,
что позволит нам создавать новые экземпляры коллекции,
имея один экземпляр, даже не зная точный тип коллекции.
```java
SELF empty();
```
Следующий метод позволит извлекать из коллекции значения,
в качестве ключа используется конкретный символ, поэтому его тип `K`.
```java
V get(K key);
```
А этот метод позволяет помещать в массив новые элементы,
причем в качестве ключа используется класс символов,
поэтому его тип `P`.
Так как одному символу типа `K` должно соответствовать одно значение,
то ключи-классы не должны пересекаться.
Если ключи пересекаются, то выбрасывается исключение `IndexOutOfBoundsException`.
```java
void put(P predicate, V value) throws IndexOutOfBoundsException;
```
Наконец, мы хотим извлекать полное содержание коллекции,
чтобы иметь возможность выполнять преобразование коллекции.
```java
Iterable<Map.Entry<P,V>> entrySet();
}
```
Так как недетерминированный автомат может делать несколько
переходов по одному символу, то однозначное соответствие между
ключами и переходами, описываемое интерфейсом `terminal.IPredicateMap`
не пригодно для хранения переходов в недетерминированном автомате.
Чтобы работать с недетерминированными автоматами, мы определим
новый интерфейс [terminal.IPredicateMap](../projects/regexp/src/main/java/terminal/IPredicateMap.java),
допускающий несклько значений для одного ключа:
```java
public interface IPredicateMultiMap<P,K,V, SELF extends IPredicateMultiMap<P,K,V,SELF>> {
SELF empty();
Iterable<V> get(K key);
void put(P predicate, V value);
Iterable<Map.Entry<P,V>> entrySet();
```
Отличие интерфейсов в том, что `get` может возвращатт несколько значений,
а `put` не выбрасывает исключение, если ключи пересекаются.
Наконец, создадим метод, добавляющий из коллекции `other` все элементы,
применив к ним предварительно функцию `map`.
```java
default void mergeMap(IPredicateMultiMap<P,K,V,?> other, Function<V,V> map) {
for(Map.Entry<P,V> entry: other.entrySet())
this.put(entry.getKey(), map.apply(entry.getValue()));
}
}
```
После длительной подготовки, перейдем к написанию класса
[fsa.FSA](../projects/regexp/src/main/java/fsa/FSA.java),
реализующего недетерминированный автомат.
```java
public class FSA<T,F,P> implements IFSA<T,F> {
```
Автомат делает переходы по символам типа `T`,
классы символов имеют тип `P`,
состояния маркируются метками типа `F`.
Структура автомата полностью описывается следующими свойствами:
```java
protected int numberOfStates;
protected HashMap<State, IPredicateMultiMap<P,T,State,?>> transitions;
protected HashMap<State, HashSet<F>> markers;
```
Автомат имеет все состояния, начиная с `0` (стартовое состояние)
и заканчивая `numberOfStates-1`.
Каждому состоянию `state` сопоставляется множество меток,
хранимых в `markers`.
Множество переходов для каждого состояния храним в `transitions`.
Мы храним в `activeStates` множество всех состояний, достигнутых
к настоящему времени, т.е. тех, в которые можно попасть из стартового
состояния переходами по переданным автомату символам.
```java
protected HashSet<State> activeStates;
```
Так как тип хранилища для переходов может быть произвольным,
мы должны дать автомату подсказку, как создавать эти хранилища,
для этого мы храним одно из хранилищ внутри обьекта,
и создаем новые с помощью функции `IPredicateMultiMap.empty()`.
```java
protected IPredicateMultiMap<P,T,State,?> factory;
```
Этот экзмепляр хранилища передается конструктуру.
Других аргументов конструктор не имеет, создавая автомат,
не имеющий ни одного состояния.
```java
public<M extends IPredicateMultiMap<P,T,State,M>> FSA(M factory) { ... };
```
Класс реализует интерфейс конечного автомата:
```java
public void reset() { ... };
public boolean makeTransition(T label) { ... };
public Iterable<F> getMarkers() { ... };
```
Реализация интерфейса достаточно очевидна.
Метки состояний уже хранятся в `markers`.
Чтобы сделать переходы, нужно для каждого состояния из `activeStates`
взять из `transitions` все переходы по данному символу,
и записать цели этих переходов в новое состояние.
Чтобы перезапустить автомат, нужно перезаписать `activeStates`,
поместив в него только стартовое состояние.
Однако при выполнении `reset` и `makeTransitions`,
необходимо учитывать, что недетерминированный автомат может
содержать эпсилон-переходы, для выполнения которых не требуется
читать ни одного символа.
Определим метод `doEpsilonTransitions`, делающий все эпсилон-переходы
из текущего состояния, он будет вызываться из `reset` и `makeTransition`
после выполнения не эпсилон-переходов.
```java
protected void doEpsilonTransition(Set<State> states) { ... };
```
Для конструирования автомата нам подтребуются метод, создающий новые состояния:
```java
public State newState() { ... };
```
метод, добавляющий переход из состояния `from` в состояние `to`
по классу меток `label`:
```java
public void newTransition(State from, State to, P label) { ... };
```
и метод, помечающий состояние `state` меткой `mark`:
```java
public void markState(State state, F mark) { ... };
```
Для отладки будет удобно иметь выводить структуру автомата
в читаемом человеком виде:
```java
@Override public String toString() { ... };
```
Текстовое представление имеет вид, подобный следующему примеру:
```
#0:0: eps>0 'b'>2 eps>1
#1: 'a'>2
#2: eps>1 'a'>0 'b'>1
```
Описание нового состояния начинается с символа `#`,
затем идет номер состояния и `:`.
Далее перечисляются метки состояния, если они есть, за ними `:`.
Затем список переходов из состояния перечисляется через пробел.
Сначала указывается метка перехода, потом `>`, потом состояние,
в которое осуществляется переход.
Если переход не имеет метки (т.е. эпсилон-переход),
то вместо метки пишется `eps`.
Если метка есть, то она указывается между обратных кавычек.
Класс `fsa.FSA` имеет еще несколько вспомогательных
методов, про которые мы поговорим, когда они потребуются.
Детерминированный автомат реализуется классом
[fsa.DFA](../projects/regexp/src/main/java/fsa/DFA.java).
Часть его методов почти идентична методам `fsa.SFA`,
но устраняет неоднозначность:
```java
public class DFA<T,F,P extends ICharSet<T,P>> implements IDFA<T, F> {
public<M extends IPredicateMap<P,T,State,M>> DFA(M factory) { ... };
public void reset() { ... };
public boolean makeTransition(T label) { ... };
public Iterable<F> getMarkers() { ... };
public F getMarker() { ... };
public State newState() { ... };
public void newTransition(State from, State to, P label) throws IllegalArgumentException { ... };
public void markState(State state, F mark) { ... };
@Override public String toString() { ... };
```
Внутреннее хранилище также почти идентично `fsa.FSA`,
с поправкой на однозначность перехода, текущего состояния, маркеров состояний и т.п.
```java
protected int activeState;
protected int numberOfStates;
protected List<IPredicateMap<P,T,State,?>> transitions;
protected List<F> markers;
protected IPredicateMap<P,T,State,?> factory;
```
Добавим новый конструктор, который будет конструировать эквивалентный детерминированный
автомат из недетерминированного автомата `automaton`.
```java
public<M extends IPredicateMap<P,T,State,M>> DFA(M factory, FSA<T,F,P> automaton) {
```
Данный метод работает как описано в лекции, уточним только несколько деталей.
Так как недетерминированный автомат работает с классами символов,
а все переходы в детерминированном автомате должны быть различными,
нам нужно уметь находить пересечения классов.
Чтобы иметь возможность это делать, мы определим интерфейс
[terminal.ICharSet](../projects/regexp/src/main/java/terminal/ICharSet.java),
определяющий операции пересечений и вычитания множеств.
```java
public interface ICharSet<T, SELF extends ICharSet<T, SELF>> {
SELF intersect(SELF other);
Collection<SELF> subtract(SELF other);
}
```
Так как стандартные классы не реализуют `terminal.ICharSet`,
мы создадим свой класс [terminal.UChar](../projects/regexp/src/main/java/terminal/UChar.java),
для символов, обертывающий `char`,
т.е. хранящий символы из подмножества `Unicode`, и реализующий
весь необходимый функционал.
```java
public class UChar implements ICharSet<UChar, UChar> {
private char value;
public UChar(char c) { this.value=c; }
public UChar(Character c) { this.value=c.charValue(); }
public char toChar() { return this.value; }
public UChar intersect(UChar other) {
return (this.equals(other))?this:null;
}
public Collection<UChar> subtract(UChar other) {
ArrayList<UChar> result=new ArrayList();
if(this.value!=other.value) result.add(new UChar(this.value));
return result;
}
@Override public boolean equals(Object obj) { ... }
@Override public int hashCode() { ... }
@Override public String toString() { ... };
```
Мы также поместим в этот класс статический метод для
преобразования строки в список символов, который мы можем передать
затем лексеру.
```java
public static List<UChar> asList(String str) {
return str.chars().mapToObj(i -> new UChar((char)i)).collect(Collectors.toList());
};
}
```
Для построения автоматов для регулярных выражений
нам потребуются комбинаторы, выполняющие примитивные операции.
Поместим эти операторы в класс
[fsa.Combinators](../projects/regexp/src/main/java/fsa/Combinators.java).
Параметры типов имеют тоже значение, что и `fsa.FSA`.
Конструктор получает образец хранилища для переходов, аналогично
конструктору `fsa.FSA`.
```java
public class Combinators<T,F,P> {
protected IPredicateMultiMap<P,T,State,?> factory;
public<M extends IPredicateMultiMap<P,T,State,M>> Combinators(M factory) {
this.factory=factory;
}
```
Следующие методы возвращают недетерминированные автоматы для примитивных операций.
```java
/** Автомат, принимающий только string с маркером остановочного состояния marker. */
public FSA<T,F,P> literal(Iterable<P> string, F marker) { ... }
/** Автомат, принимающий любой из перечисленных символов `label` с маркером о.с. marker. */
public FSA<T,F,P> anyOf(Iterable<P> labels, F marker) { ... }
/** Обьединение автоматов automata */
public FSA<T,F,P> union(Iterable<FSA<T,F,P>> automata) { ... }
/** Конкатенация автоматов */
public FSA<T,F,P> concatenation(Iterable<FSA<T,F,P>> automata) { ... }
/** Автомат, исполняющий automaton любое число раз, включая ноль.
* Остановочное состояние для пустой строки маркируется marker.
*/
public FSA<T,F,P> star(FSA<T,F,P> automaton, F marker) { ... }
/** Автомат, повторяющий automaton один или более раз. */
public FSA<T,F,P> repeat(FSA<T,F,P> automaton) { ... }
/** Автомат исполняющий automaton или принимающий пустую строку.
* Остановочное состояние для пустой строки имеет маркер marker.
*/
public FSA<T,F,P> option(FSA<T,F,P> automaton, F marker) { ... }
}
```
С использованием этих комбинаторов можно создать любое
регулярное выражение.
К сожалению, мы пока не можем создавать регулярное выражение из его текстового представления,
так как язык описания регулярных выражений контекстно-свободен, а мы пока
можем разбирать только регулярные выражения.
Теперь напишем лексер.
Лексер будет разбирать одновременно несколько регулярных выражений
и возвращать выражение, которое первым сработает.
Лексер будет пытаться собрать как можно больше символов в одно регулярное выражение.
Создадим класс для лексера и помести его в
[lexer.Lexer](../projects/regexp/src/main/java/lexer/Lexer.java).
Также как и регулярные выражения, лексер будет читать символы типа `T`,
а переходы будет делать классам символов `P`.
Чтобы узнать, какую из лексем удалось собрать, мы будем помечать остановочные
состояния маркерами типа `F`.
```java
public class Lexer<T,F,P> {
```
Конструктор лексера будет принимать на вход готовые автоматы,
каждый из которых соответствует своей лексеме.
Остановочные состояния должны быть уже помечены своим маркером для каждой лексемы.
Конструктор построит собственный автомат `this.automaton` для лексера,
который будет простым объединением автоматов, которые мы уже можем строить
с помощью `Combinators.union`.
```java
private IDFA<T,F> automaton;
public Lexer(List<FSA<T,F,P>> lexemes) { ... }
```
В отличии от регулярного выражения мы будем хранить состояние автомата
внутри объекта для лексера.
Поэтому нам потребуется метод для перезапуска лексера,
если мы захочем разбирать новую строку.
```java
private State state;
public void reset() { ... };
```
Метод `reset` должен перезапускать автомат внутри лексера,
однако также его придется перезапускать и после выделения каждой лексемы.
Поэтому мы создадим специализиорованный метод для перезапуска автомата
при старте разбора новой лексемы.
```java
public void startNewToken() {
this.state=this.automaton.initialState();
...
}
```
Самый важный метод лексера `parse_symbol`, который отдает лексеру новый символ для разбора.
Может оказаться, что такой символ не может входить ни в одну из лексем,
в этом случае лексер выбросит исключение, для которого мы создали
собственный класс [lexer.LexerError](../projects/regexp/src/main/java/lexer/LexerError.java).
Чтобы собрать лексему, прочитанного символа может быть недостаточно,
тогда метод вернет `null`.
Если лексему удалось выделить, то метод должен вернуть маркер,
который сообщит нам какая лексема найдена, и подстроку,
которую удалось свернуть в лексему.
Для хранения этих значений мы создали специальный класс:
[lexer.LexerResult](../projects/regexp/src/main/java/lexer/LexerResult.java).
Заметим, что лексема выделяется, если новый символ в нее уже не удается добавить,
т.е. последний прочитанный символ будет началом новой лексемы.
```java
public LexerResult<T,F> parse_symbol(T symbol) throws LexerError { ... }
```
Когда разбираемая строка будет прочитана полностью,
может оказаться, что суффикс строки тоже формирует лексему,
которую мы однако не могли получить при вызове `parse_symbol`.
Поэтому нам потребуется аналогичный метод,
который должен вызываться в конце строки:
```java
public LexerResult<T,F> parse_eol() throws LexerError { ... }
```
Метод `parse_symbol` делает переход в автомате,
до тех пор, пока перехода по предлагаемому символу не окажется.
Если дальше переходи некуда, то оба метода `parse_symbol` и `parse_eol`
должны выяснить, является ли состояние остановочным,
и если да, то вернуть маркеры лексем.
Так как лексер получает символы по одному, а вернуть должен
подстроку, отвечающую лексеме, то лексер должен накапливать
эту подстроку в переменной, назовем ее `terminals`.
```java
private List<T> terminals;
```
Наконец, удобно иметь метод, который будет создавать по данному потоку
терминалов поток лексем.
Это избавит нас от необходимости многократно вызываться `parse_symbol`,
чтобы получить одну лексему.
Потоки мы будем передавать через итераторы, что дает большой простор для
конкретных реализаций.
```java
public<R extends LexerResult<T,F>> Iterator<R> parse(Iterable<T> input) throws LexerError { ... }
public<R extends LexerResult<T,F>> ILexerIterator<R> parseE(Iterable<T> input) throws LexerError { ... }
}
```
Стандартный интерфейс `java.util.Iterator` не может выбрасывать исключения,
мы же используем исключения для сообщений об ошибках,
поэтому мы создали собственный интерфейс итератора
[lexer.ILexerIterator](../projects/regexp/src/main/java/lexer/ILexerIterator.java)..
```java
public interface ILexerIterator<T> {
boolean hasNextE() throws LexerError;
T nextE() throws LexerError;
}
```
Класс [lexer.LexerResult](../projects/regexp/src/main/java/lexer/LexerResult.java).
для хранения результата позволяет вернуть лексему и соответствующую ей строку,
никаких других действий он не делает.
```java
public class LexerResult<T,F> {
LexerResult(List<T> string, F lexeme) { ... }
public List<T> getString() { ... }
public F getLexeme() { ... }
@Override public String toString() { ... }
@Override public boolean equals(Object obj) { ... };
private List<T> string;
private F lexeme;
}
```
Одной из важных задач синтаксического анализа текста является
обнаружение ошибок, о которых человеку нужно сообщить в понятных ему терминах.
В частности, человеку нужно сообщить место возникновения ошибки.
Обычно место ошибки задает номеро строки и столбца.
До сих пор мы не конкретизировали понятие терминала,
однако чтобы говорить о номере строки, необходимо
выделить среди нетерминалов символы перевода строки и т.п.
Мы создадим специальный класс
[lexer.CharLexer](../projects/regexp/src/main/java/lexer/CharLexer.java),
который расширяет
[lexer.Lexer](../projects/regexp/src/main/java/lexer/Lexer.java)
тем, что считает положение лексемы в файле,
но работает только с терминалами типа `UChar`.
```java
public class CharLexer<F,P> extends Lexer<UChar,F,P> {
public CharLexer(List<FSA<UChar,F,P>> lexemes) { ... }
public void reset() { ... };
@Override public CharLexerResult<F> parse_symbol(UChar symbol) throws CharLexerError { ... }
@Override public CharLexerResult<F> parse_eol() throws CharLexerError { ... }
private int currentLine;
private int currentColumn;
private int line;
private int column;
}
```
Класс `CharLexer` использует для лексического анализа методы своего
предка, однако дополнительно обновляет при каждом чтении символа
текущее положение `currentLine`, `currentColumn` в файле,
а при выделении лексемы обновляет положение начала лексемы
`line`, `column`.
Положение лексемы в файле лексер должен каким-либо образом вернуть,
для этого мы расширяем класс результата `LexerResult`,
добавляя в новый класс
[lexer.CharLexerResult](../projects/regexp/src/main/java/lexer/CharLexerResult.java),
поля для номера строки и столбца:
```java
public class CharLexerResult<F> extends LexerResult<UChar, F> {
CharLexerResult(List<UChar> string, F lexeme, int line, int column) { ... }
public int getLine() { ... }
public int getColumn() { ... }
@Override public boolean equals(Object obj) { ... };
@Override public String toString() { ... };
private int line;
private int column;
}
```
Наконец, исключение, выбрасываемое при ошибке лексического разбора,
должно содержать информацию о месте ошибки.
Поэтому наш новый лексер `CharLexer` выбрасывает расширение
исключения `LexerError`, которое назовем
[lexer.CharLexerError](../projects/regexp/src/main/java/lexer/CharLexerError.java).
```java
public class CharLexerError extends LexerError {
public CharLexerError(String message, int line, int column) { ... }
public CharLexerError(String message, Throwable throwable) { ... }
@Override public String getMessage() { ... };
private int line;
private int column;
}
```
Для проверки корректности работы автоматов и лексера
искользуются юнит-тесты, расположенные в поддиректориях
[test/java/*](../projects/regexp/test/java/).
Код юнит-тестов также дает использования наших класссов.
В качестве еще одного примера реализуем программу,
которая будет преобразовывать последовательность символов
на стандартном потоке ввода в последовательность лексем
для разбора регулярных выражений, которые будет записывать
в стандартный поток ввода.
```java
public class App {
```
Так как наш лексер работает с итераторами, а стандартные методы Java предпочитают
коллекции, то реализуем вспосогательные метод, собирающий все данные из
итератора в список.
```java
public static<T> List<T> asList(Iterator<T> src) { ... };
```
Создадим перечисление со списком всех токенов.
```java
enum Token {
LITERAL, STAR, PLUS, BEGIN, END, OR, OPTION, ANY;
}
```
Следующий метод возвращает лексер, который будет разпознавать символы,
имеющие особенный смысл внутри регулярных выражений, а остальные
будет запаковывать в `Token.LITERAL`.
Реализация метода активно использует реализованные нами нарее комбинаторы.
```java
static CharLexer<Token,UChar> makeLexer() {
Combinators<UChar,Token,UChar> combinators=new Combinators(new KeyPredicateMultiMap());
FSA<UChar,Token,UChar> star=combinators.literal(UChar.asList("*"),Token.STAR);
FSA<UChar,Token,UChar> plus=combinators.literal(UChar.asList("+"),Token.PLUS);
FSA<UChar,Token,UChar> option=combinators.literal(UChar.asList("?"),Token.OPTION);
FSA<UChar,Token,UChar> begin=combinators.literal(UChar.asList("("),Token.BEGIN);
FSA<UChar,Token,UChar> end=combinators.literal(UChar.asList(")"),Token.END);
FSA<UChar,Token,UChar> or=combinators.literal(UChar.asList("|"),Token.OR);
FSA<UChar,Token,UChar> any=combinators.literal(UChar.asList("."),Token.ANY);
HashSet<UChar> reserved=new HashSet(UChar.asList("*+?()|\\."));
HashSet<UChar> ordinary=new HashSet();
for(char c=32; c<127; c++) {
UChar uc=new UChar(c);
if(!reserved.contains(uc)) ordinary.add(uc);
};
FSA<UChar,Token,UChar> symbolOrdinary=combinators.anyOf(ordinary,Token.LITERAL);
FSA<UChar,Token,UChar> symbolEscaped=combinators.concatenation(Arrays.asList(
combinators.literal(UChar.asList("\\"),Token.LITERAL),
combinators.anyOf(reserved,Token.LITERAL)
));
FSA<UChar,Token,UChar> symbol=combinators.union(Arrays.asList(symbolOrdinary,symbolEscaped));
return new CharLexer(Arrays.asList(star, plus, option, begin, end, or, symbol, any));
};
```
Наконец реализуем входную точку в программу метод `main`,
который будет последовательно считывать из стандартного потока ввода
строку за строкой запускать на каждой строке лексер.
```java
public static void main(String[] args) throws IOException {
CharLexer<Token,UChar> lexer=makeLexer();
BufferedReader input=new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
String str;
System.out.println("Enter regexp:");
while((str=input.readLine())!=null) {
List<UChar> list=UChar.asList(str);
try {
ILexerIterator<LexerResult<UChar,Token>> iterator=lexer.parseE(list);
while(iterator.hasNextE())
System.out.println(iterator.nextE());
} catch(LexerError error) {
System.out.println(error);
};
}
}
}
```
-------
[Содержание](../tutorial/content.md)
[Лекция: Лексический анализатор](../tutorial/lexer.md)
|
{
"content_hash": "37bc775342d7a7358eab887cc5f52baf",
"timestamp": "",
"source": "github",
"line_count": 794,
"max_line_length": 108,
"avg_line_length": 37.10579345088161,
"alnum_prop": 0.7505261014187767,
"repo_name": "alepoydes/writing-compiler-for-neophytes",
"id": "b57b3d49eb1e77e356d559d93177091bad2239a7",
"size": "43318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lesson03/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "11408"
},
{
"name": "Assembly",
"bytes": "702"
},
{
"name": "C",
"bytes": "141"
},
{
"name": "Java",
"bytes": "200207"
},
{
"name": "Rust",
"bytes": "224"
},
{
"name": "Shell",
"bytes": "232"
}
],
"symlink_target": ""
}
|
<?php
namespace Daken\ReleaseProfilerBundle\PersistManager;
use Daken\ReleaseProfilerBundle\Entity\Request;
use Doctrine\ORM\EntityManagerInterface;
class DatabasePersistManager implements PersistManagerInterface
{
/** @var EntityManagerInterface */
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function persist(Request $request)
{
$this->em->persist($request);
$this->em->flush();
}
/**
* @return EntityManagerInterface
*/
public function getEntityManager()
{
return $this->em;
}
public function getPendingRequest($blockTime = null)
{
return null;
}
}
|
{
"content_hash": "ebca546047557e18e690ccdb3e44013e",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 63,
"avg_line_length": 19.756756756756758,
"alnum_prop": 0.6415868673050615,
"repo_name": "dakenf/ReleaseProfilerBundle",
"id": "cfc463a4cba009e4b00343ec4f5088f1b2aa7f38",
"size": "731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PersistManager/DatabasePersistManager.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "5484"
},
{
"name": "PHP",
"bytes": "82992"
}
],
"symlink_target": ""
}
|
// Get the selection type.
FCKSelection.GetType = function()
{
return FCK.EditorDocument.selection.type ;
} ;
// Retrieves the selected element (if any), just in the case that a single
// element (object like and image or a table) is selected.
FCKSelection.GetSelectedElement = function()
{
if ( this.GetType() == 'Control' )
{
var oRange = FCK.EditorDocument.selection.createRange() ;
if ( oRange && oRange.item )
return FCK.EditorDocument.selection.createRange().item(0) ;
}
return null ;
} ;
FCKSelection.GetParentElement = function()
{
switch ( this.GetType() )
{
case 'Control' :
return FCKSelection.GetSelectedElement().parentElement ;
case 'None' :
return null ;
default :
return FCK.EditorDocument.selection.createRange().parentElement() ;
}
} ;
FCKSelection.SelectNode = function( node )
{
FCK.Focus() ;
FCK.EditorDocument.selection.empty() ;
var oRange ;
try
{
// Try to select the node as a control.
oRange = FCK.EditorDocument.body.createControlRange() ;
oRange.addElement( node ) ;
}
catch(e)
{
// If failed, select it as a text range.
oRange = FCK.EditorDocument.body.createTextRange() ;
oRange.moveToElementText( node ) ;
}
oRange.select() ;
} ;
FCKSelection.Collapse = function( toStart )
{
FCK.Focus() ;
if ( this.GetType() == 'Text' )
{
var oRange = FCK.EditorDocument.selection.createRange() ;
oRange.collapse( toStart == null || toStart === true ) ;
oRange.select() ;
}
} ;
// The "nodeTagName" parameter must be Upper Case.
FCKSelection.HasAncestorNode = function( nodeTagName )
{
var oContainer ;
if ( FCK.EditorDocument.selection.type == "Control" )
{
oContainer = this.GetSelectedElement() ;
}
else
{
var oRange = FCK.EditorDocument.selection.createRange() ;
oContainer = oRange.parentElement() ;
}
while ( oContainer )
{
if ( oContainer.tagName == nodeTagName ) return true ;
oContainer = oContainer.parentNode ;
}
return false ;
} ;
// The "nodeTagName" parameter must be UPPER CASE.
FCKSelection.MoveToAncestorNode = function( nodeTagName )
{
var oNode, oRange ;
if ( ! FCK.EditorDocument )
return null ;
if ( FCK.EditorDocument.selection.type == "Control" )
{
oRange = FCK.EditorDocument.selection.createRange() ;
for ( i = 0 ; i < oRange.length ; i++ )
{
if (oRange(i).parentNode)
{
oNode = oRange(i).parentNode ;
break ;
}
}
}
else
{
oRange = FCK.EditorDocument.selection.createRange() ;
oNode = oRange.parentElement() ;
}
while ( oNode && oNode.nodeName != nodeTagName )
oNode = oNode.parentNode ;
return oNode ;
} ;
FCKSelection.Delete = function()
{
// Gets the actual selection.
var oSel = FCK.EditorDocument.selection ;
// Deletes the actual selection contents.
if ( oSel.type.toLowerCase() != "none" )
{
oSel.clear() ;
}
return oSel ;
} ;
|
{
"content_hash": "18d9b762a946e8b7d46e7c73b2a81d6f",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 74,
"avg_line_length": 20.543478260869566,
"alnum_prop": 0.6758377425044092,
"repo_name": "viollarr/henriquecursos",
"id": "7e6b21f757200fa732b8675ef17338da177ad9c7",
"size": "3506",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "site/js/editor/_source/internals/fckselection_ie.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "99461"
},
{
"name": "CSS",
"bytes": "187517"
},
{
"name": "ColdFusion",
"bytes": "92513"
},
{
"name": "JavaScript",
"bytes": "3546280"
},
{
"name": "Lasso",
"bytes": "55654"
},
{
"name": "PHP",
"bytes": "2122260"
},
{
"name": "Perl",
"bytes": "69490"
},
{
"name": "Python",
"bytes": "55062"
}
],
"symlink_target": ""
}
|
package com.tinkerpop.blueprints.oupls.sail;
import static org.junit.Assert.assertTrue;
/**
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class OrientGraphSailTest {//extends GraphSailTest {
public void testTrue() {
assertTrue(true);
}
/*
public KeyIndexableGraph createGraph() {
String directory = getWorkingDirectory();
OrientGraph g = new OrientGraph("local:" + directory + "/graph");
return g;
}
private String getWorkingDirectory() {
return this.computeTestDataRoot().getAbsolutePath();
}
//*/
}
|
{
"content_hash": "8ebf5b286525837e03a4a322001f639d",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 73,
"avg_line_length": 22.846153846153847,
"alnum_prop": 0.6531986531986532,
"repo_name": "datablend/blueprints",
"id": "5c9e6ad50a765708316410da3eca06a4f66841ba",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blueprints-graph-sail/src/test/java/com/tinkerpop/blueprints/oupls/sail/OrientGraphSailTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1308002"
}
],
"symlink_target": ""
}
|
package com.amazonaws.services.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a bundle, which is a set of specs describing your virtual private server (or <i>instance</i>).
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/Bundle" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Bundle implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
* </p>
*/
private Float price;
/**
* <p>
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
* </p>
*/
private Integer cpuCount;
/**
* <p>
* The size of the SSD (e.g., <code>30</code>).
* </p>
*/
private Integer diskSizeInGb;
/**
* <p>
* The bundle ID (e.g., <code>micro_1_0</code>).
* </p>
*/
private String bundleId;
/**
* <p>
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
* </p>
*/
private String instanceType;
/**
* <p>
* A Boolean value indicating whether the bundle is active.
* </p>
*/
private Boolean isActive;
/**
* <p>
* A friendly name for the bundle (e.g., <code>Micro</code>).
* </p>
*/
private String name;
/**
* <p>
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's power
* value in conjunction with a blueprint's minimum power value to determine whether the blueprint will run on the
* bundle. For example, you need a bundle with a power value of 500 or more to create an instance that uses a
* blueprint with a minimum power value of 500.
* </p>
*/
private Integer power;
/**
* <p>
* The amount of RAM in GB (e.g., <code>2.0</code>).
* </p>
*/
private Float ramSizeInGb;
/**
* <p>
* The data transfer rate per month in GB (e.g., <code>2000</code>).
* </p>
*/
private Integer transferPerMonthInGb;
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
*/
private java.util.List<String> supportedPlatforms;
/**
* <p>
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
* </p>
*
* @param price
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
*/
public void setPrice(Float price) {
this.price = price;
}
/**
* <p>
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
* </p>
*
* @return The price in US dollars (e.g., <code>5.0</code>) of the bundle.
*/
public Float getPrice() {
return this.price;
}
/**
* <p>
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
* </p>
*
* @param price
* The price in US dollars (e.g., <code>5.0</code>) of the bundle.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withPrice(Float price) {
setPrice(price);
return this;
}
/**
* <p>
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
* </p>
*
* @param cpuCount
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
*/
public void setCpuCount(Integer cpuCount) {
this.cpuCount = cpuCount;
}
/**
* <p>
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
* </p>
*
* @return The number of vCPUs included in the bundle (e.g., <code>2</code>).
*/
public Integer getCpuCount() {
return this.cpuCount;
}
/**
* <p>
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
* </p>
*
* @param cpuCount
* The number of vCPUs included in the bundle (e.g., <code>2</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withCpuCount(Integer cpuCount) {
setCpuCount(cpuCount);
return this;
}
/**
* <p>
* The size of the SSD (e.g., <code>30</code>).
* </p>
*
* @param diskSizeInGb
* The size of the SSD (e.g., <code>30</code>).
*/
public void setDiskSizeInGb(Integer diskSizeInGb) {
this.diskSizeInGb = diskSizeInGb;
}
/**
* <p>
* The size of the SSD (e.g., <code>30</code>).
* </p>
*
* @return The size of the SSD (e.g., <code>30</code>).
*/
public Integer getDiskSizeInGb() {
return this.diskSizeInGb;
}
/**
* <p>
* The size of the SSD (e.g., <code>30</code>).
* </p>
*
* @param diskSizeInGb
* The size of the SSD (e.g., <code>30</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withDiskSizeInGb(Integer diskSizeInGb) {
setDiskSizeInGb(diskSizeInGb);
return this;
}
/**
* <p>
* The bundle ID (e.g., <code>micro_1_0</code>).
* </p>
*
* @param bundleId
* The bundle ID (e.g., <code>micro_1_0</code>).
*/
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
/**
* <p>
* The bundle ID (e.g., <code>micro_1_0</code>).
* </p>
*
* @return The bundle ID (e.g., <code>micro_1_0</code>).
*/
public String getBundleId() {
return this.bundleId;
}
/**
* <p>
* The bundle ID (e.g., <code>micro_1_0</code>).
* </p>
*
* @param bundleId
* The bundle ID (e.g., <code>micro_1_0</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withBundleId(String bundleId) {
setBundleId(bundleId);
return this;
}
/**
* <p>
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
* </p>
*
* @param instanceType
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
*/
public void setInstanceType(String instanceType) {
this.instanceType = instanceType;
}
/**
* <p>
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
* </p>
*
* @return The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
*/
public String getInstanceType() {
return this.instanceType;
}
/**
* <p>
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
* </p>
*
* @param instanceType
* The Amazon EC2 instance type (e.g., <code>t2.micro</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withInstanceType(String instanceType) {
setInstanceType(instanceType);
return this;
}
/**
* <p>
* A Boolean value indicating whether the bundle is active.
* </p>
*
* @param isActive
* A Boolean value indicating whether the bundle is active.
*/
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
/**
* <p>
* A Boolean value indicating whether the bundle is active.
* </p>
*
* @return A Boolean value indicating whether the bundle is active.
*/
public Boolean getIsActive() {
return this.isActive;
}
/**
* <p>
* A Boolean value indicating whether the bundle is active.
* </p>
*
* @param isActive
* A Boolean value indicating whether the bundle is active.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withIsActive(Boolean isActive) {
setIsActive(isActive);
return this;
}
/**
* <p>
* A Boolean value indicating whether the bundle is active.
* </p>
*
* @return A Boolean value indicating whether the bundle is active.
*/
public Boolean isActive() {
return this.isActive;
}
/**
* <p>
* A friendly name for the bundle (e.g., <code>Micro</code>).
* </p>
*
* @param name
* A friendly name for the bundle (e.g., <code>Micro</code>).
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* A friendly name for the bundle (e.g., <code>Micro</code>).
* </p>
*
* @return A friendly name for the bundle (e.g., <code>Micro</code>).
*/
public String getName() {
return this.name;
}
/**
* <p>
* A friendly name for the bundle (e.g., <code>Micro</code>).
* </p>
*
* @param name
* A friendly name for the bundle (e.g., <code>Micro</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withName(String name) {
setName(name);
return this;
}
/**
* <p>
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's power
* value in conjunction with a blueprint's minimum power value to determine whether the blueprint will run on the
* bundle. For example, you need a bundle with a power value of 500 or more to create an instance that uses a
* blueprint with a minimum power value of 500.
* </p>
*
* @param power
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's
* power value in conjunction with a blueprint's minimum power value to determine whether the blueprint will
* run on the bundle. For example, you need a bundle with a power value of 500 or more to create an instance
* that uses a blueprint with a minimum power value of 500.
*/
public void setPower(Integer power) {
this.power = power;
}
/**
* <p>
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's power
* value in conjunction with a blueprint's minimum power value to determine whether the blueprint will run on the
* bundle. For example, you need a bundle with a power value of 500 or more to create an instance that uses a
* blueprint with a minimum power value of 500.
* </p>
*
* @return A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the
* bundle's power value in conjunction with a blueprint's minimum power value to determine whether the
* blueprint will run on the bundle. For example, you need a bundle with a power value of 500 or more to
* create an instance that uses a blueprint with a minimum power value of 500.
*/
public Integer getPower() {
return this.power;
}
/**
* <p>
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's power
* value in conjunction with a blueprint's minimum power value to determine whether the blueprint will run on the
* bundle. For example, you need a bundle with a power value of 500 or more to create an instance that uses a
* blueprint with a minimum power value of 500.
* </p>
*
* @param power
* A numeric value that represents the power of the bundle (e.g., <code>500</code>). You can use the bundle's
* power value in conjunction with a blueprint's minimum power value to determine whether the blueprint will
* run on the bundle. For example, you need a bundle with a power value of 500 or more to create an instance
* that uses a blueprint with a minimum power value of 500.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withPower(Integer power) {
setPower(power);
return this;
}
/**
* <p>
* The amount of RAM in GB (e.g., <code>2.0</code>).
* </p>
*
* @param ramSizeInGb
* The amount of RAM in GB (e.g., <code>2.0</code>).
*/
public void setRamSizeInGb(Float ramSizeInGb) {
this.ramSizeInGb = ramSizeInGb;
}
/**
* <p>
* The amount of RAM in GB (e.g., <code>2.0</code>).
* </p>
*
* @return The amount of RAM in GB (e.g., <code>2.0</code>).
*/
public Float getRamSizeInGb() {
return this.ramSizeInGb;
}
/**
* <p>
* The amount of RAM in GB (e.g., <code>2.0</code>).
* </p>
*
* @param ramSizeInGb
* The amount of RAM in GB (e.g., <code>2.0</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withRamSizeInGb(Float ramSizeInGb) {
setRamSizeInGb(ramSizeInGb);
return this;
}
/**
* <p>
* The data transfer rate per month in GB (e.g., <code>2000</code>).
* </p>
*
* @param transferPerMonthInGb
* The data transfer rate per month in GB (e.g., <code>2000</code>).
*/
public void setTransferPerMonthInGb(Integer transferPerMonthInGb) {
this.transferPerMonthInGb = transferPerMonthInGb;
}
/**
* <p>
* The data transfer rate per month in GB (e.g., <code>2000</code>).
* </p>
*
* @return The data transfer rate per month in GB (e.g., <code>2000</code>).
*/
public Integer getTransferPerMonthInGb() {
return this.transferPerMonthInGb;
}
/**
* <p>
* The data transfer rate per month in GB (e.g., <code>2000</code>).
* </p>
*
* @param transferPerMonthInGb
* The data transfer rate per month in GB (e.g., <code>2000</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Bundle withTransferPerMonthInGb(Integer transferPerMonthInGb) {
setTransferPerMonthInGb(transferPerMonthInGb);
return this;
}
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
*
* @return The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You
* can only launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code>
* platform. <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* @see InstancePlatform
*/
public java.util.List<String> getSupportedPlatforms() {
return supportedPlatforms;
}
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
*
* @param supportedPlatforms
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can
* only launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* @see InstancePlatform
*/
public void setSupportedPlatforms(java.util.Collection<String> supportedPlatforms) {
if (supportedPlatforms == null) {
this.supportedPlatforms = null;
return;
}
this.supportedPlatforms = new java.util.ArrayList<String>(supportedPlatforms);
}
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSupportedPlatforms(java.util.Collection)} or {@link #withSupportedPlatforms(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param supportedPlatforms
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can
* only launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InstancePlatform
*/
public Bundle withSupportedPlatforms(String... supportedPlatforms) {
if (this.supportedPlatforms == null) {
setSupportedPlatforms(new java.util.ArrayList<String>(supportedPlatforms.length));
}
for (String ele : supportedPlatforms) {
this.supportedPlatforms.add(ele);
}
return this;
}
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
*
* @param supportedPlatforms
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can
* only launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InstancePlatform
*/
public Bundle withSupportedPlatforms(java.util.Collection<String> supportedPlatforms) {
setSupportedPlatforms(supportedPlatforms);
return this;
}
/**
* <p>
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can only
* launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* </p>
*
* @param supportedPlatforms
* The operating system platform (Linux/Unix-based or Windows Server-based) that the bundle supports. You can
* only launch a <code>WINDOWS</code> bundle on a blueprint that supports the <code>WINDOWS</code> platform.
* <code>LINUX_UNIX</code> blueprints require a <code>LINUX_UNIX</code> bundle.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InstancePlatform
*/
public Bundle withSupportedPlatforms(InstancePlatform... supportedPlatforms) {
java.util.ArrayList<String> supportedPlatformsCopy = new java.util.ArrayList<String>(supportedPlatforms.length);
for (InstancePlatform value : supportedPlatforms) {
supportedPlatformsCopy.add(value.toString());
}
if (getSupportedPlatforms() == null) {
setSupportedPlatforms(supportedPlatformsCopy);
} else {
getSupportedPlatforms().addAll(supportedPlatformsCopy);
}
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getPrice() != null)
sb.append("Price: ").append(getPrice()).append(",");
if (getCpuCount() != null)
sb.append("CpuCount: ").append(getCpuCount()).append(",");
if (getDiskSizeInGb() != null)
sb.append("DiskSizeInGb: ").append(getDiskSizeInGb()).append(",");
if (getBundleId() != null)
sb.append("BundleId: ").append(getBundleId()).append(",");
if (getInstanceType() != null)
sb.append("InstanceType: ").append(getInstanceType()).append(",");
if (getIsActive() != null)
sb.append("IsActive: ").append(getIsActive()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getPower() != null)
sb.append("Power: ").append(getPower()).append(",");
if (getRamSizeInGb() != null)
sb.append("RamSizeInGb: ").append(getRamSizeInGb()).append(",");
if (getTransferPerMonthInGb() != null)
sb.append("TransferPerMonthInGb: ").append(getTransferPerMonthInGb()).append(",");
if (getSupportedPlatforms() != null)
sb.append("SupportedPlatforms: ").append(getSupportedPlatforms());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Bundle == false)
return false;
Bundle other = (Bundle) obj;
if (other.getPrice() == null ^ this.getPrice() == null)
return false;
if (other.getPrice() != null && other.getPrice().equals(this.getPrice()) == false)
return false;
if (other.getCpuCount() == null ^ this.getCpuCount() == null)
return false;
if (other.getCpuCount() != null && other.getCpuCount().equals(this.getCpuCount()) == false)
return false;
if (other.getDiskSizeInGb() == null ^ this.getDiskSizeInGb() == null)
return false;
if (other.getDiskSizeInGb() != null && other.getDiskSizeInGb().equals(this.getDiskSizeInGb()) == false)
return false;
if (other.getBundleId() == null ^ this.getBundleId() == null)
return false;
if (other.getBundleId() != null && other.getBundleId().equals(this.getBundleId()) == false)
return false;
if (other.getInstanceType() == null ^ this.getInstanceType() == null)
return false;
if (other.getInstanceType() != null && other.getInstanceType().equals(this.getInstanceType()) == false)
return false;
if (other.getIsActive() == null ^ this.getIsActive() == null)
return false;
if (other.getIsActive() != null && other.getIsActive().equals(this.getIsActive()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getPower() == null ^ this.getPower() == null)
return false;
if (other.getPower() != null && other.getPower().equals(this.getPower()) == false)
return false;
if (other.getRamSizeInGb() == null ^ this.getRamSizeInGb() == null)
return false;
if (other.getRamSizeInGb() != null && other.getRamSizeInGb().equals(this.getRamSizeInGb()) == false)
return false;
if (other.getTransferPerMonthInGb() == null ^ this.getTransferPerMonthInGb() == null)
return false;
if (other.getTransferPerMonthInGb() != null && other.getTransferPerMonthInGb().equals(this.getTransferPerMonthInGb()) == false)
return false;
if (other.getSupportedPlatforms() == null ^ this.getSupportedPlatforms() == null)
return false;
if (other.getSupportedPlatforms() != null && other.getSupportedPlatforms().equals(this.getSupportedPlatforms()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getPrice() == null) ? 0 : getPrice().hashCode());
hashCode = prime * hashCode + ((getCpuCount() == null) ? 0 : getCpuCount().hashCode());
hashCode = prime * hashCode + ((getDiskSizeInGb() == null) ? 0 : getDiskSizeInGb().hashCode());
hashCode = prime * hashCode + ((getBundleId() == null) ? 0 : getBundleId().hashCode());
hashCode = prime * hashCode + ((getInstanceType() == null) ? 0 : getInstanceType().hashCode());
hashCode = prime * hashCode + ((getIsActive() == null) ? 0 : getIsActive().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getPower() == null) ? 0 : getPower().hashCode());
hashCode = prime * hashCode + ((getRamSizeInGb() == null) ? 0 : getRamSizeInGb().hashCode());
hashCode = prime * hashCode + ((getTransferPerMonthInGb() == null) ? 0 : getTransferPerMonthInGb().hashCode());
hashCode = prime * hashCode + ((getSupportedPlatforms() == null) ? 0 : getSupportedPlatforms().hashCode());
return hashCode;
}
@Override
public Bundle clone() {
try {
return (Bundle) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lightsail.model.transform.BundleMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
{
"content_hash": "aa07532b086f41eba49f9924cd3f5c24",
"timestamp": "",
"source": "github",
"line_count": 768,
"max_line_length": 137,
"avg_line_length": 35.10546875,
"alnum_prop": 0.5966024999072734,
"repo_name": "aws/aws-sdk-java",
"id": "e0bb93385a65118ebdf13c2bdc9071450bf51d4e",
"size": "27541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/Bundle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
from __future__ import absolute_import
from __future__ import unicode_literals
from past.builtins import basestring
from builtins import object
from future import standard_library
standard_library.install_aliases()
from ..exceptions import IllegalArgumentException
from ..model import URI, ValueFactory
from .repositoryconnection import RepositoryConnection
from ..vocabulary.xmlschema import XMLSchema
import re
class Repository(object):
"""
A repository contains RDF data that can be queried and updated. Access
to the repository can be acquired by opening a connection to it. This
connection can then be used to query and/or update the contents of the
repository.
Please note that a repository needs to be initialized before it can be
used and that it should be shut down before it is discarded/garbage
collected. Forgetting the latter can result in loss of data (depending
on the Repository implementation)!
"""
# Modes for Catalog.getRepository()
RENEW = 'RENEW'
ACCESS = 'ACCESS'
OPEN = 'OPEN'
CREATE = 'CREATE'
REPLACE = 'REPLACE'
def __init__(self, catalog, database_name, repository):
"""
Invoke through :meth:`~franz.openrdf.sail.allegrographserver.Catalog.getRepository`.
"""
self.mini_repository = repository
self.database_name = database_name
self.catalog = catalog
# system state fields:
self.value_factory = None
def getDatabaseName(self):
"""
Return the name of the database (remote triple store) that this repository is
interfacing with.
"""
return self.database_name
def getSpec(self):
"""
Return a session spec string for this repository.
See :meth:`~franz.openrdf.sail.allegrographserver.AllegroGraphServer.openSession`.
:return: A session spec.
:rtype: string
"""
mini = self.mini_repository
urlstart = re.match("^https?://", mini.url).group(0)
url = "<%s%s:%s@%s>" % (urlstart, mini.user, mini.password,
mini.url[len(urlstart):])
return url
def initialize(self):
"""
Initializes this repository. A repository must be initialized before
it can be used.
It is recommended to take advantage of the fact that repositories
are context managers and use the ``with`` statement to ensure that
:meth:`initialize` and :meth:`shutDown` are called:
.. code:: python
with catalog.getRepository() as repo:
# No need to call initialize or shutDown inside.
...
:return: ``self`` (to allow call chaining).
"""
# We've only kept this method for RDF4J compatibility, we do not actually
# need to do anything here.
return self
def registerDatatypeMapping(self, predicate=None, datatype=None, nativeType=None):
"""
Register an inlined datatype.
This allows some literals to be stored in an optimized form
on the server.
.. seealso::
http://franz.com/agraph/support/documentation/current/lisp-reference.html#ref-type-mapping
More detailed discussion of type mappings in the Lisp API documentation.
You must supply ``nativeType`` and either ``predicate`` or ``datatype``.
If ``predicate`` is supplied, then object arguments to triples with that
predicate will use an inlined encoding of type `nativeType` in their internal
representation on the server.
If ``datatype`` is supplied, then typed literal objects with a datatype matching
``datatype`` will use an inlined encoding of type `nativeType`.
Duplicated in the :class:`.RepositoryConnection` class for Python user convenience.
:param predicate: The URI of a predicate used in the triple store.
:param datatype: May be one of: ``XMLSchema.INT``, ``XMLSchema.LONG``,
``XMLSchema.FLOAT``, ``XMLSchema.DATE`` and ``XMLSchema.DATETIME``.
:param nativeType: may be ``int``, ``datetime``, or ``float``.
:type nativeType: string|type
"""
predicate = predicate.getURI() if isinstance(predicate, URI) else predicate
datatype = datatype.getURI() if isinstance(datatype, URI) else datatype
if nativeType is not None and not isinstance(nativeType, basestring):
nativeType=nativeType.__name__
def translate_inlined_type(the_type):
if the_type == 'int':
return XMLSchema.LONG.toNTriples()
if the_type == 'datetime':
return XMLSchema.DATETIME.toNTriples()
if the_type == 'time':
return XMLSchema.TIME.toNTriples()
if the_type == 'date':
return XMLSchema.DATE.toNTriples()
if the_type == "float":
return XMLSchema.DOUBLE.toNTriples()
if the_type == "bool":
return XMLSchema.BOOLEAN.toNTriples()
raise IllegalArgumentException("Unknown inlined type '%s'\n. Legal types are "\
"int, float, bool, datetime, time, and date." % the_type)
if predicate:
if not nativeType:
raise IllegalArgumentException("Missing 'nativeType' parameter in call to 'registerDatatypeMapping'")
xsdType = translate_inlined_type(nativeType)
self.mini_repository.addMappedPredicate("<%s>" % predicate, xsdType)
elif datatype:
xsdType = translate_inlined_type(nativeType or datatype)
self.mini_repository.addMappedType("<%s>" % datatype, xsdType)
def shutDown(self):
"""
Shuts the store down, releasing any resources that it keeps hold of.
Once shut down, the store can no longer be used.
It is recommended to take advantage of the fact that repositories
are context managers and use the ``with`` statement to ensure that
:meth:`initialize` and :meth:`shutDown` are called:
.. code:: python
with catalog.getRepository() as repo:
# No need to call initialize or shutDown inside.
...
"""
self.mini_repository = None
def isWritable(self):
"""
Checks whether this store is writable, i.e. if the data contained in
this store can be changed. The writability of the store is
determined by the writability of the Sail that this store operates
on.
"""
# TODO maybe remove this, it's nonsense in 4.0.
return True
def getConnection(self):
"""
Opens a connection to this store that can be used for querying and
updating the contents of the store. Created connections need to be
closed to make sure that any resources they keep hold of are released.
The best way to ensure this is to use a ``with`` statement:
.. code:: python
with repo.getConnection() as conn:
...
:return: A :class:`RepositoryConnection` object.
:rtype: RepositoryConnection
"""
return RepositoryConnection(self)
def getValueFactory(self):
"""
Return a ValueFactory for this store.
This is present for RDF4J compatibility, but in the Python API all ValueFactory
functionality has been duplicated or subsumed in the :class:`.RepositoryConnection` class.
It isn't necessary to manipulate the :class:`.ValueFactory` class at all.
:return: A ValueFactory instance.
:rtype: ValueFactory
"""
if not self.value_factory:
self.value_factory = ValueFactory(self)
return self.value_factory
def _set_bulk_mode(self, on):
self.mini_repository.setBulkMode(on)
def _get_bulk_mode(self):
return self.mini_repository.getBulkMode()
bulk_mode = property(
_get_bulk_mode, _set_bulk_mode,
doc="""Turn BulkMode on with True or off with False.
In bulk mode, all modifications to the triple-store are made without
writing to the transaction log. There is overhead to switching
in and out of bulk-mode, and it is a global repository state, so all
clients are affected.""")
def __enter__(self):
self.initialize()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
del exc_type, exc_val, exc_tb
self.shutDown()
|
{
"content_hash": "0b1a31070eb66acaef2f5554f1adeaeb",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 117,
"avg_line_length": 37.833333333333336,
"alnum_prop": 0.6283329469047066,
"repo_name": "franzinc/agraph-python",
"id": "ceb79bce79a1e571fc97f39eb019f6148c7e50e0",
"size": "9120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/franz/openrdf/repository/repository.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "250"
},
{
"name": "Java",
"bytes": "320101"
},
{
"name": "Makefile",
"bytes": "10632"
},
{
"name": "Python",
"bytes": "660320"
},
{
"name": "Shell",
"bytes": "8614"
}
],
"symlink_target": ""
}
|
"""
Unit tests for PySpark; additional tests are implemented as doctests in
individual modules.
"""
from array import array
from glob import glob
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
import random
import threading
import hashlib
from py4j.protocol import Py4JJavaError
if sys.version_info[:2] <= (2, 6):
try:
import unittest2 as unittest
except ImportError:
sys.stderr.write('Please install unittest2 to test with Python 2.6 or earlier')
sys.exit(1)
else:
import unittest
if sys.version_info[0] >= 3:
xrange = range
basestring = str
if sys.version >= "3":
from io import StringIO
else:
from StringIO import StringIO
from pyspark.conf import SparkConf
from pyspark.context import SparkContext
from pyspark.rdd import RDD
from pyspark.files import SparkFiles
from pyspark.serializers import read_int, BatchedSerializer, MarshalSerializer, PickleSerializer, \
CloudPickleSerializer, CompressedSerializer, UTF8Deserializer, NoOpSerializer, \
PairDeserializer, CartesianDeserializer, AutoBatchedSerializer, AutoSerializer, \
FlattenedValuesSerializer
from pyspark.shuffle import Aggregator, ExternalMerger, ExternalSorter
from pyspark import shuffle
from pyspark.profiler import BasicProfiler
_have_scipy = False
_have_numpy = False
try:
import scipy.sparse
_have_scipy = True
except:
# No SciPy, but that's okay, we'll skip those tests
pass
try:
import numpy as np
_have_numpy = True
except:
# No NumPy, but that's okay, we'll skip those tests
pass
SPARK_HOME = os.environ["SPARK_HOME"]
class MergerTests(unittest.TestCase):
def setUp(self):
self.N = 1 << 12
self.l = [i for i in xrange(self.N)]
self.data = list(zip(self.l, self.l))
self.agg = Aggregator(lambda x: [x],
lambda x, y: x.append(y) or x,
lambda x, y: x.extend(y) or x)
def test_small_dataset(self):
m = ExternalMerger(self.agg, 1000)
m.mergeValues(self.data)
self.assertEqual(m.spills, 0)
self.assertEqual(sum(sum(v) for k, v in m.items()),
sum(xrange(self.N)))
m = ExternalMerger(self.agg, 1000)
m.mergeCombiners(map(lambda x_y1: (x_y1[0], [x_y1[1]]), self.data))
self.assertEqual(m.spills, 0)
self.assertEqual(sum(sum(v) for k, v in m.items()),
sum(xrange(self.N)))
def test_medium_dataset(self):
m = ExternalMerger(self.agg, 20)
m.mergeValues(self.data)
self.assertTrue(m.spills >= 1)
self.assertEqual(sum(sum(v) for k, v in m.items()),
sum(xrange(self.N)))
m = ExternalMerger(self.agg, 10)
m.mergeCombiners(map(lambda x_y2: (x_y2[0], [x_y2[1]]), self.data * 3))
self.assertTrue(m.spills >= 1)
self.assertEqual(sum(sum(v) for k, v in m.items()),
sum(xrange(self.N)) * 3)
def test_huge_dataset(self):
m = ExternalMerger(self.agg, 5, partitions=3)
m.mergeCombiners(map(lambda k_v: (k_v[0], [str(k_v[1])]), self.data * 10))
self.assertTrue(m.spills >= 1)
self.assertEqual(sum(len(v) for k, v in m.items()),
self.N * 10)
m._cleanup()
def test_group_by_key(self):
def gen_data(N, step):
for i in range(1, N + 1, step):
for j in range(i):
yield (i, [j])
def gen_gs(N, step=1):
return shuffle.GroupByKey(gen_data(N, step))
self.assertEqual(1, len(list(gen_gs(1))))
self.assertEqual(2, len(list(gen_gs(2))))
self.assertEqual(100, len(list(gen_gs(100))))
self.assertEqual(list(range(1, 101)), [k for k, _ in gen_gs(100)])
self.assertTrue(all(list(range(k)) == list(vs) for k, vs in gen_gs(100)))
for k, vs in gen_gs(50002, 10000):
self.assertEqual(k, len(vs))
self.assertEqual(list(range(k)), list(vs))
ser = PickleSerializer()
l = ser.loads(ser.dumps(list(gen_gs(50002, 30000))))
for k, vs in l:
self.assertEqual(k, len(vs))
self.assertEqual(list(range(k)), list(vs))
class SorterTests(unittest.TestCase):
def test_in_memory_sort(self):
l = list(range(1024))
random.shuffle(l)
sorter = ExternalSorter(1024)
self.assertEqual(sorted(l), list(sorter.sorted(l)))
self.assertEqual(sorted(l, reverse=True), list(sorter.sorted(l, reverse=True)))
self.assertEqual(sorted(l, key=lambda x: -x), list(sorter.sorted(l, key=lambda x: -x)))
self.assertEqual(sorted(l, key=lambda x: -x, reverse=True),
list(sorter.sorted(l, key=lambda x: -x, reverse=True)))
def test_external_sort(self):
class CustomizedSorter(ExternalSorter):
def _next_limit(self):
return self.memory_limit
l = list(range(1024))
random.shuffle(l)
sorter = CustomizedSorter(1)
self.assertEqual(sorted(l), list(sorter.sorted(l)))
self.assertGreater(shuffle.DiskBytesSpilled, 0)
last = shuffle.DiskBytesSpilled
self.assertEqual(sorted(l, reverse=True), list(sorter.sorted(l, reverse=True)))
self.assertGreater(shuffle.DiskBytesSpilled, last)
last = shuffle.DiskBytesSpilled
self.assertEqual(sorted(l, key=lambda x: -x), list(sorter.sorted(l, key=lambda x: -x)))
self.assertGreater(shuffle.DiskBytesSpilled, last)
last = shuffle.DiskBytesSpilled
self.assertEqual(sorted(l, key=lambda x: -x, reverse=True),
list(sorter.sorted(l, key=lambda x: -x, reverse=True)))
self.assertGreater(shuffle.DiskBytesSpilled, last)
def test_external_sort_in_rdd(self):
conf = SparkConf().set("spark.python.worker.memory", "1m")
sc = SparkContext(conf=conf)
l = list(range(10240))
random.shuffle(l)
rdd = sc.parallelize(l, 4)
self.assertEqual(sorted(l), rdd.sortBy(lambda x: x).collect())
sc.stop()
class SerializationTestCase(unittest.TestCase):
def test_namedtuple(self):
from collections import namedtuple
from pickle import dumps, loads
P = namedtuple("P", "x y")
p1 = P(1, 3)
p2 = loads(dumps(p1, 2))
self.assertEqual(p1, p2)
from pyspark.cloudpickle import dumps
P2 = loads(dumps(P))
p3 = P2(1, 3)
self.assertEqual(p1, p3)
def test_itemgetter(self):
from operator import itemgetter
ser = CloudPickleSerializer()
d = range(10)
getter = itemgetter(1)
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
getter = itemgetter(0, 3)
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
def test_attrgetter(self):
from operator import attrgetter
ser = CloudPickleSerializer()
class C(object):
def __getattr__(self, item):
return item
d = C()
getter = attrgetter("a")
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
getter = attrgetter("a", "b")
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
d.e = C()
getter = attrgetter("e.a")
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
getter = attrgetter("e.a", "e.b")
getter2 = ser.loads(ser.dumps(getter))
self.assertEqual(getter(d), getter2(d))
# Regression test for SPARK-3415
def test_pickling_file_handles(self):
ser = CloudPickleSerializer()
out1 = sys.stderr
out2 = ser.loads(ser.dumps(out1))
self.assertEqual(out1, out2)
def test_func_globals(self):
class Unpicklable(object):
def __reduce__(self):
raise Exception("not picklable")
global exit
exit = Unpicklable()
ser = CloudPickleSerializer()
self.assertRaises(Exception, lambda: ser.dumps(exit))
def foo():
sys.exit(0)
self.assertTrue("exit" in foo.__code__.co_names)
ser.dumps(foo)
def test_compressed_serializer(self):
ser = CompressedSerializer(PickleSerializer())
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
io = StringIO()
ser.dump_stream(["abc", u"123", range(5)], io)
io.seek(0)
self.assertEqual(["abc", u"123", range(5)], list(ser.load_stream(io)))
ser.dump_stream(range(1000), io)
io.seek(0)
self.assertEqual(["abc", u"123", range(5)] + list(range(1000)), list(ser.load_stream(io)))
io.close()
def test_hash_serializer(self):
hash(NoOpSerializer())
hash(UTF8Deserializer())
hash(PickleSerializer())
hash(MarshalSerializer())
hash(AutoSerializer())
hash(BatchedSerializer(PickleSerializer()))
hash(AutoBatchedSerializer(MarshalSerializer()))
hash(PairDeserializer(NoOpSerializer(), UTF8Deserializer()))
hash(CartesianDeserializer(NoOpSerializer(), UTF8Deserializer()))
hash(CompressedSerializer(PickleSerializer()))
hash(FlattenedValuesSerializer(PickleSerializer()))
class QuietTest(object):
def __init__(self, sc):
self.log4j = sc._jvm.org.apache.log4j
def __enter__(self):
self.old_level = self.log4j.LogManager.getRootLogger().getLevel()
self.log4j.LogManager.getRootLogger().setLevel(self.log4j.Level.FATAL)
def __exit__(self, exc_type, exc_val, exc_tb):
self.log4j.LogManager.getRootLogger().setLevel(self.old_level)
class PySparkTestCase(unittest.TestCase):
def setUp(self):
self._old_sys_path = list(sys.path)
class_name = self.__class__.__name__
self.sc = SparkContext('local[4]', class_name)
def tearDown(self):
self.sc.stop()
sys.path = self._old_sys_path
class ReusedPySparkTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sc = SparkContext('local[4]', cls.__name__)
@classmethod
def tearDownClass(cls):
cls.sc.stop()
class CheckpointTests(ReusedPySparkTestCase):
def setUp(self):
self.checkpointDir = tempfile.NamedTemporaryFile(delete=False)
os.unlink(self.checkpointDir.name)
self.sc.setCheckpointDir(self.checkpointDir.name)
def tearDown(self):
shutil.rmtree(self.checkpointDir.name)
def test_basic_checkpointing(self):
parCollection = self.sc.parallelize([1, 2, 3, 4])
flatMappedRDD = parCollection.flatMap(lambda x: range(1, x + 1))
self.assertFalse(flatMappedRDD.isCheckpointed())
self.assertTrue(flatMappedRDD.getCheckpointFile() is None)
flatMappedRDD.checkpoint()
result = flatMappedRDD.collect()
time.sleep(1) # 1 second
self.assertTrue(flatMappedRDD.isCheckpointed())
self.assertEqual(flatMappedRDD.collect(), result)
self.assertEqual("file:" + self.checkpointDir.name,
os.path.dirname(os.path.dirname(flatMappedRDD.getCheckpointFile())))
def test_checkpoint_and_restore(self):
parCollection = self.sc.parallelize([1, 2, 3, 4])
flatMappedRDD = parCollection.flatMap(lambda x: [x])
self.assertFalse(flatMappedRDD.isCheckpointed())
self.assertTrue(flatMappedRDD.getCheckpointFile() is None)
flatMappedRDD.checkpoint()
flatMappedRDD.count() # forces a checkpoint to be computed
time.sleep(1) # 1 second
self.assertTrue(flatMappedRDD.getCheckpointFile() is not None)
recovered = self.sc._checkpointFile(flatMappedRDD.getCheckpointFile(),
flatMappedRDD._jrdd_deserializer)
self.assertEqual([1, 2, 3, 4], recovered.collect())
class AddFileTests(PySparkTestCase):
def test_add_py_file(self):
# To ensure that we're actually testing addPyFile's effects, check that
# this job fails due to `userlibrary` not being on the Python path:
# disable logging in log4j temporarily
def func(x):
from userlibrary import UserClass
return UserClass().hello()
with QuietTest(self.sc):
self.assertRaises(Exception, self.sc.parallelize(range(2)).map(func).first)
# Add the file, so the job should now succeed:
path = os.path.join(SPARK_HOME, "python/test_support/userlibrary.py")
self.sc.addPyFile(path)
res = self.sc.parallelize(range(2)).map(func).first()
self.assertEqual("Hello World!", res)
def test_add_file_locally(self):
path = os.path.join(SPARK_HOME, "python/test_support/hello.txt")
self.sc.addFile(path)
download_path = SparkFiles.get("hello.txt")
self.assertNotEqual(path, download_path)
with open(download_path) as test_file:
self.assertEqual("Hello World!\n", test_file.readline())
def test_add_py_file_locally(self):
# To ensure that we're actually testing addPyFile's effects, check that
# this fails due to `userlibrary` not being on the Python path:
def func():
from userlibrary import UserClass
self.assertRaises(ImportError, func)
path = os.path.join(SPARK_HOME, "python/test_support/userlibrary.py")
self.sc.addPyFile(path)
from userlibrary import UserClass
self.assertEqual("Hello World!", UserClass().hello())
def test_add_egg_file_locally(self):
# To ensure that we're actually testing addPyFile's effects, check that
# this fails due to `userlibrary` not being on the Python path:
def func():
from userlib import UserClass
self.assertRaises(ImportError, func)
path = os.path.join(SPARK_HOME, "python/test_support/userlib-0.1.zip")
self.sc.addPyFile(path)
from userlib import UserClass
self.assertEqual("Hello World from inside a package!", UserClass().hello())
def test_overwrite_system_module(self):
self.sc.addPyFile(os.path.join(SPARK_HOME, "python/test_support/SimpleHTTPServer.py"))
import SimpleHTTPServer
self.assertEqual("My Server", SimpleHTTPServer.__name__)
def func(x):
import SimpleHTTPServer
return SimpleHTTPServer.__name__
self.assertEqual(["My Server"], self.sc.parallelize(range(1)).map(func).collect())
class RDDTests(ReusedPySparkTestCase):
def test_range(self):
self.assertEqual(self.sc.range(1, 1).count(), 0)
self.assertEqual(self.sc.range(1, 0, -1).count(), 1)
self.assertEqual(self.sc.range(0, 1 << 40, 1 << 39).count(), 2)
def test_id(self):
rdd = self.sc.parallelize(range(10))
id = rdd.id()
self.assertEqual(id, rdd.id())
rdd2 = rdd.map(str).filter(bool)
id2 = rdd2.id()
self.assertEqual(id + 1, id2)
self.assertEqual(id2, rdd2.id())
def test_empty_rdd(self):
rdd = self.sc.emptyRDD()
self.assertTrue(rdd.isEmpty())
def test_sum(self):
self.assertEqual(0, self.sc.emptyRDD().sum())
self.assertEqual(6, self.sc.parallelize([1, 2, 3]).sum())
def test_save_as_textfile_with_unicode(self):
# Regression test for SPARK-970
x = u"\u00A1Hola, mundo!"
data = self.sc.parallelize([x])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsTextFile(tempFile.name)
raw_contents = b''.join(open(p, 'rb').read()
for p in glob(tempFile.name + "/part-0000*"))
self.assertEqual(x, raw_contents.strip().decode("utf-8"))
def test_save_as_textfile_with_utf8(self):
x = u"\u00A1Hola, mundo!"
data = self.sc.parallelize([x.encode("utf-8")])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsTextFile(tempFile.name)
raw_contents = b''.join(open(p, 'rb').read()
for p in glob(tempFile.name + "/part-0000*"))
self.assertEqual(x, raw_contents.strip().decode('utf8'))
def test_transforming_cartesian_result(self):
# Regression test for SPARK-1034
rdd1 = self.sc.parallelize([1, 2])
rdd2 = self.sc.parallelize([3, 4])
cart = rdd1.cartesian(rdd2)
result = cart.map(lambda x_y3: x_y3[0] + x_y3[1]).collect()
def test_transforming_pickle_file(self):
# Regression test for SPARK-2601
data = self.sc.parallelize([u"Hello", u"World!"])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsPickleFile(tempFile.name)
pickled_file = self.sc.pickleFile(tempFile.name)
pickled_file.map(lambda x: x).collect()
def test_cartesian_on_textfile(self):
# Regression test for
path = os.path.join(SPARK_HOME, "python/test_support/hello.txt")
a = self.sc.textFile(path)
result = a.cartesian(a).collect()
(x, y) = result[0]
self.assertEqual(u"Hello World!", x.strip())
self.assertEqual(u"Hello World!", y.strip())
def test_deleting_input_files(self):
# Regression test for SPARK-1025
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write(b"Hello World!")
tempFile.close()
data = self.sc.textFile(tempFile.name)
filtered_data = data.filter(lambda x: True)
self.assertEqual(1, filtered_data.count())
os.unlink(tempFile.name)
with QuietTest(self.sc):
self.assertRaises(Exception, lambda: filtered_data.count())
def test_sampling_default_seed(self):
# Test for SPARK-3995 (default seed setting)
data = self.sc.parallelize(xrange(1000), 1)
subset = data.takeSample(False, 10)
self.assertEqual(len(subset), 10)
def test_aggregate_mutable_zero_value(self):
# Test for SPARK-9021; uses aggregate and treeAggregate to build dict
# representing a counter of ints
# NOTE: dict is used instead of collections.Counter for Python 2.6
# compatibility
from collections import defaultdict
# Show that single or multiple partitions work
data1 = self.sc.range(10, numSlices=1)
data2 = self.sc.range(10, numSlices=2)
def seqOp(x, y):
x[y] += 1
return x
def comboOp(x, y):
for key, val in y.items():
x[key] += val
return x
counts1 = data1.aggregate(defaultdict(int), seqOp, comboOp)
counts2 = data2.aggregate(defaultdict(int), seqOp, comboOp)
counts3 = data1.treeAggregate(defaultdict(int), seqOp, comboOp, 2)
counts4 = data2.treeAggregate(defaultdict(int), seqOp, comboOp, 2)
ground_truth = defaultdict(int, dict((i, 1) for i in range(10)))
self.assertEqual(counts1, ground_truth)
self.assertEqual(counts2, ground_truth)
self.assertEqual(counts3, ground_truth)
self.assertEqual(counts4, ground_truth)
def test_aggregate_by_key_mutable_zero_value(self):
# Test for SPARK-9021; uses aggregateByKey to make a pair RDD that
# contains lists of all values for each key in the original RDD
# list(range(...)) for Python 3.x compatibility (can't use * operator
# on a range object)
# list(zip(...)) for Python 3.x compatibility (want to parallelize a
# collection, not a zip object)
tuples = list(zip(list(range(10))*2, [1]*20))
# Show that single or multiple partitions work
data1 = self.sc.parallelize(tuples, 1)
data2 = self.sc.parallelize(tuples, 2)
def seqOp(x, y):
x.append(y)
return x
def comboOp(x, y):
x.extend(y)
return x
values1 = data1.aggregateByKey([], seqOp, comboOp).collect()
values2 = data2.aggregateByKey([], seqOp, comboOp).collect()
# Sort lists to ensure clean comparison with ground_truth
values1.sort()
values2.sort()
ground_truth = [(i, [1]*2) for i in range(10)]
self.assertEqual(values1, ground_truth)
self.assertEqual(values2, ground_truth)
def test_fold_mutable_zero_value(self):
# Test for SPARK-9021; uses fold to merge an RDD of dict counters into
# a single dict
# NOTE: dict is used instead of collections.Counter for Python 2.6
# compatibility
from collections import defaultdict
counts1 = defaultdict(int, dict((i, 1) for i in range(10)))
counts2 = defaultdict(int, dict((i, 1) for i in range(3, 8)))
counts3 = defaultdict(int, dict((i, 1) for i in range(4, 7)))
counts4 = defaultdict(int, dict((i, 1) for i in range(5, 6)))
all_counts = [counts1, counts2, counts3, counts4]
# Show that single or multiple partitions work
data1 = self.sc.parallelize(all_counts, 1)
data2 = self.sc.parallelize(all_counts, 2)
def comboOp(x, y):
for key, val in y.items():
x[key] += val
return x
fold1 = data1.fold(defaultdict(int), comboOp)
fold2 = data2.fold(defaultdict(int), comboOp)
ground_truth = defaultdict(int)
for counts in all_counts:
for key, val in counts.items():
ground_truth[key] += val
self.assertEqual(fold1, ground_truth)
self.assertEqual(fold2, ground_truth)
def test_fold_by_key_mutable_zero_value(self):
# Test for SPARK-9021; uses foldByKey to make a pair RDD that contains
# lists of all values for each key in the original RDD
tuples = [(i, range(i)) for i in range(10)]*2
# Show that single or multiple partitions work
data1 = self.sc.parallelize(tuples, 1)
data2 = self.sc.parallelize(tuples, 2)
def comboOp(x, y):
x.extend(y)
return x
values1 = data1.foldByKey([], comboOp).collect()
values2 = data2.foldByKey([], comboOp).collect()
# Sort lists to ensure clean comparison with ground_truth
values1.sort()
values2.sort()
# list(range(...)) for Python 3.x compatibility
ground_truth = [(i, list(range(i))*2) for i in range(10)]
self.assertEqual(values1, ground_truth)
self.assertEqual(values2, ground_truth)
def test_aggregate_by_key(self):
data = self.sc.parallelize([(1, 1), (1, 1), (3, 2), (5, 1), (5, 3)], 2)
def seqOp(x, y):
x.add(y)
return x
def combOp(x, y):
x |= y
return x
sets = dict(data.aggregateByKey(set(), seqOp, combOp).collect())
self.assertEqual(3, len(sets))
self.assertEqual(set([1]), sets[1])
self.assertEqual(set([2]), sets[3])
self.assertEqual(set([1, 3]), sets[5])
def test_itemgetter(self):
rdd = self.sc.parallelize([range(10)])
from operator import itemgetter
self.assertEqual([1], rdd.map(itemgetter(1)).collect())
self.assertEqual([(2, 3)], rdd.map(itemgetter(2, 3)).collect())
def test_namedtuple_in_rdd(self):
from collections import namedtuple
Person = namedtuple("Person", "id firstName lastName")
jon = Person(1, "Jon", "Doe")
jane = Person(2, "Jane", "Doe")
theDoes = self.sc.parallelize([jon, jane])
self.assertEqual([jon, jane], theDoes.collect())
def test_large_broadcast(self):
N = 10000
data = [[float(i) for i in range(300)] for i in range(N)]
bdata = self.sc.broadcast(data) # 27MB
m = self.sc.parallelize(range(1), 1).map(lambda x: len(bdata.value)).sum()
self.assertEqual(N, m)
def test_multiple_broadcasts(self):
N = 1 << 21
b1 = self.sc.broadcast(set(range(N))) # multiple blocks in JVM
r = list(range(1 << 15))
random.shuffle(r)
s = str(r).encode()
checksum = hashlib.md5(s).hexdigest()
b2 = self.sc.broadcast(s)
r = list(set(self.sc.parallelize(range(10), 10).map(
lambda x: (len(b1.value), hashlib.md5(b2.value).hexdigest())).collect()))
self.assertEqual(1, len(r))
size, csum = r[0]
self.assertEqual(N, size)
self.assertEqual(checksum, csum)
random.shuffle(r)
s = str(r).encode()
checksum = hashlib.md5(s).hexdigest()
b2 = self.sc.broadcast(s)
r = list(set(self.sc.parallelize(range(10), 10).map(
lambda x: (len(b1.value), hashlib.md5(b2.value).hexdigest())).collect()))
self.assertEqual(1, len(r))
size, csum = r[0]
self.assertEqual(N, size)
self.assertEqual(checksum, csum)
def test_large_closure(self):
N = 200000
data = [float(i) for i in xrange(N)]
rdd = self.sc.parallelize(range(1), 1).map(lambda x: len(data))
self.assertEqual(N, rdd.first())
# regression test for SPARK-6886
self.assertEqual(1, rdd.map(lambda x: (x, 1)).groupByKey().count())
def test_zip_with_different_serializers(self):
a = self.sc.parallelize(range(5))
b = self.sc.parallelize(range(100, 105))
self.assertEqual(a.zip(b).collect(), [(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)])
a = a._reserialize(BatchedSerializer(PickleSerializer(), 2))
b = b._reserialize(MarshalSerializer())
self.assertEqual(a.zip(b).collect(), [(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)])
# regression test for SPARK-4841
path = os.path.join(SPARK_HOME, "python/test_support/hello.txt")
t = self.sc.textFile(path)
cnt = t.count()
self.assertEqual(cnt, t.zip(t).count())
rdd = t.map(str)
self.assertEqual(cnt, t.zip(rdd).count())
# regression test for bug in _reserializer()
self.assertEqual(cnt, t.zip(rdd).count())
def test_zip_with_different_object_sizes(self):
# regress test for SPARK-5973
a = self.sc.parallelize(xrange(10000)).map(lambda i: '*' * i)
b = self.sc.parallelize(xrange(10000, 20000)).map(lambda i: '*' * i)
self.assertEqual(10000, a.zip(b).count())
def test_zip_with_different_number_of_items(self):
a = self.sc.parallelize(range(5), 2)
# different number of partitions
b = self.sc.parallelize(range(100, 106), 3)
self.assertRaises(ValueError, lambda: a.zip(b))
with QuietTest(self.sc):
# different number of batched items in JVM
b = self.sc.parallelize(range(100, 104), 2)
self.assertRaises(Exception, lambda: a.zip(b).count())
# different number of items in one pair
b = self.sc.parallelize(range(100, 106), 2)
self.assertRaises(Exception, lambda: a.zip(b).count())
# same total number of items, but different distributions
a = self.sc.parallelize([2, 3], 2).flatMap(range)
b = self.sc.parallelize([3, 2], 2).flatMap(range)
self.assertEqual(a.count(), b.count())
self.assertRaises(Exception, lambda: a.zip(b).count())
def test_count_approx_distinct(self):
rdd = self.sc.parallelize(xrange(1000))
self.assertTrue(950 < rdd.countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(float).countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(str).countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(lambda x: (x, -x)).countApproxDistinct(0.03) < 1050)
rdd = self.sc.parallelize([i % 20 for i in range(1000)], 7)
self.assertTrue(18 < rdd.countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(float).countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(str).countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(lambda x: (x, -x)).countApproxDistinct() < 22)
self.assertRaises(ValueError, lambda: rdd.countApproxDistinct(0.00000001))
def test_histogram(self):
# empty
rdd = self.sc.parallelize([])
self.assertEqual([0], rdd.histogram([0, 10])[1])
self.assertEqual([0, 0], rdd.histogram([0, 4, 10])[1])
self.assertRaises(ValueError, lambda: rdd.histogram(1))
# out of range
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0], rdd.histogram([0, 10])[1])
self.assertEqual([0, 0], rdd.histogram((0, 4, 10))[1])
# in range with one bucket
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual([4], rdd.histogram([0, 10])[1])
self.assertEqual([3, 1], rdd.histogram([0, 4, 10])[1])
# in range with one bucket exact match
self.assertEqual([4], rdd.histogram([1, 4])[1])
# out of range with two buckets
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0, 0], rdd.histogram([0, 5, 10])[1])
# out of range with two uneven buckets
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0, 0], rdd.histogram([0, 4, 10])[1])
# in range with two buckets
rdd = self.sc.parallelize([1, 2, 3, 5, 6])
self.assertEqual([3, 2], rdd.histogram([0, 5, 10])[1])
# in range with two bucket and None
rdd = self.sc.parallelize([1, 2, 3, 5, 6, None, float('nan')])
self.assertEqual([3, 2], rdd.histogram([0, 5, 10])[1])
# in range with two uneven buckets
rdd = self.sc.parallelize([1, 2, 3, 5, 6])
self.assertEqual([3, 2], rdd.histogram([0, 5, 11])[1])
# mixed range with two uneven buckets
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.0, 11.01])
self.assertEqual([4, 3], rdd.histogram([0, 5, 11])[1])
# mixed range with four uneven buckets
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.01, 12.0, 199.0, 200.0, 200.1])
self.assertEqual([4, 2, 1, 3], rdd.histogram([0.0, 5.0, 11.0, 12.0, 200.0])[1])
# mixed range with uneven buckets and NaN
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.01, 12.0,
199.0, 200.0, 200.1, None, float('nan')])
self.assertEqual([4, 2, 1, 3], rdd.histogram([0.0, 5.0, 11.0, 12.0, 200.0])[1])
# out of range with infinite buckets
rdd = self.sc.parallelize([10.01, -0.01, float('nan'), float("inf")])
self.assertEqual([1, 2], rdd.histogram([float('-inf'), 0, float('inf')])[1])
# invalid buckets
self.assertRaises(ValueError, lambda: rdd.histogram([]))
self.assertRaises(ValueError, lambda: rdd.histogram([1]))
self.assertRaises(ValueError, lambda: rdd.histogram(0))
self.assertRaises(TypeError, lambda: rdd.histogram({}))
# without buckets
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual(([1, 4], [4]), rdd.histogram(1))
# without buckets single element
rdd = self.sc.parallelize([1])
self.assertEqual(([1, 1], [1]), rdd.histogram(1))
# without bucket no range
rdd = self.sc.parallelize([1] * 4)
self.assertEqual(([1, 1], [4]), rdd.histogram(1))
# without buckets basic two
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual(([1, 2.5, 4], [2, 2]), rdd.histogram(2))
# without buckets with more requested than elements
rdd = self.sc.parallelize([1, 2])
buckets = [1 + 0.2 * i for i in range(6)]
hist = [1, 0, 0, 0, 1]
self.assertEqual((buckets, hist), rdd.histogram(5))
# invalid RDDs
rdd = self.sc.parallelize([1, float('inf')])
self.assertRaises(ValueError, lambda: rdd.histogram(2))
rdd = self.sc.parallelize([float('nan')])
self.assertRaises(ValueError, lambda: rdd.histogram(2))
# string
rdd = self.sc.parallelize(["ab", "ac", "b", "bd", "ef"], 2)
self.assertEqual([2, 2], rdd.histogram(["a", "b", "c"])[1])
self.assertEqual((["ab", "ef"], [5]), rdd.histogram(1))
self.assertRaises(TypeError, lambda: rdd.histogram(2))
def test_repartitionAndSortWithinPartitions(self):
rdd = self.sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)], 2)
repartitioned = rdd.repartitionAndSortWithinPartitions(2, lambda key: key % 2)
partitions = repartitioned.glom().collect()
self.assertEqual(partitions[0], [(0, 5), (0, 8), (2, 6)])
self.assertEqual(partitions[1], [(1, 3), (3, 8), (3, 8)])
def test_distinct(self):
rdd = self.sc.parallelize((1, 2, 3)*10, 10)
self.assertEqual(rdd.getNumPartitions(), 10)
self.assertEqual(rdd.distinct().count(), 3)
result = rdd.distinct(5)
self.assertEqual(result.getNumPartitions(), 5)
self.assertEqual(result.count(), 3)
def test_external_group_by_key(self):
self.sc._conf.set("spark.python.worker.memory", "1m")
N = 200001
kv = self.sc.parallelize(xrange(N)).map(lambda x: (x % 3, x))
gkv = kv.groupByKey().cache()
self.assertEqual(3, gkv.count())
filtered = gkv.filter(lambda kv: kv[0] == 1)
self.assertEqual(1, filtered.count())
self.assertEqual([(1, N // 3)], filtered.mapValues(len).collect())
self.assertEqual([(N // 3, N // 3)],
filtered.values().map(lambda x: (len(x), len(list(x)))).collect())
result = filtered.collect()[0][1]
self.assertEqual(N // 3, len(result))
self.assertTrue(isinstance(result.data, shuffle.ExternalListOfList))
def test_sort_on_empty_rdd(self):
self.assertEqual([], self.sc.parallelize(zip([], [])).sortByKey().collect())
def test_sample(self):
rdd = self.sc.parallelize(range(0, 100), 4)
wo = rdd.sample(False, 0.1, 2).collect()
wo_dup = rdd.sample(False, 0.1, 2).collect()
self.assertSetEqual(set(wo), set(wo_dup))
wr = rdd.sample(True, 0.2, 5).collect()
wr_dup = rdd.sample(True, 0.2, 5).collect()
self.assertSetEqual(set(wr), set(wr_dup))
wo_s10 = rdd.sample(False, 0.3, 10).collect()
wo_s20 = rdd.sample(False, 0.3, 20).collect()
self.assertNotEqual(set(wo_s10), set(wo_s20))
wr_s11 = rdd.sample(True, 0.4, 11).collect()
wr_s21 = rdd.sample(True, 0.4, 21).collect()
self.assertNotEqual(set(wr_s11), set(wr_s21))
def test_null_in_rdd(self):
jrdd = self.sc._jvm.PythonUtils.generateRDDWithNull(self.sc._jsc)
rdd = RDD(jrdd, self.sc, UTF8Deserializer())
self.assertEqual([u"a", None, u"b"], rdd.collect())
rdd = RDD(jrdd, self.sc, NoOpSerializer())
self.assertEqual([b"a", None, b"b"], rdd.collect())
def test_multiple_python_java_RDD_conversions(self):
# Regression test for SPARK-5361
data = [
(u'1', {u'director': u'David Lean'}),
(u'2', {u'director': u'Andrew Dominik'})
]
data_rdd = self.sc.parallelize(data)
data_java_rdd = data_rdd._to_java_object_rdd()
data_python_rdd = self.sc._jvm.SerDe.javaToPython(data_java_rdd)
converted_rdd = RDD(data_python_rdd, self.sc)
self.assertEqual(2, converted_rdd.count())
# conversion between python and java RDD threw exceptions
data_java_rdd = converted_rdd._to_java_object_rdd()
data_python_rdd = self.sc._jvm.SerDe.javaToPython(data_java_rdd)
converted_rdd = RDD(data_python_rdd, self.sc)
self.assertEqual(2, converted_rdd.count())
def test_narrow_dependency_in_join(self):
rdd = self.sc.parallelize(range(10)).map(lambda x: (x, x))
parted = rdd.partitionBy(2)
self.assertEqual(2, parted.union(parted).getNumPartitions())
self.assertEqual(rdd.getNumPartitions() + 2, parted.union(rdd).getNumPartitions())
self.assertEqual(rdd.getNumPartitions() + 2, rdd.union(parted).getNumPartitions())
tracker = self.sc.statusTracker()
self.sc.setJobGroup("test1", "test", True)
d = sorted(parted.join(parted).collect())
self.assertEqual(10, len(d))
self.assertEqual((0, (0, 0)), d[0])
jobId = tracker.getJobIdsForGroup("test1")[0]
self.assertEqual(2, len(tracker.getJobInfo(jobId).stageIds))
self.sc.setJobGroup("test2", "test", True)
d = sorted(parted.join(rdd).collect())
self.assertEqual(10, len(d))
self.assertEqual((0, (0, 0)), d[0])
jobId = tracker.getJobIdsForGroup("test2")[0]
self.assertEqual(3, len(tracker.getJobInfo(jobId).stageIds))
self.sc.setJobGroup("test3", "test", True)
d = sorted(parted.cogroup(parted).collect())
self.assertEqual(10, len(d))
self.assertEqual([[0], [0]], list(map(list, d[0][1])))
jobId = tracker.getJobIdsForGroup("test3")[0]
self.assertEqual(2, len(tracker.getJobInfo(jobId).stageIds))
self.sc.setJobGroup("test4", "test", True)
d = sorted(parted.cogroup(rdd).collect())
self.assertEqual(10, len(d))
self.assertEqual([[0], [0]], list(map(list, d[0][1])))
jobId = tracker.getJobIdsForGroup("test4")[0]
self.assertEqual(3, len(tracker.getJobInfo(jobId).stageIds))
# Regression test for SPARK-6294
def test_take_on_jrdd(self):
rdd = self.sc.parallelize(xrange(1 << 20)).map(lambda x: str(x))
rdd._jrdd.first()
def test_sortByKey_uses_all_partitions_not_only_first_and_last(self):
# Regression test for SPARK-5969
seq = [(i * 59 % 101, i) for i in range(101)] # unsorted sequence
rdd = self.sc.parallelize(seq)
for ascending in [True, False]:
sort = rdd.sortByKey(ascending=ascending, numPartitions=5)
self.assertEqual(sort.collect(), sorted(seq, reverse=not ascending))
sizes = sort.glom().map(len).collect()
for size in sizes:
self.assertGreater(size, 0)
def test_pipe_functions(self):
data = ['1', '2', '3']
rdd = self.sc.parallelize(data)
with QuietTest(self.sc):
self.assertEqual([], rdd.pipe('cc').collect())
self.assertRaises(Py4JJavaError, rdd.pipe('cc', checkCode=True).collect)
result = rdd.pipe('cat').collect()
result.sort()
for x, y in zip(data, result):
self.assertEqual(x, y)
self.assertRaises(Py4JJavaError, rdd.pipe('grep 4', checkCode=True).collect)
self.assertEqual([], rdd.pipe('grep 4').collect())
class ProfilerTests(PySparkTestCase):
def setUp(self):
self._old_sys_path = list(sys.path)
class_name = self.__class__.__name__
conf = SparkConf().set("spark.python.profile", "true")
self.sc = SparkContext('local[4]', class_name, conf=conf)
def test_profiler(self):
self.do_computation()
profilers = self.sc.profiler_collector.profilers
self.assertEqual(1, len(profilers))
id, profiler, _ = profilers[0]
stats = profiler.stats()
self.assertTrue(stats is not None)
width, stat_list = stats.get_print_list([])
func_names = [func_name for fname, n, func_name in stat_list]
self.assertTrue("heavy_foo" in func_names)
old_stdout = sys.stdout
sys.stdout = io = StringIO()
self.sc.show_profiles()
self.assertTrue("heavy_foo" in io.getvalue())
sys.stdout = old_stdout
d = tempfile.gettempdir()
self.sc.dump_profiles(d)
self.assertTrue("rdd_%d.pstats" % id in os.listdir(d))
def test_custom_profiler(self):
class TestCustomProfiler(BasicProfiler):
def show(self, id):
self.result = "Custom formatting"
self.sc.profiler_collector.profiler_cls = TestCustomProfiler
self.do_computation()
profilers = self.sc.profiler_collector.profilers
self.assertEqual(1, len(profilers))
_, profiler, _ = profilers[0]
self.assertTrue(isinstance(profiler, TestCustomProfiler))
self.sc.show_profiles()
self.assertEqual("Custom formatting", profiler.result)
def do_computation(self):
def heavy_foo(x):
for i in range(1 << 18):
x = 1
rdd = self.sc.parallelize(range(100))
rdd.foreach(heavy_foo)
class InputFormatTests(ReusedPySparkTestCase):
@classmethod
def setUpClass(cls):
ReusedPySparkTestCase.setUpClass()
cls.tempdir = tempfile.NamedTemporaryFile(delete=False)
os.unlink(cls.tempdir.name)
cls.sc._jvm.WriteInputFormatTestDataGenerator.generateData(cls.tempdir.name, cls.sc._jsc)
@classmethod
def tearDownClass(cls):
ReusedPySparkTestCase.tearDownClass()
shutil.rmtree(cls.tempdir.name)
@unittest.skipIf(sys.version >= "3", "serialize array of byte")
def test_sequencefiles(self):
basepath = self.tempdir.name
ints = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfint/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text").collect())
ei = [(1, u'aa'), (1, u'aa'), (2, u'aa'), (2, u'bb'), (2, u'bb'), (3, u'cc')]
self.assertEqual(ints, ei)
doubles = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfdouble/",
"org.apache.hadoop.io.DoubleWritable",
"org.apache.hadoop.io.Text").collect())
ed = [(1.0, u'aa'), (1.0, u'aa'), (2.0, u'aa'), (2.0, u'bb'), (2.0, u'bb'), (3.0, u'cc')]
self.assertEqual(doubles, ed)
bytes = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfbytes/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.BytesWritable").collect())
ebs = [(1, bytearray('aa', 'utf-8')),
(1, bytearray('aa', 'utf-8')),
(2, bytearray('aa', 'utf-8')),
(2, bytearray('bb', 'utf-8')),
(2, bytearray('bb', 'utf-8')),
(3, bytearray('cc', 'utf-8'))]
self.assertEqual(bytes, ebs)
text = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sftext/",
"org.apache.hadoop.io.Text",
"org.apache.hadoop.io.Text").collect())
et = [(u'1', u'aa'),
(u'1', u'aa'),
(u'2', u'aa'),
(u'2', u'bb'),
(u'2', u'bb'),
(u'3', u'cc')]
self.assertEqual(text, et)
bools = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfbool/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.BooleanWritable").collect())
eb = [(1, False), (1, True), (2, False), (2, False), (2, True), (3, True)]
self.assertEqual(bools, eb)
nulls = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfnull/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.BooleanWritable").collect())
en = [(1, None), (1, None), (2, None), (2, None), (2, None), (3, None)]
self.assertEqual(nulls, en)
maps = self.sc.sequenceFile(basepath + "/sftestdata/sfmap/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.MapWritable").collect()
em = [(1, {}),
(1, {3.0: u'bb'}),
(2, {1.0: u'aa'}),
(2, {1.0: u'cc'}),
(3, {2.0: u'dd'})]
for v in maps:
self.assertTrue(v in em)
# arrays get pickled to tuples by default
tuples = sorted(self.sc.sequenceFile(
basepath + "/sftestdata/sfarray/",
"org.apache.hadoop.io.IntWritable",
"org.apache.spark.api.python.DoubleArrayWritable").collect())
et = [(1, ()),
(2, (3.0, 4.0, 5.0)),
(3, (4.0, 5.0, 6.0))]
self.assertEqual(tuples, et)
# with custom converters, primitive arrays can stay as arrays
arrays = sorted(self.sc.sequenceFile(
basepath + "/sftestdata/sfarray/",
"org.apache.hadoop.io.IntWritable",
"org.apache.spark.api.python.DoubleArrayWritable",
valueConverter="org.apache.spark.api.python.WritableToDoubleArrayConverter").collect())
ea = [(1, array('d')),
(2, array('d', [3.0, 4.0, 5.0])),
(3, array('d', [4.0, 5.0, 6.0]))]
self.assertEqual(arrays, ea)
clazz = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfclass/",
"org.apache.hadoop.io.Text",
"org.apache.spark.api.python.TestWritable").collect())
cname = u'org.apache.spark.api.python.TestWritable'
ec = [(u'1', {u'__class__': cname, u'double': 1.0, u'int': 1, u'str': u'test1'}),
(u'2', {u'__class__': cname, u'double': 2.3, u'int': 2, u'str': u'test2'}),
(u'3', {u'__class__': cname, u'double': 3.1, u'int': 3, u'str': u'test3'}),
(u'4', {u'__class__': cname, u'double': 4.2, u'int': 4, u'str': u'test4'}),
(u'5', {u'__class__': cname, u'double': 5.5, u'int': 5, u'str': u'test56'})]
self.assertEqual(clazz, ec)
unbatched_clazz = sorted(self.sc.sequenceFile(basepath + "/sftestdata/sfclass/",
"org.apache.hadoop.io.Text",
"org.apache.spark.api.python.TestWritable",
).collect())
self.assertEqual(unbatched_clazz, ec)
def test_oldhadoop(self):
basepath = self.tempdir.name
ints = sorted(self.sc.hadoopFile(basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapred.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text").collect())
ei = [(1, u'aa'), (1, u'aa'), (2, u'aa'), (2, u'bb'), (2, u'bb'), (3, u'cc')]
self.assertEqual(ints, ei)
hellopath = os.path.join(SPARK_HOME, "python/test_support/hello.txt")
oldconf = {"mapred.input.dir": hellopath}
hello = self.sc.hadoopRDD("org.apache.hadoop.mapred.TextInputFormat",
"org.apache.hadoop.io.LongWritable",
"org.apache.hadoop.io.Text",
conf=oldconf).collect()
result = [(0, u'Hello World!')]
self.assertEqual(hello, result)
def test_newhadoop(self):
basepath = self.tempdir.name
ints = sorted(self.sc.newAPIHadoopFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text").collect())
ei = [(1, u'aa'), (1, u'aa'), (2, u'aa'), (2, u'bb'), (2, u'bb'), (3, u'cc')]
self.assertEqual(ints, ei)
hellopath = os.path.join(SPARK_HOME, "python/test_support/hello.txt")
newconf = {"mapred.input.dir": hellopath}
hello = self.sc.newAPIHadoopRDD("org.apache.hadoop.mapreduce.lib.input.TextInputFormat",
"org.apache.hadoop.io.LongWritable",
"org.apache.hadoop.io.Text",
conf=newconf).collect()
result = [(0, u'Hello World!')]
self.assertEqual(hello, result)
def test_newolderror(self):
basepath = self.tempdir.name
self.assertRaises(Exception, lambda: self.sc.hadoopFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text"))
self.assertRaises(Exception, lambda: self.sc.newAPIHadoopFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapred.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text"))
def test_bad_inputs(self):
basepath = self.tempdir.name
self.assertRaises(Exception, lambda: self.sc.sequenceFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.io.NotValidWritable",
"org.apache.hadoop.io.Text"))
self.assertRaises(Exception, lambda: self.sc.hadoopFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapred.NotValidInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text"))
self.assertRaises(Exception, lambda: self.sc.newAPIHadoopFile(
basepath + "/sftestdata/sfint/",
"org.apache.hadoop.mapreduce.lib.input.NotValidInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text"))
def test_converters(self):
# use of custom converters
basepath = self.tempdir.name
maps = sorted(self.sc.sequenceFile(
basepath + "/sftestdata/sfmap/",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.MapWritable",
keyConverter="org.apache.spark.api.python.TestInputKeyConverter",
valueConverter="org.apache.spark.api.python.TestInputValueConverter").collect())
em = [(u'\x01', []),
(u'\x01', [3.0]),
(u'\x02', [1.0]),
(u'\x02', [1.0]),
(u'\x03', [2.0])]
self.assertEqual(maps, em)
def test_binary_files(self):
path = os.path.join(self.tempdir.name, "binaryfiles")
os.mkdir(path)
data = b"short binary data"
with open(os.path.join(path, "part-0000"), 'wb') as f:
f.write(data)
[(p, d)] = self.sc.binaryFiles(path).collect()
self.assertTrue(p.endswith("part-0000"))
self.assertEqual(d, data)
def test_binary_records(self):
path = os.path.join(self.tempdir.name, "binaryrecords")
os.mkdir(path)
with open(os.path.join(path, "part-0000"), 'w') as f:
for i in range(100):
f.write('%04d' % i)
result = self.sc.binaryRecords(path, 4).map(int).collect()
self.assertEqual(list(range(100)), result)
class OutputFormatTests(ReusedPySparkTestCase):
def setUp(self):
self.tempdir = tempfile.NamedTemporaryFile(delete=False)
os.unlink(self.tempdir.name)
def tearDown(self):
shutil.rmtree(self.tempdir.name, ignore_errors=True)
@unittest.skipIf(sys.version >= "3", "serialize array of byte")
def test_sequencefiles(self):
basepath = self.tempdir.name
ei = [(1, u'aa'), (1, u'aa'), (2, u'aa'), (2, u'bb'), (2, u'bb'), (3, u'cc')]
self.sc.parallelize(ei).saveAsSequenceFile(basepath + "/sfint/")
ints = sorted(self.sc.sequenceFile(basepath + "/sfint/").collect())
self.assertEqual(ints, ei)
ed = [(1.0, u'aa'), (1.0, u'aa'), (2.0, u'aa'), (2.0, u'bb'), (2.0, u'bb'), (3.0, u'cc')]
self.sc.parallelize(ed).saveAsSequenceFile(basepath + "/sfdouble/")
doubles = sorted(self.sc.sequenceFile(basepath + "/sfdouble/").collect())
self.assertEqual(doubles, ed)
ebs = [(1, bytearray(b'\x00\x07spam\x08')), (2, bytearray(b'\x00\x07spam\x08'))]
self.sc.parallelize(ebs).saveAsSequenceFile(basepath + "/sfbytes/")
bytes = sorted(self.sc.sequenceFile(basepath + "/sfbytes/").collect())
self.assertEqual(bytes, ebs)
et = [(u'1', u'aa'),
(u'2', u'bb'),
(u'3', u'cc')]
self.sc.parallelize(et).saveAsSequenceFile(basepath + "/sftext/")
text = sorted(self.sc.sequenceFile(basepath + "/sftext/").collect())
self.assertEqual(text, et)
eb = [(1, False), (1, True), (2, False), (2, False), (2, True), (3, True)]
self.sc.parallelize(eb).saveAsSequenceFile(basepath + "/sfbool/")
bools = sorted(self.sc.sequenceFile(basepath + "/sfbool/").collect())
self.assertEqual(bools, eb)
en = [(1, None), (1, None), (2, None), (2, None), (2, None), (3, None)]
self.sc.parallelize(en).saveAsSequenceFile(basepath + "/sfnull/")
nulls = sorted(self.sc.sequenceFile(basepath + "/sfnull/").collect())
self.assertEqual(nulls, en)
em = [(1, {}),
(1, {3.0: u'bb'}),
(2, {1.0: u'aa'}),
(2, {1.0: u'cc'}),
(3, {2.0: u'dd'})]
self.sc.parallelize(em).saveAsSequenceFile(basepath + "/sfmap/")
maps = self.sc.sequenceFile(basepath + "/sfmap/").collect()
for v in maps:
self.assertTrue(v, em)
def test_oldhadoop(self):
basepath = self.tempdir.name
dict_data = [(1, {}),
(1, {"row1": 1.0}),
(2, {"row2": 2.0})]
self.sc.parallelize(dict_data).saveAsHadoopFile(
basepath + "/oldhadoop/",
"org.apache.hadoop.mapred.SequenceFileOutputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.MapWritable")
result = self.sc.hadoopFile(
basepath + "/oldhadoop/",
"org.apache.hadoop.mapred.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.MapWritable").collect()
for v in result:
self.assertTrue(v, dict_data)
conf = {
"mapred.output.format.class": "org.apache.hadoop.mapred.SequenceFileOutputFormat",
"mapred.output.key.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.value.class": "org.apache.hadoop.io.MapWritable",
"mapred.output.dir": basepath + "/olddataset/"
}
self.sc.parallelize(dict_data).saveAsHadoopDataset(conf)
input_conf = {"mapred.input.dir": basepath + "/olddataset/"}
result = self.sc.hadoopRDD(
"org.apache.hadoop.mapred.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.MapWritable",
conf=input_conf).collect()
for v in result:
self.assertTrue(v, dict_data)
def test_newhadoop(self):
basepath = self.tempdir.name
data = [(1, ""),
(1, "a"),
(2, "bcdf")]
self.sc.parallelize(data).saveAsNewAPIHadoopFile(
basepath + "/newhadoop/",
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text")
result = sorted(self.sc.newAPIHadoopFile(
basepath + "/newhadoop/",
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text").collect())
self.assertEqual(result, data)
conf = {
"mapreduce.outputformat.class":
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
"mapred.output.key.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.value.class": "org.apache.hadoop.io.Text",
"mapred.output.dir": basepath + "/newdataset/"
}
self.sc.parallelize(data).saveAsNewAPIHadoopDataset(conf)
input_conf = {"mapred.input.dir": basepath + "/newdataset/"}
new_dataset = sorted(self.sc.newAPIHadoopRDD(
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.hadoop.io.Text",
conf=input_conf).collect())
self.assertEqual(new_dataset, data)
@unittest.skipIf(sys.version >= "3", "serialize of array")
def test_newhadoop_with_array(self):
basepath = self.tempdir.name
# use custom ArrayWritable types and converters to handle arrays
array_data = [(1, array('d')),
(1, array('d', [1.0, 2.0, 3.0])),
(2, array('d', [3.0, 4.0, 5.0]))]
self.sc.parallelize(array_data).saveAsNewAPIHadoopFile(
basepath + "/newhadoop/",
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.spark.api.python.DoubleArrayWritable",
valueConverter="org.apache.spark.api.python.DoubleArrayToWritableConverter")
result = sorted(self.sc.newAPIHadoopFile(
basepath + "/newhadoop/",
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.spark.api.python.DoubleArrayWritable",
valueConverter="org.apache.spark.api.python.WritableToDoubleArrayConverter").collect())
self.assertEqual(result, array_data)
conf = {
"mapreduce.outputformat.class":
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
"mapred.output.key.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.value.class": "org.apache.spark.api.python.DoubleArrayWritable",
"mapred.output.dir": basepath + "/newdataset/"
}
self.sc.parallelize(array_data).saveAsNewAPIHadoopDataset(
conf,
valueConverter="org.apache.spark.api.python.DoubleArrayToWritableConverter")
input_conf = {"mapred.input.dir": basepath + "/newdataset/"}
new_dataset = sorted(self.sc.newAPIHadoopRDD(
"org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat",
"org.apache.hadoop.io.IntWritable",
"org.apache.spark.api.python.DoubleArrayWritable",
valueConverter="org.apache.spark.api.python.WritableToDoubleArrayConverter",
conf=input_conf).collect())
self.assertEqual(new_dataset, array_data)
def test_newolderror(self):
basepath = self.tempdir.name
rdd = self.sc.parallelize(range(1, 4)).map(lambda x: (x, "a" * x))
self.assertRaises(Exception, lambda: rdd.saveAsHadoopFile(
basepath + "/newolderror/saveAsHadoopFile/",
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat"))
self.assertRaises(Exception, lambda: rdd.saveAsNewAPIHadoopFile(
basepath + "/newolderror/saveAsNewAPIHadoopFile/",
"org.apache.hadoop.mapred.SequenceFileOutputFormat"))
def test_bad_inputs(self):
basepath = self.tempdir.name
rdd = self.sc.parallelize(range(1, 4)).map(lambda x: (x, "a" * x))
self.assertRaises(Exception, lambda: rdd.saveAsHadoopFile(
basepath + "/badinputs/saveAsHadoopFile/",
"org.apache.hadoop.mapred.NotValidOutputFormat"))
self.assertRaises(Exception, lambda: rdd.saveAsNewAPIHadoopFile(
basepath + "/badinputs/saveAsNewAPIHadoopFile/",
"org.apache.hadoop.mapreduce.lib.output.NotValidOutputFormat"))
def test_converters(self):
# use of custom converters
basepath = self.tempdir.name
data = [(1, {3.0: u'bb'}),
(2, {1.0: u'aa'}),
(3, {2.0: u'dd'})]
self.sc.parallelize(data).saveAsNewAPIHadoopFile(
basepath + "/converters/",
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
keyConverter="org.apache.spark.api.python.TestOutputKeyConverter",
valueConverter="org.apache.spark.api.python.TestOutputValueConverter")
converted = sorted(self.sc.sequenceFile(basepath + "/converters/").collect())
expected = [(u'1', 3.0),
(u'2', 1.0),
(u'3', 2.0)]
self.assertEqual(converted, expected)
def test_reserialization(self):
basepath = self.tempdir.name
x = range(1, 5)
y = range(1001, 1005)
data = list(zip(x, y))
rdd = self.sc.parallelize(x).zip(self.sc.parallelize(y))
rdd.saveAsSequenceFile(basepath + "/reserialize/sequence")
result1 = sorted(self.sc.sequenceFile(basepath + "/reserialize/sequence").collect())
self.assertEqual(result1, data)
rdd.saveAsHadoopFile(
basepath + "/reserialize/hadoop",
"org.apache.hadoop.mapred.SequenceFileOutputFormat")
result2 = sorted(self.sc.sequenceFile(basepath + "/reserialize/hadoop").collect())
self.assertEqual(result2, data)
rdd.saveAsNewAPIHadoopFile(
basepath + "/reserialize/newhadoop",
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat")
result3 = sorted(self.sc.sequenceFile(basepath + "/reserialize/newhadoop").collect())
self.assertEqual(result3, data)
conf4 = {
"mapred.output.format.class": "org.apache.hadoop.mapred.SequenceFileOutputFormat",
"mapred.output.key.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.value.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.dir": basepath + "/reserialize/dataset"}
rdd.saveAsHadoopDataset(conf4)
result4 = sorted(self.sc.sequenceFile(basepath + "/reserialize/dataset").collect())
self.assertEqual(result4, data)
conf5 = {"mapreduce.outputformat.class":
"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat",
"mapred.output.key.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.value.class": "org.apache.hadoop.io.IntWritable",
"mapred.output.dir": basepath + "/reserialize/newdataset"}
rdd.saveAsNewAPIHadoopDataset(conf5)
result5 = sorted(self.sc.sequenceFile(basepath + "/reserialize/newdataset").collect())
self.assertEqual(result5, data)
def test_malformed_RDD(self):
basepath = self.tempdir.name
# non-batch-serialized RDD[[(K, V)]] should be rejected
data = [[(1, "a")], [(2, "aa")], [(3, "aaa")]]
rdd = self.sc.parallelize(data, len(data))
self.assertRaises(Exception, lambda: rdd.saveAsSequenceFile(
basepath + "/malformed/sequence"))
class DaemonTests(unittest.TestCase):
def connect(self, port):
from socket import socket, AF_INET, SOCK_STREAM
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('127.0.0.1', port))
# send a split index of -1 to shutdown the worker
sock.send(b"\xFF\xFF\xFF\xFF")
sock.close()
return True
def do_termination_test(self, terminator):
from subprocess import Popen, PIPE
from errno import ECONNREFUSED
# start daemon
daemon_path = os.path.join(os.path.dirname(__file__), "daemon.py")
python_exec = sys.executable or os.environ.get("PYSPARK_PYTHON")
daemon = Popen([python_exec, daemon_path], stdin=PIPE, stdout=PIPE)
# read the port number
port = read_int(daemon.stdout)
# daemon should accept connections
self.assertTrue(self.connect(port))
# request shutdown
terminator(daemon)
time.sleep(1)
# daemon should no longer accept connections
try:
self.connect(port)
except EnvironmentError as exception:
self.assertEqual(exception.errno, ECONNREFUSED)
else:
self.fail("Expected EnvironmentError to be raised")
def test_termination_stdin(self):
"""Ensure that daemon and workers terminate when stdin is closed."""
self.do_termination_test(lambda daemon: daemon.stdin.close())
def test_termination_sigterm(self):
"""Ensure that daemon and workers terminate on SIGTERM."""
from signal import SIGTERM
self.do_termination_test(lambda daemon: os.kill(daemon.pid, SIGTERM))
class WorkerTests(ReusedPySparkTestCase):
def test_cancel_task(self):
temp = tempfile.NamedTemporaryFile(delete=True)
temp.close()
path = temp.name
def sleep(x):
import os
import time
with open(path, 'w') as f:
f.write("%d %d" % (os.getppid(), os.getpid()))
time.sleep(100)
# start job in background thread
def run():
try:
self.sc.parallelize(range(1), 1).foreach(sleep)
except Exception:
pass
import threading
t = threading.Thread(target=run)
t.daemon = True
t.start()
daemon_pid, worker_pid = 0, 0
while True:
if os.path.exists(path):
with open(path) as f:
data = f.read().split(' ')
daemon_pid, worker_pid = map(int, data)
break
time.sleep(0.1)
# cancel jobs
self.sc.cancelAllJobs()
t.join()
for i in range(50):
try:
os.kill(worker_pid, 0)
time.sleep(0.1)
except OSError:
break # worker was killed
else:
self.fail("worker has not been killed after 5 seconds")
try:
os.kill(daemon_pid, 0)
except OSError:
self.fail("daemon had been killed")
# run a normal job
rdd = self.sc.parallelize(xrange(100), 1)
self.assertEqual(100, rdd.map(str).count())
def test_after_exception(self):
def raise_exception(_):
raise Exception()
rdd = self.sc.parallelize(xrange(100), 1)
with QuietTest(self.sc):
self.assertRaises(Exception, lambda: rdd.foreach(raise_exception))
self.assertEqual(100, rdd.map(str).count())
def test_after_jvm_exception(self):
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write(b"Hello World!")
tempFile.close()
data = self.sc.textFile(tempFile.name, 1)
filtered_data = data.filter(lambda x: True)
self.assertEqual(1, filtered_data.count())
os.unlink(tempFile.name)
with QuietTest(self.sc):
self.assertRaises(Exception, lambda: filtered_data.count())
rdd = self.sc.parallelize(xrange(100), 1)
self.assertEqual(100, rdd.map(str).count())
def test_accumulator_when_reuse_worker(self):
from pyspark.accumulators import INT_ACCUMULATOR_PARAM
acc1 = self.sc.accumulator(0, INT_ACCUMULATOR_PARAM)
self.sc.parallelize(xrange(100), 20).foreach(lambda x: acc1.add(x))
self.assertEqual(sum(range(100)), acc1.value)
acc2 = self.sc.accumulator(0, INT_ACCUMULATOR_PARAM)
self.sc.parallelize(xrange(100), 20).foreach(lambda x: acc2.add(x))
self.assertEqual(sum(range(100)), acc2.value)
self.assertEqual(sum(range(100)), acc1.value)
def test_reuse_worker_after_take(self):
rdd = self.sc.parallelize(xrange(100000), 1)
self.assertEqual(0, rdd.first())
def count():
try:
rdd.count()
except Exception:
pass
t = threading.Thread(target=count)
t.daemon = True
t.start()
t.join(5)
self.assertTrue(not t.isAlive())
self.assertEqual(100000, rdd.count())
def test_with_different_versions_of_python(self):
rdd = self.sc.parallelize(range(10))
rdd.count()
version = self.sc.pythonVer
self.sc.pythonVer = "2.0"
try:
with QuietTest(self.sc):
self.assertRaises(Py4JJavaError, lambda: rdd.count())
finally:
self.sc.pythonVer = version
class SparkSubmitTests(unittest.TestCase):
def setUp(self):
self.programDir = tempfile.mkdtemp()
self.sparkSubmit = os.path.join(os.environ.get("SPARK_HOME"), "bin", "spark-submit")
def tearDown(self):
shutil.rmtree(self.programDir)
def createTempFile(self, name, content, dir=None):
"""
Create a temp file with the given name and content and return its path.
Strips leading spaces from content up to the first '|' in each line.
"""
pattern = re.compile(r'^ *\|', re.MULTILINE)
content = re.sub(pattern, '', content.strip())
if dir is None:
path = os.path.join(self.programDir, name)
else:
os.makedirs(os.path.join(self.programDir, dir))
path = os.path.join(self.programDir, dir, name)
with open(path, "w") as f:
f.write(content)
return path
def createFileInZip(self, name, content, ext=".zip", dir=None, zip_name=None):
"""
Create a zip archive containing a file with the given content and return its path.
Strips leading spaces from content up to the first '|' in each line.
"""
pattern = re.compile(r'^ *\|', re.MULTILINE)
content = re.sub(pattern, '', content.strip())
if dir is None:
path = os.path.join(self.programDir, name + ext)
else:
path = os.path.join(self.programDir, dir, zip_name + ext)
zip = zipfile.ZipFile(path, 'w')
zip.writestr(name, content)
zip.close()
return path
def create_spark_package(self, artifact_name):
group_id, artifact_id, version = artifact_name.split(":")
self.createTempFile("%s-%s.pom" % (artifact_id, version), ("""
|<?xml version="1.0" encoding="UTF-8"?>
|<project xmlns="http://maven.apache.org/POM/4.0.0"
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
| http://maven.apache.org/xsd/maven-4.0.0.xsd">
| <modelVersion>4.0.0</modelVersion>
| <groupId>%s</groupId>
| <artifactId>%s</artifactId>
| <version>%s</version>
|</project>
""" % (group_id, artifact_id, version)).lstrip(),
os.path.join(group_id, artifact_id, version))
self.createFileInZip("%s.py" % artifact_id, """
|def myfunc(x):
| return x + 1
""", ".jar", os.path.join(group_id, artifact_id, version),
"%s-%s" % (artifact_id, version))
def test_single_script(self):
"""Submit and test a single script file"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(lambda x: x * 2).collect())
""")
proc = subprocess.Popen([self.sparkSubmit, script], stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 4, 6]", out.decode('utf-8'))
def test_script_with_local_functions(self):
"""Submit and test a single script file calling a global function"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|
|def foo(x):
| return x * 3
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(foo).collect())
""")
proc = subprocess.Popen([self.sparkSubmit, script], stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[3, 6, 9]", out.decode('utf-8'))
def test_module_dependency(self):
"""Submit and test a script with a dependency on another module"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|from mylib import myfunc
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(myfunc).collect())
""")
zip = self.createFileInZip("mylib.py", """
|def myfunc(x):
| return x + 1
""")
proc = subprocess.Popen([self.sparkSubmit, "--py-files", zip, script],
stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 3, 4]", out.decode('utf-8'))
def test_module_dependency_on_cluster(self):
"""Submit and test a script with a dependency on another module on a cluster"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|from mylib import myfunc
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(myfunc).collect())
""")
zip = self.createFileInZip("mylib.py", """
|def myfunc(x):
| return x + 1
""")
proc = subprocess.Popen([self.sparkSubmit, "--py-files", zip, "--master",
"local-cluster[1,1,1024]", script],
stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 3, 4]", out.decode('utf-8'))
def test_package_dependency(self):
"""Submit and test a script with a dependency on a Spark Package"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|from mylib import myfunc
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(myfunc).collect())
""")
self.create_spark_package("a:mylib:0.1")
proc = subprocess.Popen([self.sparkSubmit, "--packages", "a:mylib:0.1", "--repositories",
"file:" + self.programDir, script], stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 3, 4]", out.decode('utf-8'))
def test_package_dependency_on_cluster(self):
"""Submit and test a script with a dependency on a Spark Package on a cluster"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|from mylib import myfunc
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(myfunc).collect())
""")
self.create_spark_package("a:mylib:0.1")
proc = subprocess.Popen([self.sparkSubmit, "--packages", "a:mylib:0.1", "--repositories",
"file:" + self.programDir, "--master",
"local-cluster[1,1,1024]", script], stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 3, 4]", out.decode('utf-8'))
def test_single_script_on_cluster(self):
"""Submit and test a single script on a cluster"""
script = self.createTempFile("test.py", """
|from pyspark import SparkContext
|
|def foo(x):
| return x * 2
|
|sc = SparkContext()
|print(sc.parallelize([1, 2, 3]).map(foo).collect())
""")
# this will fail if you have different spark.executor.memory
# in conf/spark-defaults.conf
proc = subprocess.Popen(
[self.sparkSubmit, "--master", "local-cluster[1,1,1024]", script],
stdout=subprocess.PIPE)
out, err = proc.communicate()
self.assertEqual(0, proc.returncode)
self.assertIn("[2, 4, 6]", out.decode('utf-8'))
class ContextTests(unittest.TestCase):
def test_failed_sparkcontext_creation(self):
# Regression test for SPARK-1550
self.assertRaises(Exception, lambda: SparkContext("an-invalid-master-name"))
def test_get_or_create(self):
with SparkContext.getOrCreate() as sc:
self.assertTrue(SparkContext.getOrCreate() is sc)
def test_stop(self):
sc = SparkContext()
self.assertNotEqual(SparkContext._active_spark_context, None)
sc.stop()
self.assertEqual(SparkContext._active_spark_context, None)
def test_with(self):
with SparkContext() as sc:
self.assertNotEqual(SparkContext._active_spark_context, None)
self.assertEqual(SparkContext._active_spark_context, None)
def test_with_exception(self):
try:
with SparkContext() as sc:
self.assertNotEqual(SparkContext._active_spark_context, None)
raise Exception()
except:
pass
self.assertEqual(SparkContext._active_spark_context, None)
def test_with_stop(self):
with SparkContext() as sc:
self.assertNotEqual(SparkContext._active_spark_context, None)
sc.stop()
self.assertEqual(SparkContext._active_spark_context, None)
def test_progress_api(self):
with SparkContext() as sc:
sc.setJobGroup('test_progress_api', '', True)
rdd = sc.parallelize(range(10)).map(lambda x: time.sleep(100))
def run():
try:
rdd.count()
except Exception:
pass
t = threading.Thread(target=run)
t.daemon = True
t.start()
# wait for scheduler to start
time.sleep(1)
tracker = sc.statusTracker()
jobIds = tracker.getJobIdsForGroup('test_progress_api')
self.assertEqual(1, len(jobIds))
job = tracker.getJobInfo(jobIds[0])
self.assertEqual(1, len(job.stageIds))
stage = tracker.getStageInfo(job.stageIds[0])
self.assertEqual(rdd.getNumPartitions(), stage.numTasks)
sc.cancelAllJobs()
t.join()
# wait for event listener to update the status
time.sleep(1)
job = tracker.getJobInfo(jobIds[0])
self.assertEqual('FAILED', job.status)
self.assertEqual([], tracker.getActiveJobsIds())
self.assertEqual([], tracker.getActiveStageIds())
sc.stop()
def test_startTime(self):
with SparkContext() as sc:
self.assertGreater(sc.startTime, 0)
@unittest.skipIf(not _have_scipy, "SciPy not installed")
class SciPyTests(PySparkTestCase):
"""General PySpark tests that depend on scipy """
def test_serialize(self):
from scipy.special import gammaln
x = range(1, 5)
expected = list(map(gammaln, x))
observed = self.sc.parallelize(x).map(gammaln).collect()
self.assertEqual(expected, observed)
@unittest.skipIf(not _have_numpy, "NumPy not installed")
class NumPyTests(PySparkTestCase):
"""General PySpark tests that depend on numpy """
def test_statcounter_array(self):
x = self.sc.parallelize([np.array([1.0, 1.0]), np.array([2.0, 2.0]), np.array([3.0, 3.0])])
s = x.stats()
self.assertSequenceEqual([2.0, 2.0], s.mean().tolist())
self.assertSequenceEqual([1.0, 1.0], s.min().tolist())
self.assertSequenceEqual([3.0, 3.0], s.max().tolist())
self.assertSequenceEqual([1.0, 1.0], s.sampleStdev().tolist())
stats_dict = s.asDict()
self.assertEqual(3, stats_dict['count'])
self.assertSequenceEqual([2.0, 2.0], stats_dict['mean'].tolist())
self.assertSequenceEqual([1.0, 1.0], stats_dict['min'].tolist())
self.assertSequenceEqual([3.0, 3.0], stats_dict['max'].tolist())
self.assertSequenceEqual([6.0, 6.0], stats_dict['sum'].tolist())
self.assertSequenceEqual([1.0, 1.0], stats_dict['stdev'].tolist())
self.assertSequenceEqual([1.0, 1.0], stats_dict['variance'].tolist())
stats_sample_dict = s.asDict(sample=True)
self.assertEqual(3, stats_dict['count'])
self.assertSequenceEqual([2.0, 2.0], stats_sample_dict['mean'].tolist())
self.assertSequenceEqual([1.0, 1.0], stats_sample_dict['min'].tolist())
self.assertSequenceEqual([3.0, 3.0], stats_sample_dict['max'].tolist())
self.assertSequenceEqual([6.0, 6.0], stats_sample_dict['sum'].tolist())
self.assertSequenceEqual(
[0.816496580927726, 0.816496580927726], stats_sample_dict['stdev'].tolist())
self.assertSequenceEqual(
[0.6666666666666666, 0.6666666666666666], stats_sample_dict['variance'].tolist())
if __name__ == "__main__":
if not _have_scipy:
print("NOTE: Skipping SciPy tests as it does not seem to be installed")
if not _have_numpy:
print("NOTE: Skipping NumPy tests as it does not seem to be installed")
unittest.main()
if not _have_scipy:
print("NOTE: SciPy tests were skipped as it does not seem to be installed")
if not _have_numpy:
print("NOTE: NumPy tests were skipped as it does not seem to be installed")
|
{
"content_hash": "824740d79f1241a741aee92a947def15",
"timestamp": "",
"source": "github",
"line_count": 1996,
"max_line_length": 99,
"avg_line_length": 41.079659318637276,
"alnum_prop": 0.5855478992621501,
"repo_name": "pronix/spark",
"id": "3c51809444401aa73b8f1fa84139821d97deac44",
"size": "82780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/pyspark/tests.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "26730"
},
{
"name": "C",
"bytes": "1493"
},
{
"name": "CSS",
"bytes": "15314"
},
{
"name": "Groff",
"bytes": "5379"
},
{
"name": "Java",
"bytes": "1736009"
},
{
"name": "JavaScript",
"bytes": "69325"
},
{
"name": "Makefile",
"bytes": "7767"
},
{
"name": "Python",
"bytes": "1625694"
},
{
"name": "R",
"bytes": "474164"
},
{
"name": "Scala",
"bytes": "14642450"
},
{
"name": "Shell",
"bytes": "140679"
},
{
"name": "Thrift",
"bytes": "2016"
}
],
"symlink_target": ""
}
|
namespace Google.Cloud.SecurityCenter.V1.Snippets
{
// [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async_flattened]
using Google.Cloud.SecurityCenter.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedSecurityCenterClientSnippets
{
/// <summary>Snippet for DeleteBigQueryExportAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteBigQueryExportAsync()
{
// Create client
SecurityCenterClient securityCenterClient = await SecurityCenterClient.CreateAsync();
// Initialize request argument(s)
string name = "organizations/[ORGANIZATION]/bigQueryExports/[EXPORT]";
// Make the request
await securityCenterClient.DeleteBigQueryExportAsync(name);
}
}
// [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async_flattened]
}
|
{
"content_hash": "55114ad7ac8bd18d93977e21631eb955",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 97,
"avg_line_length": 44.36,
"alnum_prop": 0.6961226330027052,
"repo_name": "jskeet/gcloud-dotnet",
"id": "162a8e1a650bfb8a496a7084275bbd435136dfe9",
"size": "1731",
"binary": false,
"copies": "1",
"ref": "refs/heads/bq-migration",
"path": "apis/Google.Cloud.SecurityCenter.V1/Google.Cloud.SecurityCenter.V1.GeneratedSnippets/SecurityCenterClient.DeleteBigQueryExportAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1725"
},
{
"name": "C#",
"bytes": "1829733"
}
],
"symlink_target": ""
}
|
package com.sylvanaar.idea.Lua.debugger;
import java.util.ArrayList;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.Messages;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 3/19/11
* Time: 7:40 PM
*/
public class LuaDebugProcess extends XDebugProcess {
private static final Logger log = Logger.getInstance("Lua.LuaDebugProcess");
final LuaDebuggerController controller;
LuaLineBreakpointHandler lineBreakpointHandler;
private boolean myClosing;
private ExecutionResult executionResult;
private ConsoleView myExecutionConsole;
/**
* @param session pass <code>session</code> parameter of {@link com.intellij.xdebugger
* .XDebugProcessStarter#start} method to this constructor
* @param result
*/
protected LuaDebugProcess(@Nonnull XDebugSession session, ExecutionResult result) {
super(session);
lineBreakpointHandler = new LuaLineBreakpointHandler(this);
controller = new LuaDebuggerController(session);
executionResult = result;
}
@Nonnull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return new LuaDebuggerEditorsProvider();
}
@Override
public void startStepOver() {
controller.stepOver();
}
@Override
public void startStepInto() {
controller.stepInto();
}
@Override
public void startStepOut() {
}
@Override
public void stop() {
myClosing = true;
if (executionResult != null) executionResult.getProcessHandler().destroyProcess();
controller.terminate();
}
@Override
public void resume() {
controller.resume();
}
@Override
public void runToPosition(@Nonnull XSourcePosition position) {
throw new UnsupportedOperationException();
}
@Override
protected ProcessHandler doGetProcessHandler() {
return executionResult.getProcessHandler();
}
@Nonnull
@Override
public ExecutionConsole createConsole() {
myExecutionConsole = (ConsoleView) executionResult.getExecutionConsole();
controller.setConsole(myExecutionConsole);
return myExecutionConsole;
}
public void printToConsole(String text, ConsoleViewContentType contentType) {
myExecutionConsole.print(text, contentType);
}
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return new XBreakpointHandler<?>[]{lineBreakpointHandler};
}
public void sessionInitialized() {
super.sessionInitialized();
ProgressManager.getInstance().run(new Task.Backgroundable(null, "Connecting to debugger", false) {
public void run(@Nonnull ProgressIndicator indicator) {
indicator.setText("Connecting to debugger...");
log.debug("connecting");
try {
controller.waitForConnect();
log.debug("connected");
indicator.setText("... Debugger connected");
getSession().rebuildViews();
registerBreakpoints();
controller.resume();
} catch (final Exception e) {
if (executionResult != null && executionResult.getProcessHandler() != null)
executionResult.getProcessHandler().destroyProcess();
if (!myClosing) SwingUtilities.invokeLater(new Runnable() {
public void run() {
Messages.showErrorDialog(
(new StringBuilder()).append("Unable to establish connection with debugger:\n")
.append(e.getMessage()).toString(), "Connecting to Debugger");
}
});
}
}
});
}
java.util.List<XBreakpoint> installedBreaks = new ArrayList<XBreakpoint>();
private synchronized void registerBreakpoints() {
log.debug("registering pending breakpoints");
for (XBreakpoint b : installedBreaks) {
while (!controller.isReady()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return;
}
}
controller.addBreakPoint(b);
}
installedBreaks.clear();
}
public synchronized void addBreakPoint(XBreakpoint pos) {
log.debug("add breakpoint " + pos.toString());
if (controller.isReady()) controller.addBreakPoint(pos);
else installedBreaks.add(pos);
}
public synchronized void removeBreakPoint(XBreakpoint pos) {
log.debug("remove breakpoint " + pos.toString());
// if (controller.isReady())
controller.removeBreakPoint(pos);
}
}
|
{
"content_hash": "a0871c9648b5bafec3fb0fad24fc046a",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 119,
"avg_line_length": 31.352941176470587,
"alnum_prop": 0.6411393484564216,
"repo_name": "consulo/consulo-lua",
"id": "ce277401526d21a546bfe142e7f4b8eecddf0aa7",
"size": "6484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/sylvanaar/idea/Lua/debugger/LuaDebugProcess.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "30192"
},
{
"name": "HTML",
"bytes": "272076"
},
{
"name": "Java",
"bytes": "1479749"
},
{
"name": "Lex",
"bytes": "8843"
},
{
"name": "Lua",
"bytes": "243663"
}
],
"symlink_target": ""
}
|
package io.onedecision.engine.decisions.examples.ch11;
public interface ExamplesConstants {
static final String TENANT_ID = "examples";
static final String CH11_DMN_RESOURCE = "/decisions/examples/Ch11LoanOriginationModel.dmn";
static final String CH11_DEFINITION_ID = "LoanOriginationModel";
// Identifiers from Figure 70 in spec's chapter 11.
static final String CH11_FIG70_DMN_RESOURCE = "/decisions/examples/Fig70Strategy.dmn";
static final String CH11_FIG70_JSON_RESOURCE = "/decisions/examples/Fig70Strategy.json";
static final String CH11_FIG70_DEFINITION_ID = "StrategyModel";
static final String CH11_FIG70_DECISION_ID = "_70_d";
// Identifiers from Figure 72 in spec's chapter 11.
static final String CH11_FIG72_DMN_RESOURCE = "/decisions/examples/Fig72BureauCallType.dmn";
static final String CH11_FIG72_JSON_RESOURCE = "/decisions/examples/Fig72BureauCallType.json";
static final String CH11_FIG72_DEFINITION_ID = "BureauCallTypeModel";
static final String CH11_FIG72_DECISION_ID = "_72_d";
// Identifiers from Figure 74 in spec's chapter 11.
static final String CH11_FIG74_DMN_RESOURCE = "/decisions/examples/Fig74EligibilityRules.dmn";
static final String CH11_FIG74_JSON_RESOURCE = "/decisions/examples/Fig74EligibilityRules.json";
static final String CH11_FIG74_DEFINITION_ID = "EligibilityRulesModel";
static final String CH11_FIG74_DECISION_ID = "_74_d";
// Identifiers from Figure 76 in spec's chapter 11.
static final String CH11_FIG76_DMN_RESOURCE = "/decisions/examples/Fig76PreBureauRiskCategoryTable.dmn";
static final String CH11_FIG76_JSON_RESOURCE = "/decisions/examples/Fig76PreBureauRiskCategoryTable.json";
static final String CH11_FIG76_DEFINITION_ID = "PreBureauRiskCategoryTable";
static final String CH11_FIG76_DECISION_ID = "_76_d";
static final String CH11_FIG78_DMN_RESOURCE = "/decisions/examples/Fig78ApplicationRiskScoreModel.dmn";
static final String CH11_FIG78_DEFINITION_ID = "ApplicationRiskScoreModel";
static final String CH11_FIG78_DECISION_ID = "ApplicationRiskScore";
static final String LO_DMN_RESOURCE = "/decisions/examples/AlternateLoanOriginationModel.dmn";
static final String LO_DEFINITION_ID = "AlternateLoanOriginationModel";
}
|
{
"content_hash": "8c9bd47e4a1474f22d016205ce41aeac",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 110,
"avg_line_length": 56.292682926829265,
"alnum_prop": 0.762998266897747,
"repo_name": "OneDecision/one-decision",
"id": "d39d99872f070323b4fe4ee0f68045e8a099839e",
"size": "2308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/src/main/java/io/onedecision/engine/decisions/examples/ch11/ExamplesConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23087"
},
{
"name": "FreeMarker",
"bytes": "5812"
},
{
"name": "HTML",
"bytes": "38407"
},
{
"name": "Java",
"bytes": "667893"
},
{
"name": "JavaScript",
"bytes": "193811"
},
{
"name": "XSLT",
"bytes": "17128"
}
],
"symlink_target": ""
}
|
from __future__ import division
import timeit
from .datatypes import TimingReport
def adaptiverun(stmt, setup='pass', number=0, repeat=3):
"""
Adaptively chooses a number of times to execute stmt, then does so repeat
times. It chooses a number of executions such that each set of loops takes
more than 0.2 seconds -- so it's hopefully a representative sample -- but
takes less than 2 seconds.
This code is adapted from the source for the timeit module from the Python
3.4 standard library. See line 284 here:
https://hg.python.org/cpython/file/3.4/Lib/timeit.py
"""
timer = timeit.default_timer
t = timeit.Timer(stmt, setup, timer)
if number == 0:
# determine number so that 0.2 <= total time < 2.0
for i in range(1, 10):
number = 10**i
x = t.timeit(number)
if x >= 0.2:
break
results = t.repeat(repeat, number)
best = min(results) * 1e6 / number
return TimingReport(best=best,
number=number,
repeat=repeat)
|
{
"content_hash": "ceb2fa96390276380ff92cb9fdd5e56b",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 78,
"avg_line_length": 33.03030303030303,
"alnum_prop": 0.618348623853211,
"repo_name": "mambocab/rumble",
"id": "45cf4a61a9cfc820d1554e606d80a3fafb76a67b",
"size": "1090",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rumble/adaptiverun.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "34103"
}
],
"symlink_target": ""
}
|
<?php
/* @var $this yii\web\View */
use yeesoft\comments\widgets\Comments;
use yeesoft\post\models\Post;
/* @var $post yeesoft\post\models\Post */
$this->title = $post->title;
$this->params['breadcrumbs'][] = $post->title;
?>
<?= $this->render('/items/post.php', ['post' => $post]) ?>
<?php if ($post->comment_status == Post::COMMENT_STATUS_OPEN): ?>
<?php echo Comments::widget(['model' => Post::className(), 'model_id' => $post->id]); ?>
<?php endif; ?>
|
{
"content_hash": "480ef1011a92d67eb9260b8e382c26c1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 92,
"avg_line_length": 27.294117647058822,
"alnum_prop": 0.6163793103448276,
"repo_name": "yeesoft/yii2-yee-cms",
"id": "17dc1ade090b7ef2c129fd7fe5974d64deb2e843",
"size": "464",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "frontend/views/site/post.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "853"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "1118675"
},
{
"name": "PHP",
"bytes": "144060"
}
],
"symlink_target": ""
}
|
package com.intellij.compiler;
import com.intellij.ProjectTopics;
import com.intellij.compiler.impl.CompileDriver;
import com.intellij.compiler.impl.ExitStatus;
import com.intellij.compiler.server.BuildManager;
import com.intellij.ide.highlighter.ModuleFileType;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactManager;
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.*;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.io.DirectoryContentSpec;
import com.intellij.util.io.DirectoryContentSpecKt;
import com.intellij.util.io.TestFileSystemBuilder;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.util.JpsPathUtil;
import org.junit.Assert;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
public abstract class BaseCompilerTestCase extends JavaModuleTestCase {
@Override
protected void setUpModule() {
}
@Override
protected boolean isCreateProjectFileExplicitly() {
return false;
}
@Override
protected void setUp() throws Exception {
super.setUp();
myProject.getMessageBus().connect(getTestRootDisposable()).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() {
@Override
public void rootsChanged(@NotNull ModuleRootEvent event) {
//todo[nik] projectOpened isn't called in tests so we need to add this listener manually
forceFSRescan();
}
});
CompilerTestUtil.enableExternalCompiler();
}
protected void forceFSRescan() {
BuildManager.getInstance().clearState(myProject);
}
@NotNull
@Override
protected LanguageLevel getProjectLanguageLevel() {
return LanguageLevel.JDK_1_8;
}
@Override
protected Sdk getTestProjectJdk() {
return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
}
@Override
protected void tearDown() throws Exception {
try {
for (Artifact artifact : getArtifactManager().getArtifacts()) {
final String outputPath = artifact.getOutputPath();
if (!StringUtil.isEmpty(outputPath)) {
FileUtil.delete(new File(FileUtil.toSystemDependentName(outputPath)));
}
}
CompilerTestUtil.disableExternalCompiler(getProject());
}
catch (Throwable e) {
addSuppressedException(e);
}
finally {
super.tearDown();
}
}
protected ArtifactManager getArtifactManager() {
return ArtifactManager.getInstance(myProject);
}
protected String getProjectBasePath() {
return myProject.getBasePath();
}
protected void copyToProject(String relativePath) {
File dir = PathManagerEx.findFileUnderProjectHome(relativePath, getClass());
final File target = new File(FileUtil.toSystemDependentName(getProjectBasePath()));
try {
FileUtil.copyDir(dir, target);
}
catch (IOException e) {
throw new RuntimeException(e);
}
WriteAction.runAndWait(() -> {
VirtualFile virtualDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(target);
assertNotNull(target.getAbsolutePath() + " not found", virtualDir);
virtualDir.refresh(false, true);
});
}
protected Module addModule(final String moduleName, final @Nullable VirtualFile sourceRoot) {
return addModule(moduleName, sourceRoot, null);
}
protected Module addModule(final String moduleName, final @Nullable VirtualFile sourceRoot, final @Nullable VirtualFile testRoot) {
return WriteAction.computeAndWait(() -> {
final Module module = createModule(moduleName);
if (sourceRoot != null) {
PsiTestUtil.addSourceContentToRoots(module, sourceRoot, false);
}
if (testRoot != null) {
PsiTestUtil.addSourceContentToRoots(module, testRoot, true);
}
ModuleRootModificationUtil.setModuleSdk(module, getTestProjectJdk());
return module;
});
}
protected VirtualFile createFile(final String path) {
return createFile(path, "");
}
protected VirtualFile createFile(@NotNull String path, final String text) {
return VfsTestUtil.createFile(getOrCreateProjectBaseDir(), path, text);
}
protected CompilationLog make(final Artifact... artifacts) {
final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, Arrays.asList(artifacts));
return make(scope);
}
protected CompilationLog recompile(final Artifact... artifacts) {
final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, Arrays.asList(artifacts), true);
return make(scope);
}
protected CompilationLog make(Module... modules) {
return make(false, false, modules);
}
protected CompilationLog makeWithDependencies(final boolean includeRuntimeDependencies, Module... modules) {
return make(true, includeRuntimeDependencies, modules);
}
private CompilationLog make(boolean includeDependentModules, final boolean includeRuntimeDependencies, Module... modules) {
return make(getCompilerManager().createModulesCompileScope(modules, includeDependentModules, includeRuntimeDependencies));
}
protected CompilationLog recompile(Module... modules) {
return compile(getCompilerManager().createModulesCompileScope(modules, false), true);
}
protected CompilerManager getCompilerManager() {
return CompilerManager.getInstance(myProject);
}
protected void assertModulesUpToDate() {
boolean upToDate = getCompilerManager().isUpToDate(getCompilerManager().createProjectCompileScope(myProject));
assertTrue("Modules are not up to date", upToDate);
}
protected CompilationLog compile(boolean force, VirtualFile... files) {
return compile(getCompilerManager().createFilesCompileScope(files), force);
}
protected CompilationLog make(final CompileScope scope) {
return compile(scope, false);
}
protected CompilationLog compile(final CompileScope scope, final boolean forceCompile) {
return compile(scope, forceCompile, false);
}
protected CompilationLog compile(final CompileScope scope, final boolean forceCompile,
final boolean errorsExpected) {
return compile(errorsExpected, callback -> {
final CompilerManager compilerManager = getCompilerManager();
if (forceCompile) {
compilerManager.compile(scope, callback);
}
else {
compilerManager.make(scope, callback);
}
});
}
protected CompilationLog rebuild() {
return compile(false, compileStatusNotification -> getCompilerManager().rebuild(compileStatusNotification));
}
protected CompilationLog compile(final boolean errorsExpected, final Consumer<CompileStatusNotification> action) {
CompilationLog log = compile(action);
if (errorsExpected && log.myErrors.length == 0) {
Assert.fail("compilation finished without errors");
}
else if (!errorsExpected && log.myErrors.length > 0) {
Assert.fail("compilation finished with errors: " + Arrays.toString(log.myErrors));
}
return log;
}
private CompilationLog compile(final Consumer<CompileStatusNotification> action) {
final Ref<CompilationLog> result = Ref.create(null);
final Semaphore semaphore = new Semaphore();
semaphore.down();
final List<String> generatedFilePaths = new ArrayList<>();
myProject.getMessageBus().connect(getTestRootDisposable()).subscribe(CompilerTopics.COMPILATION_STATUS, new CompilationStatusListener() {
@Override
public void fileGenerated(@NotNull String outputRoot, @NotNull String relativePath) {
generatedFilePaths.add(relativePath);
}
});
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
final CompileStatusNotification callback = new CompileStatusNotification() {
@Override
public void finished(boolean aborted, int errors, int warnings, @NotNull CompileContext compileContext) {
try {
if (aborted) {
Assert.fail("compilation aborted");
}
ExitStatus status = CompileDriver.getExternalBuildExitStatus(compileContext);
result.set(new CompilationLog(status == ExitStatus.UP_TO_DATE,
generatedFilePaths,
compileContext.getMessages(CompilerMessageCategory.ERROR),
compileContext.getMessages(CompilerMessageCategory.WARNING)));
}
finally {
semaphore.up();
}
}
};
PlatformTestUtil.saveProject(myProject);
CompilerTestUtil.saveApplicationSettings();
try {
CompilerTester.enableDebugLogging();
}
catch (IOException e) {
throw new RuntimeException(e);
}
action.accept(callback);
});
try {
final long start = System.currentTimeMillis();
while (!semaphore.waitFor(10)) {
if (!BuildManager.getInstance().isBuildProcessDebuggingEnabled() && System.currentTimeMillis() - start > 5 * 60 * 1000) {
throw new RuntimeException("timeout");
}
if (SwingUtilities.isEventDispatchThread()) {
UIUtil.dispatchAllInvocationEvents();
}
}
if (SwingUtilities.isEventDispatchThread()) {
UIUtil.dispatchAllInvocationEvents();
}
}
finally {
CompilerTester.printBuildLog();
}
return result.get();
}
protected void changeFile(VirtualFile file) {
changeFile(file, null);
}
protected void changeFile(final VirtualFile file, @Nullable final String newText) {
try {
if (newText != null) {
setFileText(file, newText);
}
((NewVirtualFile)file).setTimeStamp(file.getTimeStamp() + 10);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
protected void deleteFile(final VirtualFile file) {
try {
WriteAction.runAndWait(() -> file.delete(this));
}
catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
protected void setUpProject() throws Exception {
super.setUpProject();
CompilerProjectExtension.getInstance(myProject).setCompilerOutputUrl("file://" + myProject.getBasePath() + "/out");
}
@NotNull
@Override
protected Module doCreateRealModule(@NotNull String moduleName) {
//todo[nik] reuse code from PlatformTestCase
final VirtualFile baseDir = getOrCreateProjectBaseDir();
final File moduleFile = new File(baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION);
myFilesToDelete.add(moduleFile);
return WriteAction.computeAndWait(() -> {
Module module = ModuleManager.getInstance(myProject)
.newModule(FileUtil.toSystemIndependentName(moduleFile.getAbsolutePath()), getModuleType().getId());
module.getModuleFile();
return module;
});
}
protected CompilationLog buildAllModules() {
return make(getCompilerManager().createProjectCompileScope(myProject));
}
protected static void assertOutput(Module module, TestFileSystemBuilder item) {
assertOutput(module, item, false);
}
protected static void assertOutput(Module module, DirectoryContentSpec spec) {
DirectoryContentSpecKt.assertMatches(getOutputDir(module, false), spec);
}
protected static void assertOutput(Module module, TestFileSystemBuilder item, final boolean forTests) {
File outputDir = getOutputDir(module, forTests);
Assert.assertTrue((forTests? "Test output" : "Output") +" directory " + outputDir.getAbsolutePath() + " doesn't exist", outputDir.exists());
item.build().assertDirectoryEqual(outputDir);
}
protected static void assertNoOutput(Module module) {
File dir = getOutputDir(module);
Assert.assertFalse("Output directory " + dir.getAbsolutePath() + " does exist", dir.exists());
}
protected static File getOutputDir(Module module) {
return getOutputDir(module, false);
}
protected static File getOutputDir(Module module, boolean forTests) {
CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module);
Assert.assertNotNull(extension);
String outputUrl = forTests? extension.getCompilerOutputUrlForTests() : extension.getCompilerOutputUrl();
Assert.assertNotNull((forTests? "Test output" : "Output") +" directory for module '" + module.getName() + "' isn't specified", outputUrl);
return JpsPathUtil.urlToFile(outputUrl);
}
protected static void createFileInOutput(Module m, final String fileName) {
try {
boolean created = new File(getOutputDir(m), fileName).createNewFile();
assertTrue(created);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
protected static void createFileInOutput(Artifact a, final String name) {
try {
boolean created = new File(a.getOutputPath(), name).createNewFile();
assertTrue(created);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
protected static class CompilationLog {
private final Set<String> myGeneratedPaths;
private final boolean myExternalBuildUpToDate;
private final CompilerMessage[] myErrors;
private final CompilerMessage[] myWarnings;
public CompilationLog(boolean externalBuildUpToDate, List<String> generatedFilePaths, CompilerMessage[] errors,
CompilerMessage[] warnings) {
myExternalBuildUpToDate = externalBuildUpToDate;
myErrors = errors;
myWarnings = warnings;
myGeneratedPaths = new THashSet<>(generatedFilePaths, FileUtil.PATH_HASHING_STRATEGY);
}
public void assertUpToDate() {
assertTrue(myExternalBuildUpToDate);
}
public void assertGenerated(String... expected) {
assertSet("generated", myGeneratedPaths, expected);
}
public CompilerMessage[] getErrors() {
return myErrors;
}
public CompilerMessage[] getWarnings() {
return myWarnings;
}
private static void assertSet(String name, Set<String> actual, String[] expected) {
for (String path : expected) {
if (!actual.remove(path)) {
Assert.fail("'" + path + "' is not " + name + ". " + name + ": " + new HashSet<>(actual));
}
}
if (!actual.isEmpty()) {
Assert.fail("'" + actual.iterator().next() + "' must not be " + name);
}
}
}
}
|
{
"content_hash": "bebf6c29e112a2ffba08065d22db2c07",
"timestamp": "",
"source": "github",
"line_count": 431,
"max_line_length": 144,
"avg_line_length": 35.52900232018561,
"alnum_prop": 0.7088748122510286,
"repo_name": "leafclick/intellij-community",
"id": "6b9641bb246b18e3a3e4d1478acaa93b99b0874c",
"size": "15454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/compiler/tests/com/intellij/compiler/BaseCompilerTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
import sys
from time import sleep
from uuid import UUID, uuid4 as _uuid4, _uuid_generate_random
try:
import ctypes
except ImportError:
ctypes = None # noqa
def say(m, *s):
sys.stderr.write(str(m) % s + "\n")
def uuid4():
# Workaround for http://bugs.python.org/issue4607
if ctypes and _uuid_generate_random:
buffer = ctypes.create_string_buffer(16)
_uuid_generate_random(buffer)
return UUID(bytes=buffer.raw)
return _uuid4()
def gen_unique_id():
"""Generate a unique id, having - hopefully - a very small chance of
collission.
For now this is provided by :func:`uuid.uuid4`.
"""
return str(uuid4())
if sys.version_info >= (3, 0):
def kwdict(kwargs):
return kwargs
else:
def kwdict(kwargs): # noqa
"""Make sure keyword arguments are not in unicode.
This should be fixed in newer Python versions,
see: http://bugs.python.org/issue4978.
"""
return dict((key.encode("utf-8"), value)
for key, value in kwargs.items())
def maybe_list(v):
if v is None:
return []
if hasattr(v, "__iter__"):
return v
return [v]
def fxrange(start=1.0, stop=None, step=1.0, repeatlast=False):
cur = start * 1.0
while 1:
if cur <= stop:
yield cur
cur += step
else:
if not repeatlast:
break
yield cur - step
def retry_over_time(fun, catch, args=[], kwargs={}, errback=None,
max_retries=None, interval_start=2, interval_step=2, interval_max=30):
"""Retry the function over and over until max retries is exceeded.
For each retry we sleep a for a while before we try again, this interval
is increased for every retry until the max seconds is reached.
:param fun: The function to try
:param catch: Exceptions to catch, can be either tuple or a single
exception class.
:keyword args: Positional arguments passed on to the function.
:keyword kwargs: Keyword arguments passed on to the function.
:keyword errback: Callback for when an exception in ``catch`` is raised.
The callback must take two arguments: ``exc`` and ``interval``, where
``exc`` is the exception instance, and ``interval`` is the time in
seconds to sleep next..
:keyword max_retries: Maximum number of retries before we give up.
If this is not set, we will retry forever.
:keyword interval_start: How long (in seconds) we start sleeping between
retries.
:keyword interval_step: By how much the interval is increased for each
retry.
:keyword interval_max: Maximum number of seconds to sleep between retries.
"""
retries = 0
interval_range = fxrange(interval_start,
interval_max + interval_start,
interval_step, repeatlast=True)
for retries, interval in enumerate(interval_range):
try:
return fun(*args, **kwargs)
except catch, exc:
if max_retries and retries > max_retries:
raise
if errback:
errback(exc, interval)
sleep(interval)
def emergency_dump_state(state, open_file=open, dump=None):
from pprint import pformat
from tempfile import mktemp
if dump is None:
import pickle
dump = pickle.dump
persist = mktemp()
say("EMERGENCY DUMP STATE TO FILE -> %s <-" % persist)
fh = open_file(persist, "w")
try:
try:
dump(state, fh, protocol=0)
except Exception, exc:
say("Cannot pickle state: %r. Fallback to pformat." % (exc, ))
fh.write(pformat(state))
finally:
fh.flush()
fh.close()
return persist
############## str.partition/str.rpartition #################################
def _compat_rl_partition(S, sep, direction=None, reverse=False):
items = direction(sep, 1)
if len(items) == 1:
if reverse:
return '', '', items[0]
return items[0], '', ''
return items[0], sep, items[1]
def _compat_partition(S, sep):
"""``partition(S, sep) -> (head, sep, tail)``
Search for the separator ``sep`` in ``S``, and return the part before
it, the separator itself, and the part after it. If the separator is not
found, return ``S`` and two empty strings.
"""
return _compat_rl_partition(S, sep, direction=S.split)
def _compat_rpartition(S, sep):
"""``rpartition(S, sep) -> (tail, sep, head)``
Search for the separator ``sep`` in ``S``, starting at the end of ``S``,
and return the part before it, the separator itself, and the part
after it. If the separator is not found, return two empty
strings and ``S``.
"""
return _compat_rl_partition(S, sep, direction=S.rsplit, reverse=True)
def partition(S, sep):
if hasattr(S, 'partition'):
return S.partition(sep)
else: # Python <= 2.4:
return _compat_partition(S, sep)
def rpartition(S, sep):
if hasattr(S, 'rpartition'):
return S.rpartition(sep)
else: # Python <= 2.4:
return _compat_rpartition(S, sep)
class cached_property(object):
"""Property descriptor that caches the return value
of the get function.
*Examples*
.. code-block:: python
@cached_property
def connection(self):
return Connection()
@connection.setter # Prepares stored value
def connection(self, value):
if value is None:
raise TypeError("Connection must be a connection")
return value
@connection.deleter
def connection(self, value):
# Additional action to do at del(self.attr)
if value is not None:
print("Connection %r deleted" % (value, ))
"""
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.__get = fget
self.__set = fset
self.__del = fdel
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
self.__module__ = fget.__module__
def __get__(self, obj, type=None):
if obj is None:
return self
try:
return obj.__dict__[self.__name__]
except KeyError:
value = obj.__dict__[self.__name__] = self.__get(obj)
return value
def __set__(self, obj, value):
if obj is None:
return self
if self.__set is not None:
value = self.__set(obj, value)
obj.__dict__[self.__name__] = value
def __delete__(self, obj):
if obj is None:
return self
try:
value = obj.__dict__.pop(self.__name__)
except KeyError:
pass
else:
if self.__del is not None:
self.__del(obj, value)
def setter(self, fset):
return self.__class__(self.__get, fset, self.__del)
def deleter(self, fdel):
return self.__class__(self.__get, self.__set, fdel)
|
{
"content_hash": "d0bb2398edc9504f12f4487674f10853",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 78,
"avg_line_length": 28.833333333333332,
"alnum_prop": 0.5777527139433244,
"repo_name": "pantheon-systems/kombu",
"id": "85822a6d0e3c441d746ba41b5d787fdd47bc6e11",
"size": "7093",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kombu/utils/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "340782"
},
{
"name": "Shell",
"bytes": "428"
}
],
"symlink_target": ""
}
|
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
#include "UNIX_IPsecTransportActionProvider.h"
extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
else if (String::equalNoCase(providerName, "UNIX_IPsecTransportActionProvider")) return new UNIX_IPsecTransportActionProvider();
return NULL;
}
|
{
"content_hash": "38ecdf73ccccf6f450ec0b8af50f6a39",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 129,
"avg_line_length": 25.5625,
"alnum_prop": 0.8019559902200489,
"repo_name": "brunolauze/pegasus-providers",
"id": "72e5b65569856e44f0adebba94690e77a15a417f",
"size": "2213",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportActionMain.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "2623404"
},
{
"name": "C++",
"bytes": "897179702"
},
{
"name": "Objective-C",
"bytes": "64"
},
{
"name": "Shell",
"bytes": "258"
}
],
"symlink_target": ""
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RapidGame.tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
}
}
|
{
"content_hash": "5266c4ee9bf6e8f6e59626133573140c",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 51,
"avg_line_length": 15.266666666666667,
"alnum_prop": 0.611353711790393,
"repo_name": "TRex22/RapidGame",
"id": "a5863e4aea0cebb0a7668c0b0d0ea5e6b3672ffd",
"size": "231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RapidGame.tests/UnitTest1.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9429"
}
],
"symlink_target": ""
}
|
define(function(){
var postView = Backbone.View.extend({
tagName:"div",
template:_.template( $( '#post' ).html() ),
events: {
'click .J_post_delete': 'deletePost'
},
initialize:function(){
},
render:function(){
this.$el.html( this.template( this.model.toJSON() ) );
return this;
},
deletePost:function(){
var w = this;
w.model.destroy();
w.remove();
}
});
return postView;
});
|
{
"content_hash": "c682783fb2a22a19ec88615b255a31f4",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 58,
"avg_line_length": 18.166666666666668,
"alnum_prop": 0.5688073394495413,
"repo_name": "gitoneman/paper",
"id": "0415609c5b78a821d05f0e59555ac847049a0262",
"size": "436",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/js/view/post.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "451"
},
{
"name": "JavaScript",
"bytes": "12429"
}
],
"symlink_target": ""
}
|
package org.multibit.hd.ui.views.wizards.welcome.restore_wallet;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import net.miginfocom.swing.MigLayout;
import org.multibit.commons.utils.Dates;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.Components;
import org.multibit.hd.ui.views.components.Labels;
import org.multibit.hd.ui.views.components.ModelAndView;
import org.multibit.hd.ui.views.components.Panels;
import org.multibit.hd.ui.views.components.confirm_password.ConfirmPasswordModel;
import org.multibit.hd.ui.views.components.confirm_password.ConfirmPasswordView;
import org.multibit.hd.ui.views.components.enter_seed_phrase.EnterSeedPhraseModel;
import org.multibit.hd.ui.views.components.enter_seed_phrase.EnterSeedPhraseView;
import org.multibit.hd.ui.views.components.panels.PanelDecorator;
import org.multibit.hd.ui.views.fonts.AwesomeIcon;
import org.multibit.hd.ui.views.wizards.AbstractWizard;
import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView;
import org.multibit.hd.ui.views.wizards.WizardButton;
import org.multibit.hd.ui.views.wizards.welcome.WelcomeWizardModel;
import javax.swing.*;
/**
* <p>Wizard to provide the following to UI:</p>
* <ul>
* <li>Restore wallet from seed phrase with optional timestamp</li>
* </ul>
*
* @since 0.0.1
*
*/
public class RestoreWalletTimestampPanelView extends AbstractWizardPanelView<WelcomeWizardModel, RestoreWalletTimestampPanelModel> {
private ModelAndView<EnterSeedPhraseModel, EnterSeedPhraseView> enterSeedPhraseMaV;
private ModelAndView<ConfirmPasswordModel, ConfirmPasswordView> confirmPasswordMaV;
/**
* @param wizard The wizard managing the states
* @param panelName The panel name to filter events from components
*/
public RestoreWalletTimestampPanelView(AbstractWizard<WelcomeWizardModel> wizard, String panelName) {
super(wizard, panelName, AwesomeIcon.MAGIC, MessageKey.RESTORE_WALLET_TIMESTAMP_TITLE);
}
@Override
public void newPanelModel() {
// Do not ask for seed phrase (we already have it)
enterSeedPhraseMaV = Components.newEnterSeedPhraseMaV(getPanelName(), true, false);
confirmPasswordMaV = Components.newConfirmPasswordMaV(getPanelName());
// Create a panel model for the information
RestoreWalletTimestampPanelModel panelModel = new RestoreWalletTimestampPanelModel(
getPanelName(),
enterSeedPhraseMaV.getModel(),
confirmPasswordMaV.getModel()
);
setPanelModel(panelModel);
getWizardModel().setRestoreWalletEnterTimestampModel(enterSeedPhraseMaV.getModel());
getWizardModel().setRestoreWalletConfirmPasswordModel(confirmPasswordMaV.getModel());
// Register components
registerComponents(confirmPasswordMaV, enterSeedPhraseMaV);
}
@Override
public void initialiseContent(JPanel contentPanel) {
contentPanel.setLayout(new MigLayout(
Panels.migLayout("fill,insets 0,hidemode 1"),
"[]", // Column constraints
"[][][][]" // Row constraints
));
// Add to the panel
contentPanel.add(Labels.newRestoreFromTimestampNote(), "grow,push,wrap");
contentPanel.add(enterSeedPhraseMaV.getView().newComponentPanel(), "wrap");
contentPanel.add(Labels.newRestorePasswordNote(), "grow,push,wrap");
contentPanel.add(confirmPasswordMaV.getView().newComponentPanel(), "wrap");
}
@Override
protected void initialiseButtons(AbstractWizard<WelcomeWizardModel> wizard) {
PanelDecorator.addExitCancelPreviousNext(this, wizard);
}
@Override
public void afterShow() {
enterSeedPhraseMaV.getView().requestInitialFocus();
}
@Override
public void updateFromComponentModels(Optional componentModel) {
// No need to update the wizard it has the references
// Determine any events
ViewEvents.fireWizardButtonEnabledEvent(
getPanelName(),
WizardButton.NEXT,
isNextEnabled()
);
}
/**
* A blank or empty timestamp is valid for panel navigation but does not show a 'Verified' text
* @return True if the "next" button should be enabled
*/
private boolean isNextEnabled() {
boolean isPasswordValid = confirmPasswordMaV.getModel().comparePasswords();
String timestamp = enterSeedPhraseMaV.getModel().getSeedTimestamp();
// Is the timestamp present ? (i.e. some text has been entered)
boolean isTimestampPresent = !Strings.isNullOrEmpty(timestamp);
// Work out if timestamp is valid
boolean isTimestampValid = false;
try {
if (timestamp != null) {
Dates.parseSeedTimestamp(timestamp);
isTimestampValid = true;
}
} catch (IllegalArgumentException e) {
// Do nothing
}
final boolean finalIsTimestampPresentAndValid = isTimestampPresent && isTimestampValid;
// Fire the "timestamp verified" event
ViewEvents.fireVerificationStatusChangedEvent(getPanelName() + ".timestamp", finalIsTimestampPresentAndValid);
// Next is enabled if (the timestamp is missing or is valid) and the password is valid
return (!isTimestampPresent || isTimestampValid) && isPasswordValid;
}
}
|
{
"content_hash": "2cf966af6a2500479254c937109c2184",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 132,
"avg_line_length": 33.77922077922078,
"alnum_prop": 0.7570165321030373,
"repo_name": "akonring/multibit-hd-modified",
"id": "bf80631419432aad65e48e5c86ea3c2642a267d4",
"size": "5202",
"binary": false,
"copies": "3",
"ref": "refs/heads/fd67c33",
"path": "mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/welcome/restore_wallet/RestoreWalletTimestampPanelView.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "120111"
},
{
"name": "Java",
"bytes": "3971702"
},
{
"name": "Protocol Buffer",
"bytes": "8583"
},
{
"name": "Shell",
"bytes": "7380"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML>
<html>
<head>
<title>A separate Report-Only policy does not influence `strict-dynamic` in the script-src directive.</title>
<script src='/resources/testharness.js' nonce='dummy'></script>
<script src='/resources/testharnessreport.js' nonce='dummy'></script>
<!-- CSP served:
1) Content-Security-Policy: script-src 'strict-dynamic' 'nonce-dummy'
2) Content-Security-Policy-Report-Only: script-src 'none'
-->
</head>
<body>
<h1>A separate Report-Only policy does not influence `strict-dynamic` in the script-src directive.</h1>
<div id='log'></div>
<script nonce='dummy'>
async_test(function(t) {
window.addEventListener('message', t.step_func(function(e) {
if (e.data === 'appendChild-reportOnly') {
t.done();
}
}));
window.addEventListener('securitypolicyviolation', t.step_func(function(violation) {
if (violation.blockedURI.split('?')[1] !== 'appendChild-reportOnly') {
return;
}
assert_equals(violation.effectiveDirective, 'script-src-elem');
// Check that the violation comes from the Report-Only policy.
assert_equals(violation.originalPolicy, "script-src 'none'");
t.done();
}));
var e = document.createElement('script');
e.id = 'appendChild-reportOnly';
e.src = 'simpleSourcedScript.js?' + e.id;
e.onerror = t.unreached_func('Error should not be triggered.');
document.body.appendChild(e);
}, 'Script injected via `appendChild` is allowed with `strict-dynamic` + Report-Only `script-src \'none\'` policy.');
</script>
</body>
</html>
|
{
"content_hash": "cd211590d64971bcbb37f3ab467baf83",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 125,
"avg_line_length": 40.86363636363637,
"alnum_prop": 0.5884315906562848,
"repo_name": "ric2b/Vivaldi-browser",
"id": "1ceb74c63d1392672a36a2506b63c50199aa39fd",
"size": "1798",
"binary": false,
"copies": "42",
"ref": "refs/heads/master",
"path": "chromium/third_party/blink/web_tests/external/wpt/content-security-policy/script-src/script-src-strict_dynamic_double_policy_report_only.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
from __future__ import absolute_import, unicode_literals, print_function, division
from datetime import timedelta
from flask import Flask
from restfulgit.plumbing.routes import plumbing
from restfulgit.porcelain.routes import porcelain
from restfulgit.archives import archives
from restfulgit.utils.json_err_pages import json_error_page, register_general_error_handler
from restfulgit.utils.json import jsonify
from restfulgit.utils.cors import corsify
BLUEPRINTS = (plumbing, porcelain, archives)
class DefaultConfig(object):
RESTFULGIT_DEFAULT_COMMIT_LIST_LIMIT = 50
RESTFULGIT_ENABLE_CORS = False
RESTFULGIT_CORS_ALLOWED_HEADERS = []
RESTFULGIT_CORS_ALLOW_CREDENTIALS = False
RESTFULGIT_CORS_MAX_AGE = timedelta(days=30)
RESTFULGIT_CORS_ALLOWED_ORIGIN = "*"
def create_app(config_obj_dotted_path=None):
# pylint: disable=W0612
app = Flask(__name__)
app.config.from_object(DefaultConfig)
if config_obj_dotted_path is not None: # pragma: no cover
app.config.from_object(config_obj_dotted_path)
register_general_error_handler(app, json_error_page)
for blueprint in BLUEPRINTS:
app.register_blueprint(blueprint)
@app.route('/')
@corsify
@jsonify
def index(): # pragma: no cover
links = []
for rule in app.url_map.iter_rules():
if str(rule).startswith("/repos"):
links.append(str(rule))
return links
return app
|
{
"content_hash": "30c578f780ffab6bb444c2a241cf7ee7",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 91,
"avg_line_length": 29.22,
"alnum_prop": 0.7104722792607803,
"repo_name": "cvrebert/restfulgit",
"id": "6a731ca952544f59c894990c34cbc3b2a788e2d5",
"size": "1476",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "restfulgit/app_factory.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "209318"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "ac398184843a1b6db3a1a5f5924e2b0b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "77852683eebc2ce020e77c05907fbfc10267e229",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Pteridaceae/Acrostichum/Acrostichum aureum/Acrostichum aureum cristata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>
<title>Linux Quake III Arena Known issues</title></head>
<body text="#000000" bgcolor="#ffffff">
<font size="+2"><b>Linux Quake III Arena Known issues</b></font><br>
<i>Known issues and frequently asked questions - 1.32b</i><br>
<br>
<a href="mailto:ttimo@idsoftware.com">TTimo</a><br>
<i>Changes history</i><br>
2004.2.20 Last update<br>
2001.6.18 Initial version
<hr size="1"><br>
<font size="+1">Current topics</font>
<ul>
<li><a href="#install">Installation instructions</a></li>
<li><a href="#setupfiles">What do I do with a .x86.run file?</a></li>
<li><a href="#glibc">The setup crashes with <i>Segmentation fault "$setup" "$@" 2>/dev/null</i></a></li>
<li><a href="#bsd">Installation on BSD</a></li>
<li><a href="#auth">CLIENT_UNKNOWN_TO_AUTH</a></li>
<li><a href="#pk3">Sys_Error: Couldn't load default.cfg / Sys_Error: FS_FreeFile(
NULL )</a></li>
<li><a href="#setupbug29h">I get <i>./setup.sh {: ==: binary operator expected</i>
when running the setup?</a></li>
<li><a href="#hints">The game doesn't start, I have performance problems,
etc.</a></li>
<li><a href="#aureal">Aureal sound drivers</a></li>
<li><a href="#nosound">The sound doesn't work / sound crashes</a></li>
<li><a href="#discuss">Where can I report bugs and discuss about linux
Quake III Arena?</a></li>
<li><a href="#gameso">The *.so files are not in the setups? (<i>cgamei386.so
qagamei386.so uii386.so</i>)</a></li>
<li><a href="#vm_game">I get <i>Sys_Error: Sys_LoadDll(..) failed dlopen()
completely!</i> when running quake3?</a></li>
<li><a href="#3dnow">I have an AMD CPU and a kernel 2.4.*, Quake III Arena
is slowing down to a complete stop after a while?</a></li>
<li><a href="#gamma">How do I set up the gamma correction?</a></li>
<li><a href="#browser">Servers don't show up in the ingame browser</a></li>
<li><a href="#libsafe">Detected an attempt to write across stack boundary</a></li>
<li><a href="#libmesa">libMesaVoodooGL.so</a></li>
<li><a href="#UDPwide">Running a LAN dedicated server with multiple network
interfaces</a></li>
<li><a href="#64bits">Setup and execution on 64 bits CPUs</a></li>
<li><a href="#links">Links</a></li>
</ul>
<hr size="1"><font size="+1"><a name="install"><b>Installation instructions</b></a></font>
<a name="install"><br>
</a>
<p><a name="install">Linux Quake III Arena is using a graphical installer
(based on Loki software's </a><a href="http://www.icculus.org/loki_setup/">Setup Graphic Installer
</a>). However, since it's a Point Release, you need a retail CD-ROM of Quake
III Arena to perform a complete installation (and optionally your Quake III:
Team Arena CD-ROM). This process is documented in the <a href="http://zerowing.idsoftware.com/linux/q3a/INSTALL">INSTALL</a>file
(this file is also in the setups, it's default location is /usr/local/games/quake3/INSTALL
.. you can run the PR setup and read it to finish the installation afterwards).</p>
<font size="+1"><a name="setupfiles"><b>What do I do with a .x86.run file?</b></a></font>
<a name="setupfiles"><br>
</a>
<p>Those are setup files, meant to be executed. They
come with graphical installation UI or console installation, depending on
what's available on your system. You may need to <i>chmod +x file.x86.run</i>
to make them executable.</p>
<font size="+1"><a name="glibc"><b>The setup crashes with <i>Segmentation fault "$setup" "$@" 2>/dev/null</i></b></a></font>
<p>This is happening on glibc 2.3 systems such as RedHat 9 and Suze. The text mode installer will crash. If you can do a graphical installation, make sure you have Gtk1 installed and avoid the text installer altogether.
If you are doing a remote installation (such as a dedicated server through ssh), you need to use a newer text mode installer. Run the installer with <i>--keep</i> to extract the files
(look for a <i>setup*</i> directory in the current directory for the extracted setup).
Then replace <i>setup.data/bin/Linux/x86/setup</i> by <a href="http://zerowing.idsoftware.com/linux/setup-RH9/setup">this newer version</a>. Run <i>setup.sh</i> at top level and things should work fine.</p>
<p>
<b>Update</b>: Turns out this solution is working for RTCW and ET, but not for Q3 (because the last q3 setup uses an older version of the installer). Will update a specific solution for Q3 'soon'.
</p>
<font size="+1"><a name="bsd"><b>Installation on
BSD</b></a></font><a name="bsd"><br>
</a>
<p><a name="bsd">The linux binaries will run fine on the BSD family (FreeBSD,
NetBSD and OpenBSD) with the linux binary compatibility software. However
if you are getting the error message <i>ELF binary type "0" not known</i>
while installing or trying to run the binaries, that means you need to run
<i>brandelf</i> on the files.</a></p>
<p><a name="bsd">If it's a setup problem, proceed with the following steps:
</a></p>
<pre><a name="bsd">./linuxq3apoint-1.31.x86.run --keep<br>brandelf -t Linux setup.tmp/setup.data/bin/FreeBSD/x86/setup<br>cd setup.tmp<br>sh ./setup.sh<br></a></pre>
<p><a name="bsd">The --keep option will extract the files and leave them
somewhere below your current directory. Depending on the game (Q3 or RTCW)
and the setup version, your mileage may vary (setup.tmp or another directory).</a></p>
<p><a name="bsd">The game binaries might need to be brandelf'ed too, with
a command such as</a></p>
<pre><a name="bsd">brandelf -t Linux /usr/local/games/quake3/quake3.x86<br></a></pre>
<a name="bsd"></a><font size="+1"><a name="auth"><b>CLIENT_UNKNOWN_TO_AUTH</b></a></font>
<a name="auth"><br>
</a>
<p><a name="auth">Graeme Devine recently updated his <i>.plan</i> with very
complete </a><a href="http://www.webdog.org/cgi-bin/finger.plm?id=279&time=20011210020942" target="_new">information about CLIENT_UNKNOWN_TO_AUTH errors</a>.</p>
<p>
See some additional information from the <a href="http://www.gameadmins.com/modules.php?name=Mail_List">gameadmins.com mailing list</a>:
</p>
<pre>If the server you are playing on and the auth server don't see you as the
same IP (for instance you are trying to play on a public internet server
that's on your LAN, and your internet access is using NAT), then it won't
work.
It used to work in 1.31, and it doesn't in 1.32. PunkBuster requires
reliable auth of the players. What you can do:
- run a server with sv_strictauth 0 and you'll be able to join your
server. This will be the same behaviour as 1.31
- connect to a server on the internet before you connect to your local
server (this will trigger your IP into the cache of the auth server for
15mn and let you in to your local server).
- setup two NATs, one for your client one for your server and make sure
your server and Id's auth see the same IP. (this one ain't for network
setup newbies)
</pre>
<font size="+1"><a name="pk3"><b>Sys_Error: Couldn't load default.cfg / Sys_Error:
FS_FreeFile( NULL )</b></a></font><br>
<p>If you get one of these errors after installing Quake III Arena or Return
To Castle Wolfenstein, it means that the engine didn't find all the required
.pk3 files. Either you didn't copy them, or you copied them to the wrong
place. Check the INSTALL instructions for the game for more details, make
sure they are in baseq3/ for quake3 (missionpack/ for TA files) and main/
for Return To Castle Wolfenstein.</p>
<font size="+1"><a name="setupbug29h"><b>I get <i>./setup.sh {: ==: binary
operator expected</i> when running the setup?</b></a></font><a name="setupbug29h"><br>
</a>
<p><a name="setupbug29h">This is a known issue to 1.29h setups and prior.
It happens on systems with bash version < 2.*. There are several solutions:<br>
- Upgrade bash to something more recent and run the setup again - Run the
setup with the --keep option. It will fail but it will leave a <i>setup-full</i>
directory. You can then copy the files manually from that dir. - Once you
used the --keep option above, you can edit setup.sh and replace occurences
of == by =. Then run setup.sh and the installer will execute.</a></p>
<a name="setupbug29h"></a><font size="+1"><a name="hints"><b>The game doesn't
start, I have performance problems, etc.</b></a></font><br>
<p>The first thing to do is to check on the forums and various FAQs (this
one, but there are others. See the <a href="#links">links</a>). The Quake3World
forums have a great search function.</p>
<p>Before reporting the problem to <a href="mailto:ttimo@idsoftware.com">me</a>
make sure it's an issue with the game, and not an issue with your OS/OpenGL/sound
configuration. Common OS issues are listed in this FAQ. You should make sure
you have OpenGL configured correctly (by checking if <i>gears</i>is running
for instance, and how well it runs). And see if non-Id linux games are running
fine too.</p>
<p>When you are going to report a bug, first make sure you are using the
latest version of the game. Include the game version in your report.</p>
<p>Include general information about your OS:<br>
</p>
<ul>
<li>Motherboard brand, CPU type, RAM</li>
<li>distribution name and version</li>
<li>kernel / OS info (from <i>uname -a</i>)</li>
<li>libc version (<i>ls -l /lib/libc.so.*</i>)<br>
please specify if you can if the libc is your distribution's standard
version, or if you compiled yourself, and what binary target was used (x86,
or AMD, i686 etc.)</li>
</ul>
<p>If it's a problem with the client, send the output of <i>glxinfo</i>.</p>
<p>If you have an nvidia board, send the output of <i>cat /proc/nv/card0</i>
</p>
<p>Send output of the run:<br>
run the game with <i>+set developer 1</i> option, and send the output. You
can do something like <i>quake3 +set developer 1 &>q3run.log</i>.</p>
<p>If it's a crash, you can send a backtrace of the game running through
<i>gdb</i>.</p>
<p>You can also send a log of the game running with <i>strace</i>:</p>
<pre>cd /usr/local/games/quake3<br>strace -o ~/strace.log ./quake3.x86<br></pre>
<p>NOTE: please <b>avoid</b> sending me the <i>strace</i> of <i>/usr/local/games/quake3/quake3</i>,
which is a shell script wrapper and probably no interest to your problem.
</p>
<font size="+1"><a name="aureal"><b>Aureal sound drivers</b></a></font><a name="aureal"><br>
</a>
<p><a name="aureal">It seems that some versions of the Aureal sound drivers
don't work right with Q3. Last I heard, a kernel upgrade to 2.4.17 + Aureal
1.1.3, and/or using the old 1.1.1 drivers from </a><a href="http://aureal.sourceforge.net/" target="_new">Aureal's website</a>fixed
the problem.</p>
<p>If you need to know more about this, have a look at this <a href="http://www.quake3world.com/ubb/Forum15/HTML/001348.html" target="_new">Q3W forum thread</a>.</p>
<font size="+1"><a name="nosound"><b>The sound doesn't work / sound crashes</b></a></font><br>
<p>The first thing to check is that it is actually a sound related. Run
the game with <i>+set s_initsound 0</i> and see what happens. All problems
reported so far about sound turned out to be OS/drivers. Listed below:</p>
<p>On some Mandrake distributions:<br>
Check if you are running the enlightenment sound daemon (esd). With <i>ps
aux | grep esd</i>for instance. It is a multiplexer for /dev/dsp, and might
block use of /dev/dsp by Quake III Arena. You can disable esd with <i>esdctl
stop</i> (as root).</p>
<p><b><a href="http://www.linux-mandrake.com/">Mandrake 8</a></b>'s default
sound drivers seem broken, installing the <a href="http://www.alsa-project.org/" target="_new">Alsa drivers</a> or the
<a href="http://www.opensound.com/">http://www.opensound.com</a> drivers
fixes the problem.</p>
<p>Some beta <a href="http://www.alsa-project.org/" target="_new">Alsa drivers</a>
have been reported to crash with Q3. Non-beta ones are fine.</p>
<p>VIA chipset and AC97 driver:<br>
This combination is known to have various issues. They have been fixed in
recent drivers (thanks to Arne Schmitz for the heads up):<br>
</p>
<pre>http://sourceforge.net/projects/gkernel has got the up to date version of <br>the AC97 kernel driver. The current version can be found here:<br><br>http://prdownloads.sourceforge.net/gkernel/via82cxxx-1.1.15.tar.gz<br><br>It has working mmap sound, so Q3 shouldn't be a problem any more.<br></pre>
(thanks to Arne Schmitz for the heads up)<p></p>
<font size="+1"><a name="discuss"><b>Where can I report bugs and discuss about linux Quake III
Arena?</b></a></font><a name="discuss"><br>
</a>
<p><a name="discuss">Reports bugs to </a><a href="mailto:bugs@idsoftware.com">bugs@idsoftware.com</a>. If you are pretty
sure this is a linux-only issue, you can shorten the loop by emailing <a href="mailto:ttimo@idsoftware.com">ttimo@idsoftware.com</a> directly.</p>
<p>You will find the discussion forums for linux Quake III Arena on <a href="http://www.quake3world.com/cgi-bin/forumdisplay.cgi?action=topics&forum=*nix+Discussion&number=15&DaysPrune=30&LastLogin=">
Quake3World forums</a>. There is for sure a lot of other places to talk about
linux Quake III Arena, but this is the one we read regularly to track bugs
and common issues.</p>
<font size="+1"><a name="gameso"><b>The *.so files are not in the setups?
(<i>cgamei386.so qagamei386.so uii386.so</i>)</b></a></font><a name="gameso"><br>
</a>
<p><a name="gameso">If you still have <i>baseq3/*.so</i> and <i>missionpack/*.so</i>
files, then those come from the earlier 1.27g beta installation and you should
REMOVE them. They were provided in 1.27g to go around a bug in the VM code,
which made win32 VMs incompatible with linux. This problem has been fixed
and the two files are no longer required.</a></p>
<p><a name="gameso">If you are upgrading from 1.27g, it is likely that your
<i>q3config.cfg</i> files are set to use the native libraries (*.so files)
instead of the bytecode. Run quake3 with the following options to set things
right:<br>
<i>quake3 +set vm_game 2 +set vm_cgame 2 +set vm_ui 2</i></a></p>
<a name="gameso"></a><font size="+1"><a name="vm_game"><b>I get <i>Sys_Error:
Sys_LoadDll(..) failed dlopen() completely!</i>when running quake3?</b></a></font><a name="vm_game"><br>
</a>
<p><a name="vm_game">Try running quake3 with the following options:<br>
<i>quake3 +set vm_game 2 +set vm_cgame 2 +set vm_ui 2</i><br>
You should also read the </a><a href="#gameso">above answer</a>.</p>
<font size="+1"><a name="3dnow"><b>I have an AMD CPU and a kernel 2.4.*,
Quake III Arena is slowing down to a complete stop after a while?</b></a></font><br>
<p>It seems the 3DNow! copy routines have issues with the southbridge chip
in the KT133A, this results in performances degrading while playing for a
while. Re-compile your kernel without 3DNow! instructions to avoid the problem,
and wait for newer kernels with better support for 3DNow! / KT133A.</p>
<font size="+1"><a name="gamma"><b>How do I set up the gamma correction?</b></a></font><br>
<p>Starting with 1.29h, you can set the gamma correction with the brightness
slider in the graphical menu (under setup). On some older systems which don't
have the appropriate XFree86 extensions, you might have to set <b>r_gamma</b>
manually from the console, and issue a <b>vid_restart</b> command.</p>
<font size="+1"><a name="browser"><b>Servers don't show up in the ingame
browser</b></a></font>
<p>The reason for this has not been clearly identified yet, seems to be related
to upgrade from older versions. Deleting ~/.q3a/baseq3/q3config.cfg fixes
the problem (you will have to reconfigure your bindings)</p>
<font size="+1"><a name="libsafe"><b>Detected an attempt to write across
stack boundary</b></a></font>
<p>If Quake III Arena exits with the error "Detected an attempt to write
across stack boundary", this probably means that you are running libsafe
on this system. Quake III Arena is compiled with some options that confuse
libsafe, you should disable it before running. See <a href="http://www.mudos.org/?faq" target="_new">this page</a> for more details.
</p>
<font size="+1"><a name="libmesa"><b>libMesaVoodooGL.so</b></a></font>
<p>The GL driver for Voodoo cards (libMesaVoodoGL.so) used to be distributed
in older Q3 setups. <b>This is no longer the case.</b> If you have this .so
in your Quake III Arena directory (<i>/usr/local/games/quake3</i>), you should
remove it. Any recent/decent linux distribution should support your Voodoo
card out of the box, otherwise it is recommended that you setup XFree 4.*
and the correct DRI infrastructure for it.</p>
<font size="+1"><a name="UDPwide"><b>Running a LAN dedicated server with
multiple network interfaces</b></a></font>
<p>A LAN dedicated server will use the <i>net_ip</i> cvar to identify the
NIC it is going to use (default is "localhost"). As it only opens one socket,
it is not possible to have a server broadcast it's packets on all the NICs.
This can be a problem if the server is serving games for a LAN and runs several
NICs to access the various sub networks.<br>
</p>
<p>The following Linux kernel patch (2.4.19) was provided by Rogier Mulhujzen
and John Tobin, it will force broadcasts to be emitted on all interfaces:<br>
<a href="http://zerowing.idsoftware.com/linux/q3a/udp_wide_broadcast.patch">udp_wide_broadcast.patch</a><br>
<a href="http://zerowing.idsoftware.com/linux/q3a/udp_wide_README.txt">udp_wide_README.txt</a><br>
The equivalent <a href="http://www.bsdchicks.com/patches/">patch for FreeBSD</a>
is available too.<br>
</p>
<font size="+1"><a name="64bits"><b>Setup and execution on 64 bits CPUs</b></a></font><br>
<p>If you are running Linux on a 64 bit CPU (such as AMD's Opteron), and if your system is backwards compatible so that it can execute 32 bits x86 binaries, then the regular Quake III Arena binaries should work (your mileage may vary).</p>
<p>It's likely that the installer scripts will get confused though, and will refuse to install giving you an error: "This installation doesn't support glibc-2.1 on Linux / unknown". You will have to extract the game files manually by passing --keep on the command line when running the setup script. Once the files are unpacked, you will need to copy them manually to /usr/local/games. You probably want to have a working installation to refer to while doing this. This also applies to RTCW and ET</p>
<font size="+1"><a name="links"><b>Links</b></a></font><br>
<p>The <a href="http://www.icculus.org/lgfaq" target="_new">Linux Gamer's
faq</a> is a very good resource for general Linux Gaming topics.</p>
<p>Also at <a href="http://www.icculus.org/" target="_new">icculus.org</a>,
the <a href="http://www.icculus.org/lgfaq/loki/q3faq.html" target="_new">old
Q3 FAQ from Loki Software</a>.</p>
<p><a href="http://www.quake3world.com/ubb/Forum15/HTML/000529.html">Quake3World's
linux FAQ</a></p>
<br>
</body></html>
|
{
"content_hash": "305bed5c8e8bcc8f9dd75c7a4463ede3",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 501,
"avg_line_length": 66.17314487632508,
"alnum_prop": 0.7177871522400812,
"repo_name": "ooonum/q3ultima",
"id": "e87ef29ea6ea3a96fce3e0b0d9d20c9be48009af",
"size": "18728",
"binary": false,
"copies": "27",
"ref": "refs/heads/master",
"path": "code/unix/LinuxSupport/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2595374"
},
{
"name": "C++",
"bytes": "30729"
},
{
"name": "HTML",
"bytes": "18728"
},
{
"name": "Makefile",
"bytes": "190"
},
{
"name": "Objective-C",
"bytes": "13357"
},
{
"name": "Shell",
"bytes": "13263"
}
],
"symlink_target": ""
}
|
package cmd
import (
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
ttnlog "github.com/TheThingsNetwork/go-utils/log"
pb "github.com/TheThingsNetwork/ttn/api/handler"
"github.com/TheThingsNetwork/ttn/api/pool"
"github.com/TheThingsNetwork/ttn/core/component"
"github.com/TheThingsNetwork/ttn/core/handler"
"github.com/TheThingsNetwork/ttn/core/proxy"
"github.com/TheThingsNetwork/ttn/core/proxy/jsonpb"
"github.com/TheThingsNetwork/ttn/utils/parse"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/net/context" // See https://github.com/grpc/grpc-go/issues/711"
"google.golang.org/grpc"
"gopkg.in/redis.v5"
)
// handlerCmd represents the handler command
var handlerCmd = &cobra.Command{
Use: "handler",
Short: "The Things Network handler",
Long: ``,
PreRun: func(cmd *cobra.Command, args []string) {
ctx.WithFields(ttnlog.Fields{
"Server": fmt.Sprintf("%s:%d", viper.GetString("handler.server-address"), viper.GetInt("handler.server-port")),
"HTTP Proxy": fmt.Sprintf("%s:%d", viper.GetString("handler.http-address"), viper.GetInt("handler.http-port")),
"Announce": fmt.Sprintf("%s:%d", viper.GetString("handler.server-address-announce"), viper.GetInt("handler.server-port")),
"Database": fmt.Sprintf("%s/%d", viper.GetString("handler.redis-address"), viper.GetInt("handler.redis-db")),
"TTN Broker ID": viper.GetString("handler.broker-id"),
"MQTT": viper.GetString("handler.mqtt-address"),
"AMQP": viper.GetString("handler.amqp-address"),
}).Info("Initializing Handler")
},
Run: func(cmd *cobra.Command, args []string) {
ctx.Info("Starting")
// Redis Client
client := redis.NewClient(&redis.Options{
Addr: viper.GetString("handler.redis-address"),
Password: viper.GetString("handler.redis-password"),
DB: viper.GetInt("handler.redis-db"),
})
if err := connectRedis(client); err != nil {
ctx.WithError(err).Fatal("Could not initialize database connection")
}
// Component
component, err := component.New(ttnlog.Get(), "handler", fmt.Sprintf("%s:%d", viper.GetString("handler.server-address-announce"), viper.GetInt("handler.server-port")))
if err != nil {
ctx.WithError(err).Fatal("Could not initialize component")
}
httpActive := viper.GetString("handler.http-address") != "" && viper.GetInt("handler.http-port") != 0
if httpActive && component.Identity.ApiAddress == "" {
component.Identity.ApiAddress = fmt.Sprintf("http://%s:%d", viper.GetString("handler.server-address-announce"), viper.GetInt("handler.http-port"))
}
// Handler
handler := handler.NewRedisHandler(
client,
viper.GetString("handler.broker-id"),
)
if viper.GetString("handler.mqtt-address") != "" {
handler = handler.WithMQTT(
viper.GetString("handler.mqtt-username"),
viper.GetString("handler.mqtt-password"),
viper.GetBool("handler.mqtt-use-tls"),
viper.GetString("handler.mqtt-address"),
)
mqttPort, err := parse.Port(viper.GetString("handler.mqtt-address"))
if err != nil {
ctx.WithError(err).Error("Could not announce the handler")
}
if announceAddr := viper.GetString("handler.mqtt-address-announce"); announceAddr != "" {
component.Identity.MqttAddress = fmt.Sprintf("%s:%d", announceAddr, mqttPort)
} else {
component.Identity.MqttAddress = fmt.Sprintf("%s:%d", viper.GetString("handler.server-address-announce"), mqttPort)
}
} else {
ctx.Warn("MQTT is not enabled in your configuration")
}
if viper.GetString("handler.amqp-address") != "" {
handler = handler.WithAMQP(
viper.GetString("handler.amqp-username"),
viper.GetString("handler.amqp-password"),
viper.GetString("handler.amqp-address"),
viper.GetString("handler.amqp-exchange"),
)
amqpPort, err := parse.Port(viper.GetString("handler.amqp-address"))
if err != nil {
ctx.WithError(err).Error("Could not announce the handler")
}
if announceAddr := viper.GetString("handler.amqp-address-announce"); announceAddr != "" {
component.Identity.AmqpAddress = fmt.Sprintf("%s:%d", announceAddr, amqpPort)
} else {
component.Identity.AmqpAddress = fmt.Sprintf("%s:%d", viper.GetString("handler.server-address-announce"), amqpPort)
}
} else {
ctx.Warn("AMQP is not enabled in your configuration")
}
err = handler.Init(component)
if err != nil {
ctx.WithError(err).Fatal("Could not initialize handler")
}
defer handler.Shutdown()
// gRPC Server
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", viper.GetString("handler.server-address"), viper.GetInt("handler.server-port")))
if err != nil {
ctx.WithError(err).Fatal("Could not start gRPC server")
}
grpc := grpc.NewServer(component.ServerOptions()...)
// Register and Listen
component.RegisterHealthServer(grpc)
handler.RegisterRPC(grpc)
handler.RegisterManager(grpc)
go grpc.Serve(lis)
defer grpc.Stop()
if httpActive {
proxyConn, err := component.Identity.Dial(pool.Global)
if err != nil {
ctx.WithError(err).Fatal("Could not start client for gRPC proxy")
}
mux := runtime.NewServeMux(runtime.WithMarshalerOption("*", &jsonpb.GoGoJSONPb{
OrigName: true,
}))
netCtx, cancel := context.WithCancel(context.Background())
defer cancel()
pb.RegisterApplicationManagerHandler(netCtx, mux, proxyConn)
prxy := proxy.WithToken(mux)
prxy = proxy.WithPagination(prxy)
prxy = proxy.WithLogger(prxy, ctx)
go func() {
err := http.ListenAndServe(
fmt.Sprintf("%s:%d", viper.GetString("handler.http-address"), viper.GetInt("handler.http-port")),
prxy,
)
if err != nil {
ctx.WithError(err).Fatal("Error in gRPC proxy")
}
}()
}
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
ctx.WithField("signal", <-sigChan).Info("signal received")
},
}
func init() {
RootCmd.AddCommand(handlerCmd)
handlerCmd.Flags().String("redis-address", "localhost:6379", "Redis host and port")
viper.BindPFlag("handler.redis-address", handlerCmd.Flags().Lookup("redis-address"))
handlerCmd.Flags().String("redis-password", "", "Redis password")
viper.BindPFlag("handler.redis-password", handlerCmd.Flags().Lookup("redis-password"))
handlerCmd.Flags().Int("redis-db", 0, "Redis database")
viper.BindPFlag("handler.redis-db", handlerCmd.Flags().Lookup("redis-db"))
handlerCmd.Flags().String("broker-id", "dev", "The ID of the TTN Broker as announced in the Discovery server")
viper.BindPFlag("handler.broker-id", handlerCmd.Flags().Lookup("broker-id"))
handlerCmd.Flags().String("mqtt-address", "", "MQTT host and port. Leave empty to disable MQTT")
handlerCmd.Flags().String("mqtt-address-announce", "", "MQTT address to announce (takes value of server-address-announce if empty while enabled)")
handlerCmd.Flags().String("mqtt-username", "", "MQTT username")
handlerCmd.Flags().String("mqtt-password", "", "MQTT password")
viper.BindPFlag("handler.mqtt-address", handlerCmd.Flags().Lookup("mqtt-address"))
viper.BindPFlag("handler.mqtt-address-announce", handlerCmd.Flags().Lookup("mqtt-address-announce"))
viper.BindPFlag("handler.mqtt-username", handlerCmd.Flags().Lookup("mqtt-username"))
viper.BindPFlag("handler.mqtt-password", handlerCmd.Flags().Lookup("mqtt-password"))
handlerCmd.Flags().String("amqp-address", "", "AMQP host and port. Leave empty to disable AMQP")
handlerCmd.Flags().String("amqp-address-announce", "", "AMQP address to announce (takes value of server-address-announce if empty while enabled)")
handlerCmd.Flags().String("amqp-username", "guest", "AMQP username")
handlerCmd.Flags().String("amqp-password", "guest", "AMQP password")
handlerCmd.Flags().String("amqp-exchange", "ttn.handler", "AMQP exchange")
viper.BindPFlag("handler.amqp-address", handlerCmd.Flags().Lookup("amqp-address"))
viper.BindPFlag("handler.amqp-address-announce", handlerCmd.Flags().Lookup("amqp-address-announce"))
viper.BindPFlag("handler.amqp-username", handlerCmd.Flags().Lookup("amqp-username"))
viper.BindPFlag("handler.amqp-password", handlerCmd.Flags().Lookup("amqp-password"))
viper.BindPFlag("handler.amqp-exchange", handlerCmd.Flags().Lookup("amqp-exchange"))
handlerCmd.Flags().String("server-address", "0.0.0.0", "The IP address to listen for communication")
handlerCmd.Flags().String("server-address-announce", "localhost", "The public IP address to announce")
handlerCmd.Flags().Int("server-port", 1904, "The port for communication")
viper.BindPFlag("handler.server-address", handlerCmd.Flags().Lookup("server-address"))
viper.BindPFlag("handler.server-address-announce", handlerCmd.Flags().Lookup("server-address-announce"))
viper.BindPFlag("handler.server-port", handlerCmd.Flags().Lookup("server-port"))
handlerCmd.Flags().String("http-address", "0.0.0.0", "The IP address where the gRPC proxy should listen")
handlerCmd.Flags().Int("http-port", 8084, "The port where the gRPC proxy should listen")
viper.BindPFlag("handler.http-address", handlerCmd.Flags().Lookup("http-address"))
viper.BindPFlag("handler.http-port", handlerCmd.Flags().Lookup("http-port"))
}
|
{
"content_hash": "ccbb5bdb280c91e9546d06a0bf8943de",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 169,
"avg_line_length": 43.53080568720379,
"alnum_prop": 0.7070223189983669,
"repo_name": "jvanmalder/ttn",
"id": "fdba68f77555bb4f65f2f743d6ec25cf5dc67d97",
"size": "9323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cmd/handler.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "1160953"
},
{
"name": "Makefile",
"bytes": "6172"
},
{
"name": "Protocol Buffer",
"bytes": "45258"
},
{
"name": "Ruby",
"bytes": "124"
},
{
"name": "Shell",
"bytes": "1093"
}
],
"symlink_target": ""
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "media/capture/webm_muxer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Mock;
using ::testing::WithArgs;
namespace media {
// Dummy interface class to be able to MOCK its only function below.
class EventHandlerInterface {
public:
virtual void WriteCallback(const base::StringPiece& encoded_data) = 0;
virtual ~EventHandlerInterface() {}
};
class WebmMuxerTest : public testing::Test, public EventHandlerInterface {
public:
WebmMuxerTest()
: webm_muxer_(base::Bind(&WebmMuxerTest::WriteCallback,
base::Unretained(this))),
last_encoded_length_(0),
accumulated_position_(0) {
EXPECT_EQ(webm_muxer_.Position(), 0);
EXPECT_FALSE(webm_muxer_.Seekable());
EXPECT_EQ(webm_muxer_.segment_.mode(), mkvmuxer::Segment::kLive);
}
MOCK_METHOD1(WriteCallback, void(const base::StringPiece&));
void SaveEncodedDataLen(const base::StringPiece& encoded_data) {
last_encoded_length_ = encoded_data.size();
accumulated_position_ += encoded_data.size();
}
mkvmuxer::int64 GetWebmMuxerPosition() const {
return webm_muxer_.Position();
}
const mkvmuxer::Segment& GetWebmMuxerSegment() const {
return webm_muxer_.segment_;
}
mkvmuxer::int32 WebmMuxerWrite(const void* buf, mkvmuxer::uint32 len) {
return webm_muxer_.Write(buf, len);
}
WebmMuxer webm_muxer_;
size_t last_encoded_length_;
int64_t accumulated_position_;
private:
DISALLOW_COPY_AND_ASSIGN(WebmMuxerTest);
};
// Checks that AddVideoTrack adds a Track.
TEST_F(WebmMuxerTest, AddVideoTrack) {
const uint64_t track_number = webm_muxer_.AddVideoTrack(gfx::Size(320, 240),
30.0f);
EXPECT_TRUE(GetWebmMuxerSegment().GetTrackByNumber(track_number));
}
// Checks that the WriteCallback is called with appropriate params when
// WebmMuxer::Write() method is called.
TEST_F(WebmMuxerTest, Write) {
const base::StringPiece encoded_data("abcdefghijklmnopqrstuvwxyz");
EXPECT_CALL(*this, WriteCallback(encoded_data));
WebmMuxerWrite(encoded_data.data(), encoded_data.size());
EXPECT_EQ(GetWebmMuxerPosition(), static_cast<int64_t>(encoded_data.size()));
}
// This test sends two frames and checks that the WriteCallback is called with
// appropriate params in both cases.
TEST_F(WebmMuxerTest, OnEncodedVideoNormalFrames) {
const base::StringPiece encoded_data("abcdefghijklmnopqrstuvwxyz");
const uint64_t track_number = webm_muxer_.AddVideoTrack(gfx::Size(320, 240),
30.0f);
EXPECT_CALL(*this, WriteCallback(_))
.Times(AtLeast(1))
.WillRepeatedly(WithArgs<0>(
Invoke(this, &WebmMuxerTest::SaveEncodedDataLen)));
webm_muxer_.OnEncodedVideo(track_number,
encoded_data,
base::TimeDelta::FromMicroseconds(0),
false /* keyframe */);
// First time around WriteCallback() is pinged a number of times to write the
// Matroska header, but at the end it dumps |encoded_data|.
EXPECT_EQ(last_encoded_length_, encoded_data.size());
EXPECT_EQ(GetWebmMuxerPosition(), accumulated_position_);
EXPECT_GE(GetWebmMuxerPosition(), static_cast<int64_t>(last_encoded_length_));
const int64_t begin_of_second_block = accumulated_position_;
EXPECT_CALL(*this, WriteCallback(_))
.Times(AtLeast(1))
.WillRepeatedly(WithArgs<0>(
Invoke(this, &WebmMuxerTest::SaveEncodedDataLen)));
webm_muxer_.OnEncodedVideo(track_number,
encoded_data,
base::TimeDelta::FromMicroseconds(1),
false /* keyframe */);
// The second time around the callbacks should include a SimpleBlock header,
// namely the track index, a timestamp and a flags byte, for a total of 6B.
EXPECT_EQ(last_encoded_length_, encoded_data.size());
EXPECT_EQ(GetWebmMuxerPosition(), accumulated_position_);
const uint32_t kSimpleBlockSize = 6u;
EXPECT_EQ(static_cast<int64_t>(begin_of_second_block + kSimpleBlockSize +
encoded_data.size()),
accumulated_position_);
}
} // namespace media
|
{
"content_hash": "5d135c547c2acb88562c0b2c5a650f3e",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 80,
"avg_line_length": 36.3671875,
"alnum_prop": 0.6698174006444683,
"repo_name": "lihui7115/ChromiumGStreamerBackend",
"id": "6ae525c4ffd1c0b79e431371ab499ac7b800bbe7",
"size": "4655",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "media/capture/webm_muxer_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9508834"
},
{
"name": "C++",
"bytes": "242598549"
},
{
"name": "CSS",
"bytes": "943747"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27281878"
},
{
"name": "Java",
"bytes": "14561064"
},
{
"name": "JavaScript",
"bytes": "20540839"
},
{
"name": "Makefile",
"bytes": "70864"
},
{
"name": "Objective-C",
"bytes": "1745880"
},
{
"name": "Objective-C++",
"bytes": "10008668"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "482954"
},
{
"name": "Python",
"bytes": "8626890"
},
{
"name": "Shell",
"bytes": "481888"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
}
|
package net.kaoriya.lmdb_playground;
import java.util.Arrays;
import org.fusesource.lmdbjni.Cursor;
import org.fusesource.lmdbjni.Database;
import org.fusesource.lmdbjni.Entry;
import org.fusesource.lmdbjni.Env;
import org.fusesource.lmdbjni.SeekOp;
import org.fusesource.lmdbjni.Transaction;
import static org.fusesource.lmdbjni.Constants.bytes;
import static org.fusesource.lmdbjni.Constants.string;
/**
* Longest prefix match implementation using lmdb-jni.
*/
public class LongestPrefixMatch {
/**
* Perform longest prefix match.
*
* Make a match with implicit temporal transaction.
*
* @param env instance of Env
* @param db instance of Database
* @param s query string
*/
public static Entry match(Env env, Database db, String s) {
try (Transaction tx = env.createReadTransaction()) {
return match(tx, db, s);
}
}
/**
* Perform longest prefix match with a transaction.
*
* Explicit trancation version for speed.
*
* @param tx instance of Transaction
* @param db instance of Database
* @param s query string
*/
public static Entry match(Transaction tx, Database db, String s) {
if (s == null || s.length() == 0) {
return null;
}
byte[] targetBytes = bytes(s);
try (Cursor c = db.openCursor(tx)) {
Entry found = null;
for (int i = 1, l = targetBytes.length; i <= l; ++i) {
byte[] queryBytes = Arrays.copyOf(targetBytes, i);
Entry e = c.seek(SeekOp.RANGE, queryBytes);
if (e == null) {
break;
}
byte[] keyBytes = e.getKey();
int n = countPrefixMatch(targetBytes, keyBytes);
if (n < i) {
break;
} else if (n >= i) {
i = n;
if (n == keyBytes.length) {
found = e;
}
}
}
return found;
}
}
static int countPrefixMatch(byte[] s, byte[] t) {
int max = Math.min(s.length, t.length);
int i;
for (i = 0; i < max; ++i) {
if (s[i] != t[i]) {
break;
}
}
return i;
}
}
|
{
"content_hash": "03c020ce721ded8553ba307c5e16806b",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 70,
"avg_line_length": 28.373493975903614,
"alnum_prop": 0.5256900212314225,
"repo_name": "koron/java-lmdb-playground",
"id": "3cef11f8e1ab137ad86b4152e57dc916f9ae6783",
"size": "2355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/kaoriya/lmdb_playground/LongestPrefixMatch.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1915"
},
{
"name": "Java",
"bytes": "19328"
}
],
"symlink_target": ""
}
|
from setuptools import setup
setup(
author = 'Juliano Martinez',
author_email = 'juliano.martinez@locaweb.com.br',
name = 'servicenow',
version = '2.1.1',
url = 'https://github.com/locaweb/python-servicenow',
description = 'Python Library to interact with and manage the ServiceNow database',
install_requires = ['requests','redis','SOAPpy'],
long_description = open('README.md').read(),
maintainer = 'Francisco Freire',
maintainer_email = 'francisco.freire@locaweb.com.br',
package_dir = {'servicenow': 'src/servicenow', 'servicenow.drivers': 'src/servicenow/drivers'},
packages = ['servicenow', 'servicenow.drivers'],
license = 'Apache',
)
|
{
"content_hash": "6a700e7c10684d5055b6cd4a0dff4f68",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 99,
"avg_line_length": 40.88235294117647,
"alnum_prop": 0.6776978417266187,
"repo_name": "locaweb/python-servicenow",
"id": "676151ea8c6ebb7352305998cfe862fcbae02007",
"size": "714",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "18568"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html class="no-js" ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link type="text/css" rel="stylesheet" href="app/build/main.css">
<base href="/">
</head>
<body>
<div class="page">
<header ui-view="header"></header>
<div class="main-content" ui-view></div>
<footer ui-view="footer"></footer>
</div>
<script type="text/javascript" src="components/lodash/dist/lodash.min.js"></script>
<script type="text/javascript" src="app/build/libraries.js"></script>
<script type="text/javascript" src="app/build/application.js"></script>
</body>
</html>
|
{
"content_hash": "75b044a8e25625dbb5f2ab8ccaf2ae75",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 87,
"avg_line_length": 33.291666666666664,
"alnum_prop": 0.6307884856070087,
"repo_name": "nucleus-angular/svg",
"id": "214cce58345b48b6cfbe97cc079c74a8fbe2489b",
"size": "799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dalek-web/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "38"
},
{
"name": "JavaScript",
"bytes": "28969"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="true">
<description>Apache CXF的 SOAP Web Service配置</description>
<!-- WebService的实现Bean定义 -->
<bean id="accountSoapService" class="com.xyz.app.business.webservice.AccountServiceImpl" />
<!-- jax-ws endpoint定义 -->
<jaxws:endpoint address="/soap/accountservice">
<jaxws:implementor ref="accountSoapService" />
</jaxws:endpoint>
<!-- 引入CXF的文件 -->
<import resource="classpath*:META-INF/cxf/cxf.xml" />
<import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath*:META-INF/cxf/cxf-servlet.xml" />
</beans>
|
{
"content_hash": "71fcae8a54733d3d52d054437a0ab4d8",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 154,
"avg_line_length": 44.95454545454545,
"alnum_prop": 0.717896865520728,
"repo_name": "leeyazhou/xyz",
"id": "227f04b6134e797596467213abcd2e0e54140259",
"size": "1019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xyz-app/src/main/resources/conf/webservice/spr-soap-server.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "30821"
},
{
"name": "CSS",
"bytes": "352327"
},
{
"name": "FreeMarker",
"bytes": "123"
},
{
"name": "HTML",
"bytes": "610458"
},
{
"name": "Java",
"bytes": "384454"
},
{
"name": "JavaScript",
"bytes": "2040735"
},
{
"name": "PHP",
"bytes": "4548"
},
{
"name": "Ruby",
"bytes": "1206"
},
{
"name": "Shell",
"bytes": "46922"
}
],
"symlink_target": ""
}
|
#import <AppKit/AppKit.h>
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTInvalidating.h>
#import <React/RCTRootView.h>
#import <React/RCTViewManager.h>
/**
* Posted right before re-render happens. This is a chance for views to invalidate their state so
* next render cycle will pick up updated views and layout appropriately.
*/
RCT_EXTERN NSString *const RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification;
@class RCTLayoutAnimationGroup;
@class RCTUIManagerObserverCoordinator;
/**
* The RCTUIManager is the module responsible for updating the view hierarchy.
*/
@interface RCTUIManager : NSObject <RCTBridgeModule, RCTInvalidating>
/**
* Register a root view tag and creates corresponding `rootView` and
* `rootShadowView`.
*/
- (void)registerRootViewTag:(NSNumber *)rootTag;
/**
* Register a root view with the RCTUIManager.
*/
- (void)registerRootView:(NSView *)rootView;
/**
* Gets the view name associated with a reactTag.
*/
- (NSString *)viewNameForReactTag:(NSNumber *)reactTag;
/**
* Gets the view associated with a reactTag.
*/
- (NSView *)viewForReactTag:(NSNumber *)reactTag;
/**
* Gets the shadow view associated with a reactTag.
*/
- (RCTShadowView *)shadowViewForReactTag:(NSNumber *)reactTag;
/**
* Set the available size (`availableSize` property) for a root view.
* This might be used in response to changes in external layout constraints.
* This value will be directly trasmitted to layout engine and defines how big viewport is;
* this value does not affect root node size style properties.
* Can be considered as something similar to `setSize:forView:` but applicable only for root view.
*/
- (void)setAvailableSize:(CGSize)availableSize forRootView:(NSView *)rootView;
/**
* Sets local data for a shadow view corresponded with given view.
* In some cases we need a way to specify some environmental data to shadow view
* to improve layout (or do something similar), so `localData` serves these needs.
* For example, any stateful embedded native views may benefit from this.
* Have in mind that this data is not supposed to interfere with the state of
* the shadow view.
* Please respect one-directional data flow of React.
*/
- (void)setLocalData:(NSObject *)localData forView:(NSView *)view;
/**
* Set the size of a view. This might be in response to a screen rotation
* or some other layout event outside of the React-managed view hierarchy.
*/
- (void)setSize:(CGSize)size forView:(NSView *)view;
/**
* Set the natural size of a view, which is used when no explicit size is set.
* Use `UIViewNoIntrinsicMetric` to ignore a dimension.
* The `size` must NOT include padding and border.
*/
- (void)setIntrinsicContentSize:(CGSize)intrinsicContentSize forView:(NSView *)view;
/**
* Sets up layout animation which will perform on next layout pass.
* The animation will affect only one next layout pass.
* Must be called on the main queue.
*/
- (void)setNextLayoutAnimationGroup:(RCTLayoutAnimationGroup *)layoutAnimationGroup;
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute
* view logic after all currently queued view updates have completed.
*/
- (void)addUIBlock:(RCTViewManagerUIBlock)block;
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute
* view logic before all currently queued view updates have completed.
*/
- (void)prependUIBlock:(RCTViewManagerUIBlock)block;
/**
* Used by native animated module to bypass the process of updating the values through the shadow
* view hierarchy. This method will directly update native views, which means that updates for
* layout-related propertied won't be handled properly.
* Make sure you know what you're doing before calling this method :)
*/
- (void)synchronouslyUpdateViewOnUIThread:(NSNumber *)reactTag
viewName:(NSString *)viewName
props:(NSDictionary *)props;
/**
* Given a reactTag from a component, find its root view, if possible.
* Otherwise, this will give back nil.
*
* @param reactTag the component tag
* @param completion the completion block that will hand over the rootView, if any.
*
*/
- (void)rootViewForReactTag:(NSNumber *)reactTag withCompletion:(void (^)(NSView *view))completion;
/**
* Finds a view that is tagged with nativeID as its nativeID prop
* with the associated rootTag root tag view hierarchy. Returns the
* view if found, nil otherwise.
*
* @param nativeID the id reference to native component relative to root view.
* @param rootTag the react tag of root view hierarchy from which to find the view.
*/
- (NSView *)viewForNativeID:(NSString *)nativeID withRootTag:(NSNumber *)rootTag;
/**
* The view that is currently first responder, according to the JS context.
*/
+ (NSView *)JSResponder;
/**
* In some cases we might want to trigger layout from native side.
* React won't be aware of this, so we need to make sure it happens.
*/
- (void)setNeedsLayout;
/**
* Dedicated object for subscribing for UIManager events.
* See `RCTUIManagerObserver` protocol for more details.
*/
@property (atomic, retain, readonly) RCTUIManagerObserverCoordinator *observerCoordinator;
@end
/**
* This category makes the current RCTUIManager instance available via the
* RCTBridge, which is useful for RCTBridgeModules or RCTViewManagers that
* need to access the RCTUIManager.
*/
@interface RCTBridge (RCTUIManager)
@property (nonatomic, readonly) RCTUIManager *uiManager;
@end
|
{
"content_hash": "d09a76efac17435f0ffa7a747662cbea",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 99,
"avg_line_length": 34.60248447204969,
"alnum_prop": 0.7445700951355232,
"repo_name": "ptmt/react-native-macos",
"id": "be058d4e0aec9df22ecedb2c5a2e13526d6cf36a",
"size": "5879",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "React/Modules/RCTUIManager.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "15392"
},
{
"name": "Batchfile",
"bytes": "682"
},
{
"name": "C",
"bytes": "44835"
},
{
"name": "C++",
"bytes": "900849"
},
{
"name": "CSS",
"bytes": "1116"
},
{
"name": "HTML",
"bytes": "162528"
},
{
"name": "Java",
"bytes": "2847888"
},
{
"name": "JavaScript",
"bytes": "3661796"
},
{
"name": "Kotlin",
"bytes": "698"
},
{
"name": "Makefile",
"bytes": "7402"
},
{
"name": "Objective-C",
"bytes": "1911883"
},
{
"name": "Objective-C++",
"bytes": "317352"
},
{
"name": "Ruby",
"bytes": "15240"
},
{
"name": "Shell",
"bytes": "52222"
},
{
"name": "Starlark",
"bytes": "108010"
}
],
"symlink_target": ""
}
|
/* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: stdext/mmap/FileMapping.h
// Creator: xushiwei
// Email: xushiweizh@gmail.com
// Date: 2006-8-13 9:41:58
//
// $Id: $
// -----------------------------------------------------------------------*/
#ifndef STDEXT_MMAP_FILEMAPPING_H
#define STDEXT_MMAP_FILEMAPPING_H
#ifndef STDEXT_MMAP_MAPFILE_H
#include "MapFile.h"
#endif
#ifndef STDEXT_MMAP_ACCESSBUFFER_H
#include "AccessBuffer.h"
#endif
NS_STDEXT_BEGIN
// -------------------------------------------------------------------------
// class HandleProxy
template <class Owner>
class HandleProxy
{
private:
Owner* m_owner;
public:
enum { AllocationGranularityBits = Owner::AllocationGranularityBits };
enum { AllocationGranularity = Owner::AllocationGranularity };
enum { AllocationGranularityMask = Owner::AllocationGranularityMask };
public:
typedef typename Owner::size_type size_type;
typedef typename Owner::pos_type pos_type;
typedef typename Owner::Utils Utils;
public:
HandleProxy(Owner& owner) : m_owner(&owner) {
}
void winx_call close() {
}
char* winx_call viewSegment(DWORD iBasePage, DWORD nPageCount) {
return m_owner->viewSegment(iBasePage, nPageCount);
}
char* winx_call accessSegment(DWORD iBasePage, DWORD nPageCount) {
return m_owner->accessSegment(iBasePage, nPageCount);
}
char* winx_call allocSegment(DWORD nPageCount, DWORD& iBasePage) {
return m_owner->allocSegment(nPageCount, iBasePage);
}
};
// -------------------------------------------------------------------------
// class FileMapping
template <class Config>
class FileMapping : public MapFile<Config>
{
private:
typedef MapFile<Config> BaseClass;
DWORD m_nTotalPage;
FileMapping(const FileMapping&);
void operator=(const FileMapping&);
private:
enum { _nAGBits = 16 };
enum { _nAllocationGranularityInvBits = sizeof(DWORD)*8 - _nAGBits };
public:
enum { AllocationGranularityBits = _nAGBits };
enum { AllocationGranularity = (1 << _nAGBits) };
enum { AllocationGranularityMask = (AllocationGranularity - 1) };
public:
typedef typename BaseClass::size_type size_type;
typedef typename BaseClass::pos_type pos_type;
typedef HandleProxy<FileMapping> Handle;
typedef BaseClass Utils;
public:
FileMapping() {}
FileMapping(LPCSTR szFile, pos_type* offset = NULL) {
open(szFile, offset);
}
public:
DWORD winx_call getTotalPages() const {
return m_nTotalPage;
}
void winx_call close() {
BaseClass::close();
m_nTotalPage = 0;
}
HRESULT winx_call resize(pos_type cbSize) {
m_nTotalPage = (DWORD)((cbSize + AllocationGranularityMask) >> AllocationGranularityBits);
return BaseClass::resize(cbSize);
}
HRESULT winx_call open(LPCSTR szFile, pos_type* offset = NULL)
{
if (Config::GetSizeOnOpen) {
pos_type cbSize;
HRESULT hr = BaseClass::open(szFile, &cbSize);
m_nTotalPage = (DWORD)((cbSize + AllocationGranularityMask) >> AllocationGranularityBits);
if (offset)
*offset = cbSize;
return hr;
}
else {
m_nTotalPage = 0;
return BaseClass::open(szFile, NULL);
}
}
char* winx_call viewSegment(DWORD iBasePage, DWORD nPageCount)
{
WINX_ASSERT(BaseClass::good());
if (iBasePage + nPageCount > m_nTotalPage)
{
if (iBasePage >= m_nTotalPage)
return NULL;
else
nPageCount = m_nTotalPage - iBasePage;
}
return (char*)BaseClass::map(
(off_t)iBasePage << AllocationGranularityBits,
nPageCount << AllocationGranularityBits);
}
char* winx_call accessSegment(DWORD iBasePage, DWORD nPageCount)
{
WINX_ASSERT(BaseClass::good());
if (iBasePage + nPageCount > m_nTotalPage)
{
m_nTotalPage = iBasePage + nPageCount;
BaseClass::resize((off_t)m_nTotalPage << AllocationGranularityBits);
}
return (char*)BaseClass::map(
(off_t)iBasePage << AllocationGranularityBits,
nPageCount << AllocationGranularityBits);
}
char* winx_call allocSegment(DWORD nPageCount, DWORD& iBasePage)
{
WINX_ASSERT(BaseClass::good());
iBasePage = m_nTotalPage;
m_nTotalPage += nPageCount;
BaseClass::resize((off_t)m_nTotalPage << AllocationGranularityBits);
return (char*)BaseClass::map(
(off_t)iBasePage << AllocationGranularityBits,
nPageCount << AllocationGranularityBits);
}
};
typedef FileMapping<MappingReadWrite> FileMappingRW;
typedef FileMapping<MappingReadOnly> FileMappingRO;
// -------------------------------------------------------------------------
// $Log: $
NS_STDEXT_END
#endif /* STDEXT_MMAP_FILEMAPPING_H */
|
{
"content_hash": "b2c0581ec86f184add40583089b512db",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 93,
"avg_line_length": 26.4,
"alnum_prop": 0.6491841491841492,
"repo_name": "qiniu/cerl",
"id": "e8a7248f2628f25fc7f92c27f0a6f7f1cc6db43a",
"size": "5148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stdext/include/stdext/mmap/FileMapping.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "291528"
},
{
"name": "C++",
"bytes": "2365234"
},
{
"name": "CMake",
"bytes": "11502"
},
{
"name": "HTML",
"bytes": "6794"
},
{
"name": "Makefile",
"bytes": "45977"
},
{
"name": "Objective-C",
"bytes": "19258"
},
{
"name": "PHP",
"bytes": "77087"
},
{
"name": "Python",
"bytes": "14211"
},
{
"name": "Shell",
"bytes": "994"
}
],
"symlink_target": ""
}
|
o2.inputCount = function(elm, countContainerId, maxLength) {
var currentCount = 0;
var type = "element";
if (elm == parseInt(elm)) {
currentCount = elm;
type = "count";
}
else {
currentCount = elm.value.length;
}
var counter = currentCount || 0;
if (maxLength >= 0) {
if (type == "element" && counter > maxLength) { elm.value = elm.value.substring(0,maxLength); }
counter += "/" + maxLength;
}
var countContainer = document.getElementById( countContainerId );
if (countContainer) {
countContainer.innerHTML = counter;
}
}
|
{
"content_hash": "b317213af665e74752bdfd85b8bf418a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 99,
"avg_line_length": 29.5,
"alnum_prop": 0.6169491525423729,
"repo_name": "haakonsk/O2-Framework",
"id": "3c89c9c0d278046ca630f5d255fb0a3b3ce01c9b",
"size": "590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "var/www/js/inputCounter.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "321037"
},
{
"name": "CSS",
"bytes": "83670"
},
{
"name": "Emacs Lisp",
"bytes": "140999"
},
{
"name": "JavaScript",
"bytes": "1127586"
},
{
"name": "PHP",
"bytes": "1316824"
},
{
"name": "Perl",
"bytes": "1879776"
},
{
"name": "Prolog",
"bytes": "1284"
},
{
"name": "Rebol",
"bytes": "350"
},
{
"name": "Shell",
"bytes": "1220"
}
],
"symlink_target": ""
}
|
namespace NServiceBus.AcceptanceTests.ScenarioDescriptors
{
using System;
using AcceptanceTesting.Support;
using NServiceBus.Persistence;
public class AllOutboxCapableStorages : ScenarioDescriptor
{
public AllOutboxCapableStorages()
{
var defaultSettings = Persistence.Default;
var definitionType = defaultSettings.Settings.Get<Type>("Persistence");
var definition = (PersistenceDefinition) Activator.CreateInstance(definitionType, true);
if (definition.HasSupportFor<StorageType.Outbox>())
{
Add(defaultSettings);
}
}
}
}
|
{
"content_hash": "5f5cc02ee8c628258416a8a8c702ce25",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 100,
"avg_line_length": 32.42857142857143,
"alnum_prop": 0.6358296622613803,
"repo_name": "sbmako/NServiceBus.MongoDB",
"id": "005715e3020df942af1e98be208332a188938522",
"size": "683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NServiceBus.MongoDB.Acceptance.Tests/App_Packages/NSB.AcceptanceTests.6.0.0/ScenarioDescriptors/AllOutboxCapableStorages.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "986392"
},
{
"name": "Dockerfile",
"bytes": "540"
},
{
"name": "Makefile",
"bytes": "1045"
}
],
"symlink_target": ""
}
|
/*
* Globals
*/
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
body {
}
.main-content {
padding-top: 80px;
}
h1, .h1,
h2, .h2,
h3, .h3,
h4, .h4,
h5, .h5,
h6, .h6 {
margin-top: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 300;
color: #333;
}
.no-margin {
margin: 0;
}
.no-padding {
padding: 0;
}
.navbar-brand,
.navbar-brand:hover {
background-image: url(/images/logo.png);
background-size: 130px;
width: 132px;
color: transparent !important;
margin-left: 10px !important;
background-repeat: no-repeat;
background-position-x: 0;
background-position-y: 14px;
}
.menu-links {
margin-left: 10px;
}
.navbar-nav {
margin:0;
}
.add-new-top-button,
.add-new-top-button:hover
{
height: 35px;
line-height: 10px !important;
padding-top: 8px !important;
color: #fff !important;
font-weight: normal !important;
text-shadow: none !important;
margin-top: 3px;
margin-right: 0;
background-color: #419641 !important;
}
.login-top,
.create-new-user-top {
height: 35px;
padding-top: 8px !important;
font-weight: normal !important;
text-shadow: none !important;
margin-top: 7px;
display: inline-block;
line-height: 16px !important;
}
.top-menu-dropdown-icon {
font-size: 10px;
}
.login-top {
width: 100px;
color: #fff !important;
background-color: #286090 !important;
}
.create-new-user-top,
.create-new-user-top:hover
{
width: 120px;
background-color: #e0e0e0 !important;
}
.login-or-create {
display: inline-block;
height: 33px;
padding: 10px 6px 0;
vertical-align: middle;
}
.login-home {
width: 300px;
}
.profile-image {
height: 32px;
width: 32px;
display: inline-block;
margin-right: 7px;
}
a.contains-profile-img {
padding-top: 8px !important;
padding-bottom: 8px !important;
}
.jumbotron {
text-align: left;
background-color: transparent;
margin-bottom: 0;
margin-top: -50px;
}
.jumbotron h2 {
font-size: 38px;
margin-bottom: 20px;
margin-top: 20px;
}
.jumbotron .home-intro {
font-size: 14px;
margin-bottom:20px;
}
.jumbotron .btn {
font-size: 14px;
}
.first-page-banner {
width: 70%;
}
.first-page-preview {
width: 100%;
margin-left: -50px;
margin-top: 17px;
}
.home-page-carousel {
margin-bottom: 40px;
}
/*
* Override Bootstrap's default container.
*/
@media (min-width: 1200px) {
.container {
width: 970px;
}
}
/*
* Main column and sidebar layout
*/
/* Sidebar modules for boxing content */
.sidebar-module {
padding: 15px;
margin: 0 -15px 15px;
}
.sidebar-module-inset {
padding: 15px;
background-color: #f5f5f5;
border-radius: 4px;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child {
margin-bottom: 0;
}
.nav-tab-pop {
margin-bottom: 15px;
}
.thumbnail-preview {
width: 100%;
border: 1px solid lightgray;
}
.thumbnail.thumbnail-first-page {
//height: 270px;
}
.thumbnail p.thumbnail-caption {
font-size: 12px;
height: 50px;
overflow: hidden;
text-overflow: ellipsis;
}
.thumbnail h4 {
height: 41px;
overflow: hidden;
text-overflow: ellipsis;
}
.open-link {
margin-bottom: -15px;
margin-top: -5px;
padding: 5px;
}
.favorited-and-comments {
font-size: 12px;
color: gray;
}
.favorited-and-comments span{
padding-left: 6px;
}
.favorited-and-comments span .icon-space-after {
padding-left: 5px;
}
.simple-search {
margin-top: 40px;
margin-bottom: 40px;
}
.simple-search input {
display: inline-block;
}
.simple-search h3 {
margin-left: 10px;
display: inline-block;
}
.search-desc {
font-size: 12px;
margin-left: 10px;
}
.search-form .multiselect-parent.btn-group.dropdown-multiselect,
.btn-fixed-width {
width: 100% !important;
}
.simple-browse h3 {
margin-left: 25px;
margin-bottom: 20px;
}
.simple-browse a {
display: inline-block;
width: 30%;
}
.simple-browse .col-sm-11 {
margin-left: 30px;
}
.more-spec-search {
float: right;
margin-top: 10px;
}
.simple-search .input-group {
margin-top: 35px;
}
.footer {
margin-top: 50px;
}
.footer ul {
list-style: none;
}
span.selected {
padding-right: 7px;
}
span.not-selected {
padding-right: 21px;
}
.drop-down-search {
width: 90%;
margin: 0 auto;
}
.main-input-search-top {
text-overflow: ellipsis;
}
.search-fields-top .col-sm-2 button,
.search-fields-top .col-sm-3 button {
text-align: left;
}
.search-fields-top .col-sm-2 .caret,
.search-fields-top .col-sm-3 .caret {
position: absolute;
right: 10px;
margin-top: 10px;
}
.search-fields-top .dropdown-menu>li>a span {
padding-left: 18px;
}
.search-fields-top .dropdown-menu>li>a span.glyphicon {
padding-left: 0px;
}
.search-fields-top .col-sm-2,
.search-fields-top .col-sm-3 {
padding-right: 3px;
padding-left: 3px;
}
.advanced-options-and-results .col-sm-3 {
padding-left: 3px;
}
.advanced-options-and-results .col-sm-3 .panel {
margin-bottom: 10px;
cursor: pointer;
}
.advanced-options-and-results .col-sm-3 .panel span {
float: right;
}
.results-heading {
margin-top: 30px;
}
.advanced-options-and-results .col-sm-3 .panel h4 {
font-size: 12px;
}
.advanced-options-and-results .col-sm-3 .panel-heading {
font-size: 13px;
}
.advanced-options-and-results .col-sm-3 .list-group-item {
font-size: 12px;
}
.advanced-options-and-results .col-sm-3 .panel .filter-items {
margin-bottom: 5px;
font-size: 12px;
}
.advanced-options-and-results .col-sm-3 .panel .items {
height: 200px;
overflow-y: scroll;
}
.advanced-options-and-results .single_scenario_item .thumbnail {
margin-bottom: 0;
}
.advanced-options-and-results .results-buttons {
margin-top: 10px;
}
.advanced-options-and-results hr {
margin-top: 10px;
margin-bottom: 10px;
}
.dropdown-multiselect .dropdown-toggle {
overflow: hidden;
padding-right: 20px !important;
text-overflow: ellipsis;
}
#subject > .dropdown-multiselect .dropdown-toggle,
#subject > button.dropdown-toggle,
#subject > .dropdown-multiselect {
width: 100%;
text-align: left;
}
#subject li>a span {
padding-left: 18px;
}
#subject li>a span.glyphicon {
padding-left: 0px;
}
.single_scenario_item p {
font-size: 13px;
}
.single_scenario_item p.description {
max-height: 90px;
overflow: hidden;
}
.single_scenario_item {
padding-bottom: 10px;
}
.single_scenario_item .thumbnail {
margin-bottom: 10px;
}
.single_scenario_item .extra-info {
}
.single_scenario_item .rating {
}
.pagination-scenarios-list {
text-align: center;
}
.subject-page .panel,
.subject-page .list-group-item {
font-size: 13px;
}
.subject-heading {
display: inline-block;
}
.follow-subject {
display: inline-block;
margin-left: 20px;
margin-top: -17px;
}
.subject-inro {
margin-bottom: 25px;
}
.profile-sidebar {
}
.small-profile {
margin-bottom: 10px;
}
.profile-userpic img {
border-radius: 50% !important;
}
.subject-image {
width: 72px;
margin-right: 22px;
margin-bottom: 10px;
float: left;
}
.profile-usertitle {
margin-top: 20px;
}
.profile-usertitle-name {
font-weight: bold;
font-size: 18px;
}
.profile-userbuttons {
margin-top: 25px;
}
.profile-userbuttons a {
width: 100%;
}
.small-profile-userbuttons a {
margin-bottom: 10px;
}
.profile-usertitle-sign-up {
margin-top: 10px;
font-size: 12px;
color: gray;
}
.small-profile-usertitle-sign-up {
margin-top: 0;
font-size: 12px;
color: gray;
}
.profile-side-box {
margin-top: 40px;
padding: 10px;
}
.profile-side-box h3 {
margin-left: -10px;
}
.profile-side-box .col-md-3 {
padding-left: 3px;
padding-right: 3px;
}
.profile-side-box .thumbnail {
margin-bottom: 2px;
padding: 2px;
}
.profile-side-box .thumbnail img {
width:100%;
}
.full-scenario-image {
width: 100%;
border: 1px solid lightgrey;
margin-bottom: 20px;
}
.comments-list {
margin-right: 0;
margin-left: 0;
}
.similar-scenarios {
margin-top: 30px;
}
.similar-scenarios h3 {
font-size: 22px;
}
.commets {
margin-top: 20px;
font-size: 13px;
}
.commets .comment-date {
color: gray;
margin-bottom: 10px;
}
.comment-closer {
padding-left: 0;
}
.comment-post {
margin-top: 15px;
word-wrap: break-word;
}
.commets p.text-right {
margin: 0;
}
.post-comment .name,
.post-comment .email {
width: 200px;
}
.main-login {
max-width: 320px;
margin: 0 auto;
font-size: 12px
}
.main-login .login-or {
position: relative;
font-size: 18px;
color: #aaa;
margin-top: 10px;
margin-bottom: 10px;
padding-top: 10px;
padding-bottom: 10px;
}
.main-login .span-or {
display: block;
position: absolute;
left: 50%;
top: -2px;
margin-left: -25px;
background-color: #fff;
width: 50px;
text-align: center;
}
.main-login .hr-or {
background-color: #cdcdcd;
height: 1px;
margin-top: 0px !important;
margin-bottom: 0px !important;
}
.main-login h3 {
text-align: center;
line-height: 300%;
}
.print-button,
.save-button {
margin-top: 0;
}
/*
SIDE menu
*/
.side-menu ul {
width: 100%;
}
.side-menu ul li {
float: none;
display: block;
font-size: 12px;
}
.side-menu ul li span {
margin-right: 5px;
}
.side-menu ul li .badge {
float: right;
}
.dashboard-main-content {
/* height: 100%;
overflow-y: scroll; /* has to be scroll, not auto */
-webkit-overflow-scrolling: touch;
font-size: 13px;
padding-top: 5px;
}
.dashboard-main-content .badge {
//float: right;
margin-left: 5px;
}
/*::-webkit-scrollbar {
display: none;
}*/
.input-group.search {
padding-bottom: 20px;
border-bottom: 1px solid gray;
}
.dashboard-main-content .single_scenario_item {
padding-bottom: 0px;
}
.dashboard-main-content .single_scenario_item .extra-info {
display: inline-block;
}
.dashboard-main-content .single_scenario_item .rating {
float: right;
display: inline-block;
margin-left: 38px;
}
.dashboard-main-content .single_scenario_item .open-button {
margin-top: -10px;
}
.dashboard-main-content a h3.panel-title {
color: #fff;
text-decoration: none;
}
.dashboard-main-content a.black-link h3.panel-title {
color: #000;
text-decoration: none;
}
.dashboard-user-thumb {
width: 40px;
padding: 10px 0;
overflow: hidden;
}
.loading-gif-animation {
text-align: center;
margin: 0 auto;
}
.notifications
{
list-style: none;
margin: 0;
padding: 0;
font-size: 12px;
}
.notifications img {
width: 35px;
}
.notifications li
{
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px dotted #B3A9A9;
}
.notifications li.left .notification-body
{
margin-left: 50px;
}
.notifications li .notification-body p
{
margin: 0;
color: #777777;
}
.notifications {
height: 300px;
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
}
p.content-for-notification {
float: left;
padding-top: 6px;
}
.notifications li.new {
font-weight: bold;
color: #000;
}
/* user list dashboard */
.user-list-follow-unfollow-btn {
margin-top: 19px;
}
.user-list-image {
padding-right: 15px;
}
.user-list-organization {
color:gray;
}
/* enable absolute positioning */
.inner-addon {
position: relative;
}
/* style glyph */
.inner-addon .glyphicon {
position: absolute;
padding: 10px;
}
/* align glyph */
.left-addon .glyphicon { left: 0px;}
.right-addon .glyphicon { right: 0px;}
/* add padding */
.left-addon input { padding-left: 30px; }
.right-addon input { padding-right: 30px; }
.header-search {
margin-top: 8px;
}
.header-login {
margin-left: 30px;
margin-top: 14px;
}
#bottom {
position: absolute;
bottom: 10%;
}
.search-dash {
margin-right: 20px;
width: 24%;
}
.dash-scenario-label {
margin-right: 15px;
}
label {
display: inline-block;
}
.learining-outcomes-list-container {
margin-bottom: 30px;
}
.activity-item {
background-color: #fff;
width: 100%;
}
.activity-item .multiselect-parent,
.activity-item .multiselect-parent button {
width: 100%;
text-align: left;
}
.activity-item .multiselect-parent button .caret {
position: absolute;
right: 10px;
margin-top: 10px;
}
.activity-item .dropdown-menu>li>a span {
padding-left: 18px;
}
.activity-item .dropdown-menu>li>a span.glyphicon {
padding-left: 0px;
}
.dropdown-menu li {
cursor: pointer;
}
.activity-list-container {
margin-top: 30px;
margin-bottom: 30px;
}
.drag-selector {
cursor: move;
position: absolute;
right: 10px;
}
.drag-selector span {
font-size: 1.2em;
color: gray;
padding-top: 8px;
}
/* position add-material-modal to center */
.modal {
text-align: center;
}
@media screen and (min-width: 768px) {
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
.show {
display: block;
}
.hide {
display: none;
}
a.delete-link {
color: red;
}
.clear:before,
.clear:after {
content: " ";
display: table;
}
.clear:after {
clear: both;
}
#scenario-wrapper {
border: 1px solid lightgray;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.legend,
.legend-text,
.timeline-line,
.activity-container,
.activity-org-icon,
.activity-org-title,
.material-container,
.material-wrapper,
.conveyor-container,
.display-container,
.material-edit,
.new-add,
.new-material-button {
position: absolute;
}
.activity-container,
.material-wrapper,
.conveyor-container,
.display-container,
.material-edit,
.new-material-button {
-webkit-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.legend-text {
font-size: 11px;
line-height: 1;
}
.activity-container {
font-size: 11px;
z-index: 1;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
color: #000;
}
.material-container {
color: #000;
width: 100%;
height: 100%;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
padding: 3px;
line-height: 1.1;
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
word-wrap: break-word;
z-index: 5;
}
.material-wrapper.bottom,
.new-material-button.bottom,
.conveyor-container.bottom {
-webkit-animation: bottomAnimation 0.4s; /* Chrome, Safari, Opera */
-webkit-animation-fill-mode: forwards; /* Chrome, Safari, Opera */
-webkit-animation-timing-function: ease-in; /* Chrome, Safari, Opera */
-webkit-animation: bottomAnimation 0.4s;
animation: bottomAnimation 0.4s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
.material-container.top {
padding-top: 2px;
}
.material-wrapper.top,
.new-material-button.top,
.conveyor-container.top {
-webkit-animation: topAnimation 0.4s; /* Chrome, Safari, Opera */
-webkit-animation-fill-mode: forwards; /* Chrome, Safari, Opera */
-webkit-animation-timing-function: ease-in; /* Chrome, Safari, Opera */
-webkit-animation: topAnimation 0.4s;
animation: topAnimation 0.4s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
.material-container a {
color: black;
text-decoration: underline;
}
.conveyor-container {
display: block;
}
.activity-container-hover {
height: 100px !important;
margin-top: -40px;
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23) !important;
-webkit-box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23) !important;
z-index: 10;
}
.activity-container span.activity-text-container {
position: absolute;
top: 4px;
left: 4px;
width: 100%;
height: 100%;
overflow:hidden !important;
text-overflow: ellipsis;
line-height: 1.2;
cursor: pointer;
z-index: 30;
border-right: 23px solid transparent;
white-space: nowrap; /* does not work ie and edge */
border-bottom: 8px solid transparent; /* white-space fallback */
}
.activity-container-hover span.activity-text-container {
word-wrap: break-word;
white-space: normal; /* does not work ie and edge */
padding-right: 4px;
padding-bottom: 16px;
border-right: 4px solid transparent;
border-bottom: 22px solid transparent;
}
.activity-container-hover span.activity-text-container,
.activity-container-hover img.activity-org-icon {
display: block !important;
}
.activity-duration-container {
font-size: 11px;
padding-right: 3px;
}
.activity-container-hover .activity-duration-container {
position: absolute;
bottom: 0;
left: 0;
}
.activity-duration-min-container {
display: none;
}
.activity-container-hover .activity-duration-min-container {
display: inline-block;
padding-left: 3px;
}
.activity-org-icon {
height: 13px;
right: 4px;
bottom: 4px;
}
.activity-container-hover .activity-org-icon {
left: 4px;
right: 0;
}
.activity-org-title {
display: none;
}
.activity-container-hover .activity-org-title {
display: block;
left: 20px;
bottom: 3px;
}
.conveyor-container,
.display-container {
background-color: #F7F7F7 !important;
width: 20px;
height: 20px;
z-index: 2;
border-radius: 999em;
}
.conveyor-container img,
.display-container img{
margin-left: 4px;
margin-right: 4px;
margin-top: -2px;
}
.conveyor-container.bottom ,
.display-container.bottom {
/*border-bottom-left-radius: 4px;*/
/*border-bottom-right-radius: 4px;*/
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
}
.conveyor-container.top ,
.display-container.top {
/*border-top-left-radius: 4px;*/
/*border-top-right-radius: 4px;*/
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
}
.new-material-button.top,
.new-material-button.bottom {
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) !important;
}
.activity-container {
-webkit-animation: leftAnimation 0.4s; /* Chrome, Safari, Opera */
-webkit-animation-fill-mode: forwards; /* Chrome, Safari, Opera */
-webkit-animation-timing-function: ease-in; /* Chrome, Safari, Opera */
-webkit-animation: leftAnimation 0.4s;
animation: leftAnimation 0.4s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
/* ANIMATION */
@-webkit-keyframes leftAnimation {
from {
//opacity: 0;
-webkit-transform: scale3d(0, 0, 1);
transform: scale3d(0, 0, 1);
-webkit-transform-origin: left;
transform-origin: left;
}
to {
//opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
-webkit-transform-origin: left;
transform-origin: left;
}
}
@-webkit-keyframes bottomAnimation {
from {
//opacity: 0;
-webkit-transform: scale3d(0, 0, 1);
transform: scale3d(0, 0, 1);
-webkit-transform-origin: top;
transform-origin: top;
}
to {
//opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
-webkit-transform-origin: top;
transform-origin: top;
}
}
@-webkit-keyframes topAnimation {
from {
//opacity: 0;
-webkit-transform: scale3d(0, 0, 1);
transform: scale3d(0, 0, 1);
-webkit-transform-origin: bottom;
transform-origin: bottom;
}
to {
//opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
-webkit-transform-origin: bottom;
transform-origin: bottom;
}
}
.material-edit,
.new-add {
height: 100%;
width: 100%;
z-index: 6;
cursor: pointer;
font-size: 13px;
color: #fff;
text-align: center;
text-shadow: 1px 1px 1px rgba(0,0,0,0.3) !important;
overflow: hidden;
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
user-select: none;
}
.new-add {
border-radius: 999em;
}
.material-edit span,
.new-add span {
position: absolute;
top: 50%;
left: 50%;
margin-left: -11px;
margin-top: -9px;
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
user-select: none;
}
.new-add span {
margin-top: -14px;
margin-left: -5px;
font-size: 18px;
}
.material-edit:hover,
.new-add:hover {
background-color: rgba(0,0,0,0.5) !important;
color: #fff;
text-decoration: none;
}
.new-material-button {
border-radius: 999em;
}
.tooltip {
z-index: 25;
}
.tooltip-inner {
border-radius: 0;
}
.popover {
line-height: 1.4;
font-size: 12px;
border-radius: 0;
border-color: #e6e6e6;
border: 1px solid rgba(0,0,0,.1);
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.14) !important;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.14) !important;
}
.popover.right>.arrow {
border-right-color: #ededed;
border-right-color:rgba(0,0,0,.1);
}
.popover.left>.arrow {
border-left-color: #ededed;
border-left-color:rgba(0,0,0,.1);
}
.popover-content {
padding: 1px 5px;
}
.inner-display-icon img,
.inner-conveyor-icon img {
margin-right: 5px;
margin-top: -2px;
}
.inner-conveyor-icon {
cursor: pointer;
display: block;
}
textarea#description {
max-width: 100%;
min-width: 100px;
}
.enable-lines {
white-space: pre-line;
}
/* without link */
.popover a.inner-conveyor-icon:hover {
cursor: default;
text-decoration: none;
}
.popover a.inner-conveyor-icon[href]:hover {
cursor: pointer;;
text-decoration: underline;
}
#scenario-text-container {
margin-top: 20px;
}
.subject-labels {
margin-right: 2px;
font-weight: normal;
display: inline-block;
}
.only-print-title {
display: none;
margin-top: 15px;
}
@page { size: A4 landscape }
@media print {
body {
padding: 0;
-webkit-print-color-adjust: exact;
}
.conveyor-container.top,
.display-container.top,
.conveyor-container.bottom,
.display-container.bottom,
.activity-container-hover,
.material-container,
.activity-container,
.new-material-button.top,
.new-material-button.bottom {
box-shadow: none !important;
}
.main-content {
padding: 0;
}
.scenario-page {
display: none;
}
.only-print-title {
display: block !important;
}
.timeline-back-button {
display: none;
}
#scenario-timeline-wrapper {
width: 100%;
overflow: visible;
}
.footer .pull-left{
display: none;
}
.footer .pull-right{
display: none;
position: fixed;
bottom: 25mm;
right: 25mm;
margin-left: -70mm;
}
a[href]:after {
content: none !important;
}
.scenario-text-container a {
color: blue !important;
}
.only-print-title a {
color: blue !important;
text-decoration: underline;
}
a.link-for-print {
color: blue !important;
text-decoration: underline;
}
.p-with-links a {
color: blue !important;
text-decoration: underline;
}
}
|
{
"content_hash": "3fd423b68a8e53146738c9a3197920ef",
"timestamp": "",
"source": "github",
"line_count": 1397,
"max_line_length": 92,
"avg_line_length": 17.797423049391554,
"alnum_prop": 0.6251457989784016,
"repo_name": "romilrobtsenkov/leplanner-beta",
"id": "f071f593bd609a5d2015024e19e6d25ff96d39c1",
"size": "24863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/stylesheets/style.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24863"
},
{
"name": "HTML",
"bytes": "99537"
},
{
"name": "JavaScript",
"bytes": "272114"
}
],
"symlink_target": ""
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class StableMatchingBruteforce{
public static void main(String[] args){
char input;
int inChar;
int count;
Scanner keyboard = new Scanner(System.in);
File file = null;
FileInputStream reader = null;
do{
printMenu();
input = keyboard.next().charAt(0);
if(input == 'A'){
printCase(input);
try{
file = new file("testcase0.txt");
reader = new FileInputStream(file);
// read first item size n of the lists and number of people
count = reader.read() - '0';
// initialize arrays with n we just read
int[][] preferenceList = new int[2*count][count];
// start filling up the preferences
int i=0;
int j=0;
while(reader.available() > 0){
inChar = reader.read() - '0';
if(inChar >= 0 && inChar <= 9){
preferenceList[j][i] = inChar;
i++;
if(i == count){
i=0;
j++;
if(j == 2*count)
j=0;
}
}
}
reader.close();
} catch(IOException e){
e.printStackTrace();
}
}
else if(input == 'B'){
printCase(input);
try{
file = new file("testcase1.txt");
reader = new FileInputStream(file);
// read first item size n of the lists and number of people
count = reader.read() - '0';
// initialize arrays with n we just read
int[][] preferenceList = new int[2*count][count];
// start filling up the preferences
int i=0;
int j=0;
while(reader.available() > 0){
inChar = reader.read() - '0';
if(inChar >= 0 && inChar <= 9){
preferenceList[j][i] = inChar;
i++;
if(i == count){
i=0;
j++;
if(j == 2*count)
j=0;
}
}
}
reader.close();
} catch(IOException e){
e.printStackTrace();
}
}
else if(input == 'C'){
printCase(input);
try{
file = new file("testcase2.txt");
reader = new FileInputStream(file);
// read first item size n of the lists and number of people
count = reader.read() - '0';
// initialize arrays with n we just read
int[][] preferenceList = new int[2*count][count];
// start filling up the preferences
int i=0;
int j=0;
while(reader.available() > 0){
inChar = reader.read() - '0';
if(inChar >= 0 && inChar <= 9){
preferenceList[j][i] = inChar;
i++;
if(i == count){
i=0;
j++;
if(j == 2*count)
j=0;
}
}
}
reader.close();
} catch(IOException e){
e.printStackTrace();
}
}
else if(input == 'D'){
System.out.println("What is the size of n?");
}
else if(input == 'E'){
System.out.println("Good Bye.");
}
else{
System.out.println("Error! Try Again!");
}
} while(input != 'D');
}
public static void printMenu(){
System.out.println("Welcome to Stable Matching Bruteforce");
System.out.println("--------------------------------------");
System.out.println("Please Select an option");
System.out.println("A) Read test case 0")
System.out.println("B) Read test case 1");
System.out.println("C) Read test case 2");
System.out.println("D) Generate Randomly");
System.out.println("E) Quit");
}
public static void printCase(char flag){
if(flag == 'A')
System.out.println("Reading test case 0...");
else if(flag == 'B')
System.out.println("Reading test case 1...");
else
System.out.println("Reading test case 2...");
}
}
|
{
"content_hash": "61ae00fbf9ed5809e70f7a6746eb7cc3",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 64,
"avg_line_length": 25.585714285714285,
"alnum_prop": 0.5538805136795086,
"repo_name": "klinster/School-Work",
"id": "a64e566006330a85ea698e37039dfbf2c501e1e7",
"size": "3582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "496/project1/StableMatchingBruteforce.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "C",
"bytes": "23383"
},
{
"name": "C++",
"bytes": "54557"
},
{
"name": "CSS",
"bytes": "3077"
},
{
"name": "HTML",
"bytes": "30700"
},
{
"name": "Java",
"bytes": "222494"
},
{
"name": "JavaScript",
"bytes": "538"
},
{
"name": "Makefile",
"bytes": "2413"
},
{
"name": "PHP",
"bytes": "80440"
},
{
"name": "Shell",
"bytes": "2194"
}
],
"symlink_target": ""
}
|
<dom-module id="x-child">
<template>
<div id="simple">simple</div>
<div id="complex1" class="scoped">complex1</div>
<div id="complex2" selected>complex2</div>
<div id="media">media</div>
<div id="shadow" class="shadowTarget">shadowTarget</div>
<div id="deep" class="deepTarget">deepTarget</div>
</template>
</dom-module>
<script>
Polymer({
is: 'x-child',
hostAttributes: {
class: 'nug'
}
});
</script>
<dom-module id="x-child2">
<style>
:host(.wide) #target{
border: none;
}
</style>
<template>
<div id="target">x-child2</div>
</template>
</dom-module>
<script>
Polymer({
is: 'x-child2',
_scopeCssViaAttr: true
});
</script>
<dom-module id="x-styled">
<style>
:host {
display: block;
border: 1px solid orange;
}
:host(.wide) {
border-width: 2px;
}
#simple {
border: 3px solid orange;
}
.scoped, [selected] {
border: 4px solid pink;
}
@media(max-width: 10000px) {
.media {
border: 5px solid brown;
}
}
.container ::content > * {
border: 6px solid navy;
}
x-child::shadow .shadowTarget {
border: 7px solid tomato;
}
x-child /deep/ .deepTarget {
border: 8px solid red;
}
#priority {
border: 9px solid orange;
}
x-child2.wide::shadow #target {
border: 12px solid brown;
}
.container1 > ::content > .content1 {
border: 13px solid navy;
}
.container2 > ::content .content2 {
border: 14px solid navy;
}
.computed {
border: 15px solid orange;
}
.computeda {
border: 20px solid orange;
}
#child {
border: 16px solid tomato;
display: block;
}
svg {
margin-top: 20px;
}
#circle {
fill: seagreen;
stroke-width: 1px;
stroke: tomato;
}
</style>
<template>
<content select=".blank"></content>
<div id="simple">simple</div>
<div id="complex1" class="scoped">complex1</div>
<div id="complex2" selected>complex2</div>
<div id="media" class="media">media</div>
<div class="container1">
<content select=".content1"></content>
</div>
<div class="container2">
<content select=".content2"></content>
</div>
<div class="container">
<content></content>
</div>
<x-child id="child"></x-child>
<div id="priority">priority</div>
<x-child2 class="wide" id="child2"></x-child2>
<div id="computed" class$="{{computeClass(aClass)}}">Computed</div>
<div id="repeatContainer">
<template id="repeat" is="dom-repeat" items="{{items}}">
<a class$="{{aaClass}}">A Computed</a>
</template>
</div>
<svg height="25" width="25">
<circle id="circle" cx="12" cy="12" r="10"></circle>
</svg>
</template>
</dom-module>
<script>
Polymer({
is: 'x-styled',
properties: {
items: {value: [{}]}
},
computeClass: function(className) {
return className;
}
});
</script>
<dom-module id="x-button">
<style>
:host {
border: 10px solid beige;
}
:host(.special) {
border: 11px solid beige;
}
</style>
<template>
Button!
</template>
</dom-module>
<script>
Polymer({
is: 'x-button',
extends: 'button'
});
</script>
<template id="dynamic">
<div class="added">
Added
<div class="sub-added">
Sub-added
</div>
</div>
</div>
</template>
<dom-module id="x-dynamic-scope">
<style>
.added {
border: 17px solid beige;
}
.sub-added {
border: 18px solid #fafafa;
}
</style>
<template>
<div id="container"></div>
</template>
</dom-module>
<script>
(function() {
var doc = document._currentScript.ownerDocument;
var dynamic = doc.querySelector('template#dynamic');
Polymer({
is: 'x-dynamic-scope',
ready: function() {
// setup node for scope watching
this.scopeSubtree(this.$.container, true);
// simulate 3rd party action by using normal dom to add to element.
var dom = document.importNode(dynamic.content, true);
this.$.container.appendChild(dom);
}
});
})();
</script>
|
{
"content_hash": "166e7db85bf9928427e795cd1e86ab1a",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 73,
"avg_line_length": 19.27853881278539,
"alnum_prop": 0.5611084793936523,
"repo_name": "degranda/Polymer-0.9",
"id": "d01bedfc926c1abd06931f06d78716caf38ca653",
"size": "4222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/styling-scoped-elements.html",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "433"
},
{
"name": "HTML",
"bytes": "744391"
},
{
"name": "JavaScript",
"bytes": "36999"
}
],
"symlink_target": ""
}
|
package shiver.me.timbers.http.mock.integration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import shiver.me.timbers.http.mock.HttpMockServer;
import shiver.me.timbers.http.mock.HttpMockTomcat7Server;
public class ITHttpNoMock extends AbstractHttpNoMock {
private static HttpMockServer http;
@BeforeClass
public static void setUp() {
http = new HttpMockTomcat7Server();
}
@AfterClass
public static void tearDown() {
http.stop();
}
@Override
protected HttpMockServer http() {
return http;
}
}
|
{
"content_hash": "708c145f5733e42e5bbc70df3a7b9e52",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 57,
"avg_line_length": 20.714285714285715,
"alnum_prop": 0.7051724137931035,
"repo_name": "shiver-me-timbers/smt-http-mock-parent",
"id": "a5dd2e10a2ce07d19f22b5267a4325b3708b35e4",
"size": "1175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "smt-http-mock-test/smt-http-mock-tomcat7-integration/src/test/java/shiver/me/timbers/http/mock/integration/ITHttpNoMock.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "287853"
}
],
"symlink_target": ""
}
|
namespace NPOI.OpenXmlFormats.Dml
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using NPOI.OpenXml4Net.Util;
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBulletColorFollowText
{
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBulletSizeFollowText
{
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBulletSizePercent
{
public static CT_TextBulletSizePercent Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_TextBulletSizePercent ctObj = new CT_TextBulletSizePercent();
ctObj.val = XmlHelper.ReadInt(node.Attributes["val"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "val", this.val);
sw.Write(">");
sw.Write(string.Format("</a:{0}>", nodeName));
}
private int valField;
private bool valFieldSpecified;
[XmlAttribute]
public int val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
[XmlIgnore]
public bool valSpecified
{
get
{
return this.valFieldSpecified;
}
set
{
this.valFieldSpecified = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBulletSizePoint
{
public static CT_TextBulletSizePoint Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_TextBulletSizePoint ctObj = new CT_TextBulletSizePoint();
ctObj.val = XmlHelper.ReadInt(node.Attributes["val"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "val", this.val);
sw.Write(">");
sw.Write(string.Format("</a:{0}>", nodeName));
}
private int valField;
private bool valFieldSpecified;
[XmlAttribute]
public int val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
[XmlIgnore]
public bool valSpecified
{
get
{
return this.valFieldSpecified;
}
set
{
this.valFieldSpecified = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBulletTypefaceFollowText
{
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextAutonumberBullet
{
public static CT_TextAutonumberBullet Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_TextAutonumberBullet ctObj = new CT_TextAutonumberBullet();
if (node.Attributes["type"] != null)
ctObj.type = (ST_TextAutonumberScheme)Enum.Parse(typeof(ST_TextAutonumberScheme), node.Attributes["type"].Value);
ctObj.startAt = XmlHelper.ReadInt(node.Attributes["startAt"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "type", this.type.ToString());
XmlHelper.WriteAttribute(sw, "startAt", this.startAt);
sw.Write(">");
sw.Write(string.Format("</a:{0}>", nodeName));
}
private ST_TextAutonumberScheme typeField;
private int startAtField;
public CT_TextAutonumberBullet()
{
this.startAtField = 1;
}
[XmlAttribute]
public ST_TextAutonumberScheme type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
[XmlAttribute]
[DefaultValue(1)]
public int startAt
{
get
{
return this.startAtField;
}
set
{
this.startAtField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
public enum ST_TextAutonumberScheme
{
/// <remarks/>
alphaLcParenBoth,
/// <remarks/>
alphaUcParenBoth,
/// <remarks/>
alphaLcParenR,
/// <remarks/>
alphaUcParenR,
/// <remarks/>
alphaLcPeriod,
/// <remarks/>
alphaUcPeriod,
/// <remarks/>
arabicParenBoth,
/// <remarks/>
arabicParenR,
/// <remarks/>
arabicPeriod,
/// <remarks/>
arabicPlain,
/// <remarks/>
romanLcParenBoth,
/// <remarks/>
romanUcParenBoth,
/// <remarks/>
romanLcParenR,
/// <remarks/>
romanUcParenR,
/// <remarks/>
romanLcPeriod,
/// <remarks/>
romanUcPeriod,
/// <remarks/>
circleNumDbPlain,
/// <remarks/>
circleNumWdBlackPlain,
/// <remarks/>
circleNumWdWhitePlain,
/// <remarks/>
arabicDbPeriod,
/// <remarks/>
arabicDbPlain,
/// <remarks/>
ea1ChsPeriod,
/// <remarks/>
ea1ChsPlain,
/// <remarks/>
ea1ChtPeriod,
/// <remarks/>
ea1ChtPlain,
/// <remarks/>
ea1JpnChsDbPeriod,
/// <remarks/>
ea1JpnKorPlain,
/// <remarks/>
ea1JpnKorPeriod,
/// <remarks/>
arabic1Minus,
/// <remarks/>
arabic2Minus,
/// <remarks/>
hebrew2Minus,
/// <remarks/>
thaiAlphaPeriod,
/// <remarks/>
thaiAlphaParenR,
/// <remarks/>
thaiAlphaParenBoth,
/// <remarks/>
thaiNumPeriod,
/// <remarks/>
thaiNumParenR,
/// <remarks/>
thaiNumParenBoth,
/// <remarks/>
hindiAlphaPeriod,
/// <remarks/>
hindiNumPeriod,
/// <remarks/>
hindiNumParenR,
/// <remarks/>
hindiAlpha1Period,
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextCharBullet
{
public static CT_TextCharBullet Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if(node==null)
return null;
CT_TextCharBullet ctObj = new CT_TextCharBullet();
ctObj.@char = XmlHelper.ReadString(node.Attributes["char"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
XmlHelper.WriteAttribute(sw, "char", this.@char);
sw.Write(">");
sw.Write(string.Format("</a:{0}>", nodeName));
}
private string charField;
[XmlAttribute]
public string @char
{
get
{
return this.charField;
}
set
{
this.charField = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextBlipBullet
{
public static CT_TextBlipBullet Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_TextBlipBullet ctObj = new CT_TextBlipBullet();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "blip")
ctObj.blip = CT_Blip.Parse(childNode, namespaceManager);
}
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<a:{0}", nodeName));
sw.Write(">");
if (this.blip != null)
this.blip.Write(sw, "blip");
sw.Write(string.Format("</a:{0}>", nodeName));
}
private CT_Blip blipField;
public CT_TextBlipBullet()
{
this.blipField = new CT_Blip();
}
[XmlElement(Order = 0)]
public CT_Blip blip
{
get
{
return this.blipField;
}
set
{
this.blipField = value;
}
}
}
[Serializable]
[DebuggerStepThrough]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)]
public class CT_TextNoBullet
{
}
}
|
{
"content_hash": "e0e76d373952b7959f219578371ff3bb",
"timestamp": "",
"source": "github",
"line_count": 462,
"max_line_length": 129,
"avg_line_length": 25.20995670995671,
"alnum_prop": 0.5451189147419937,
"repo_name": "JesseQin/npoi",
"id": "d45821eb17961773f6cc2161def68b36995ac4e2",
"size": "13238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ooxml/OpenXmlFormats/Drawing/TextBullet.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "991"
},
{
"name": "Batchfile",
"bytes": "1500"
},
{
"name": "C#",
"bytes": "20640428"
},
{
"name": "PowerShell",
"bytes": "96"
},
{
"name": "Smalltalk",
"bytes": "62554"
}
],
"symlink_target": ""
}
|
var Canvas = require('canvas')
, Image = Canvas.Image
, canvas
, ctx
, fs = require('fs')
, dao = require('./decisionDao');
var setCanvas = exports.setCanvas= function( width, height ){
canvas = new Canvas( width, height );
ctx = canvas.getContext('2d');
}
var getPngByFiles = exports.getPngByFiles = function( file1, file2, id, which, callback ){
canvas.width = canvas.width;
var img1 = getImageFromFoler(file1);
var iW = img1.width;
var iH = img1.height;
var img2 = getImageFromFoler(file2);
var gap = 50;
var startTop =70;
var startLeft =20;
var versusTxt = "vs";
ctx.font = '30px Impact';
ctx.save();
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.rotate(.1);
var te = ctx.measureText(versusTxt);
ctx.fillText(versusTxt, iW + gap , 100);
ctx.beginPath();
ctx.lineTo(iW +gap , 102);
ctx.lineTo(iW +gap + te.width, 102);
ctx.stroke();
ctx.restore();
ctx.fillText("A", startLeft , startTop -30);
ctx.fillText("B", startLeft + iW + gap*2 + te.width, startTop-30);
ctx.drawImage(img1, startLeft, startTop, img1.width, img1.height);
ctx.drawImage(img2, iW+ gap + te.width+startLeft, startTop, img2.width, img2.height);
if(parseInt(which) >0 ){
dao.updateDecision( id, which, function( decision ){
drawCount( decision["vote1"]||0, decision["vote2"]||0 );
callback(canvas.toBuffer());
})
}else{
console.log(which);
dao.getFilesById( id, function( decision ){
drawCount( decision["vote1"]||0, decision["vote2"]||0 );
callback(canvas.toBuffer());
} );
}
var drawCount = function( countA, countB ){
ctx.font ='70px Impact';
ctx.strokeStyle = 'rgba(0,128,255,0.5)';
ctx.fillText( countA +" likes", 50 + startLeft , startTop + 400 );
ctx.fillText( countB +" likes", 50 + iW+ gap + te.width+startLeft , startTop + 400 );
}
}
var getImageFromFoler = function( filename ){
var img = new Image;
img.src = fs.readFileSync(__dirname + '/upload/'+ filename);
return img;
}
|
{
"content_hash": "fd5fcae724bcffd0bc53f687c9cf34e3",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 90,
"avg_line_length": 29.484848484848484,
"alnum_prop": 0.656731757451182,
"repo_name": "ehrudxo/shma",
"id": "29ab5768a79e1d02d4ad75cbe5cd23e9ae59ea37",
"size": "1946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "renderImage.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2761"
},
{
"name": "JavaScript",
"bytes": "15626"
}
],
"symlink_target": ""
}
|
var express = require('express'),
bodyParser = require('body-parser');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/react/test', function(req, res) {
res.render('react/test', {title: 'React test'});
});
router.get('/api/comment/list', function(req, res) {
res.send([{
author: 'Peter Hunt',
text: 'This is one comment'
}, {
author: 'Jordan Walke',
text: 'This is another comment'
}]);
});
router.post('/api/comment/add', bodyParser.urlencoded({extended: false}), function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
|
{
"content_hash": "4913cc66a2d3cfa7e0503f7b334b83cb",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 94,
"avg_line_length": 23.5,
"alnum_prop": 0.625531914893617,
"repo_name": "meniac/todo-app",
"id": "c791c33a7c3532f34febf41936a4fdf7b6630514",
"size": "705",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "routes/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "110"
},
{
"name": "HTML",
"bytes": "640"
},
{
"name": "JavaScript",
"bytes": "5890"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
Index Fungorum
#### Published in
Ceské Houby 2: 382 (1920)
#### Original name
Inocybe picetorum Velen.
### Remarks
null
|
{
"content_hash": "963cbbf83f97dcd3aaabf19ae3890e2a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 25,
"avg_line_length": 11.538461538461538,
"alnum_prop": 0.7,
"repo_name": "mdoering/backbone",
"id": "de934c733082a5f9a5ec23c61fe1765ad4c71825",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Inocybaceae/Inocybe/Inocybe picetorum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
class EFCMenuScene < SKScene
def didMoveToView(view)
# super.didMoveToView(view)
super
self.setup
end
def setup
self.createWorld
# self.createHero
EFCTerrain.addNewNodeTo(self)
self.createStartButton
self.showHero
end
def createStartButton
location = CGPointMake(CGRectGetMidX(UIScreen.mainScreen.bounds),CGRectGetMidY(UIScreen.mainScreen.bounds))
@startButton = SKSpriteNode.spriteNodeWithImageNamed("start.png")
@startButton.position = location
self.addChild(@startButton)
end
def createWorld
backgroundTexture = SKTexture.textureWithImageNamed("Background5.png")
background = SKSpriteNode.spriteNodeWithTexture(backgroundTexture, size: UIScreen.mainScreen.bounds.size)
background.position = CGPointMake(CGRectGetMidX(UIScreen.mainScreen.bounds),CGRectGetMidY(UIScreen.mainScreen.bounds))
self.addChild(background)
self.scaleMode = SKSceneScaleModeAspectFit
end
def createHero
hero = EFCHero.createSpriteOn(self)
hero.position = CGPointMake(CGRectGetMidX(self.view.frame),CGRectGetMidY(self.view.frame))
end
def showHero
rudyTexture = SKTexture.textureWithImageNamed("CircleRudy.png")
rudy = SKSpriteNode.spriteNodeWithTexture(rudyTexture, size: CGSizeMake(100,100))
rudy.position = CGPointMake(CGRectGetMidX(UIScreen.mainScreen.bounds),CGRectGetMidY(UIScreen.mainScreen.bounds) + 150 )
self.addChild(rudy)
end
def touchesBegan(touches, withEvent: event)
touch = touches.anyObject
positionInScene = touch.locationInNode(self)
if CGRectContainsPoint(@startButton.frame, positionInScene)
reveal = SKTransition.fadeWithDuration(0.5)
newScene = EFCGameScene.alloc.initWithSize(UIScreen.mainScreen.bounds.size)
self.scene.view.presentScene(newScene, transition: reveal)
end
end
end
|
{
"content_hash": "3f4f171aa11ba483b776a27c2779c3df",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 121,
"avg_line_length": 33.264150943396224,
"alnum_prop": 0.8020419739081112,
"repo_name": "ztnark/RubyMotionFlappyBirdClone",
"id": "bd4aae0b86d8f5c25432fbfb84d390b3747fd3ec",
"size": "1763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/efc_menu_scene.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12687"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<SAXEvents>
<startDocument/>
<startElement>
<namespaceURI/>
<localName>tokenizer</localName>
<qualifiedName>tokenizer</qualifiedName>
<attributes>
<attribute>
<namespaceURI/>
<localName>UniqueName</localName>
<qualifiedName>UniqueName</qualifiedName>
<value>AC1999</value>
<type>ID</type>
<isDeclared>true</isDeclared>
<isSpecified>true</isSpecified>
</attribute>
</attributes>
</startElement>
<characters>
</characters>
<characters>T</characters>
<characters>h</characters>
<characters>i</characters>
<characters>s</characters>
<characters> </characters>
<characters>i</characters>
<characters>s</characters>
<characters> </characters>
<characters>a</characters>
<characters> </characters>
<characters>p</characters>
<characters>o</characters>
<characters>s</characters>
<characters>i</characters>
<characters>t</characters>
<characters>i</characters>
<characters>v</characters>
<characters>e</characters>
<characters> </characters>
<characters>t</characters>
<characters>e</characters>
<characters>s</characters>
<characters>t</characters>
<characters> </characters>
<characters>f</characters>
<characters>o</characters>
<characters>r</characters>
<characters> </characters>
<characters>v</characters>
<characters>a</characters>
<characters>l</characters>
<characters>i</characters>
<characters>d</characters>
<characters>i</characters>
<characters>t</characters>
<characters>y</characters>
<characters> </characters>
<characters>c</characters>
<characters>o</characters>
<characters>n</characters>
<characters>s</characters>
<characters>t</characters>
<characters>r</characters>
<characters>a</characters>
<characters>i</characters>
<characters>n</characters>
<characters>t</characters>
<characters>s</characters>
<characters>
</characters>
<characters>G</characters>
<characters>i</characters>
<characters>v</characters>
<characters>i</characters>
<characters>n</characters>
<characters>g</characters>
<characters> </characters>
<characters>I</characters>
<characters>D</characters>
<characters> </characters>
<characters>a</characters>
<characters>t</characters>
<characters>t</characters>
<characters>r</characters>
<characters>i</characters>
<characters>b</characters>
<characters>u</characters>
<characters>t</characters>
<characters>e</characters>
<characters> </characters>
<characters>d</characters>
<characters>e</characters>
<characters>f</characters>
<characters>a</characters>
<characters>u</characters>
<characters>l</characters>
<characters>t</characters>
<characters> </characters>
<characters>a</characters>
<characters>s</characters>
<characters> </characters>
<characters>#</characters>
<characters>I</characters>
<characters>M</characters>
<characters>P</characters>
<characters>L</characters>
<characters>I</characters>
<characters>E</characters>
<characters>D</characters>
<characters>
</characters>
<endElement>
<namespaceURI/>
<localName>tokenizer</localName>
<qualifiedName>tokenizer</qualifiedName>
</endElement>
<endDocument/>
</SAXEvents>
|
{
"content_hash": "3e5e9cf4296d752e30e7e81c0f5f72f0",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 49,
"avg_line_length": 29.06896551724138,
"alnum_prop": 0.701067615658363,
"repo_name": "reznikmm/matreshka",
"id": "046651c8052847c406b3f99deea6cc18421afb63",
"size": "3372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testsuite/xml/xmlconf-expected-sax/ibm/valid/P56/ibm56v03.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "77822094"
},
{
"name": "C",
"bytes": "50705"
},
{
"name": "CSS",
"bytes": "2253"
},
{
"name": "HTML",
"bytes": "780653"
},
{
"name": "JavaScript",
"bytes": "24113"
},
{
"name": "Lex",
"bytes": "117165"
},
{
"name": "Makefile",
"bytes": "27341"
},
{
"name": "Perl",
"bytes": "4796"
},
{
"name": "Python",
"bytes": "10482"
},
{
"name": "Roff",
"bytes": "13069"
},
{
"name": "Shell",
"bytes": "3034"
},
{
"name": "TeX",
"bytes": "116491"
},
{
"name": "XSLT",
"bytes": "6108"
},
{
"name": "Yacc",
"bytes": "96865"
}
],
"symlink_target": ""
}
|
/**
* Event.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
id: {
type: 'string',
primaryKey: true,
required: true
},
title: {
type: 'string',
required: true
},
dateStart: {
type: 'datetime',
required: true
},
cron: {
type: 'json'
}
},
beforeCreate: function (values, cb) {
// Création de la CRON qui va appeler Milight
ParseEvent(values.title, function (hue, options) {
cb();
});
},
beforeUpdate: function (values, cb) {
// Arrêt de la CRON et recréation de celle-ci
var cronJob = values.cron;
cronJob.stop();
ParseEvent(values.title, function (hue, options) {
CronService.addCron(values.dateStart, hue, options, function (cronJob) {
values.cron = cronJob;
cb();
});
});
},
afterDestroy: function (record, cb) {
// Arrêt de la CRON
var cronJob = record.cron;
cronJob.stop();
}
};
|
{
"content_hash": "bc7eff131a64c09a514701b5580c22e6",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 109,
"avg_line_length": 19.576271186440678,
"alnum_prop": 0.5757575757575758,
"repo_name": "RaspPiXelnet/Millight",
"id": "af6bb982c7f840f463529d8b2e7029f23717ddbf",
"size": "1159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/api/models/Event.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1758"
},
{
"name": "HTML",
"bytes": "90255"
},
{
"name": "JavaScript",
"bytes": "294434"
}
],
"symlink_target": ""
}
|
using System;
using System.IO;
namespace AttachR.VisualStudio
{
public class AvailableVisualStudioInstall : IEquatable<AvailableVisualStudioInstall>
{
public Version Version { get; }
public FileInfo Executable { get; }
public AvailableVisualStudioInstall(Version version, FileInfo executable)
{
Version = version;
Executable = executable;
}
public bool Equals(AvailableVisualStudioInstall other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(Version, other.Version) && Equals(Executable, other.Executable);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((AvailableVisualStudioInstall) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Version?.GetHashCode() ?? 0)*397) ^ (Executable?.GetHashCode() ?? 0);
}
}
public static bool operator ==(AvailableVisualStudioInstall left, AvailableVisualStudioInstall right)
{
return Equals(left, right);
}
public static bool operator !=(AvailableVisualStudioInstall left, AvailableVisualStudioInstall right)
{
return !Equals(left, right);
}
}
}
|
{
"content_hash": "382a99469bf1046d865db0a800646671",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 109,
"avg_line_length": 31.44,
"alnum_prop": 0.601145038167939,
"repo_name": "julienadam/AttachR",
"id": "e6e062b82169c3d8f997633ef898410d4abb0e39",
"size": "1572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AttachR/VisualStudio/AvailableVisualStudioInstall.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "483"
},
{
"name": "C#",
"bytes": "104506"
}
],
"symlink_target": ""
}
|
package com.idp.web.system.service;
import java.util.List;
import com.idp.common.persistence.Page;
import com.idp.web.system.entity.SysUser;
public interface SysUserService {
public SysUser findByUsername(SysUser user);
public Page<SysUser> findByPage(SysUser user,Page<SysUser> page);
public SysUser getById(Long id);
public void add(SysUser user);
public void update(SysUser user);
public void delete(Long id);
/**
* 查询用户的所有角色
* @param userId
* @return
*/
public List<Long> findByUserId(Long userId);
/**
* 获取用户所有有权限的菜单id
* @param userId
* @return
*/
public List<Long> findMenuIdByUserId(Long userId);
}
|
{
"content_hash": "9eefc3f74161744bd8082805f956b219",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 66,
"avg_line_length": 18.571428571428573,
"alnum_prop": 0.72,
"repo_name": "jiangyuanlin/hello",
"id": "08882493838fbaa6e87674df4facda909ef5a7a2",
"size": "692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/idp/web/system/service/SysUserService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1395119"
},
{
"name": "FreeMarker",
"bytes": "16593"
},
{
"name": "Java",
"bytes": "623817"
},
{
"name": "JavaScript",
"bytes": "684607"
}
],
"symlink_target": ""
}
|
namespace MassTransit.Monitoring
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Reflection;
using System.Text;
using Metadata;
public static class Instrumentation
{
static readonly ConcurrentDictionary<string, string> _labelCache = new ConcurrentDictionary<string, string>();
static bool _isConfigured;
static string _serviceName;
static Counter<long> _receiveTotal;
static Counter<long> _receiveFaultTotal;
static Counter<long> _receiveInProgress;
static Histogram<double> _receiveDuration;
static Counter<long> _consumeTotal;
static Counter<long> _consumeFaultTotal;
static Counter<long> _consumeRetryTotal;
static Counter<long> _publishTotal;
static Counter<long> _publishFaultTotal;
static Counter<long> _sendTotal;
static Counter<long> _sendFaultTotal;
static Counter<long> _executeTotal;
static Counter<long> _executeFaultTotal;
static Counter<long> _compensateTotal;
static Counter<long> _compensateFailureTotal;
static Counter<long> _consumerInProgress;
static Counter<long> _handlerInProgress;
static Counter<long> _sagaInProgress;
static Counter<long> _executeInProgress;
static Counter<long> _compensateInProgress;
static Histogram<double> _consumeDuration;
static Histogram<double> _deliveryDuration;
static Histogram<double> _executeDuration;
static Histogram<double> _compensateDuration;
static readonly char[] _delimiters = { '<', '>' };
static Meter _meter;
static InstrumentationOptions _options;
public static void MeasureReceived(ReceiveContext context, Exception exception = default)
{
if (!_receiveTotal.Enabled)
return;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.EndpointLabel, GetEndpointLabel(context.InputAddress) },
};
_receiveTotal.Add(1, tagList);
_receiveDuration.Record(context.ElapsedTime.TotalMilliseconds, tagList);
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_receiveFaultTotal.Add(1, tagList);
}
}
public static void MeasureConsume<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType, Exception exception = default)
where T : class
{
if (!_consumeTotal.Enabled)
return;
var messageTypeLabel = GetMessageTypeLabel<T>();
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, messageTypeLabel },
{ _options.ConsumerTypeLabel, GetConsumerTypeLabel(consumerType, TypeCache<T>.ShortName, messageTypeLabel) }
};
_consumeTotal.Add(1, tagList);
_consumeDuration.Record(duration.TotalMilliseconds, tagList);
var retryAttempt = context.GetRetryAttempt();
if (retryAttempt > 0)
_consumeRetryTotal.Add(1, tagList);
if (context.SentTime.HasValue)
{
var deliveryDuration = DateTime.UtcNow - context.SentTime.Value;
if (deliveryDuration < TimeSpan.Zero)
deliveryDuration = TimeSpan.Zero;
_deliveryDuration.Record(deliveryDuration.TotalMilliseconds, tagList);
}
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_consumeFaultTotal.Add(1, tagList);
}
}
public static void MeasureExecute<TActivity, TArguments>(ExecuteActivityContext<TActivity, TArguments> context, Exception exception = default)
where TActivity : class, IExecuteActivity<TArguments>
where TArguments : class
{
if (!_executeTotal.Enabled)
return;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.ActivityNameLabel, context.ActivityName },
{ _options.ArgumentTypeLabel, GetArgumentTypeLabel<TArguments>() }
};
_executeTotal.Add(1, tagList);
_executeDuration.Record(context.Elapsed.TotalMilliseconds, tagList);
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_executeFaultTotal.Add(1, tagList);
}
}
public static void MeasureCompensate<TActivity, TLog>(CompensateActivityContext<TActivity, TLog> context, Exception exception = default)
where TActivity : class, ICompensateActivity<TLog>
where TLog : class
{
if (!_compensateTotal.Enabled)
return;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.ActivityNameLabel, context.ActivityName },
{ _options.LogTypeLabel, GetLogTypeLabel<TLog>() }
};
_compensateTotal.Add(1, tagList);
_compensateDuration.Record(context.Elapsed.TotalMilliseconds, tagList);
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_compensateFailureTotal.Add(1, tagList);
}
}
public static void MeasurePublish<T>(Exception exception = default)
where T : class
{
if (!_publishTotal.Enabled)
return;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, GetMessageTypeLabel<T>() },
};
_publishTotal.Add(1, tagList);
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_publishFaultTotal.Add(1, tagList);
}
}
public static void MeasureSend<T>(Exception exception = default)
where T : class
{
if (!_sendTotal.Enabled)
return;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, GetMessageTypeLabel<T>() },
};
_sendTotal.Add(1, tagList);
if (exception != null)
{
tagList.Add(_options.ExceptionTypeLabel, exception.GetType().Name);
_sendFaultTotal.Add(1, tagList);
}
}
public static IDisposable TrackReceiveInProgress(ReceiveContext context)
{
if (!_receiveTotal.Enabled)
return null;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.EndpointLabel, GetEndpointLabel(context.InputAddress) },
};
return TrackInProgress(_receiveInProgress, tagList);
}
public static IDisposable TrackConsumerInProgress<TConsumer, TMessage>()
where TConsumer : class
where TMessage : class
{
if (!_consumeTotal.Enabled)
return null;
var messageTypeLabel = GetMessageTypeLabel<TMessage>();
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, messageTypeLabel },
{ _options.ConsumerTypeLabel, GetConsumerTypeLabel(TypeCache<TConsumer>.ShortName, TypeCache<TMessage>.ShortName, messageTypeLabel) }
};
return TrackInProgress(_consumerInProgress, tagList);
}
public static IDisposable TrackSagaInProgress<TSaga, TMessage>()
where TSaga : class, ISaga
where TMessage : class
{
if (!_sagaInProgress.Enabled)
return null;
var messageTypeLabel = GetMessageTypeLabel<TMessage>();
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, messageTypeLabel },
{ _options.ConsumerTypeLabel, GetConsumerTypeLabel(TypeCache<TSaga>.ShortName, TypeCache<TMessage>.ShortName, messageTypeLabel) }
};
return TrackInProgress(_sagaInProgress, tagList);
}
public static IDisposable TrackExecuteActivityInProgress<TActivity, TArguments>(ExecuteActivityContext<TActivity, TArguments> context)
where TActivity : class, IExecuteActivity<TArguments>
where TArguments : class
{
if (!_executeTotal.Enabled)
return null;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.ActivityNameLabel, context.ActivityName },
{ _options.ArgumentTypeLabel, GetArgumentTypeLabel<TArguments>() }
};
return TrackInProgress(_executeInProgress, tagList);
}
public static IDisposable TrackCompensateActivityInProgress<TActivity, TLog>(CompensateActivityContext<TActivity, TLog> context)
where TActivity : class, ICompensateActivity<TLog>
where TLog : class
{
if (!_compensateTotal.Enabled)
return null;
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.ActivityNameLabel, context.ActivityName },
{ _options.LogTypeLabel, GetLogTypeLabel<TLog>() }
};
return TrackInProgress(_compensateInProgress, tagList);
}
public static IDisposable TrackHandlerInProgress<TMessage>()
where TMessage : class
{
var tagList = new TagList
{
{ _options.ServiceNameLabel, _serviceName },
{ _options.MessageTypeLabel, GetMessageTypeLabel<TMessage>() },
};
return TrackInProgress(_handlerInProgress, tagList);
}
static IDisposable TrackInProgress(Counter<long> counter, TagList tagList)
{
counter.Add(1, tagList);
return new InProgressTracker(counter, tagList);
}
public static void TryConfigure(string serviceName, InstrumentationOptions options)
{
if (_isConfigured)
return;
_meter = new Meter("MassTransit", HostMetadataCache.Host.MassTransitVersion);
_serviceName = serviceName;
_options = options;
// Counters
_receiveTotal = _meter.CreateCounter<long>(options.ReceiveTotal, "ea", "Number of messages received");
_receiveFaultTotal = _meter.CreateCounter<long>(options.ReceiveFaultTotal, "ea", "Number of messages receive faults");
_consumeTotal = _meter.CreateCounter<long>(options.ConsumeTotal, "ea", "Number of messages consumed");
_consumeFaultTotal = _meter.CreateCounter<long>(options.ConsumeFaultTotal, "ea", "Number of message consume faults");
_consumeRetryTotal = _meter.CreateCounter<long>(options.ConsumeRetryTotal, "ea", "Number of message consume faults");
_publishTotal = _meter.CreateCounter<long>(options.PublishTotal, "ea", "Number of messages published");
_publishFaultTotal = _meter.CreateCounter<long>(options.PublishFaultTotal, "ea", "Number of message publish faults");
_sendTotal = _meter.CreateCounter<long>(options.SendTotal, "ea", "Number of messages sent");
_sendFaultTotal = _meter.CreateCounter<long>(options.SendFaultTotal, "ea", "Number of message send faults");
_executeTotal = _meter.CreateCounter<long>(options.ActivityExecuteTotal, "ea", "Number of activities executed");
_executeFaultTotal = _meter.CreateCounter<long>(options.ActivityExecuteFaultTotal, "ea", "Number of activity execution faults");
_compensateTotal = _meter.CreateCounter<long>(options.ActivityCompensateTotal, "ea", "Number of activities compensated");
_compensateFailureTotal = _meter.CreateCounter<long>(options.ActivityCompensateFailureTotal, "ea", "Number of activity compensation failures");
// Gauges
_receiveInProgress = _meter.CreateCounter<long>(options.ReceiveInProgress, "ea", "Number of messages being received");
_handlerInProgress = _meter.CreateCounter<long>(options.HandlerInProgress, "ea", "Number of handlers in progress");
_consumerInProgress = _meter.CreateCounter<long>(options.ConsumerInProgress, "ea", "Number of consumers in progress");
_sagaInProgress = _meter.CreateCounter<long>(options.SagaInProgress, "ea", "Number of sagas in progress");
_executeInProgress = _meter.CreateCounter<long>(options.ExecuteInProgress, "ea", "Number of activity executions in progress");
_compensateInProgress = _meter.CreateCounter<long>(options.CompensateInProgress, "ea", "Number of activity compensations in progress");
// Histograms
_receiveDuration = _meter.CreateHistogram<double>(options.ReceiveDuration, "ms", "Elapsed time spent receiving a message, in seconds");
_consumeDuration = _meter.CreateHistogram<double>(options.ConsumeDuration, "ms", "Elapsed time spent consuming a message, in seconds");
_deliveryDuration = _meter.CreateHistogram<double>(options.DeliveryDuration, "ms",
"Elapsed time between when the message was sent and when it was consumed, in seconds.");
_executeDuration = _meter.CreateHistogram<double>(options.ActivityExecuteDuration, "ms", "Elapsed time spent executing an activity, in seconds");
_compensateDuration = _meter.CreateHistogram<double>(options.ActivityCompensateDuration, "ms",
"Elapsed time spent compensating an activity, in seconds");
_isConfigured = true;
}
static string GetConsumerTypeLabel(string consumerType, string messageType, string messageLabel)
{
return _labelCache.GetOrAdd(consumerType, type =>
{
if (type.StartsWith("MassTransit.MessageHandler<"))
return "Handler";
var genericMessageType = "<" + messageType + ">";
if (type.IndexOf(genericMessageType, StringComparison.Ordinal) >= 0)
type = type.Replace(genericMessageType, "_" + messageLabel);
return CleanupLabel(type);
});
}
static string CleanupLabel(string label)
{
string SimpleClean(string text)
{
return text.Split('.', '+').Last();
}
var indexOf = label.IndexOfAny(_delimiters);
if (indexOf >= 0)
{
if (label[indexOf] == '<')
return SimpleClean(label.Substring(0, indexOf)) + "_" + CleanupLabel(label.Substring(indexOf + 1));
if (label[indexOf] == '>')
return SimpleClean(label.Substring(0, indexOf)) + CleanupLabel(label.Substring(indexOf + 1));
return SimpleClean(label);
}
return SimpleClean(label);
}
static string GetArgumentTypeLabel<TArguments>()
{
return _labelCache.GetOrAdd(TypeCache<TArguments>.ShortName, type => FormatTypeName(new StringBuilder(), typeof(TArguments))
.Replace("Arguments", ""));
}
static string GetLogTypeLabel<TLog>()
{
return _labelCache.GetOrAdd(TypeCache<TLog>.ShortName, type => FormatTypeName(new StringBuilder(), typeof(TLog)).Replace("Log", ""));
}
static string GetEndpointLabel(Uri inputAddress)
{
return inputAddress?.AbsolutePath.Split('/').LastOrDefault()?.Replace(".", "_").Replace("/", "_");
}
static string GetMessageTypeLabel<TMessage>()
{
return _labelCache.GetOrAdd(TypeCache<TMessage>.ShortName, type => FormatTypeName(new StringBuilder(), typeof(TMessage)));
}
static string FormatTypeName(StringBuilder sb, Type type)
{
if (type.IsGenericParameter)
return "";
if (type.GetTypeInfo().IsGenericType)
{
var name = type.GetGenericTypeDefinition().Name;
//remove `1
var index = name.IndexOf('`');
if (index > 0)
name = name.Remove(index);
sb.Append(name);
sb.Append('_');
Type[] arguments = type.GetTypeInfo().GenericTypeArguments;
for (var i = 0; i < arguments.Length; i++)
{
if (i > 0)
sb.Append('_');
FormatTypeName(sb, arguments[i]);
}
}
else
sb.Append(type.Name);
return sb.ToString();
}
class InProgressTracker :
IDisposable
{
readonly Counter<long> _counter;
readonly TagList _tagList;
public InProgressTracker(Counter<long> counter, TagList tagList)
{
_counter = counter;
_tagList = tagList;
}
public void Dispose()
{
_counter.Add(-1, _tagList);
}
}
}
}
|
{
"content_hash": "c84b61f9ab4ffd57fa30147bf9f7bab7",
"timestamp": "",
"source": "github",
"line_count": 474,
"max_line_length": 157,
"avg_line_length": 38.4451476793249,
"alnum_prop": 0.5888163310102618,
"repo_name": "MassTransit/MassTransit",
"id": "359882ea7ccdbfdb0d9ded2f042df73e4ad22bbd",
"size": "18223",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "src/MassTransit/Monitoring/Instrumentation.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "12668130"
},
{
"name": "Dockerfile",
"bytes": "781"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Shell",
"bytes": "907"
},
{
"name": "Smalltalk",
"bytes": "4"
}
],
"symlink_target": ""
}
|
package org.apache.geode.cache30;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.*;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;
/**
* An abstract class whose test methods test the functionality of {@link CacheWriter}s that are
* invoked locally.
*
* @see MultiVMRegionTestCase#testRemoteCacheWriter
*
*
* @since GemFire 3.0
*/
public abstract class CacheWriterTestCase extends RegionAttributesTestCase {
public CacheWriterTestCase() {
super();
}
/////////////////////// Test Methods ///////////////////////
/**
* Tests that the <code>CacheWriter</code> is called before an entry is
* {@linkplain CacheWriter#beforeCreate created}.
*/
@Test
public void testCacheWriterBeforeCreate() throws CacheException {
String name = this.getUniqueName();
final Object key = this.getUniqueName();
final Object value = new Integer(42);
final Object arg = "ARG";
final String exception = "EXCEPTION";
TestCacheWriter writer = new TestCacheWriter() {
public void beforeCreate2(EntryEvent event) throws CacheWriterException {
assertEquals(key, event.getKey());
assertEquals(value, event.getNewValue());
assertNull(event.getOldValue());
assertTrue(event.getOperation().isCreate());
assertFalse(event.getOperation().isLoad());
assertFalse(event.getOperation().isLocalLoad());
assertFalse(event.getOperation().isNetLoad());
assertFalse(event.getOperation().isNetSearch());
Object argument = event.getCallbackArgument();
if (argument != null) {
if (argument.equals(exception)) {
String s = "Test CacheWriterException";
throw new CacheWriterException(s);
} else {
assertEquals(arg, argument);
}
}
}
public void beforeDestroy2(EntryEvent event) throws CacheWriterException {
// This method will get invoked when the region is populated
}
};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
Region region = createRegion(name, factory.create());
region.create(key, value);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.put(key, value);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.create(key, value, arg);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.put(key, value, arg);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
try {
region.create(key, value, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
}
try {
region.put(key, value, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
}
}
/**
* Tests that the <code>CacheWriter</code> is called before an entry is
* {@linkplain CacheWriter#beforeUpdate updated}.
*/
@Test
public void testCacheWriterBeforeUpdate() throws CacheException {
String name = this.getUniqueName();
final Object key = this.getUniqueName();
final Object oldValue = new Integer(42);
final Object newValue = new Integer(43);
final Object arg = "ARG";
final String exception = "EXCEPTION";
TestCacheWriter writer = new TestCacheWriter() {
public void beforeCreate2(EntryEvent event) throws CacheWriterException {
// This method will get invoked when the region is populated
}
public void beforeDestroy2(EntryEvent event) throws CacheWriterException {
// This method will get invoked when the region is populated
}
public void beforeUpdate2(EntryEvent event) throws CacheWriterException {
assertEquals(key, event.getKey());
assertEquals(newValue, event.getNewValue());
assertEquals(oldValue, event.getOldValue());
assertTrue(event.getOperation().isUpdate());
assertFalse(event.getOperation().isLoad());
assertFalse(event.getOperation().isLocalLoad());
assertFalse(event.getOperation().isNetLoad());
assertFalse(event.getOperation().isNetSearch());
Object argument = event.getCallbackArgument();
if (argument != null) {
if (argument.equals(exception)) {
String s = "Test CacheWriterException";
throw new CacheWriterException(s);
} else {
assertEquals(arg, argument);
}
}
}
};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
Region region = createRegion(name, factory.create());
region.create(key, oldValue);
assertTrue(writer.wasInvoked());
region.put(key, newValue);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.put(key, oldValue);
assertTrue(writer.wasInvoked());
region.put(key, newValue);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.create(key, oldValue);
assertTrue(writer.wasInvoked());
region.put(key, newValue, arg);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.put(key, oldValue);
assertTrue(writer.wasInvoked());
region.put(key, newValue, arg);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.create(key, oldValue);
assertTrue(writer.wasInvoked());
try {
region.put(key, newValue, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
}
region.destroy(key);
assertTrue(writer.wasInvoked());
region.create(key, oldValue);
assertTrue(writer.wasInvoked());
try {
region.put(key, newValue, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
}
}
/**
* Tests that the <code>CacheWriter</code> is called before an entry is
* {@linkplain CacheWriter#beforeDestroy destroyed}.
*/
@Test
public void testCacheWriterBeforeDestroy() throws CacheException {
String name = this.getUniqueName();
final Object key = this.getUniqueName();
final Object value = new Integer(42);
final Object arg = "ARG";
final String exception = "EXCEPTION";
TestCacheWriter writer = new TestCacheWriter() {
public void beforeCreate2(EntryEvent event) throws CacheWriterException {
// This method will get invoked when the region is populated
}
public void beforeDestroy2(EntryEvent event) throws CacheWriterException {
assertEquals(key, event.getKey());
assertEquals(value, event.getOldValue());
assertNull(event.getNewValue());
assertTrue(event.getOperation().isDestroy());
assertFalse(event.getOperation().isLoad());
assertFalse(event.getOperation().isLocalLoad());
assertFalse(event.getOperation().isNetLoad());
assertFalse(event.getOperation().isNetSearch());
Object argument = event.getCallbackArgument();
if (argument != null) {
if (argument.equals(exception)) {
String s = "Test CacheWriterException";
throw new CacheWriterException(s);
} else {
assertEquals(arg, argument);
}
}
}
};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
Region region = createRegion(name, factory.create());
region.create(key, value);
assertTrue(writer.wasInvoked());
region.destroy(key);
assertTrue(writer.wasInvoked());
region.create(key, value);
assertTrue(writer.wasInvoked());
region.destroy(key, arg);
assertTrue(writer.wasInvoked());
region.create(key, value);
assertTrue(writer.wasInvoked());
try {
region.destroy(key, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
}
}
/**
* Tests that the <code>CacheWriter</code> is called before a region is destroyed.
*
* @see CacheWriter#beforeRegionDestroy
* @see CacheWriter#close
*/
@Test
public void testCacheWriterBeforeRegionDestroy() throws CacheException {
final String name = this.getUniqueName();
final Object arg = "ARG";
final String exception = "EXCEPTION";
TestCacheWriter writer = new TestCacheWriter() {
private boolean closed = false;
private boolean destroyed = false;
public boolean wasInvoked() {
boolean value = closed && destroyed;
super.wasInvoked();
return value;
}
public void close2() {
this.closed = true;
}
public void beforeRegionDestroy2(RegionEvent event) throws CacheWriterException {
assertEquals(name, event.getRegion().getName());
// this should be a distributed destroy unless the region
// is local scope
assertTrue(event.getOperation().isRegionDestroy());
assertFalse(event.getOperation().isExpiration());
assertFalse(event.isOriginRemote());
Object argument = event.getCallbackArgument();
if (argument != null) {
if (argument.equals(exception)) {
String s = "Test CacheWriterException";
throw new CacheWriterException(s);
} else {
assertEquals(arg, argument);
}
}
this.destroyed = true;
}
};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
RegionAttributes attrs = factory.create();
Region region;
region = createRegion(name, attrs);
region.destroyRegion();
assertTrue(region.isDestroyed());
assertTrue(writer.wasInvoked());
region = createRegion(name, attrs);
region.destroyRegion(arg);
assertTrue(writer.wasInvoked());
assertTrue(region.isDestroyed());
try {
region = createRegion(name, attrs);
region.destroyRegion(exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
// pass...
assertTrue(writer.wasInvoked());
assertFalse(region.isDestroyed());
assertNull(region.getSubregion(name));
}
}
/**
* Tests that a <code>CacheWriter</code> is <I>not</I> invoked on a
* {@linkplain Region#localDestroyRegion local destroy}.
*/
@Test
public void testCacheWriterLocalDestroy() throws CacheException {
final String name = this.getUniqueName();
// If any of the writer's callback methods are invoked
TestCacheWriter writer = new TestCacheWriter() {};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
RegionAttributes attrs = factory.create();
Region region = createRegion(name, attrs);
region.localDestroyRegion();
}
/**
* Tests that a {@link CacheWriter} throwing a {@link CacheWriterException} aborts the operation.
*/
@Test
public void testCacheWriterExceptionAborts() throws CacheException {
final String name = this.getUniqueName();
final String exception = "EXCEPTION";
TestCacheWriter writer = new TestCacheWriter() {
private void handleEvent(Object argument) throws CacheWriterException {
if (exception.equals(argument)) {
String s = "Test Exception";
throw new CacheWriterException(s);
}
}
public void beforeCreate2(EntryEvent event) throws CacheWriterException {
handleEvent(event.getCallbackArgument());
}
public void beforeUpdate2(EntryEvent event) throws CacheWriterException {
handleEvent(event.getCallbackArgument());
}
public void beforeDestroy2(EntryEvent event) throws CacheWriterException {
handleEvent(event.getCallbackArgument());
}
public void beforeRegionDestroy2(RegionEvent event) throws CacheWriterException {
handleEvent(event.getCallbackArgument());
}
};
AttributesFactory factory = new AttributesFactory(getRegionAttributes());
factory.setCacheWriter(writer);
RegionAttributes attrs = factory.create();
Region region;
region = createRegion(name, attrs);
Object value = new Integer(42);
String p1 = "Test Exception";
getCache().getLogger().info("<ExpectedException action=add>" + p1 + "</ExpectedException>");
try {
region.put(name, value, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
assertNull(region.getEntry(name));
} finally {
getCache().getLogger()
.info("<ExpectedException action=remove>" + p1 + "</ExpectedException>");
}
region.put(name, value);
try {
region.put(name, "NEVER SEEN", exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
Region.Entry entry = region.getEntry(name);
assertNotNull(entry);
assertEquals(value, entry.getValue());
}
try {
region.destroy(name, exception);
fail("Should have thrown a CacheWriterException");
} catch (CacheWriterException ex) {
Region.Entry entry = region.getEntry(name);
assertNotNull(entry);
assertEquals(value, entry.getValue());
}
try {
region.destroyRegion(exception);
} catch (CacheWriterException ex) {
assertTrue(!region.isDestroyed());
assertNotNull(region.getParentRegion().getSubregion(name));
}
}
}
|
{
"content_hash": "a09c389364109c71cac66797178eb79e",
"timestamp": "",
"source": "github",
"line_count": 476,
"max_line_length": 99,
"avg_line_length": 30.241596638655462,
"alnum_prop": 0.6625217089267107,
"repo_name": "smanvi-pivotal/geode",
"id": "72a2f4a4635e7a6a56de9c229c08dd3d8d600d6e",
"size": "15184",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "geode-core/src/test/java/org/apache/geode/cache30/CacheWriterTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "106707"
},
{
"name": "Groovy",
"bytes": "2928"
},
{
"name": "HTML",
"bytes": "3998074"
},
{
"name": "Java",
"bytes": "26700079"
},
{
"name": "JavaScript",
"bytes": "1781013"
},
{
"name": "Ruby",
"bytes": "6751"
},
{
"name": "Shell",
"bytes": "21891"
}
],
"symlink_target": ""
}
|
namespace {
const char kPortForwardingTestPage[] = "/devtools/port_forwarding/main.html";
const int kDefaultDebuggingPort = 9223;
const int kAlternativeDebuggingPort = 9224;
}
class PortForwardingTest: public InProcessBrowserTest {
virtual int GetRemoteDebuggingPort() {
return kDefaultDebuggingPort;
}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitchASCII(
switches::kRemoteDebuggingPort,
base::NumberToString(GetRemoteDebuggingPort()));
}
protected:
class Listener : public DevToolsAndroidBridge::PortForwardingListener {
public:
explicit Listener(Profile* profile)
: profile_(profile),
skip_empty_devices_(true) {
DevToolsAndroidBridge::Factory::GetForProfile(profile_)->
AddPortForwardingListener(this);
}
~Listener() override {
DevToolsAndroidBridge::Factory::GetForProfile(profile_)->
RemovePortForwardingListener(this);
}
void PortStatusChanged(const ForwardingStatus& status) override {
if (status.empty() && skip_empty_devices_)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
void set_skip_empty_devices(bool skip_empty_devices) {
skip_empty_devices_ = skip_empty_devices;
}
private:
Profile* profile_;
bool skip_empty_devices_;
};
};
// Flaky on all platforms. https://crbug.com/477696
IN_PROC_BROWSER_TEST_F(PortForwardingTest,
DISABLED_LoadPageWithStyleAnsScript) {
Profile* profile = browser()->profile();
AndroidDeviceManager::DeviceProviders device_providers;
device_providers.push_back(
TCPDeviceProvider::CreateForLocalhost(kDefaultDebuggingPort));
DevToolsAndroidBridge::Factory::GetForProfile(profile)->
set_device_providers_for_test(device_providers);
ASSERT_TRUE(embedded_test_server()->Start());
GURL original_url = embedded_test_server()->GetURL(kPortForwardingTestPage);
std::string forwarding_port("8000");
GURL forwarding_url(original_url.scheme() + "://" +
original_url.host() + ":" + forwarding_port + original_url.path());
PrefService* prefs = profile->GetPrefs();
prefs->SetBoolean(prefs::kDevToolsPortForwardingEnabled, true);
base::DictionaryValue config;
config.SetStringKey(forwarding_port,
original_url.host() + ":" + original_url.port());
prefs->Set(prefs::kDevToolsPortForwardingConfig, config);
Listener wait_for_port_forwarding(profile);
content::RunMessageLoop();
RemoteDebuggingServer::EnableTetheringForDebug();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), forwarding_url));
content::WebContents* wc = browser()->tab_strip_model()->GetWebContentsAt(0);
std::string result;
ASSERT_TRUE(content::ExecuteScriptAndExtractString(
wc, "window.domAutomationController.send(document.title)", &result));
ASSERT_EQ("Port forwarding test", result) << "Document has not loaded.";
ASSERT_TRUE(content::ExecuteScriptAndExtractString(
wc, "window.domAutomationController.send(getBodyTextContent())",
&result));
ASSERT_EQ("content", result) << "Javascript has not loaded.";
ASSERT_TRUE(content::ExecuteScriptAndExtractString(
wc, "window.domAutomationController.send(getBodyMarginLeft())", &result));
ASSERT_EQ("100px", result) << "CSS has not loaded.";
// Test that disabling port forwarding is handled normally.
wait_for_port_forwarding.set_skip_empty_devices(false);
prefs->SetBoolean(prefs::kDevToolsPortForwardingEnabled, false);
content::RunMessageLoop();
}
class PortForwardingDisconnectTest : public PortForwardingTest {
int GetRemoteDebuggingPort() override {
return kAlternativeDebuggingPort;
}
};
IN_PROC_BROWSER_TEST_F(PortForwardingDisconnectTest, DisconnectOnRelease) {
Profile* profile = browser()->profile();
AndroidDeviceManager::DeviceProviders device_providers;
scoped_refptr<TCPDeviceProvider> self_provider(
TCPDeviceProvider::CreateForLocalhost(kAlternativeDebuggingPort));
device_providers.push_back(self_provider);
DevToolsAndroidBridge::Factory::GetForProfile(profile)->
set_device_providers_for_test(device_providers);
ASSERT_TRUE(embedded_test_server()->Start());
GURL original_url = embedded_test_server()->GetURL(kPortForwardingTestPage);
std::string forwarding_port("8000");
GURL forwarding_url(original_url.scheme() + "://" +
original_url.host() + ":" + forwarding_port + original_url.path());
PrefService* prefs = profile->GetPrefs();
prefs->SetBoolean(prefs::kDevToolsPortForwardingEnabled, true);
base::DictionaryValue config;
config.SetStringKey(forwarding_port,
original_url.host() + ":" + original_url.port());
prefs->Set(prefs::kDevToolsPortForwardingConfig, config);
std::unique_ptr<Listener> wait_for_port_forwarding(new Listener(profile));
content::RunMessageLoop();
base::RunLoop run_loop;
self_provider->set_release_callback_for_test(base::BindOnce(
base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask),
base::ThreadTaskRunnerHandle::Get(), FROM_HERE,
run_loop.QuitWhenIdleClosure()));
wait_for_port_forwarding.reset();
content::RunThisRunLoop(&run_loop);
}
|
{
"content_hash": "0e13f76a36db348cfc0274f98f236d0b",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 80,
"avg_line_length": 34.76470588235294,
"alnum_prop": 0.7221282195901485,
"repo_name": "scheib/chromium",
"id": "dd6db2069a478efc4f8b4b2844446b9cd4f35f31",
"size": "6602",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "chrome/browser/devtools/device/port_forwarding_browsertest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
#include <math.h>
#include <math_private.h>
long double
__ieee754_exp10l (long double arg)
{
/* This is a very stupid and inprecise implementation. It'll get
replaced sometime (soon?). */
return __ieee754_expl (M_LN10l * arg);
}
strong_alias (__ieee754_exp10l, __exp10l_finite)
|
{
"content_hash": "c871f2321c34bdfc45ec4e02377d7235",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 67,
"avg_line_length": 20.928571428571427,
"alnum_prop": 0.6791808873720137,
"repo_name": "andrewjylee/omniplay",
"id": "6bd859fde5c2678e7e6549b60feae02b9d287d90",
"size": "1209",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "eglibc-2.15/math/e_exp10l.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "4528"
},
{
"name": "Assembly",
"bytes": "8662249"
},
{
"name": "Awk",
"bytes": "79791"
},
{
"name": "Batchfile",
"bytes": "903"
},
{
"name": "C",
"bytes": "451499135"
},
{
"name": "C++",
"bytes": "6338106"
},
{
"name": "Groff",
"bytes": "2522798"
},
{
"name": "HTML",
"bytes": "47935"
},
{
"name": "Java",
"bytes": "2193"
},
{
"name": "Lex",
"bytes": "44513"
},
{
"name": "Logos",
"bytes": "97869"
},
{
"name": "Makefile",
"bytes": "1700085"
},
{
"name": "Objective-C",
"bytes": "1148023"
},
{
"name": "Perl",
"bytes": "530370"
},
{
"name": "Perl6",
"bytes": "3727"
},
{
"name": "Python",
"bytes": "493452"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "409014"
},
{
"name": "SourcePawn",
"bytes": "11760"
},
{
"name": "TeX",
"bytes": "283872"
},
{
"name": "UnrealScript",
"bytes": "6143"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "Yacc",
"bytes": "93190"
}
],
"symlink_target": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.