text stringlengths 2 1.04M | meta dict |
|---|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tommytcchan.propertiesdiff;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import org.netbeans.api.diff.Diff;
import org.netbeans.api.diff.DiffController;
import org.netbeans.api.diff.DiffView;
import org.netbeans.api.diff.StreamSource;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
@ActionID(
category = "File",
id = "com.tommytcchan.propertiesdiff.PropertiesDiffListener")
@ActionRegistration(
iconBase = "com/tommytcchan/propertiesdiff/propertiesDiff16.png",
displayName = "#CTL_PropertiesDiffListener")
@ActionReferences({
@ActionReference(path = "Menu/Tools", position = 10, separatorBefore = -50, separatorAfter = 50),
@ActionReference(path = "Toolbars/File", position = 0)
})
@Messages("CTL_PropertiesDiffListener=Properies Diff")
public final class PropertiesDiffListener implements ActionListener {
String fileLeft;
String fileLeftName;
String fileRight;
String fileRightName;
@Override
public void actionPerformed(ActionEvent e) {
openFiles(e);
if (fileLeft != null && fileRight != null) {
StreamSource local = StreamSource.createSource("left", fileLeftName, "text/plain", new StringReader(fileLeft));
StreamSource remote = StreamSource.createSource("right", fileRightName, "text/plain", new StringReader(fileRight));
diff(local, remote);
}
}
public void diff(final StreamSource local, final StreamSource remote) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
DiffController view = DiffController.create(local, remote);
TopComponent tc = new TopComponent();
tc.setDisplayName("Diff Viewer");
tc.setLayout(new BorderLayout());
tc.add(view.getJComponent(), BorderLayout.CENTER);
tc.open();
tc.requestActive();
} catch (IOException ex) {
}
}
});
}
private void openFiles(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new javax.swing.JFileChooser();
fileChooser.setDialogTitle("Open the left file to compare...");
fileChooser.setFileFilter(new PropertiesFileFilter());
final Component source = (Component) evt.getSource();
int returnVal = fileChooser.showOpenDialog(source);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileLeftName = file.getName();
fileLeft = new PropertiesLoader().loadPropertiesSorted(file.getAbsolutePath());
//open the second file
openSecondFile(evt);
} else {
error(source, "Cancelled.");
}
}
private void openSecondFile(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new javax.swing.JFileChooser();
fileChooser.setDialogTitle("Open the right file to compare...");
fileChooser.setFileFilter(new PropertiesFileFilter());
final Component source = (Component) evt.getSource();
int returnVal = fileChooser.showOpenDialog(source);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileRightName = file.getName();
fileRight = new PropertiesLoader().loadPropertiesSorted(file.getAbsolutePath());
} else {
error(source, "Cancelled.");
}
}
private void error(Component comp, String msg) {
JOptionPane.showMessageDialog(comp, msg,
"Error", JOptionPane.ERROR_MESSAGE);
}
private class PropertiesFileFilter extends FileFilter {
@Override
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().contains(".properties");
}
@Override
public String getDescription() {
return "Properties (.properties) file.";
}
}
}
| {
"content_hash": "d1e02d3701615c4b67ada6b0fb7d8486",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 118,
"avg_line_length": 33.024,
"alnum_prop": 0.7478197674418605,
"repo_name": "tommytcchan/properties-file-differ-netbeans",
"id": "4e34191a7052ba3c547e495462ff3a907462cc73",
"size": "4128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/tommytcchan/propertiesdiff/PropertiesDiffListener.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5002"
}
],
"symlink_target": ""
} |
class ServerSession < ActiveRecord::Base
# translate pseudo session id received from other gofreerev server to pseudo session id used on this gofreerev server
# (online users message)
# create_table "server_sessions", force: true do |t|
# t.integer "server_id", null: false
# t.integer "session_id", null: false
# t.integer "remote_session_id", null: false
# t.datetime "created_at"
# t.datetime "updated_at"
# end
# add_index "server_sessions", ["server_id", "remote_session_id"], name: "index_server_session_pk", unique: true, using: :btree
# add_index "server_sessions", ["session_id"], name: "index_server_session_uk", unique: true, using: :btree
# 1: server_id
validates_presence_of :server_id
# 2: session_id - pseudo session id used on this Gofreerev server
# generated when receiving online users message from other gofreerev servers
validates_presence_of :session_id
validates_uniqueness_of :session_id, :allow_blank => true, :scope => :server_id
# 3: remote_session_id - pseudo session id received in online users message from other Gofreerev server
# must be translated to pseudo session id on this gofreerev server
validates_presence_of :remote_session_id
validates_uniqueness_of :remote_session_id, :allow_blank => true
end
| {
"content_hash": "202fe26aa936dcf60fb7d9a9065f01a5",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 129,
"avg_line_length": 45.275862068965516,
"alnum_prop": 0.7105864432597105,
"repo_name": "jaros1/gofreerev-lo",
"id": "86f0c11afb2ed31904f9daec68ce21d798895331",
"size": "1313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/server_session.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "435268"
},
{
"name": "CoffeeScript",
"bytes": "104"
},
{
"name": "HTML",
"bytes": "176320"
},
{
"name": "JavaScript",
"bytes": "1454189"
},
{
"name": "Ruby",
"bytes": "1095047"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Mar 06 22:11:40 CST 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.fs.ZeroCopyUnavailableException (Apache Hadoop Common 2.3.0 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.fs.ZeroCopyUnavailableException (Apache Hadoop Common 2.3.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/fs/ZeroCopyUnavailableException.html" title="class in org.apache.hadoop.fs"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/fs//class-useZeroCopyUnavailableException.html" target="_top"><B>FRAMES</B></A>
<A HREF="ZeroCopyUnavailableException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.fs.ZeroCopyUnavailableException</B></H2>
</CENTER>
No usage of org.apache.hadoop.fs.ZeroCopyUnavailableException
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/fs/ZeroCopyUnavailableException.html" title="class in org.apache.hadoop.fs"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/fs//class-useZeroCopyUnavailableException.html" target="_top"><B>FRAMES</B></A>
<A HREF="ZeroCopyUnavailableException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2015 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "2402aebf08a9d2c8c081a7fc9d232f4e",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 226,
"avg_line_length": 43.13103448275862,
"alnum_prop": 0.6258394627438439,
"repo_name": "jsrudani/HadoopHDFSProject",
"id": "98e331fbe8999b95f1d1844f63efb983db946f4e",
"size": "6254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hadoop-common-project/hadoop-common/target/org/apache/hadoop/fs/class-use/ZeroCopyUnavailableException.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "31146"
},
{
"name": "C",
"bytes": "1198902"
},
{
"name": "C++",
"bytes": "164551"
},
{
"name": "CMake",
"bytes": "131069"
},
{
"name": "CSS",
"bytes": "131494"
},
{
"name": "Erlang",
"bytes": "464"
},
{
"name": "HTML",
"bytes": "485534855"
},
{
"name": "Java",
"bytes": "37974886"
},
{
"name": "JavaScript",
"bytes": "80446"
},
{
"name": "Makefile",
"bytes": "104088"
},
{
"name": "Perl",
"bytes": "18992"
},
{
"name": "Protocol Buffer",
"bytes": "159216"
},
{
"name": "Python",
"bytes": "11309"
},
{
"name": "Shell",
"bytes": "724779"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "91404"
}
],
"symlink_target": ""
} |
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="trimPathStart"
android:valueFrom="1"
android:valueTo="0"
android:valueType="floatType"
android:duration="500"
android:interpolator="@android:interpolator/linear_out_slow_in" /> | {
"content_hash": "b56419c22bf4689a54fdae9d4f46febd",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 37.625,
"alnum_prop": 0.7308970099667774,
"repo_name": "xingui66/keer",
"id": "22c66b5258975f0d296c04c26445031fdb24939b",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/animator/anim_bar_fill2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "34992"
}
],
"symlink_target": ""
} |
import {remote} from "./remote";
import {CORE_API} from "../common/services/core-api-utils";
export function mkSurveyTemplateStore() {
const findAll = (force = false) => remote.fetchViewList(
"GET",
"api/survey-template",
[],
{force});
const getByQuestionId = (id, force = false) => remote.fetchViewDatum(
"GET",
`api/survey-template/question-id/${id}`,
[],
{force});
return {
findAll,
getByQuestionId
};
}
export const surveyTemplateStore = mkSurveyTemplateStore(); | {
"content_hash": "0d7638589d657cbec4d4b4b8fab8cc95",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 73,
"avg_line_length": 21.884615384615383,
"alnum_prop": 0.5869947275922671,
"repo_name": "khartec/waltz",
"id": "65b1d732349f2f6d04e879cdb446754e1d15f85d",
"size": "1206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "waltz-ng/client/svelte-stores/survey-template-store.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "154584"
},
{
"name": "HTML",
"bytes": "1387746"
},
{
"name": "Java",
"bytes": "3415267"
},
{
"name": "JavaScript",
"bytes": "2270186"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
/*!
* vue-i18n v9.0.0-beta.14
* (c) 2020 kazuya kawaguchi
* Released under the MIT License.
*/
import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, isString, isFunction, isObject, isBoolean, isRegExp, isNumber, warn, isEmptyObject } from '@intlify/shared';
import { setupDevtoolsPlugin } from '@vue/devtools-api';
import { DevToolsLabels, DevToolsPlaceholders, DevToolsTimelineColors, DevToolsTimelineLayerMaps, createCompileError, parse, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, NOT_REOSLVED, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, createEmitter, registerMessageCompiler, compileToFunction } from '@intlify/core-base';
import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
let devtools;
function setDevtoolsHook(hook) {
devtools = hook;
}
function devtoolsRegisterI18n(i18n, version) {
if (!devtools) {
return;
}
devtools.emit("intlify:register" /* REGISTER */, i18n, version);
}
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
app
}, api => {
devtoolsApi = api;
api.on.inspectComponent(payload => {
const componentInstance = payload.componentInstance;
if (componentInstance.vnode.el.__INTLIFY__ &&
payload.instanceData) {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
inspectScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
label: DevToolsLabels["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */],
color: DevToolsTimelineColors["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]
});
api.addTimelineLayer({
id: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
label: DevToolsLabels["vue-i18n-performance" /* TIMELINE_PERFORMANCE */],
color: DevToolsTimelineColors["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]
});
api.addTimelineLayer({
id: "vue-i18n-missing" /* TIMELINE_MISSING */,
label: DevToolsLabels["vue-i18n-missing" /* TIMELINE_MISSING */],
color: DevToolsTimelineColors["vue-i18n-missing" /* TIMELINE_MISSING */]
});
api.addTimelineLayer({
id: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
label: DevToolsLabels["vue-i18n-fallback" /* TIMELINE_FALLBACK */],
color: DevToolsTimelineColors["vue-i18n-fallback" /* TIMELINE_FALLBACK */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
function inspectComposer(instanceData, composer) {
const type = 'vue-i18n: composer properties';
instanceData.state.push({
type,
key: 'locale',
editable: false,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: composer.messages.value
});
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
function registerScope(payload, i18n) {
const children = [];
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
const label = keyInstance.type.name ||
keyInstance.type.displayName ||
keyInstance.type.__file;
children.push({
id: composer.id.toString(),
label: `${label} Scope`
});
}
payload.rootNodes.push({
id: 'global',
label: 'Global Scope',
children
});
}
function inspectScope(payload, i18n) {
if (payload.nodeId === 'global') {
payload.state = makeScopeInspectState(i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer);
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId);
if (instance) {
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
payload.state = makeScopeInspectState(composer);
}
}
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: false,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: composer.messages.value
}
];
state[localeMessagesType] = localeMessagesStates;
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
devtoolsApi.addTimelineEvent({
layerId: DevToolsTimelineLayerMaps[event],
event: {
time: Date.now(),
meta: {},
data: payload || {}
}
});
}
}
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.0.0-beta.14';
/**
* This is only called in esm-bundler builds.
* istanbul-ignore-next
*/
function initFeatureFlags() {
let needWarn = false;
if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {
needWarn = true;
getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;
}
if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {
needWarn = true;
getGlobalThis().__VUE_I18N_LEGACY_API__ = true;
}
if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
needWarn = true;
getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
}
if ((process.env.NODE_ENV !== 'production') && needWarn) {
console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` +
`configure your bundler to explicitly replace feature flag globals ` +
`with boolean literals to get proper tree-shaking in the final bundle.`);
}
}
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
const target = getGlobalThis();
target.__INTLIFY__ = true;
setDevtoolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
const warnMessages = {
[6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
[7 /* NOT_SUPPORTED_PRESERVE */]: `Not supportted 'preserve'.`,
[8 /* NOT_SUPPORTED_FORMATTER */]: `Not supportted 'formatter'.`,
[9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supportted 'preserveDirectiveContent'.`,
[10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supportted 'getChoiceIndex'.`,
[11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
};
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
function createI18nError(code, ...args) {
return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);
}
const errorMessages = {
[12 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
[13 /* INVALID_ARGUMENT */]: 'Invalid argument',
[14 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
[15 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
[20 /* UNEXPECTED_ERROR */]: 'Unexpected error',
[16 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
[17 /* REQUIRED_VALUE */]: `Required in value: {0}`,
[18 /* INVALID_VALUE */]: `Invalid value`,
[19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
};
/**
* Composer
*
* Composer is offered composable API for Vue 3
* This module is offered new style vue-i18n API
*/
const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
const DatetimePartsSymbol = makeSymbol('__datetimeParts');
const NumberPartsSymbol = makeSymbol('__numberParts');
const EnableEmitter = makeSymbol('__enableEmitter');
const DisableEmitter = makeSymbol('__disableEmitter');
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
function getLocaleMessages(locale, options) {
const { messages, __i18n } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(raw => {
deepCopy(isString(raw) ? JSON.parse(raw) : raw, ret);
});
return ret;
}
if (isFunction(__i18n)) {
const { functions } = __i18n();
addPreCompileMessages(ret, functions);
}
return ret;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(source, destination) {
for (const key in source) {
if (hasOwn(source, key)) {
if (!isObject(source[key])) {
destination[key] = destination[key] != null ? destination[key] : {};
destination[key] = source[key];
}
else {
destination[key] = destination[key] != null ? destination[key] : {};
deepCopy(source[key], destination[key]);
}
}
}
}
function addPreCompileMessages(messages, functions) {
const keys = Object.keys(functions);
keys.forEach(key => {
const compiled = functions[key];
const { l, k } = JSON.parse(key);
if (!messages[l]) {
messages[l] = {};
}
const targetLocaleMessage = messages[l];
const paths = parse(k);
if (paths != null) {
const len = paths.length;
let last = targetLocaleMessage; // eslint-disable-line @typescript-eslint/no-explicit-any
let i = 0;
while (i < len) {
const path = paths[i];
if (i === len - 1) {
last[path] = compiled;
break;
}
else {
let val = last[path];
if (!val) {
last[path] = val = {};
}
last = val;
i++;
}
}
}
});
}
/**
* Create composer interface factory
*
* @internal
*/
function createComposer(options = {}) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: 'en-US');
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} });
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} });
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
let _fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall bakck to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
const _pluralRules = options.pluralRules;
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
return createCoreContext({
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
datetimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
__datetimeFormatters: isPlainObject(_context)
? _context.__datetimeFormatters
: undefined,
__numberFormatters: isPlainObject(_context)
? _context.__numberFormatters
: undefined,
__emitter: isPlainObject(_context)
? _context.__emitter
: undefined
});
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
/*!
* define properties
*/
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = computed(() => _numberFormats.value);
/**
* define methods
*/
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
const context = getCoreContext();
const ret = fn(context); // track reactive dependency, see the getRuntimeContext
if (isNumber(ret) && ret === NOT_REOSLVED) {
const key = argumentParser();
if ((process.env.NODE_ENV !== 'production') && _fallbackRoot && __root) {
warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
key,
type: warnType
}));
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
const { __emitter: emitter } = context;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global'
});
}
}
}
return _fallbackRoot && __root
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(12 /* UNEXPECTED_RETURN_TYPE */);
}
}
// t
function t(...args) {
return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val));
}
// d
function d(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// __transrateVNode, using for `i18n-t` component
function __transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = translate(_context, ...args);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args)[0], 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// __numberParts, using for `i18n-n` component
function __numberParts(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// __datetimeParts, using for `i18n-d` component
function __datetimeParts(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return resolveValue(message, key) !== null;
}
// tm
function tm(key) {
const messages = _messages.value[_locale.value] || {};
const target = resolveValue(messages, key);
// prettier-ignore
return target != null
? target
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = Object.assign(_messages.value[locale] || {}, message);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// export composition API!
const composer = {
// properties
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
datetimeFormats,
numberFormats,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
// methods
t,
d,
n,
te,
tm,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[TransrateVNodeSymbol]: __transrateVNode,
[NumberPartsSymbol]: __numberParts,
[DatetimePartsSymbol]: __datetimeParts
};
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
composer[EnableEmitter] = (emitter) => {
_context.__emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__emitter = undefined;
};
}
return composer;
}
/**
* Legacy
*
* This module is offered legacy vue-i18n API compatibility
*/
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if ((process.env.NODE_ENV !== 'production') && options.formatter) {
warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
}
if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
Object.assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
return {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
inheritLocale,
__i18n,
__root
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
function createVueI18n(options = {}) {
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
/**
* properties
*/
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
(process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
(process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
return true;
},
set preserveDirectiveContent(val) {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
/**
* methods
*/
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessasge
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return composer.d(...args);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return composer.n(...args);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
vueI18n.__enableEmitter = (emitter) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
validator: (val) => val === 'parent' || val === 'global',
default: 'parent'
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = {
/* eslint-disable */
name: 'i18n-t',
props: {
...baseFormatProps,
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
},
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
const i18n = useI18n({ useScope: props.scope });
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
};
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let orverrides = {};
if (props.locale) {
options.locale = props.locale;
}
if (isString(props.format)) {
options.key = props.format;
}
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
orverrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, orverrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = {
/* eslint-disable */
name: 'i18n-n',
props: {
...baseFormatProps,
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
};
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = {
/* eslint-disable */
name: 'i18n-d',
props: {
...baseFormatProps,
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
};
function getComposer(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const composer = getComposer(i18n, instance.$);
if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {
warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
}
const parsedValue = parseValue(value);
el.textContent = composer.t(...makeParams(parsedValue));
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(17 /* REQUIRED_VALUE */, 'path');
}
return value;
}
else {
throw createI18nError(18 /* INVALID_VALUE */);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {
warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
app.directive('t', vTDirective(i18n));
}
// supports compatibility for legacy vue-i18n APIs
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
this.$el.__INTLIFY__ = this.$i18n.__composer;
const emitter = (this.__emitter = createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
beforeUnmount() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
/* istanbul ignore if */
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
if (this.__emitter) {
this.__emitter.off('*', addTimelineEvent);
delete this.__emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__INTLIFY__;
}
delete this.$t;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
}
};
}
function mergeToRoot(root, optoins) {
root.locale = optoins.locale || root.locale;
root.fallbackLocale = optoins.fallbackLocale || root.fallbackLocale;
root.missing = optoins.missing || root.missing;
root.silentTranslationWarn =
optoins.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
optoins.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
optoins.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = optoins.postTranslation || root.postTranslation;
root.warnHtmlInMessage = optoins.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
optoins.escapeParameterHtml || root.escapeParameterHtml;
root.sync = optoins.sync || root.sync;
const messages = getLocaleMessages(root.locale, {
messages: optoins.messages,
__i18n: optoins.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (optoins.datetimeFormats) {
Object.keys(optoins.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, optoins.datetimeFormats[locale]));
}
if (optoins.numberFormats) {
Object.keys(optoins.numberFormats).forEach(locale => root.mergeNumberFormat(locale, optoins.numberFormats[locale]));
}
return root;
}
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../essentials/started)
* @VueI18nSee [Composition API](../advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'lagacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
function createI18n(options = {}) {
// prettier-ignore
const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)
? options.legacy
: true;
const __globalInjection = __VUE_I18N_LEGACY_API__ && !!options.globalInjection;
const __instances = new Map();
// prettier-ignore
const __global = __VUE_I18N_LEGACY_API__ && __legacyMode
? createVueI18n(options)
: createComposer(options);
const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');
const i18n = {
// mode
get mode() {
// prettier-ignore
return __VUE_I18N_LEGACY_API__
? __legacyMode
? 'legacy'
: 'composition'
: 'composition';
},
// install plugin
async install(app, ...options) {
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
app.__VUE_I18N__ = i18n;
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
if (__VUE_I18N_FULL_INSTALL__) {
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if (__VUE_I18N_LEGACY_API__ && __legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accsessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance(component) {
return __instances.get(component) || null;
},
// @internal
__setInstance(component, instance) {
__instances.set(component, instance);
},
// @internal
__deleteInstance(component) {
__instances.delete(component);
}
};
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
devtoolsRegisterI18n(i18n, VERSION);
}
return i18n;
}
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(14 /* MUST_BE_CALL_SETUP_TOP */);
}
if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(15 /* NOT_INSLALLED */);
}
const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
// prettier-ignore
const scope = isEmptyObject(options)
? ('__i18n' in instance.type)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
if (scope === 'global') {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in instance.type) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: instance.type.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
return global;
}
if (scope === 'parent') {
let composer = getComposer$1(i18n, instance);
if (composer == null) {
if ((process.env.NODE_ENV !== 'production')) {
warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(16 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const type = instance.type;
const composerOptions = {
...options
};
if (type.__i18n) {
composerOptions.__i18n = type.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function getComposer$1(i18n, target) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) &&
!false &&
target.vnode.el) {
target.vnode.el.__INTLIFY__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) &&
!false &&
target.vnode.el &&
target.vnode.el.__INTLIFY__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__INTLIFY__;
}
i18n.__deleteInstance(target);
}, target);
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'd', 'n', 'tm'];
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
// register message compiler at vue-i18n
registerMessageCompiler(compileToFunction);
{
initFeatureFlags();
}
(process.env.NODE_ENV !== 'production') && initDev();
export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
| {
"content_hash": "ecc48d649ab65871de2bfb91e8987130",
"timestamp": "",
"source": "github",
"line_count": 2089,
"max_line_length": 428,
"avg_line_length": 34.43992340832934,
"alnum_prop": 0.5341441378831051,
"repo_name": "cdnjs/cdnjs",
"id": "147d00ab1046ee810727d4305ed36b34fdb1aa03",
"size": "71973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/vue-i18n/9.0.0-beta.14/vue-i18n.esm-bundler.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
HOMOTYPIC_SYNONYM
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "509bf7e14cb3eda93d1779cdfd40924f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 9.384615384615385,
"alnum_prop": 0.6967213114754098,
"repo_name": "mdoering/backbone",
"id": "02dcdd51cbb20f65378a59ca32426e448ec4732b",
"size": "204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium dragicola/ Syn. Hieracium leiocephalum dragicola/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module SimpleState
module Mixins
def self.included(klass)
klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
attr_reader :state unless method_defined?(:state)
@@states = {}
@@initial_state = nil
unless method_defined?(:state=)
attr_writer :state
private :state=
end
extend Singleton
include Instance
RUBY
end
##
# Defines singleton methods which are mixed in to a class when
# state_machine is called.
#
module Singleton
# @api private
def states
class_variable_get(:@@states)
end
# @api public
def initial_state=(state)
class_variable_set(:@@initial_state, state)
end
# @api public
def initial_state
class_variable_get(:@@initial_state)
end
# @api private
def _determine_new_state(current, to)
states[current] && (t = states[current].assoc(to)) && t.last
end
# @api private
def _event_permitted?(current, to)
states[current] and not states[current].assoc(to).nil?
end
end
##
# Defines instance methods which are mixed in to a class when
# state_machine is called.
#
module Instance
##
# Set the initial value for the state machine after calling the original
# initialize method.
#
def initialize(*args, &blk)
super
self.state = self.class.initial_state
end
end # Instance
end # Mixins
end # SimpleState
| {
"content_hash": "f1b19ae592e80c46279f1d843a8a29e7",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 78,
"avg_line_length": 23.70769230769231,
"alnum_prop": 0.5781959766385464,
"repo_name": "antw/simple_state",
"id": "dab4ff26f8cc8b8d00caec6a33ded033c1451b26",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/simple_state/mixins.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "18276"
}
],
"symlink_target": ""
} |
<?php
// Creating the widget
class rcity_more_posts_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'rcity_more_posts_widget',
// Widget name will appear in UI
__('#:More Posts', 'rcity_more_posts_widget_domain'),
// Widget description
array( 'description' => __( 'Sample widget based on RumorsCity Tutorial', 'rcity_more_posts_widget_domain' ), )
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
global $post;
if (is_single()) {
foreach((get_the_category()) as $category) {
$cat_name[] = strtolower($category->cat_name);
$cat_id[] = $category->cat_ID;
// echo '<img src="http://example.com/images/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />';
}
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title .' <a href="/'.$cat_name[0].'/"> '.$cat_name[0].'</a>'. $args['after_title'];
// This is where you run the code and display the output
// echo __( 'Hello, World!', 'rcity_more_posts_widget_domain' );
?>
<div class="list-group recommended-list-group">
<?php
$args = array( 'posts_per_page' => 5, 'orderby' => 'rand', 'category' => $cat_id[0] );
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ) :
setup_postdata( $post );
$category = get_the_category($post->ID);
// echo end($category)->cat_name;
?>
<a data-ng-repeat="post in more_posts | limitTo:5" class="list-group-item ng-scope" data-ng-href="<?php the_permalink(); ?>" data-ng-click="SendEvent($index)" href="<?php the_permalink(); ?>">
<div class="recommended-photo">
<!--
<img data-pin-no-hover="true" data-ng-src="http://cdn.diply.com/img/b4de0e53-c9a6-42c2-a330-a527f47a8351_t.jpg" src="http://cdn.diply.com/img/b4de0e53-c9a6-42c2-a330-a527f47a8351_t.jpg">
-->
<?php echo get_the_post_thumbnail($post->ID, 'thumbnail'); ?>
</div>
<div class="recommended-title ng-binding"><?php the_title(); ?></div>
<div class="externalPost ng-binding"><?php echo end($category)->cat_name; ?></div>
<div class="clearfix"></div>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
</div>
<?php
}
echo $args['after_widget'];
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'New title', 'rcity_more_posts_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class rcity_more_posts_widget ends here
// Register and load the widget
function rcity_more_posts_load_widget() {
register_widget( 'rcity_more_posts_widget' );
}
add_action( 'widgets_init', 'rcity_more_posts_load_widget' );
?> | {
"content_hash": "22d2884400d81f65aee3a09dfbec4571",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 194,
"avg_line_length": 34.18811881188119,
"alnum_prop": 0.6200405444540978,
"repo_name": "juzhax/rcity",
"id": "029de96649b65c040c6b38a562992759c4e8a668",
"size": "3453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/widget-more-posts.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "145955"
},
{
"name": "HTML",
"bytes": "324210"
},
{
"name": "JavaScript",
"bytes": "1333951"
},
{
"name": "PHP",
"bytes": "93853"
}
],
"symlink_target": ""
} |
A Home Dashboard using IoT Edison Board
| {
"content_hash": "efc653d0516fa484fdce601f242173f1",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 39,
"avg_line_length": 40,
"alnum_prop": 0.825,
"repo_name": "zerooneit/houservis",
"id": "6138cb9c026f03296fd21a11b89410565e59cc1a",
"size": "52",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.caleydo.vis.lineup.model.mapping;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.caleydo.vis.lineup.data.ADoubleFunction;
/**
* @author Samuel Gratzl
*
*/
public class BaseCategoricalMappingFunction<T> extends ADoubleFunction<T> implements ICategoricalMappingFunction<T>,
Cloneable {
private final Map<T, Double> mapping = new LinkedHashMap<>();
private double missingValue = Double.NaN;
public BaseCategoricalMappingFunction(Set<T> items) {
int i = 1;
double f = 1.f / items.size();
for (T key : items)
mapping.put(key, (i++) * f);
}
public BaseCategoricalMappingFunction(BaseCategoricalMappingFunction<T> copy) {
this.mapping.putAll(copy.mapping);
}
@Override
public BaseCategoricalMappingFunction<T> clone() {
return new BaseCategoricalMappingFunction<T>(this);
}
@Override
public boolean isComplexMapping() {
return false;
}
@Override
public double applyPrimitive(T in) {
if (in == null)
return missingValue;
Double r = mapping.get(in);
return r == null ? missingValue : r.doubleValue();
}
public void put(T in, double value) {
mapping.put(in, value);
}
public void remove(T in) {
mapping.remove(in);
}
@Override
public void reset() {
int i = 1;
double f = 1.f / mapping.size();
for (Map.Entry<T, Double> entry : mapping.entrySet())
entry.setValue((i++) * f);
}
}
| {
"content_hash": "955dc5cbe1a676a8e7df543b0ffab39d",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 116,
"avg_line_length": 22.158730158730158,
"alnum_prop": 0.7048710601719198,
"repo_name": "Caleydo/caleydo",
"id": "5c6a98533decff636ee8c9c4a42d5f9fceed4b0b",
"size": "1762",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/model/mapping/BaseCategoricalMappingFunction.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "2493"
},
{
"name": "GLSL",
"bytes": "2781"
},
{
"name": "HTML",
"bytes": "27930"
},
{
"name": "Java",
"bytes": "9111375"
},
{
"name": "JavaScript",
"bytes": "81257"
},
{
"name": "PHP",
"bytes": "546"
},
{
"name": "Python",
"bytes": "33906"
},
{
"name": "R",
"bytes": "5894"
},
{
"name": "Shell",
"bytes": "14669"
}
],
"symlink_target": ""
} |
// Copyright 2021 Google Inc.
//
// 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.
// [START spanner_insert_datatypes_data]
using Google.Cloud.Spanner.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class InsertDataTypesDataAsyncSample
{
public class Venue
{
public int VenueId { get; set; }
public string VenueName { get; set; }
public byte[] VenueInfo { get; set; }
public int Capacity { get; set; }
public List<DateTime> AvailableDates { get; set; }
public DateTime LastContactDate { get; set; }
public bool OutdoorVenue { get; set; }
public float PopularityScore { get; set; }
}
public async Task InsertDataTypesDataAsync(string projectId, string instanceId, string databaseId)
{
string connectionString = $"Data Source=projects/{projectId}/instances/{instanceId}/databases/{databaseId}";
byte[] exampleBytes1 = Encoding.UTF8.GetBytes("Hello World 1");
byte[] exampleBytes2 = Encoding.UTF8.GetBytes("Hello World 2");
byte[] exampleBytes3 = Encoding.UTF8.GetBytes("Hello World 3");
var availableDates1 = new List<DateTime>
{
DateTime.Parse("2020-12-01"),
DateTime.Parse("2020-12-02"),
DateTime.Parse("2020-12-03")
};
var availableDates2 = new List<DateTime>
{
DateTime.Parse("2020-11-01"),
DateTime.Parse("2020-11-05"),
DateTime.Parse("2020-11-15")
};
var availableDates3 = new List<DateTime>
{
DateTime.Parse("2020-10-01"),
DateTime.Parse("2020-10-07")
};
List<Venue> venues = new List<Venue> {
new Venue {
VenueId = 4,
VenueName = "Venue 4",
VenueInfo = exampleBytes1,
Capacity = 1800,
AvailableDates = availableDates1,
LastContactDate = DateTime.Parse("2018-09-02"),
OutdoorVenue = false,
PopularityScore = 0.85543f
},
new Venue {
VenueId = 19,
VenueName = "Venue 19",
VenueInfo = exampleBytes2,
Capacity = 6300,
AvailableDates = availableDates2,
LastContactDate = DateTime.Parse("2019-01-15"),
OutdoorVenue = true,
PopularityScore = 0.98716f
},
new Venue {
VenueId = 42,
VenueName = "Venue 42",
VenueInfo = exampleBytes3,
Capacity = 3000,
AvailableDates = availableDates3,
LastContactDate = DateTime.Parse("2018-10-01"),
OutdoorVenue = false,
PopularityScore = 0.72598f
}};
using var connection = new SpannerConnection(connectionString);
await connection.OpenAsync();
await Task.WhenAll(venues.Select(venue =>
{
var cmd = connection.CreateInsertCommand("Venues",
new SpannerParameterCollection {
{ "VenueId", SpannerDbType.Int64, venue.VenueId },
{ "VenueName", SpannerDbType.String, venue.VenueName },
{ "VenueInfo", SpannerDbType.Bytes, venue.VenueInfo },
{ "Capacity", SpannerDbType.Int64, venue.Capacity },
{ "AvailableDates", SpannerDbType.ArrayOf(SpannerDbType.Date), venue.AvailableDates },
{ "LastContactDate", SpannerDbType.Date, venue.LastContactDate },
{ "OutdoorVenue", SpannerDbType.Bool, venue.OutdoorVenue },
{ "PopularityScore", SpannerDbType.Float64, venue.PopularityScore },
{ "LastUpdateTime", SpannerDbType.Timestamp, SpannerParameter.CommitTimestamp },
});
return cmd.ExecuteNonQueryAsync();
}));
}
}
// [END spanner_insert_datatypes_data]
| {
"content_hash": "fb2db6427979d3d2efbc86177fff4c06",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 116,
"avg_line_length": 38.559322033898304,
"alnum_prop": 0.5905494505494505,
"repo_name": "GoogleCloudPlatform/dotnet-docs-samples",
"id": "2e0c4fab1f8c1dcf982e8f87a471c796575b0582",
"size": "4552",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spanner/api/Spanner.Samples/InsertDatatypesDataAsync.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP.NET",
"bytes": "44935"
},
{
"name": "Batchfile",
"bytes": "2016"
},
{
"name": "C#",
"bytes": "3481210"
},
{
"name": "CSS",
"bytes": "17293"
},
{
"name": "Dockerfile",
"bytes": "16003"
},
{
"name": "F#",
"bytes": "7661"
},
{
"name": "HTML",
"bytes": "148172"
},
{
"name": "JavaScript",
"bytes": "202743"
},
{
"name": "PowerShell",
"bytes": "259637"
},
{
"name": "Shell",
"bytes": "7852"
},
{
"name": "Visual Basic .NET",
"bytes": "2494"
}
],
"symlink_target": ""
} |
function service_worker_unregister_and_register(test, url, scope) {
if (!scope || scope.length == 0)
return Promise.reject(new Error('tests must define a scope'));
var options = { scope: scope };
return service_worker_unregister(test, scope)
.then(function() {
return navigator.serviceWorker.register(url, options);
})
.catch(unreached_rejection(test,
'unregister and register should not fail'));
}
function service_worker_unregister(test, documentUrl) {
return navigator.serviceWorker.getRegistration(documentUrl)
.then(function(registration) {
if (registration)
return registration.unregister();
})
.catch(unreached_rejection(test, 'unregister should not fail'));
}
function service_worker_unregister_and_done(test, scope) {
return service_worker_unregister(test, scope)
.then(test.done.bind(test));
}
function unreached_fulfillment(test, prefix) {
return test.step_func(function(result) {
var error_prefix = prefix || 'unexpected fulfillment';
assert_unreached(error_prefix + ': ' + result);
});
}
// Rejection-specific helper that provides more details
function unreached_rejection(test, prefix) {
return test.step_func(function(error) {
var reason = error.message || error.name || error;
var error_prefix = prefix || 'unexpected rejection';
assert_unreached(error_prefix + ': ' + reason);
});
}
// Adds an iframe to the document and returns a promise that resolves to the
// iframe when it finishes loading. When |options.auto_remove| is set to
// |false|, the caller is responsible for removing the iframe
// later. Otherwise, the frame will be removed after all tests are finished.
function with_iframe(url, options) {
return new Promise(function(resolve) {
var frame = document.createElement('iframe');
frame.src = url;
frame.onload = function() { resolve(frame); };
document.body.appendChild(frame);
if (typeof options === 'undefined')
options = {};
if (typeof options.auto_remove === 'undefined')
options.auto_remove = true;
if (options.auto_remove)
add_completion_callback(function() { frame.remove(); });
});
}
function with_sandboxed_iframe(url, sandbox) {
return new Promise(function(resolve) {
var frame = document.createElement('iframe');
frame.sandbox = sandbox;
frame.src = url;
frame.onload = function() { resolve(frame); };
document.body.appendChild(frame);
});
}
function normalizeURL(url) {
return new URL(url, self.location).toString().replace(/#.*$/, '');
}
function wait_for_update(test, registration) {
if (!registration || registration.unregister == undefined) {
return Promise.reject(new Error(
'wait_for_update must be passed a ServiceWorkerRegistration'));
}
return new Promise(test.step_func(function(resolve) {
registration.addEventListener('updatefound', test.step_func(function() {
resolve(registration.installing);
}));
}));
}
function wait_for_state(test, worker, state) {
if (!worker || worker.state == undefined) {
return Promise.reject(new Error(
'wait_for_state must be passed a ServiceWorker'));
}
if (worker.state === state)
return Promise.resolve(state);
if (state === 'installing') {
switch (worker.state) {
case 'installed':
case 'activating':
case 'activated':
case 'redundant':
return Promise.reject(new Error(
'worker is ' + worker.state + ' but waiting for ' + state));
}
}
if (state === 'installed') {
switch (worker.state) {
case 'activating':
case 'activated':
case 'redundant':
return Promise.reject(new Error(
'worker is ' + worker.state + ' but waiting for ' + state));
}
}
if (state === 'activating') {
switch (worker.state) {
case 'activated':
case 'redundant':
return Promise.reject(new Error(
'worker is ' + worker.state + ' but waiting for ' + state));
}
}
if (state === 'activated') {
switch (worker.state) {
case 'redundant':
return Promise.reject(new Error(
'worker is ' + worker.state + ' but waiting for ' + state));
}
}
return new Promise(test.step_func(function(resolve) {
worker.addEventListener('statechange', test.step_func(function() {
if (worker.state === state)
resolve(state);
}));
}));
}
// Declare a test that runs entirely in the ServiceWorkerGlobalScope. The |url|
// is the service worker script URL. This function:
// - Instantiates a new test with the description specified in |description|.
// The test will succeed if the specified service worker can be successfully
// registered and installed.
// - Creates a new ServiceWorker registration with a scope unique to the current
// document URL. Note that this doesn't allow more than one
// service_worker_test() to be run from the same document.
// - Waits for the new worker to begin installing.
// - Imports tests results from tests running inside the ServiceWorker.
function service_worker_test(url, description) {
// If the document URL is https://example.com/document and the script URL is
// https://example.com/script/worker.js, then the scope would be
// https://example.com/script/scope/document.
var scope = new URL('scope' + window.location.pathname,
new URL(url, window.location)).toString();
promise_test(function(test) {
return service_worker_unregister_and_register(test, url, scope)
.then(function(registration) {
add_completion_callback(function() {
registration.unregister();
});
return wait_for_update(test, registration)
.then(function(worker) {
return fetch_tests_from_worker(worker);
});
});
}, description);
}
function base_path() {
return location.pathname.replace(/\/[^\/]*$/, '/');
}
function test_login(test, origin, username, password, cookie) {
return new Promise(function(resolve, reject) {
with_iframe(
origin +
'/serviceworker/resources/fetch-access-control-login.html')
.then(test.step_func(function(frame) {
var channel = new MessageChannel();
channel.port1.onmessage = test.step_func(function() {
frame.remove();
resolve();
});
frame.contentWindow.postMessage(
{username: username, password: password, cookie: cookie},
origin, [channel.port2]);
}));
});
}
function login(test, local, remote) {
var suffix = (local.indexOf("https") != -1) ? "s": "";
return test_login(test, local, 'username1' + suffix, 'password1' + suffix,
'cookie1')
.then(function() {
return test_login(test, remote, 'username2' + suffix,
'password2' + suffix, 'cookie2');
});
}
| {
"content_hash": "96ae780740b9fc42676b3da14940e486",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 80,
"avg_line_length": 34.67156862745098,
"alnum_prop": 0.6305669447193553,
"repo_name": "was4444/chromium.src",
"id": "1859b2aff52e4ef8f23f16dabb76e4bd820e5a50",
"size": "7137",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/test-helpers.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.avanza.astrix.versioning.core;
public interface ObjectSerializerFactory {
public AstrixObjectSerializer create(ObjectSerializerDefinition serializerDefinition);
}
| {
"content_hash": "110d3fdf946c1cb6e18de676db2ca6b3",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 87,
"avg_line_length": 22.625,
"alnum_prop": 0.850828729281768,
"repo_name": "kerlandsson/astrix",
"id": "dd805f2fd36e8bd12a0a9c0bc8ca21d1de7f7bfb",
"size": "779",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "astrix-versioning/src/main/java/com/avanza/astrix/versioning/core/ObjectSerializerFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "212"
},
{
"name": "HTML",
"bytes": "2017"
},
{
"name": "Java",
"bytes": "1268188"
},
{
"name": "JavaScript",
"bytes": "992"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: hp
* Date: 26/12/2014
* Time: 10:51
*/
namespace Sise\Bundle\CoreBundle\Repository;
use Doctrine\ORM\EntityRepository;
class OrientationFilieresportRepository extends EntityRepository
{
public function getOrientationFilieresport($items)
{
return $this->createQueryBuilder('p')
->leftJoin('p.codefiliorig', 'c')
->where('p.codeetab = :codeetab')
->andWhere('p.codetypeetab = :codetypeetab')
->andWhere('p.annescol = :annescol')
->andWhere('p.coderece = :coderece')
->setParameter('codeetab', $items['codeetab'])
->setParameter('codetypeetab', $items['codetypeetab'])
->setParameter('annescol', $items['annescol'])
->setParameter('coderece', $items['coderece'])
->orderBy('c.ordraffi', 'DESC')
->getQuery()->getResult();
}
}
| {
"content_hash": "d4f911a52ebae6290258226ef57e5898",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 66,
"avg_line_length": 28.09090909090909,
"alnum_prop": 0.5976267529665588,
"repo_name": "fareh/sise",
"id": "65bb84203d31c93d61ab2c945d2ebf8261e85841",
"size": "927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Sise/Bundle/CoreBundle/Repository/OrientationFilieresportRepository.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1722"
},
{
"name": "CSS",
"bytes": "175375"
},
{
"name": "HTML",
"bytes": "968406"
},
{
"name": "JavaScript",
"bytes": "67066"
},
{
"name": "PHP",
"bytes": "2159498"
},
{
"name": "Shell",
"bytes": "2419"
}
],
"symlink_target": ""
} |
<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>com.schneider.utils</groupId>
<artifactId>file</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>file</name>
<url>http://www.donaldmcdougal.com/</url>
<properties>
<!-- Maven build properties -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "c1cb8a4b7dd10918a2243afbf3330da4",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 104,
"avg_line_length": 31.303030303030305,
"alnum_prop": 0.6786060019361084,
"repo_name": "donaldmcdougal/file",
"id": "3fc92c2a4f234dce00adc7cd256befaac1918e3a",
"size": "1033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13287"
}
],
"symlink_target": ""
} |
template <class TYPE>
void invokeAdlSwap(TYPE& a, TYPE& b)
// Exchange the values of the specified 'a' and 'b' objects using the
// 'swap' method found by ADL (Argument Dependent Lookup). The behavior
// is undefined unless 'a' and 'b' were created with the same allocator.
{
BSLS_ASSERT_OPT(a.allocator() == b.allocator());
using namespace bsl;
swap(a, b);
}
// The following 'using' directives must come *after* the definition of
// 'invokeAdlSwap' (above).
using namespace BloombergLP;
using namespace bsl;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// The component under test implements a single, unconstrained (value-semantic)
// attribute class that characterizes a local time value as a aggregation of a
// 'bdlt::DatetimeTz' value (i.e., 'bdlt::Datetime' value aggregated with an
// offset value (in minutes) from Coordinated Universal Time [UTC]), and an a
// time-zone identifier. In practice, the time-zone identifier will correspond
// to an identifier from the Zoneinfo (a.k.a., Olson) database; however, the
// class does not enforce the practice. The Primary Manipulators and Basic
// Accessors are therefore respectively the attribute setters and getters, each
// of which follows our standard unconstrained attribute-type naming
// conventions: 'setAttributeName' and 'attributeName'.
//
// Primary Manipulators:
//: o 'setDatetimeTz'
//: o 'setTimeZoneId'
//
// Basic Accessors:
//: o 'allocator' (orthogonal to value)
//: o 'datetimeTz'
//: o 'timeZoneId'
//
// This particular attribute class also provides a value constructor capable of
// creating an object in any state relevant for thorough testing, obviating the
// primitive generator function, 'gg', normally used for this purpose. We will
// therefore follow our standard 10-case approach to testing value-semantic
// types except that we will test the value constructor in case 3 (in lieu of
// the generator function), with the default constructor and primary
// manipulators tested fully in case 2.
//
// Global Concerns:
//: o The test driver is robust w.r.t. reuse in other, similar components.
//: o ACCESSOR methods are declared 'const'.
//: o CREATOR & MANIPULATOR pointer/reference parameters are declared 'const'.
//: o No memory is ever allocated from the global allocator.
//: o Any allocated memory is always from the object allocator.
//: o An object's value is independent of the allocator used to supply memory.
//: o Injected exceptions are safely propagated during memory allocation.
//
// Global Assumptions:
//: o All explicit memory allocations are presumed to use the global, default,
//: or object allocator.
//: o ACCESSOR methods are 'const' thread-safe.
//: o Individual attribute types are presumed to be *alias-safe*; hence, only
//: certain methods require the testing of this property:
//: o copy-assignment
//: o swap
// ----------------------------------------------------------------------------
// CLASS METHODS
// [11] static int maxSupportedBdexVersion();
//
// CREATORS
// [ 2] baltzo::LocalDatetime(bslma::Allocator *bA = 0);
// [ 3] baltzo::LocalDatetime(DatetimeTz& d, const char *t, *bA = 0);
// [ 7] baltzo::LocalDatetime(const baltzo::LocalDatetime& o, *bA = 0);
//
// MANIPULATORS
// [ 9] baltzo::LocalDatetime& operator=(const baltzo::LocalDatetime& rhs);
// [ 2] setDatetimeTz(const bdlt::DatetimeTz& value);
// [ 2] setTimeZoneId(const char *value);
//
// [ 8] swap(baltzo::LocalDatetime& other);
// [10] STREAM& bdexStreamIn(STREAM& stream, int version);
//
// ACCESSORS
// [ 4] bslma::Allocator *allocator() const;
// [ 4] const bdlt::DatetimeTz& datetimeTz() const;
// [ 4] const bsl::string& timeZoneId() const;
//
// [ 5] ostream& print(ostream& s, int level = 0, int sPL = 4) const;
// [10] STREAM& bdexStreamOut(STREAM& stream, int version) const;
//
// FREE OPERATORS
// [ 6] bool operator==(const baltzo::LocalDatetime& lhs, rhs);
// [ 6] bool operator!=(const baltzo::LocalDatetime& lhs, rhs);
// [ 5] operator<<(ostream& s, const baltzo::LocalDatetime& d);
//
// FREE FUNCTIONS
// [ 8] swap(baltzo::LocalDatetime& a, b);
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [11] USAGE EXAMPLE
// [ *] CONCERN: This test driver is reusable w/other, similar components.
// [ *] CONCERN: In no case does memory come from the global allocator.
// [ 3] CONCERN: All creator/manipulator ptr./ref. parameters are 'const'.
// [ 5] CONCERN: All accessor methods are declared 'const'.
// [ 3] CONCERN: String arguments can be either 'char *' or 'string'.
// [ 9] CONCERN: All memory allocation is from the object's allocator.
// [ 9] CONCERN: All memory allocation is exception neutral.
// [ 9] CONCERN: Object value is independent of the object allocator.
// [ 9] CONCERN: There is no temporary allocation from any allocator.
// [ 8] CONCERN: Precondition violations are detected when enabled.
// ============================================================================
// STANDARD BDE ASSERT TEST MACROS
// ----------------------------------------------------------------------------
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i) {
if (c) {
cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << endl;
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
// ============================================================================
// STANDARD BDE LOOP-ASSERT TEST MACROS
// ----------------------------------------------------------------------------
#define LOOP_ASSERT(I,X) { \
if (!(X)) { cout << #I << ": " << I << "\n"; aSsErT(1, #X, __LINE__);}}
#define LOOP2_ASSERT(I,J,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " \
<< J << "\n"; aSsErT(1, #X, __LINE__); } }
#define LOOP3_ASSERT(I,J,K,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " << J << "\t" \
<< #K << ": " << K << "\n"; aSsErT(1, #X, __LINE__); } }
#define LOOP4_ASSERT(I,J,K,L,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " << J << "\t" << \
#K << ": " << K << "\t" << #L << ": " << L << "\n"; \
aSsErT(1, #X, __LINE__); } }
#define LOOP5_ASSERT(I,J,K,L,M,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " << J << "\t" << \
#K << ": " << K << "\t" << #L << ": " << L << "\t" << \
#M << ": " << M << "\n"; \
aSsErT(1, #X, __LINE__); } }
// ============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
// ----------------------------------------------------------------------------
#define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally.
#define P_(X) cout << #X " = " << (X) << ", " << flush; // 'P(X)' without '\n'
#define T_ cout << "\t" << flush; // Print tab w/o newline.
#define L_ __LINE__ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_FAIL(expr) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(expr)
#define ASSERT_SAFE_PASS(expr) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(expr)
// ============================================================================
// GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------
typedef baltzo::LocalDatetime Obj;
typedef bslma::TestAllocator TestAllocator;
typedef bslx::TestInStream In;
typedef bslx::TestOutStream Out;
#define VERSION_SELECTOR 20140601
// ============================================================================
// HELPER FUNCTIONS FOR TESTING
// ----------------------------------------------------------------------------
static bool someDiff(const Obj& a, const Obj& b)
{
return a.datetimeTz() != b.datetimeTz()
|| a.timeZoneId() != b.timeZoneId();
}
// ============================================================================
// TYPE TRAITS
// ----------------------------------------------------------------------------
BSLMF_ASSERT(bslmf::IsBitwiseMoveable<Obj>::value);
BSLMF_ASSERT(bslma::UsesBslmaAllocator<Obj>::value);
// ============================================================================
// GLOBAL CONSTANTS USED FOR TESTING
// ----------------------------------------------------------------------------
// Define 'bsl::string' value long enough to ensure dynamic memory allocation.
// JSL: Do we want to move this string to the component of bsl::string itself?
// JSL: e.g., #define BSLSTL_LONG_STRING ... TBD!
#ifdef BSLS_PLATFORM_CPU_32_BIT
#define SUFFICIENTLY_LONG_STRING "123456789012345678901234567890123"
#else // 64_BIT
#define SUFFICIENTLY_LONG_STRING "12345678901234567890123456789012" \
"123456789012345678901234567890123"
#endif
BSLMF_ASSERT(sizeof SUFFICIENTLY_LONG_STRING > sizeof(bsl::string));
const char *const LONG_STRING = "a_" SUFFICIENTLY_LONG_STRING;
const char *const LONGER_STRING = "ab_" SUFFICIENTLY_LONG_STRING;
const char *const LONGEST_STRING = "abc_" SUFFICIENTLY_LONG_STRING;
// ============================================================================
// TEST APPARATUS
// ----------------------------------------------------------------------------
// JSL: REMOVE THIS after it is moved to the test allocator.
// JSL: change the name to 'TestAllocatorMonitor'.
class TestAllocatorMonitor {
// TBD
// DATA
int d_lastInUse;
int d_lastMax;
int d_lastTotal;
const bslma::TestAllocator *const d_allocator_p;
public:
// CREATORS
TestAllocatorMonitor(const bslma::TestAllocator& basicAllocator);
// TBD
~TestAllocatorMonitor();
// TBD
// ACCESSORS
bool isInUseSame() const;
// TBD
bool isInUseUp() const;
// TBD
bool isMaxSame() const;
// TBD
bool isMaxUp() const;
// TBD
bool isTotalSame() const;
// TBD
bool isTotalUp() const;
// TBD
};
// CREATORS
inline
TestAllocatorMonitor::TestAllocatorMonitor(
const bslma::TestAllocator& basicAllocator)
: d_lastInUse(basicAllocator.numBlocksInUse())
, d_lastMax(basicAllocator.numBlocksMax())
, d_lastTotal(basicAllocator.numBlocksTotal())
, d_allocator_p(&basicAllocator)
{
}
inline
TestAllocatorMonitor::~TestAllocatorMonitor()
{
}
// ACCESSORS
inline
bool TestAllocatorMonitor::isInUseSame() const
{
BSLS_ASSERT(d_lastInUse <= d_allocator_p->numBlocksInUse());
return d_allocator_p->numBlocksInUse() == d_lastInUse;
}
inline
bool TestAllocatorMonitor::isInUseUp() const
{
BSLS_ASSERT(d_lastInUse <= d_allocator_p->numBlocksInUse());
return d_allocator_p->numBlocksInUse() != d_lastInUse;
}
inline
bool TestAllocatorMonitor::isMaxSame() const
{
return d_allocator_p->numBlocksMax() == d_lastMax;
}
inline
bool TestAllocatorMonitor::isMaxUp() const
{
return d_allocator_p->numBlocksMax() != d_lastMax;
}
inline
bool TestAllocatorMonitor::isTotalSame() const
{
return d_allocator_p->numBlocksTotal() == d_lastTotal;
}
inline
bool TestAllocatorMonitor::isTotalUp() const
{
return d_allocator_p->numBlocksTotal() != d_lastTotal;
}
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
bool veryVeryVerbose = argc > 4;
bool veryVeryVeryVerbose = argc > 5;
cout << "TEST " << __FILE__ << " CASE " << test << endl;
// CONCERN: This test driver is reusable w/other, similar components.
// CONCERN: In no case does memory come from the global allocator.
TestAllocator globalAllocator(veryVeryVerbose);
bslma::Default::setGlobalAllocator(&globalAllocator);
switch (test) { case 0:
case 11: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
//: 1 The usage example provided in the component header file compiles,
//: links, and runs as shown.
//
// Plan:
//: 1 Incorporate usage example from header into test driver, remove
//: leading comment characters, and replace 'assert' with 'ASSERT'.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "USAGE EXAMPLE" << endl
<< "=============" << endl;
///Usage
///-----
// In this section we show intended usage of this component.
//
///Example 1: Creation and Use of a 'baltzo::LocalDatetime' Object
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// First, we default-construct a 'baltzo::LocalDatetime' object:
//..
baltzo::LocalDatetime localDatetime;
//..
// Next, we update the time referred to by 'localDatetime' to the New York
// time "December 25, 2009, 11:00" with the time-zone identifier set to
// "America/New_York":
//..
bdlt::Datetime datetime(2009, 12, 25, 11, 00, 00);
bdlt::DatetimeTz datetimeTz(datetime, -5 * 60); // offset is specified
// in minutes from UTC
bsl::string timeZoneId("America/New_York");
localDatetime.setDatetimeTz(datetimeTz);
localDatetime.setTimeZoneId(timeZoneId);
ASSERT(datetimeTz == localDatetime.datetimeTz());
ASSERT(timeZoneId == localDatetime.timeZoneId());
//..
// Now, we change the time-zone identifier to another string, for example
// "Europe/Berlin":
//..
bsl::string anotherTimeZoneId("Europe/Berlin");
localDatetime.setTimeZoneId(anotherTimeZoneId);
ASSERT(datetimeTz == localDatetime.datetimeTz());
ASSERT(anotherTimeZoneId == localDatetime.timeZoneId());
//..
// Finally, we stream 'localDatetime' to 'bsl::cout':
//..
bsl::cout << localDatetime << bsl::endl;
//..
// This statement produces the following output on 'stdout':
//..
// [ 25DEC2009_11:00:00.000-0500 "Europe/Berlin" ]
//..
} break;
case 10: {
// --------------------------------------------------------------------
// BSLX STREAMING
// Ensure that we can serialize the value of any object of the class
// via its 'bdexStreamOut' method, and then deserialize that value
// back into any object of the class, via its 'bdexStreamIn' method.
//
// Concerns:
//: 1 The signature and return type of 'bdexStreamOut', 'bdexStreamIn',
//: and 'maxSupportedBdexVersion' are standard.
//:
//: 2 The 'maxSupportedBdexVersion' method returns the expected value.
//:
//: 3 For all supported versions, any sequence of valid values can be
//: externalized using the 'bdexStreamOut' method.
//:
//: 4 For all supported versions, any valid value on the wire can
//: unexternalized by 'bdexStreamIn' into an object having that
//: value, irrespective of the initial value of the object.
//:
//: 5 Both stream methods always return a reference with modifiable
//: access to the specified 'stream'.
//:
//: 6 For both stream methods, the specified 'stream' is left in an
//: invalid state, with no other effect, if the specified 'version'
//: is outside the range '[1 .. maxSupportedBdexVersion]'.
//:
//: 7 Both stream methods must return with no effect, if the specified
//: 'stream' is invalid on entry.
//:
//: 8 If 'stream' becomes invalid during an invocation of
//: 'bdexStreamIn', the object is left in a valid state, but possibly
//: modified, state.
//:
//: 9 If an exception is thrown during a call to the 'bdexStreamIn'
//: method, the object is left in an unspecified but valid state.
//: In no event is memory leaked.
//:
//:10 The wire format of this object is be the concatenation of the
//: wire formats of its constituent attributes, in the order of their
//: declaration. (TBD)
//:
//:11 The specified 'version' is not part of the wire format generated
//: by the 'bdexStreamOut' method, and is not expected by the
//: 'bdexStreamIn' method.
//:
//:12 The 'bdexStreamIn' method leaves the object unchanged, when the
//: specified 'stream' is empty.
//:
//:13 The 'bdexStreamIn' method leaves the object in a valid but
//: unspecified state, when the specified 'stream' contains
//: well-formed data that violates object constraints.
//:
//:14 The 'bdexStreamIn' method leaves the object in a valid (but
//: unspecified) state when the specified 'stream' contains valid but
//: incomplete data.
//:
//:15 QoI: No memory is allocated by the object by the 'bdexStreamOut'
//: method.
//:
//:16 QoI: All memory allocated by the 'bdexStreamIn' method is from
//: the object allocator.
//
// Plan:
//: 1 Use the addresses of the (templated) 'bdexStreamIn' and
//: 'bdexStreamOut', instantiated using the 'bslx::TestInStream' and
//: 'bslx::TestOutStream types, respectively, to initialize
//: member-function pointers each having the standard signature and
//: return type for the for these member-functions. Use the
//: 'maxSupportedBdexVersion' static function to initialize a
//: function pointer having the standard signature and return type
//: for that function. (C-1)
//:
//: 2 Compare the return value of the 'maxSupportedBdexVersion' to the
//: expected value for this implementation. (C-2)
//:
//: 3 In test cases with both valid and invalid input, compare the
//: return values of 'bdexStreamIn' and 'bdexStreamOut' methods with
//: their specified 'stream'. (C-5)
//:
//: 3 Specify a set 'S' of unique object values with substantial and
//: varied differences. For each value in 'S', construct an object
//: 'x' along with a sequence of similarly constructed duplicates
//: 'x1, x2, ..., xN'. Attempt to affect every aspect of white-box
//: state by altering each 'xi' in a unique way. Let the union of
//: all such objects be the set 'T', programmatically represented by
//: the 'VALUES' array of objects.
//:
//: 4 Using all combinations of '(u, v)' in 'T X T', stream-out the
//: value of u into a buffer and stream it back into (an independent
//: object of) 'v', and assert that 'u == v'. (C-3) Compare the
//: return value of the each 'bdexStreamIn' and 'bdexStreamOut'
//: method call with the supplied 'stream'. (C-4)
//:
//: 5 Throughout this test case, wrap 'bdexStreamIn' calls with the
//: standard 'BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN' and
//: 'BSLX_TESTINSTREAM_EXCEPTION_TEST_END' macros to confirm
//: exception neutrality. (C-7)
//:
//: 6 For each 'x' in 'T', attempt to stream into (a temporary copy of)
//: 'x' from an empty (but valid) and then invalid stream. Verify
//: after each try that the object is unchanged and that the stream
//: is invalid. (C-7, C-12) For each 'x' in 'T' attempt to stream
//: 'x' into an initially invalid stream. Check that the stream is
//: unchanged. For each stream operation (both in and out), compare
//: the return value of the each 'bdexStreamIn' and 'bdexStreamOut'
//: method call with the supplied 'stream'. (C-5)
//:
//: 7 Write three distinct objects to an output stream buffer of total
//: length 'N'. For each partial stream length from 0 to 'N - 1',
//: construct a truncated input stream and attempt to read into
//: objects initialized with distinct values. Verify values of
//: objects that are either successfully modified or left entirely
//: unmodified, and that the stream became invalid immediately after
//: the first incomplete read. Finally ensure that each object
//: streamed into is in some valid state by creating a copy and then
//: assigning a known value to that copy; allow the original object
//: to leave scope without further modification, so that the
//: destructor asserts internal object invariants appropriately.
//: (C-14)
//:
//: 8 TBD: Iteratively write three distinct objects to an output
//: stream buffer, instructing the output stream to make the next
//: output operation invalid before one of the calls to the
//: object's 'bdexStreamOut' method. On each iteration, change the
//: point at which the invalid operation is introduced. In each
//: case, the reconstruction of the object from the stream must
//: return normally up to the point at which the error was introduced
//: (known) and, after that point, an invalid stream, with valid
//: though unspecified objects. (C-8)
//:
//: 9 For every supported version, check that an object can be streamed
//: and reconstructed (streamed) successfully. For version numbers
//: below and above the supported range (i.e., 0 and
//: 'maxBdexVersion() + 1), confirm that these operations have no
//: effect and the initially valid stream is left in an invalid
//: state. (C-6)
//:
//:10 For every object 'x' in 'T' create two outstream: one via the
//: object's 'bdexStreamOut' method, and the other by explicitly
//: outstreaming each constituent attribute (in order of
//: declaration). (C-10) Confirm that the outstream created via
//: individual attributes can be used to reconstruct the object, with
//: no data left unread. This accounts for all of the information
//: conveyed from the original to the duplicate object; thus, no
//: version information was sent. (C-11).
//:
//:11 This class imposes no restrictions on the values of its
//: constituent attributes. If an instream contains data that is
//: well-formed but in violation of object constraints, the
//: 'bdexStreamIn' method of that constituent attribute will fail and
//: leave this object in some valid, though unspecified, state.
//: (C-13)
//:
//:12 In each test using the 'bdexStreamIn' or 'bdexStreamOut' method
//: install 'bslma::TestAllocator' object as the default allocator.
//: After each 'bdexStreamIn' and 'bdexStreamOut' invocation check
//: that the default allocator was not used. Additionally, after
//: 'bdexStreamOut' invocation, check that the object allocator was
//: not used. (C15, C-16)
//
// Testing:
// static int maxSupportedBdexVersion();
// STREAM& bdexStreamIn(STREAM& stream, int version);
// STREAM& bdexStreamOut(STREAM& stream, int version) const;
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "BSLX STREAMING" << endl
<< "==============" << endl;
if (verbose) cout <<
"\nAssign the addresses of the 'bdex' methods to variables."
<< endl;
{
// Verify that the signatures and return types are standard.
typedef In& (Obj::*funcInPtr) (In&, int);
typedef Out& (Obj::*funcOutPtr)(Out&, int) const;
typedef int (*funcVerPtr)(int);
funcInPtr fIn = &Obj::bdexStreamIn<In>;
funcOutPtr fOut = &Obj::bdexStreamOut<Out>;
funcVerPtr fVer = Obj::maxSupportedBdexVersion;
// quash potential compiler warnings
(void)fIn;
(void)fOut;
(void)fVer;
}
if (verbose) cout << "\nTesting 'maxSupportedBdexVersion()'." << endl;
{
if (veryVerbose) cout << "\tusing object syntax:" << endl;
const Obj X;
ASSERT(1 == X.maxSupportedBdexVersion(VERSION_SELECTOR));
if (veryVerbose) cout << "\tusing class method syntax:" << endl;
ASSERT(1 == Obj::maxSupportedBdexVersion(VERSION_SELECTOR));
}
// ------------------------------------
// Values used in several stream tests.
// ------------------------------------
const int MAX_VERSION = Obj::maxSupportedBdexVersion(VERSION_SELECTOR);
bdlt::DatetimeTz defaultDtz;
bdlt::Datetime smallDt; smallDt.addMilliseconds(1);
bdlt::Datetime someDt(2011, 5, 3, 15, 32);
bdlt::Datetime largeDt(9999, 12, 31, 23, 59, 59, 999);
bdlt::DatetimeTz smallDtz(smallDt, -(24 * 60 - 1));
bdlt::DatetimeTz someDtz( someDt, -( 4 * 60 - 0));
bdlt::DatetimeTz largeDtz(largeDt, (24 * 60 - 1));
const char *defaultTzId = "";
const char *smallTzId = "a";
const char *largeTzId = LONGEST_STRING;
const Obj V0(defaultDtz, defaultTzId);
const Obj V1( smallDtz, defaultTzId);
const Obj V2( someDtz, defaultTzId);
const Obj V3( largeDtz, defaultTzId);
const Obj V4(defaultDtz, smallTzId);
const Obj V5( smallDtz, smallTzId);
const Obj V6( someDtz, smallTzId);
const Obj V7( largeDtz, smallTzId);
const Obj V8(defaultDtz, largeTzId);
const Obj V9(defaultDtz, largeTzId);
const Obj VA( someDtz, largeTzId);
const Obj VB( someDtz, largeTzId);
const Obj VALUES[] =
{ V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, VA, VB };
const int NUM_VALUES = sizeof VALUES / sizeof *VALUES;
if (verbose) cout << "\nDirect initial trial of 'streamOut' and"
" (valid) 'streamIn' functionality." << endl;
//TBD: What does this *test*?
{
for (int version = 1; version < MAX_VERSION; ++version) {
if (veryVerbose) { T_ T_ P(version) }
bslma::TestAllocator testAllocator("tA", veryVeryVeryVerbose);
const Obj X(bdlt::DatetimeTz(bdlt::Datetime(2011, 5, 3, 15),
-4 * 60),
"a_" SUFFICIENTLY_LONG_STRING,
&testAllocator);
if (veryVerbose) { cout << "\t Value being streamed: ";
P(X); }
Out out(1);
ASSERT(&out == &(X.bdexStreamOut(out, version)));
const char *const OD = out.data();
const int LOD = out.length();
In in(OD, LOD); ASSERT(in); ASSERT(!in.isEmpty());
Obj t(&testAllocator); ASSERT(X != t);
if (veryVerbose) { cout << "\tValue being overwritten: ";
P(t); }
ASSERT(X != t);
t.bdexStreamIn(in, version);
ASSERT(in);
ASSERT(in.isEmpty());
if (veryVerbose) { cout << "\t Value after overwrite: ";
P(t); }
ASSERT(X == t);
}
}
if (verbose) cout << "\tOn valid, non-empty stream data." << endl;
{
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard guard(&da);
for (int version = 1; version < MAX_VERSION; ++version) {
if (veryVerbose) { T_ T_ P(version) }
for (int ui = 0; ui < NUM_VALUES; ++ui) {
if (veryVerbose) { T_ T_ P(ui) }
bslma::TestAllocator oau("oau", veryVeryVeryVerbose);
Obj mU(VALUES[ui], &oau); const Obj& U = mU;
const Obj Z(VALUES[ui], &oau);
Out out(1);
TestAllocatorMonitor oaum(oau), dam(da);
LOOP_ASSERT(ui, &out == &(U.bdexStreamOut(out, version)));
LOOP_ASSERT(ui, oaum.isTotalSame());
LOOP_ASSERT(ui, dam.isTotalSame());
const char *const OD = out.data();
const int LOD = out.length();
In in(OD, LOD);
LOOP_ASSERT(U, in);
LOOP_ASSERT(U, !in.isEmpty());
// Verify that each new value overwrites every old value
// and that the input stream is emptied, but remains valid.
for (int vi = 0; vi < NUM_VALUES; ++vi) {
if (veryVerbose) { T_ T_ P(vi) }
bslma::TestAllocator oav("oav", veryVeryVeryVerbose);
Obj mV(VALUES[vi], &oav); const Obj& V = mV;
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oav) {
BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) {
in.reset();
TestAllocatorMonitor dam(da);
LOOP_ASSERT(vi,
&in == &(mV.bdexStreamIn(in,
version)));
LOOP3_ASSERT(version, ui, vi, dam.isTotalSame());
} BSLX_TESTINSTREAM_EXCEPTION_TEST_END
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP3_ASSERT(version, ui, vi, U == Z);
LOOP3_ASSERT(version, ui, vi, V == Z);
LOOP3_ASSERT(version, ui, vi, in);
LOOP3_ASSERT(version, ui, vi, in.isEmpty());
}
}
}
}
if (verbose) cout << "\tOn empty and invalid input streams." << endl;
{
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard guard(&da);
Out out(1);
const char *const OD = out.data();
const int LOD = out.length();
ASSERT(0 == LOD);
for (int version = 1; version < MAX_VERSION; ++version) {
if (veryVerbose) { T_ T_ P(version) }
for (int i = 0; i < NUM_VALUES; ++i) {
In in(OD, LOD);
LOOP_ASSERT(i, in);
LOOP_ASSERT(i, in.isEmpty());
// Ensure that reading from an empty or invalid input
// stream leaves the stream invalid and the target object
// unchanged.
const Obj X(VALUES[i]); Obj t1(X), t2(X);
LOOP_ASSERT(i, X == t1);
LOOP_ASSERT(i, X == t2);
BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) {
in.reset();
LOOP_ASSERT(i, in);
// read from empty
TestAllocatorMonitor dam1(da);
LOOP_ASSERT(i, &in == &(t1.bdexStreamIn(in, version)));
LOOP_ASSERT(i, dam1.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, X == t1);
// read from (the now) invalid stream
TestAllocatorMonitor dam2(da);
LOOP_ASSERT(i, &in == &(t2.bdexStreamIn(in, version)));
LOOP_ASSERT(i, dam2.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, X == t2);
} BSLX_TESTINSTREAM_EXCEPTION_TEST_END
}
}
}
if (verbose) cout << "\tOn invalid out streams." << endl;
{
for (int version = 1; version < MAX_VERSION; ++version) {
if (veryVerbose) { T_ T_ P(version) }
for (int i = 0; i < NUM_VALUES; ++i) {
if (veryVerbose) { T_ T_ P(i) }
bslma::TestAllocator oa("oa", veryVeryVeryVerbose);
bslma::TestAllocator da("default",
veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard guard(&da);
Obj mU(VALUES[i], &oa); const Obj& U = mU;
Out out(1);
out.invalidate();
LOOP_ASSERT(i, !out);
const void *data = out.data();
bsl::size_t length = out.length();
TestAllocatorMonitor oam(oa), dam(da);
LOOP2_ASSERT(version, i, &out ==
&(U.bdexStreamOut(out, version)));
LOOP2_ASSERT(version, i, dam.isTotalSame());
LOOP2_ASSERT(version, i, oam.isTotalSame());
LOOP2_ASSERT(version, i, !out);
LOOP2_ASSERT(version, i, data == out.data());
LOOP2_ASSERT(version, i, length == out.length());
}
}
}
if (verbose) cout << "\tOn incomplete (but otherwise valid) data."
<< endl;
{
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard guard(&da);
// Each object has unique attributes w.r.t. objects to be compared
// (e.g., W1, X1, Y1). Note that 'smallDtz', 'someDtz', and
// 'largeDtz' differ in each constituent attribute and that each
// 'timeZoneId' is unique. Thus, partially constructed 'tn'
// objects will match their target value only when 'tn' is
// completed assembled.
const int VERSION = 1;
const Obj W1(smallDtz, "");
const Obj X1( someDtz, "a");
const Obj Y1(largeDtz, "bb");
const Obj W2(largeDtz, "ccc");
const Obj X2(smallDtz, "dddd");
const Obj Y2( someDtz, "eeeee");
const Obj W3( someDtz, "ffffff");
const Obj X3(largeDtz, "hhhhhhh");
const Obj Y3(smallDtz, "iiiiiiii");
Out out(1);
X1.bdexStreamOut(out, VERSION); const int LOD1 = out.length();
X2.bdexStreamOut(out, VERSION); const int LOD2 = out.length();
X3.bdexStreamOut(out, VERSION); const int LOD = out.length();
const char *const OD = out.data();
for (int i = 0; i < LOD; ++i) {
In in(OD, i);
BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) {
in.reset();
LOOP_ASSERT(i, in);
LOOP_ASSERT(i, !i == in.isEmpty());
Obj t1(W1), t2(W2), t3(W3);
if (i < LOD1) {
TestAllocatorMonitor dam1(da);
LOOP_ASSERT(i, &in == &(t1.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam1.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, someDiff(X1, t1));
LOOP_ASSERT(i, bdlt::DatetimeTz::isValid(
t1.datetimeTz().dateTz().localDate(),
t1.datetimeTz().offset()));
TestAllocatorMonitor dam2(da);
LOOP_ASSERT(i, &in == &(t2.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam2.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, W2 == t2);
TestAllocatorMonitor dam3(da);
LOOP_ASSERT(i, &in == &(t3.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam3.isTotalSame());
LOOP_ASSERT(i, !in); LOOP_ASSERT(i, W3 == t3);
}
else if (i < LOD2) {
TestAllocatorMonitor dam1(da);
LOOP_ASSERT(i, &in == &(t1.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam1.isTotalSame());
LOOP_ASSERT(i, in);
LOOP_ASSERT(i, X1 == t1);
TestAllocatorMonitor dam2(da);
LOOP_ASSERT(i, &in == &(t2.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam2.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, someDiff(X2, t2));
LOOP_ASSERT(i, bdlt::DatetimeTz::isValid(
t2.datetimeTz().dateTz().localDate(),
t2.datetimeTz().offset()));
TestAllocatorMonitor dam3(da);
LOOP_ASSERT(i, &in == &(t3.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam3.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, W3 == t3);
}
else {
TestAllocatorMonitor dam1(da);
LOOP_ASSERT(i, &in == &(t1.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam1.isTotalSame());
LOOP_ASSERT(i, in);
LOOP_ASSERT(i, X1 == t1);
TestAllocatorMonitor dam2(da);
LOOP_ASSERT(i, &in == &(t2.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam2.isTotalSame());
LOOP_ASSERT(i, in);
LOOP_ASSERT(i, X2 == t2);
TestAllocatorMonitor dam3(da);
LOOP_ASSERT(i, &in == &(t3.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, dam3.isTotalSame());
LOOP_ASSERT(i, !in);
LOOP_ASSERT(i, someDiff(X3, t3));
LOOP_ASSERT(i, bdlt::DatetimeTz::isValid(
t3.datetimeTz().dateTz().localDate(),
t3.datetimeTz().offset()));
}
// Check the validity of the target objects, 'tn', with some
// (light) usage (assignment).
LOOP_ASSERT(i, Y1 != t1);
t1 = Y1; LOOP_ASSERT(i, Y1 == t1);
LOOP_ASSERT(i, Y2 != t2);
t2 = Y2; LOOP_ASSERT(i, Y2 == t2);
LOOP_ASSERT(i, Y3 != t3);
t3 = Y3; LOOP_ASSERT(i, Y3 == t3);
} BSLX_TESTINSTREAM_EXCEPTION_TEST_END
}
}
#if TBD // Check 'makeNextInvalid' method.
if (verbose) cout << "\tOn complete data in an invalidated stream."
<< endl;
{
// Each object unique has unique attributes w.r.t. objects to be
// compared (e.g., W1, X1, Y1). Note that 'smallDtz', 'someDtz',
// and 'largeDtz' differ in each constituent attribute and that
// each 'timeZoneId' is unique. Thus, partially constructed 'tn'
// objects will match their target value only 'tn' is completed
// assembled.
const int VERSION = 1;
const Obj W1(smallDtz, "");
const Obj X1( someDtz, "a");
const Obj Y1(largeDtz, "bb");
const Obj W2(largeDtz, "ccc");
const Obj X2(smallDtz, "dddd");
const Obj Y2( someDtz, "eeeee");
const Obj W3( someDtz, "ffffff");
const Obj X3(largeDtz, "hhhhhhh");
const Obj Y3(smallDtz, "iiiiiiii");
Out out(1);
X1.bdexStreamOut(out, VERSION);
ASSERT(&out == &(X1.bdexStreamOut(out, VERSION)));
ASSERT(&out == &(X2.bdexStreamOut(out, VERSION)));
out.makeNextInvalid();
ASSERT(&out == &(X3.bdexStreamOut(out, VERSION)));
In in(out.data(), out.length());
BSLX_TESTINSTREAM_EXCEPTION_TEST_BEGIN(in) {
Obj t1(W1), t2(W2), t3(W3);
ASSERT(&in == &(t1.bdexStreamIn(in, VERSION)));
ASSERT( out);
ASSERT(&in == &(t2.bdexStreamIn(in, VERSION)));
ASSERT( out);
ASSERT(&in == &(t3.bdexStreamIn(in, VERSION)));
ASSERT(!out);
// Check the validity of the target objects, 'tn', with some
// (light) usage (assignment).
ASSERT(Y1 != t1);
t1 = Y1; ASSERT(Y1 == t1);
ASSERT(Y2 != t2);
t2 = Y2; ASSERT(Y2 == t2);
ASSERT(Y3 != t3);
t3 = Y3; ASSERT(Y3 == t3);
} BSLX_TESTINSTREAM_EXCEPTION_TEST_END
}
#endif
if (verbose) cout << "\tOn invalid versions" << endl;
{
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
const Obj W(&oa); // default value
const Obj X(someDtz, "A", &oa); // original (control) value
const Obj Y(someDtz, "B", &oa); // new (streamed-out) value
if (veryVerbose) cout << "\t\tGood Version on instream" << endl;
{
const char version = 1;
Out out(1);
out.putString(Y.timeZoneId()); // 1. Stream out "new"
// value
Y.datetimeTz().bdexStreamOut(out, 1); // 2. Stream out "new"
// value
const char *const OD = out.data();
const int LOD = out.length();
Obj t(X); ASSERT(W != t); ASSERT(X == t); ASSERT(Y != t);
In in(OD, LOD); ASSERT(in);
TestAllocatorMonitor dam(da);
ASSERT(&in == &(t.bdexStreamIn(in, version)));
ASSERT(dam.isTotalSame());
ASSERT(in);
ASSERT(W != t); ASSERT(X != t); ASSERT(Y == t);
}
if (veryVerbose) cout << "\t\tBad versions on instream." << endl;
{
const char version = 0; // too small ('version' must be >= 1)
Out out(1);
Y.datetimeTz().bdexStreamOut(out, 1); // 1. Stream out "new"
// value
out.putString(Y.timeZoneId()); // 2. Stream out "new"
// value
const char *const OD = out.data();
const int LOD = out.length();
Obj t(X); ASSERT(W != t); ASSERT(X == t); ASSERT(Y != t);
In in(OD, LOD); ASSERT(in);
in.setQuiet(!veryVerbose);
TestAllocatorMonitor dam(da);
ASSERT(&in == &(t.bdexStreamIn(in, version)));
ASSERT(dam.isTotalSame());
ASSERT(!in);
ASSERT(W != t); ASSERT(X == t); ASSERT(Y != t);
}
{
const char version = 2 ; // too large (current version is 1)
Out out(1);
Y.datetimeTz().bdexStreamOut(out, 1); // 1. Stream out "new"
// value
out.putString(Y.timeZoneId()); // 2. Stream out "new"
// value
const char *const OD = out.data();
const int LOD = out.length();
Obj t(X); ASSERT(W != t); ASSERT(X == t); ASSERT(Y != t);
In in(OD, LOD); ASSERT(in);
in.setQuiet(!veryVerbose);
TestAllocatorMonitor dam(da);
ASSERT(&in == &(t.bdexStreamIn(in, version)));
ASSERT(dam.isTotalSame());
ASSERT(!in);
ASSERT(W != t); ASSERT(X == t); ASSERT(Y != t);
}
if (veryVerbose) cout << "\t\tGood Version on outstream" << endl;
{
const char version = 1;
bslma::TestAllocator sa("scratch", veryVeryVeryVerbose);
Out out(1, &sa);
ASSERT(out);
ASSERT(0 == out.length());
TestAllocatorMonitor oam(oa), dam(da);
ASSERT(&out == &(Y.bdexStreamOut(out, version)));
ASSERT(dam.isTotalSame());
ASSERT(oam.isTotalSame());
ASSERT(out);
ASSERT(0 != out.length());
}
if (veryVerbose) cout << "\t\tBad versions on instream." << endl;
{
const char version = 0; // too small ('version' must be >= 1)
Out out(1);
ASSERT(out);
ASSERT(0 == out.length());
TestAllocatorMonitor oam(oa), dam(da);
ASSERT(&out == &(Y.bdexStreamOut(out, version)));
ASSERT(dam.isTotalSame());
ASSERT(oam.isTotalSame());
ASSERT(!out);
ASSERT(0 == out.length());
}
{
const char version = 2 ; // too large, current max version is 1
Out out(1);
ASSERT(out);
ASSERT(0 == out.length());
TestAllocatorMonitor oam(oa), dam(da);
ASSERT(&out == &(Y.bdexStreamOut(out, version)));
ASSERT(dam.isTotalSame());
ASSERT(oam.isTotalSame());
ASSERT(!out);
ASSERT(0 == out.length());
}
}
if (verbose) cout << "\nWire format direct tests." << endl;
{
for (int i = 0; i < NUM_VALUES; ++i) {
Obj mX(VALUES[i]); const Obj& X = mX;
const int VERSION = 1;
if (veryVerbose) { T_ P(X) }
Out outO(1); X.bdexStreamOut(outO, VERSION);
Out outA(1); outA.putString(X.timeZoneId());
X.datetimeTz().bdexStreamOut(outA, VERSION);
LOOP_ASSERT(i, outA.length() == outO.length());
LOOP_ASSERT(i, 0 == memcmp(outO.data(),
outA.data(),
outA.length()));
Obj mY; const Obj& Y = mY;
In in(outA.data(), outA.length());
ASSERT(&in == &(mY.bdexStreamIn(in, VERSION)));
LOOP_ASSERT(i, in.isEmpty());
LOOP_ASSERT(i, X == Y);
}
}
} break;
case 9: {
// --------------------------------------------------------------------
// COPY-ASSIGNMENT OPERATOR
// Ensure that we can assign the value of any object of the class to
// any object of the class, such that the two objects subsequently
// have the same value.
//
// Concerns:
//: 1 The assignment operator can change the value of any modifiable
//: target object to that of any source object.
//:
//: 2 The allocator address held by the target object is unchanged.
//:
//: 3 Any memory allocation is from the target object's allocator.
//:
//: 4 The signature and return type are standard.
//:
//: 5 The reference returned is to the target object (i.e., '*this').
//:
//: 6 The value of the source object is not modified.
//:
//: 7 The allocator address held by the source object is unchanged.
//:
//: 8 QoI: Assigning a source object having the default-constructed
//: value allocates no memory.
//:
//: 9 Any memory allocation is exception neutral.
//:
//:10 Assigning an object to itself behaves as expected (alias-safety).
//:
//:11 Every object releases any allocated memory at destruction.
//
// Plan:
//: 1 Use the address of 'operator=' to initialize a member-function
//: pointer having the appropriate signature and return type for the
//: copy-assignment operator defined in this component. (C-4)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the
//: default allocator (note that a ubiquitous test allocator is
//: already installed as the global allocator).
//:
//: 3 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values (one per row) in
//: terms of their individual attributes, including (a) first, the
//: default value, (b) boundary values corresponding to every range
//: of values that each individual attribute can independently
//: attain, and (c) values that should require allocation from each
//: individual attribute that can independently allocate memory.
//:
//: 2 Additionally, provide a (tri-valued) column, 'MEM', indicating
//: the expectation of memory allocation for all typical
//: implementations of individual attribute types: ('Y') "Yes",
//: ('N') "No", or ('?') "implementation-dependent".
//:
//: 4 For each row 'R1' (representing a distinct object value, 'V') in
//: the table described in P-3: (C-1..2, 5..8, 11)
//:
//: 1 Use the value constructor and a "scratch" allocator to create
//: two 'const' 'Obj', 'Z' and 'ZZ', each having the value 'V'.
//:
//: 2 Execute an inner loop that iterates over each row 'R2'
//: (representing a distinct object value, 'W') in the table
//: described in P-3:
//:
//: 3 For each of the iterations (P-4.2): (C-1..2, 5..8, 11)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable
//: 'Obj', 'mX', having the value 'W'.
//:
//: 3 Assign 'mX' from 'Z' in the presence of injected exceptions
//: (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros).
//:
//: 4 Verify that the address of the return value is the same as
//: that of 'mX'. (C-5)
//:
//: 5 Use the equality-comparison operator to verify that: (C-1, 6)
//:
//: 1 The target object, 'mX', now has the same value as that of
//: 'Z'. (C-1)
//:
//: 2 'Z' still has the same value as that of 'ZZ'. (C-6)
//:
//: 6 Use the 'allocator' accessor of both 'mX' and 'Z' to verify
//: that the respective allocator addresses held by the target
//: and source objects are unchanged. (C-2, 7)
//:
//: 7 Use the appropriate test allocators to verify that:
//: (C-8, 11)
//:
//: 1 For an object that (a) is initialized with a value that did
//: NOT require memory allocation, and (b) is then assigned a
//: value that DID require memory allocation, the target object
//: DOES allocate memory from its object allocator only
//: (irrespective of the specific number of allocations or the
//: total amount of memory allocated); also cross check with
//: what is expected for 'mX' and 'Z'.
//:
//: 2 An object that is assigned a value that did NOT require
//: memory allocation, does NOT allocate memory from its object
//: allocator; also cross check with what is expected for 'Z'.
//:
//: 3 No additional memory is allocated by the source object.
//: (C-8)
//:
//: 4 All object memory is released when the object is destroyed.
//: (C-11)
//:
//: 5 Repeat steps similar to those described in P-2 except that, this
//: time, there is no inner loop (as in P-4.2); instead, the source
//: object, 'Z', is a reference to the target object, 'mX', and both
//: 'mX' and 'ZZ' are initialized to have the value 'V'. For each
//: row (representing a distinct object value, 'V') in the table
//: described in P-3: (C-9)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable 'Obj'
//: 'mX'; also use the value constructor and a distinct "scratch"
//: allocator to create a 'const' 'Obj' 'ZZ'.
//:
//: 3 Let 'Z' be a reference providing only 'const' access to 'mX'.
//:
//: 4 Assign 'mX' from 'Z' in the presence of injected exceptions
//: (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros).
//: (C-9)
//:
//: 5 Verify that the address of the return value is the same as that
//: of 'mX'.
//:
//: 6 Use the equality-comparison operator to verify that the
//: target object, 'mX', still has the same value as that of 'ZZ'.
//:
//: 7 Use the 'allocator' accessor of 'mX' to verify that it is still
//: the object allocator.
//:
//: 8 Use the appropriate test allocators to verify that:
//:
//: 1 Any memory that is allocated is from the object allocator.
//:
//: 2 No additional (e.g., temporary) object memory is allocated
//: when assigning an object value that did NOT initially require
//: allocated memory.
//:
//: 3 All object memory is released when the object is destroyed.
//:
//: 6 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-3)
//
// Testing:
// operator=(const baltzo::LocalTimeDescriptor& rhs);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "COPY-ASSIGNMENT OPERATOR" << endl
<< "========================" << endl;
if (verbose) cout <<
"\nAssign the address of the operator to a variable." << endl;
{
typedef Obj& (Obj::*operatorPtr)(const Obj&);
// Verify that the signature and return type are standard.
operatorPtr operatorAssignment = &Obj::operator=;
(void)operatorAssignment; // quash potential compiler warning
}
if (verbose) cout <<
"\nCreate a test allocator and install it as the default." << endl;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) cout <<
"\nUse a table of distinct object values and expected memory usage."
<< endl;
bdlt::DatetimeTz defaultDtz;
bdlt::Datetime smallDt; smallDt.addMilliseconds(1);
bdlt::Datetime someDt(2011, 5, 3, 15, 32);
bdlt::Datetime largeDt(9999, 12, 31, 23, 59, 59, 999);
bdlt::DatetimeTz smallDtz(smallDt, -(24 * 60 - 1));
bdlt::DatetimeTz someDtz( someDt, -( 4 * 60 - 0));
bdlt::DatetimeTz largeDtz(largeDt, (24 * 60 - 1));
const char *defaultTzId = "";
const char *smallTzId = "a";
const char *largeTzId = LONGEST_STRING;
const struct {
int d_line; // source line number
char d_mem; // expected allocation: 'Y', 'N', '?'
bdlt::DatetimeTz *d_datetimeTz;
const char *d_timeZoneId;
} DATA[] = {
//LINE MEM DTTZ TZID
//---- --- ----------- -----------
// default (must be first)
{ L_, 'N', &defaultDtz, defaultTzId },
// 'datetimeTz'
{ L_, 'N', &smallDtz, defaultTzId },
{ L_, 'N', &someDtz, defaultTzId },
{ L_, 'N', &largeDtz, defaultTzId },
// 'timeZoneId'
{ L_, '?', &defaultDtz, smallTzId },
{ L_, 'Y', &defaultDtz, largeTzId },
// other
{ L_, '?', &someDtz, smallTzId },
{ L_, 'Y', &someDtz, largeTzId },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
bool anyObjectMemoryAllocatedFlag = false; // We later check that
// this test allocates
// some object memory.
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const char MEMSRC1 = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ1 = *DATA[ti].d_datetimeTz;
const char *const TZID1 = DATA[ti].d_timeZoneId;
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
const Obj Z(DTTZ1, TZID1, &scratch);
const Obj ZZ(DTTZ1, TZID1, &scratch);
if (veryVerbose) { T_ P_(LINE1) P_(Z) P(ZZ) }
// Ensure the first row of the table contains the
// default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
LOOP3_ASSERT(LINE1, Obj(), Z, Obj() == Z);
firstFlag = false;
}
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const char MEMDST2 = DATA[tj].d_mem;
const bdlt::DatetimeTz& DTTZ2 = *DATA[tj].d_datetimeTz;
const char *const TZID2 = DATA[tj].d_timeZoneId;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
{
Obj mX(DTTZ2, TZID2, &oa); const Obj& X = mX;
if (veryVerbose) { T_ P_(LINE2) P(X) }
LOOP4_ASSERT(LINE1, LINE2, Z, X,
(Z == X) == (LINE1 == LINE2));
TestAllocatorMonitor oam(oa), sam(scratch);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj *mR = &(mX = Z);
LOOP4_ASSERT(LINE1, LINE2, Z, X, Z == X);
LOOP4_ASSERT(LINE1, LINE2, mR, &mX, mR == &mX);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP4_ASSERT(LINE1, LINE2, ZZ, Z, ZZ == Z);
LOOP4_ASSERT(LINE1, LINE2, &oa, X.allocator(),
&oa == X.allocator());
LOOP4_ASSERT(LINE1, LINE2, &scratch, Z.allocator(),
&scratch == Z.allocator());
if ('N' == MEMDST2 && 'Y' == MEMSRC1) {
LOOP2_ASSERT(LINE1, LINE2, oam.isInUseUp());
}
else if ('Y' == MEMDST2) {
LOOP2_ASSERT(LINE1, LINE2, oam.isInUseSame());
}
// Record if some object memory was allocated.
anyObjectMemoryAllocatedFlag |= !!oa.numBlocksInUse();
LOOP2_ASSERT(LINE1, LINE2, sam.isInUseSame());
LOOP2_ASSERT(LINE1, LINE2, 0 == da.numBlocksTotal());
}
// Verify all memory is released on object destruction.
LOOP3_ASSERT(LINE1, LINE2, oa.numBlocksInUse(),
0 == oa.numBlocksInUse());
}
// self-assignment
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
{
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mX(DTTZ1, TZID1, &oa);
const Obj ZZ(DTTZ1, TZID1, &scratch);
const Obj& Z = mX;
LOOP3_ASSERT(LINE1, ZZ, Z, ZZ == Z);
TestAllocatorMonitor oam(oa), sam(scratch);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj *mR = &(mX = Z);
LOOP3_ASSERT(LINE1, ZZ, Z, ZZ == Z);
LOOP3_ASSERT(LINE1, mR, &mX, mR == &mX);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP3_ASSERT(LINE1, &oa, Z.allocator(), &oa == Z.allocator());
LOOP_ASSERT(LINE1, oam.isInUseSame());
LOOP_ASSERT(LINE1, sam.isInUseSame());
LOOP_ASSERT(LINE1, 0 == da.numBlocksTotal());
}
// Verify all object memory is released on destruction.
LOOP2_ASSERT(LINE1, oa.numBlocksInUse(), 0 == oa.numBlocksInUse());
}
// Double check that some object memory was allocated.
ASSERT(anyObjectMemoryAllocatedFlag);
} break;
case 8: {
// --------------------------------------------------------------------
// SWAP MEMBER AND FREE FUNCTIONS
// Ensure that, when member and free 'swap' are implemented, we can
// exchange the values of any two objects that use the same
// allocator.
//
// Concerns:
//: 1 Both functions exchange the values of the (two) supplied objects.
//:
//: 2 The common object allocator address held by both objects is
//: unchanged.
//:
//: 3 Neither function allocates memory from any allocator.
//:
//: 4 Both functions have standard signatures and return types.
//:
//: 5 Using either function to swap an object with itself does not
//: affect the value of the object (alias-safety).
//:
//: 6 The free 'swap' function is discoverable through ADL (Argument
//: Dependent Lookup).
//:
//: 7 QoI: Asserted precondition violations are detected when enabled.
//
// Plan:
//: 1 Use the addresses of the 'swap' member and free functions defined
//: in this component to initialize, respectively, member-function
//: and free-function pointers having the appropriate signatures and
//: return types. (C-4)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the
//: default allocator (note that a ubiquitous test allocator is
//: already installed as the global allocator).
//:
//: 3 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values (one per row) in
//: terms of their individual attributes, including (a) first, the
//: default value, (b) boundary values corresponding to every range
//: of values that each individual attribute can independently
//: attain, and (c) values that should require allocation from each
//: individual attribute that can independently allocate memory.
//:
//: 2 Additionally, provide a (tri-valued) column, 'MEM', indicating
//: the expectation of memory allocation for all typical
//: implementations of individual attribute types: ('Y') "Yes",
//: ('N') "No", or ('?') "implementation-dependent".
//:
//: 4 For each row 'R1' in the table of P-3: (C-1..2, 5)
//:
//: 1 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 2 Use the value constructor and 'oa' to create a modifiable
//: 'Obj', 'mW', having the value described by 'R1'; also use the
//: copy constructor and a "scratch" allocator to create a 'const'
//: 'Obj' 'XX' from 'mW'.
//:
//: 3 Use the member and free 'swap' functions to swap the value of
//: 'mW' with itself; verify, after each swap, that: (C-5)
//:
//: 1 The value is unchanged. (C-5)
//:
//: 2 The allocator address held by the object is unchanged.
//:
//: 3 There was no additional object memory allocation.
//:
//: 4 For each row 'R2' in the table of P-3: (C-1..2)
//:
//: 1 Use the copy constructor and 'oa' to create a modifiable
//: 'Obj', 'mX', from 'XX' (P-4.2).
//:
//: 2 Use the value constructor and 'oa' to create a modifiable
//: 'Obj', 'mY', and having the value described by 'R2'; also use
//: the copy constructor to create, using a "scratch" allocator,
//: a 'const' 'Obj', 'YY', from 'Y'.
//:
//: 3 Use, in turn, the member and free 'swap' functions to swap
//: the values of 'mX' and 'mY'; verify, after each swap, that:
//: (C-1..2)
//:
//: 1 The values have been exchanged. (C-1)
//:
//: 2 The common object allocator address held by 'mX' and 'mY'
//: is unchanged in both objects. (C-2)
//:
//: 3 There was no additional object memory allocation.
//:
//: 5 Verify that the free 'swap' function is discoverable through ADL:
//: (C-6)
//:
//: 1 Create a set of attribute values, 'A', distinct from the values
//: corresponding to the default-constructed object, choosing
//: values that allocate memory if possible.
//:
//: 2 Create a 'bslma::TestAllocator' object, 'oa'.
//:
//: 3 Use the default constructor and 'oa' to create a modifiable
//: 'Obj' 'mX' (having default attribute values); also use the copy
//: constructor and a "scratch" allocator to create a 'const' 'Obj'
//: 'XX' from 'mX'.
//:
//: 4 Use the value constructor and 'oa' to create a modifiable 'Obj'
//: 'mY' having the value described by the 'Ai' attributes; also
//: use the copy constructor and a "scratch" allocator to create a
//: 'const' 'Obj' 'YY' from 'mY'.
//:
//: 5 Use the 'invokeAdlSwap' helper function template to swap the
//: values of 'mX' and 'mY', using the free 'swap' function defined
//: in this component, then verify that: (C-6)
//:
//: 1 The values have been exchanged.
//:
//: 2 There was no additional object memory allocation. (C-6)
//:
//: 6 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-3)
//:
//: 7 Verify that, in appropriate build modes, defensive checks are
//: triggered when an attempt is made to swap objects that do not
//: refer to the same allocator, but not when the allocators are the
//: same (using the 'BSLS_ASSERTTEST_*' macros). (C-7)
//
// Testing:
// void swap(baltzo::LocalTimeDescriptor& other);
// void swap(baltzo::LocalTimeDescriptor& a, b);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "SWAP MEMBER AND FREE FUNCTIONS" << endl
<< "==============================" << endl;
if (verbose) cout <<
"\nAssign the address of each function to a variable." << endl;
{
typedef void (Obj::*funcPtr)(Obj&);
typedef void (*freeFuncPtr)(Obj&, Obj&);
// Verify that the signatures and return types are standard.
funcPtr memberSwap = &Obj::swap;
freeFuncPtr freeSwap = swap;
(void)memberSwap; // quash potential compiler warnings
(void)freeSwap;
}
if (verbose) cout <<
"\nCreate a test allocator and install it as the default." << endl;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) cout <<
"\nUse a table of distinct object values and expected memory usage."
<< endl;
bdlt::DatetimeTz defaultDtz;
bdlt::Datetime smallDt; smallDt.addMilliseconds(1);
bdlt::Datetime someDt(2011, 5, 3, 15, 32);
bdlt::Datetime largeDt(9999, 12, 31, 23, 59, 59, 999);
bdlt::DatetimeTz smallDtz(smallDt, -(24 * 60 - 1));
bdlt::DatetimeTz someDtz( someDt, -( 4 * 60 - 0));
bdlt::DatetimeTz largeDtz(largeDt, (24 * 60 - 1));
const char *defaultTzId = "";
const char *smallTzId = "a";
const char *largeTzId = LONGEST_STRING;
const struct {
int d_line; // source line number
char d_mem; // expected allocation: 'Y', 'N', '?'
bdlt::DatetimeTz *d_datetimeTz;
const char *d_timeZoneId;
} DATA[] = {
//LINE MEM DTTZ TZID
//---- --- ----------- -----------
// default (must be first)
{ L_, 'N', &defaultDtz, defaultTzId },
// 'datetimeTz'
{ L_, 'N', &smallDtz, defaultTzId },
{ L_, 'N', &someDtz, defaultTzId },
{ L_, 'N', &largeDtz, defaultTzId },
// 'timeZoneId'
{ L_, '?', &defaultDtz, smallTzId },
{ L_, 'Y', &defaultDtz, largeTzId },
// other
{ L_, '?', &someDtz, smallTzId },
{ L_, 'Y', &someDtz, largeTzId },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
bool anyObjectMemoryAllocatedFlag = false; // We later check that
// this test allocates
// some object memory.
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const char MEM1 = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ1 = *DATA[ti].d_datetimeTz;
const char *const TZID1 = DATA[ti].d_timeZoneId;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mW(DTTZ1, TZID1, &oa); const Obj& W = mW;
const Obj XX(W, &scratch);
if (veryVerbose) { T_ P_(LINE1) P_(W) P(XX) }
// Ensure the first row of the table contains the
// default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
LOOP3_ASSERT(LINE1, Obj(), W, Obj() == W);
firstFlag = false;
}
// member 'swap'
{
TestAllocatorMonitor oam(oa);
mW.swap(mW);
LOOP3_ASSERT(LINE1, XX, W, XX == W);
LOOP_ASSERT(LINE1, &oa == W.allocator());
LOOP_ASSERT(LINE1, oam.isTotalSame());
}
// free function 'swap'
{
TestAllocatorMonitor oam(oa);
swap(mW, mW);
LOOP3_ASSERT(LINE1, XX, W, XX == W);
LOOP_ASSERT(LINE1, &oa == W.allocator());
LOOP_ASSERT(LINE1, oam.isTotalSame());
}
// Verify expected ('Y'/'N') object-memory allocations.
if ('?' != MEM1) {
LOOP3_ASSERT(LINE1, MEM1, oa.numBlocksInUse(),
('N' == MEM1) == (0 == oa.numBlocksInUse()));
}
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const bdlt::DatetimeTz& DTTZ2 = *DATA[tj].d_datetimeTz;
const char *const TZID2 = DATA[tj].d_timeZoneId;
Obj mX(XX, &oa); const Obj& X = mX;
Obj mY(DTTZ2, TZID2, &oa); const Obj& Y = mY;
const Obj YY(Y, &scratch);
if (veryVerbose) { T_ P_(LINE2) P_(X) P_(Y) P(YY) }
// member 'swap'
{
TestAllocatorMonitor oam(oa);
mX.swap(mY);
LOOP4_ASSERT(LINE1, LINE2, YY, X, YY == X);
LOOP4_ASSERT(LINE1, LINE2, XX, Y, XX == Y);
LOOP2_ASSERT(LINE1, LINE2, &oa == X.allocator());
LOOP2_ASSERT(LINE1, LINE2, &oa == Y.allocator());
LOOP2_ASSERT(LINE1, LINE2, oam.isTotalSame());
}
// free function 'swap'
{
TestAllocatorMonitor oam(oa);
swap(mX, mY);
LOOP4_ASSERT(LINE1, LINE2, XX, X, XX == X);
LOOP4_ASSERT(LINE1, LINE2, YY, Y, YY == Y);
LOOP2_ASSERT(LINE1, LINE2, &oa == X.allocator());
LOOP2_ASSERT(LINE1, LINE2, &oa == Y.allocator());
LOOP2_ASSERT(LINE1, LINE2, oam.isTotalSame());
}
}
// Record if some object memory was allocated.
anyObjectMemoryAllocatedFlag |= !!oa.numBlocksInUse();
}
// Double check that some object memory was allocated.
ASSERT(anyObjectMemoryAllocatedFlag);
if (verbose) cout <<
"\nInvoke free 'swap' function in a context where ADL is used."
<< endl;
{
// 'A' values: Should cause memory allocation if possible.
const bdlt::DatetimeTz A1(bdlt::Datetime(2011, 5, 3, 15), -4 * 60);
const char A2[] = "a_" SUFFICIENTLY_LONG_STRING;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
Obj mX(&oa); const Obj& X = mX;
const Obj XX(X, &scratch);
Obj mY(A1, A2, &oa); const Obj& Y = mY;
const Obj YY(Y, &scratch);
if (veryVerbose) { T_ P_(X) P(Y) }
TestAllocatorMonitor oam(oa);
invokeAdlSwap(mX, mY);
LOOP2_ASSERT(YY, X, YY == X);
LOOP2_ASSERT(XX, Y, XX == Y);
ASSERT(oam.isTotalSame());
if (veryVerbose) { T_ P_(X) P(Y) }
}
// Verify no memory is allocated from the default allocator.
LOOP_ASSERT(da.numBlocksTotal(), 0 == da.numBlocksTotal());
if (verbose) cout << "\nNegative Testing." << endl;
{
bsls::AssertFailureHandlerGuard hG(
bsls::AssertTest::failTestDriver);
if (veryVerbose) cout << "\t'swap' member function" << endl;
{
bslma::TestAllocator oa1("object1", veryVeryVeryVerbose);
bslma::TestAllocator oa2("object2", veryVeryVeryVerbose);
Obj mA(&oa1); Obj mB(&oa1);
Obj mZ(&oa2);
ASSERT_SAFE_PASS(mA.swap(mB));
ASSERT_SAFE_FAIL(mA.swap(mZ));
}
if (veryVerbose) cout << "\t'swap' free function" << endl;
{
bslma::TestAllocator oa1("object1", veryVeryVeryVerbose);
bslma::TestAllocator oa2("object2", veryVeryVeryVerbose);
Obj mA(&oa1); Obj mB(&oa1);
Obj mZ(&oa2);
ASSERT_SAFE_PASS(swap(mA, mB));
ASSERT_SAFE_FAIL(swap(mA, mZ));
}
}
} break;
case 7: {
// --------------------------------------------------------------------
// COPY CONSTRUCTOR
// Ensure that we can create a distinct object of the class from any
// other one, such that the two objects have the same value.
//
// Concerns:
//: 1 The copy constructor (with or without a supplied allocator)
//: creates an object having the same value as that of the supplied
//: original object.
//:
//: 2 If an allocator is NOT supplied to the copy constructor, the
//: default allocator in effect at the time of construction becomes
//: the object allocator for the resulting object (i.e., the
//: allocator of the original object is never copied).
//:
//: 3 If an allocator IS supplied to the copy constructor, that
//: allocator becomes the object allocator for the resulting object.
//:
//: 4 Supplying a null allocator address has the same effect as not
//: supplying an allocator.
//:
//: 5 Supplying an allocator to the copy constructor has no effect
//: on subsequent object values.
//:
//: 6 Any memory allocation is from the object allocator.
//:
//: 7 There is no temporary memory allocation from any allocator.
//:
//: 8 Every object releases any allocated memory at destruction.
//:
//: 9 The original object is passed as a reference providing
//: non-modifiable access to that object.
//:
//:10 The value of the original object is unchanged.
//:
//:11 The allocator address held by the original object is unchanged.
//:
//:12 QoI: Copying an object having the default-constructed value
//: allocates no memory.
//:
//:13 Any memory allocation is exception neutral.
//
// Plan:
//: 1 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values (one per row) in
//: terms of their individual attributes, including (a) first, the
//: default value, (b) boundary values corresponding to every range
//: of values that each individual attribute can independently
//: attain, and (c) values that should require allocation from each
//: individual attribute that can independently allocate memory.
//:
//: 2 Additionally, provide a (tri-valued) column, 'MEM', indicating
//: the expectation of memory allocation for all typical
//: implementations of individual attribute types: ('Y') "Yes",
//: ('N') "No", or ('?') "implementation-dependent".
//:
//: 2 For each row (representing a distinct object value, 'V') in the
//: table described in P-1: (C-1..12)
//:
//: 1 Use the value constructor and a "scratch" allocator to create
//: two 'const' 'Obj', 'Z' and 'ZZ', each having the value 'V'.
//:
//: 2 Execute an inner loop creating three distinct objects in turn,
//: each using the copy constructor on 'Z' from P-2.1, but
//: configured differently: (a) without passing an allocator,
//: (b) passing a null allocator address explicitly, and (c)
//: passing the address of a test allocator distinct from the
//: default.
//:
//: 3 For each of these three iterations (P-2.2): (C-1..12)
//:
//: 1 Create three 'bslma::TestAllocator' objects, and install one
//: as the current default allocator (note that a ubiquitous test
//: allocator is already installed as the global allocator).
//:
//: 2 Use the copy constructor to dynamically create an object 'X',
//: with its object allocator configured appropriately (see
//: P-2.2), supplying it the 'const' object 'Z' (see P-2.1); use
//: a distinct test allocator for the object's footprint. (C-9)
//:
//: 3 Use the equality-comparison operator to verify that:
//: (C-1, 5, 10)
//:
//: 1 The newly constructed object, 'X', has the same value as
//: that of 'Z'. (C-1, 5)
//:
//: 2 'Z' still has the same value as that of 'ZZ'. (C-10)
//:
//: 4 Use the 'allocator' accessor of each underlying attribute
//: capable of allocating memory to ensure that its object
//: allocator is properly installed; also use the 'allocator'
//: accessor of 'X' to verify that its object allocator is
//: properly installed, and use the 'allocator' accessor of 'Z'
//: to verify that the allocator address that it holds is
//: unchanged. (C-6, 11)
//:
//: 5 Use the appropriate test allocators to verify that: (C-2..4,
//: 7..8, 12)
//:
//: 1 An object that IS expected to allocate memory does so
//: from the object allocator only (irrespective of the
//: specific number of allocations or the total amount of
//: memory allocated). (C-2, 4)
//:
//: 2 An object that is expected NOT to allocate memory doesn't.
//: (C-12)
//:
//: 3 If an allocator was supplied at construction (P-2.1c), the
//: current default allocator doesn't allocate any memory.
//: (C-3)
//:
//: 4 No temporary memory is allocated from the object allocator.
//: (C-7)
//:
//: 5 All object memory is released when the object is destroyed.
//: (C-8)
//:
//: 3 Test again, using the data of P-1, but this time just for the
//: supplied allocator configuration (P-2.2c), and create the object
//: as an automatic variable in the presence of injected exceptions
//: (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros).
//: (C-13)
//
// Testing:
// baltzo::LocalTimeDescriptor(const LTDescriptor& o, *bA = 0);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "COPY CONSTRUCTOR" << endl
<< "================" << endl;
if (verbose) cout <<
"\nUse a table of distinct object values and expected memory usage."
<< endl;
bdlt::DatetimeTz defaultDtz;
bdlt::Datetime smallDt; smallDt.addMilliseconds(1);
bdlt::Datetime someDt(2011, 5, 3, 15, 32);
bdlt::Datetime largeDt(9999, 12, 31, 23, 59, 59, 999);
bdlt::DatetimeTz smallDtz(smallDt, -(24 * 60 - 1));
bdlt::DatetimeTz someDtz( someDt, -( 4 * 60 - 0));
bdlt::DatetimeTz largeDtz(largeDt, (24 * 60 - 1));
const char *defaultTzId = "";
const char *smallTzId = "a";
const char *largeTzId = LONGEST_STRING;
const struct {
int d_line; // source line number
char d_mem; // expected allocation: 'Y', 'N', '?'
bdlt::DatetimeTz *d_datetimeTz;
const char *d_timeZoneId;
} DATA[] = {
//LINE MEM DTTZ TZID
//---- --- ----------- -----------
// default (must be first)
{ L_, 'N', &defaultDtz, defaultTzId },
// 'datetimeTz'
{ L_, 'N', &smallDtz, defaultTzId },
{ L_, 'N', &someDtz, defaultTzId },
{ L_, 'N', &largeDtz, defaultTzId },
// 'timeZoneId'
{ L_, '?', &defaultDtz, smallTzId },
{ L_, 'Y', &defaultDtz, largeTzId },
// other
{ L_, '?', &someDtz, smallTzId },
{ L_, 'Y', &someDtz, largeTzId },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) cout <<
"\nCreate objects with various allocator configurations." << endl;
{
bool anyObjectMemoryAllocatedFlag = false; // We later check that
// this test allocates
// some object memory.
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char MEM = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ = *DATA[ti].d_datetimeTz;
const char *const TZID = DATA[ti].d_timeZoneId;
LOOP2_ASSERT(LINE, MEM, MEM && strchr("YN?", MEM));
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
const Obj Z(DTTZ, TZID, &scratch);
const Obj ZZ(DTTZ, TZID, &scratch);
if (veryVerbose) { T_ P_(Z) P(ZZ) }
for (char cfg = 'a'; cfg <= 'c'; ++cfg) {
const char CONFIG = cfg; // how we specify the allocator
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(Z);
objAllocatorPtr = &da;
} break;
case 'b': {
objPtr = new (fa) Obj(Z, 0);
objAllocatorPtr = &da;
} break;
case 'c': {
objPtr = new (fa) Obj(Z, &sa);
objAllocatorPtr = &sa;
} break;
default: {
LOOP_ASSERT(CONFIG, !"Bad allocator config.");
} break;
}
LOOP2_ASSERT(LINE, CONFIG,
sizeof(Obj) == fa.numBytesInUse());
Obj& mX = *objPtr; const Obj& X = mX;
if (veryVerbose) { T_ T_ P_(CONFIG) P(X) }
bslma::TestAllocator& oa = *objAllocatorPtr;
bslma::TestAllocator& noa = 'c' != CONFIG ? sa : da;
// Ensure the first row of the table contains the
// default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
LOOP4_ASSERT(LINE, CONFIG, Obj(), *objPtr,
Obj() == *objPtr)
firstFlag = false;
}
// Verify the value of the object.
LOOP4_ASSERT(LINE, CONFIG, Z, X, Z == X);
// Verify that the value of 'Z' has not changed.
LOOP4_ASSERT(LINE, CONFIG, ZZ, Z, ZZ == Z);
// -------------------------------------------------------
// Verify any attribute allocators are installed properly.
// -------------------------------------------------------
LOOP2_ASSERT(LINE, CONFIG,
&oa == X.timeZoneId().allocator());
// Also invoke the object's 'allocator' accessor, as well
// as that of 'Z'.
LOOP4_ASSERT(LINE, CONFIG, &oa, X.allocator(),
&oa == X.allocator());
LOOP4_ASSERT(LINE, CONFIG, &scratch, Z.allocator(),
&scratch == Z.allocator());
// Verify no allocation from the non-object allocator.
LOOP3_ASSERT(LINE, CONFIG, noa.numBlocksTotal(),
0 == noa.numBlocksTotal());
// Verify no temporary memory is allocated from the object
// allocator.
LOOP4_ASSERT(LINE, CONFIG, oa.numBlocksTotal(),
oa.numBlocksInUse(),
oa.numBlocksTotal() == oa.numBlocksInUse());
// Verify expected ('Y'/'N') object-memory allocations.
if ('?' != MEM) {
LOOP4_ASSERT(LINE, CONFIG, MEM, oa.numBlocksInUse(),
('N' == MEM) == (0 == oa.numBlocksInUse()));
}
// Record if some object memory was allocated.
anyObjectMemoryAllocatedFlag |= !!oa.numBlocksInUse();
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
LOOP3_ASSERT(LINE, CONFIG, da.numBlocksInUse(),
0 == da.numBlocksInUse());
LOOP3_ASSERT(LINE, CONFIG, fa.numBlocksInUse(),
0 == fa.numBlocksInUse());
LOOP3_ASSERT(LINE, CONFIG, sa.numBlocksInUse(),
0 == sa.numBlocksInUse());
} // end foreach configuration
} // end foreach row
// Double check that some object memory was allocated.
ASSERT(anyObjectMemoryAllocatedFlag);
// Note that memory should be independently allocated for each
// attribute capable of allocating memory.
}
if (verbose) cout << "\nTesting with injected exceptions." << endl;
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char MEM = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ = *DATA[ti].d_datetimeTz;
const char *const TZID = DATA[ti].d_timeZoneId;
if (veryVerbose) { T_ P_(MEM) P_(DTTZ) P(TZID) }
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
const Obj Z(DTTZ, TZID, &scratch);
const Obj ZZ(DTTZ, TZID, &scratch);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(sa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj obj(Z, &sa);
LOOP3_ASSERT(LINE, Z, obj, Z == obj);
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP3_ASSERT(LINE, ZZ, Z, ZZ == Z);
LOOP3_ASSERT(LINE, &scratch, Z.allocator(),
&scratch == Z.allocator());
LOOP2_ASSERT(LINE, da.numBlocksInUse(),
0 == da.numBlocksInUse());
LOOP2_ASSERT(LINE, sa.numBlocksInUse(),
0 == sa.numBlocksInUse());
}
}
} break;
case 6: {
// --------------------------------------------------------------------
// EQUALITY-COMPARISON OPERATORS
// Ensure that '==' and '!=' are the operational definition of value.
//
// Concerns:
//: 1 Two objects, 'X' and 'Y', compare equal if and only if each of
//: their corresponding salient attributes respectively compares
//: equal.
//:
//: 2 All salient attributes participate in the comparison.
//:
//: 3 No non-salient attributes (i.e., 'allocator') participate.
//:
//: 4 'true == (X == X)' (i.e., identity)
//:
//: 5 'false == (X != X)' (i.e., identity)
//:
//: 6 'X == Y' if and only if 'Y == X' (i.e., commutativity)
//:
//: 7 'X != Y' if and only if 'Y != X' (i.e., commutativity)
//:
//: 8 'X != Y' if and only if '!(X == Y)'
//:
//: 9 Comparison is symmetric with respect to user-defined conversion
//: (i.e., both comparison operators are free functions).
//:
//:10 Non-modifiable objects can be compared (i.e., objects or
//: references providing only non-modifiable access).
//:
//:11 No memory allocation occurs as a result of comparison (e.g., the
//: arguments are not passed by value).
//:
//:12 The equality operator's signature and return type are standard.
//:
//:13 The inequality operator's signature and return type are standard.
//
// Plan:
//: 1 Use the respective addresses of 'operator==' and 'operator!=' to
//: initialize function pointers having the appropriate signatures
//: and return types for the two homogeneous, free equality-
//: comparison operators defined in this component.
//: (C-9..10, 12..13)
//:
//: 2 Create a 'bslma::TestAllocator' object, and install it as the
//: default allocator (note that a ubiquitous test allocator is
//: already installed as the global allocator).
//:
//: 3 Using the table-driven technique, specify a set of distinct
//: object values (one per row) in terms of their individual salient
//: attributes such that (a) for each salient attribute, there exists
//: a pair of rows that differ (slightly) in only the column
//: corresponding to that attribute, and (b) all attribute values
//: that can allocate memory on construction do so.
//:
//: 4 For each row 'R1' in the table of P-3: (C-1..8)
//:
//: 1 Create a single object, using a "scratch" allocator, and
//: use it to verify the reflexive (anti-reflexive) property of
//: equality (inequality) in the presence of aliasing. (C-4..5)
//:
//: 2 For each row 'R2' in the table of P-3: (C-1..3, 6..8)
//:
//: 1 Record, in 'EXP', whether or not distinct objects created
//: from 'R1' and 'R2', respectively, are expected to have the
//: same value.
//:
//: 2 For each of two configurations, 'a' and 'b': (C-1..3, 6..8)
//:
//: 1 Create two (object) allocators, 'oax' and 'oay'.
//:
//: 2 Create an object 'X', using 'oax', having the value 'R1'.
//:
//: 3 Create an object 'Y', using 'oax' in configuration 'a' and
//: 'oay' in configuration 'b', having the value 'R2'.
//:
//: 4 Verify the commutativity property and expected return value
//: for both '==' and '!=', while monitoring both 'oax' and
//: 'oay' to ensure that no object memory is ever allocated by
//: either operator. (C-1..3, 6..8)
//:
//: 5 Use the test allocator from P-2 to verify that no memory is ever
//: allocated from the default allocator. (C-11)
//
// Testing:
// bool operator==(const baltzo::LocalTimeDescriptor& lhs, rhs);
// bool operator!=(const baltzo::LocalTimeDescriptor& lhs, rhs);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "EQUALITY-COMPARISON OPERATORS" << endl
<< "=============================" << endl;
if (verbose) cout <<
"\nAssign the address of each operator to a variable." << endl;
{
using namespace baltzo;
typedef bool (*operatorPtr)(const Obj&, const Obj&);
// Verify that the signatures and return types are standard.
operatorPtr operatorEq = operator==;
operatorPtr operatorNe = operator!=;
(void)operatorEq; // quash potential compiler warnings
(void)operatorNe;
}
if (verbose) cout <<
"\nCreate a test allocator and install it as the default." << endl;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) cout <<
"\nDefine appropriate individual attribute values, 'Ai' and 'Bi'."
<< endl;
// Attribute Types
typedef bdlt::DatetimeTz T1; // 'datetimeTz'
typedef const char *T2; // 'timeZoneId'
// Attribute 1 Values: 'datetimeTz'
const T1 A1(bdlt::Datetime(2011, 5, 3, 15), -4 * 60);
const T1 B1(bdlt::Datetime(2011, 5, 3, 15), -5 * 60);
// Attribute 2 Values: 'timeZoneId'
const T2 A2 = LONG_STRING;
const T2 B2 = LONGER_STRING;
if (verbose) cout <<
"\nCreate a table of distinct, but similar object values." << endl;
struct {
int d_line; // source line number
const T1 *d_datetimeTz;
const T2 d_timeZoneId;
} DATA[] = {
// The first row of the table below represents an object value
// consisting of "baseline" attribute values (A1..An). Each
// subsequent row differs (slightly) from the first in exactly one
// attribute value (Bi).
//LINE DTTZ TZID
//---- ----------- -----------
{ L_, &A1, A2}, // baseline
{ L_, &B1, A2},
{ L_, &A1, B2},
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) cout << "\nCompare every value with every value." << endl;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const T1& DTTZ1 = *DATA[ti].d_datetimeTz;
const T2 TZID1 = DATA[ti].d_timeZoneId;
if (veryVerbose) { T_ P_(LINE1) P_(DTTZ1) P(TZID1) }
// Ensure an object compares correctly with itself (alias test).
{
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
const Obj X(DTTZ1, TZID1, &scratch);
LOOP2_ASSERT(LINE1, X, X == X);
LOOP2_ASSERT(LINE1, X, !(X != X));
}
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const T1& DTTZ2 = *DATA[tj].d_datetimeTz;
const T2 TZID2 = DATA[tj].d_timeZoneId;
if (veryVerbose) {
T_ T_ P_(LINE2) P_(DTTZ2) P(TZID2) }
const bool EXP = ti == tj; // expected for equality comparison
for (char cfg = 'a'; cfg <= 'b'; ++cfg) {
const char CONFIG = cfg; // Determines 'Y's allocator.
// Create two distinct test allocators, 'oax' and 'oay'.
bslma::TestAllocator oax("objectx", veryVeryVeryVerbose);
bslma::TestAllocator oay("objecty", veryVeryVeryVerbose);
// Map allocators above to objects 'X' and 'Y' below.
bslma::TestAllocator& xa = oax;
bslma::TestAllocator& ya = 'a' == CONFIG ? oax : oay;
const Obj X(DTTZ1, TZID1, &xa);
const Obj Y(DTTZ2, TZID2, &ya);
if (veryVerbose) {
T_ T_ T_ P_(EXP) P_(CONFIG) P_(X) P(Y) }
// Verify value, commutativity, and no memory allocation.
TestAllocatorMonitor oaxm(oax), oaym(oay);
LOOP5_ASSERT(LINE1, LINE2, CONFIG, X, Y, EXP == (X == Y));
LOOP5_ASSERT(LINE1, LINE2, CONFIG, Y, X, EXP == (Y == X));
LOOP5_ASSERT(LINE1, LINE2, CONFIG, X, Y, !EXP == (X != Y));
LOOP5_ASSERT(LINE1, LINE2, CONFIG, Y, X, !EXP == (Y != X));
LOOP3_ASSERT(LINE1, LINE2, CONFIG, oaxm.isTotalSame());
LOOP3_ASSERT(LINE1, LINE2, CONFIG, oaym.isTotalSame());
// Double check that some object memory was allocated.
LOOP3_ASSERT(LINE1, LINE2, CONFIG,
1 <= xa.numBlocksInUse());
LOOP3_ASSERT(LINE1, LINE2, CONFIG,
1 <= ya.numBlocksInUse());
// Note that memory should be independently allocated for
// each attribute capable of allocating memory.
}
}
LOOP_ASSERT(da.numBlocksTotal(), 0 == da.numBlocksTotal());
}
} break;
case 5: {
// --------------------------------------------------------------------
// PRINT AND OUTPUT OPERATOR
// Ensure that the value of the object can be formatted appropriately
// on an 'ostream' in some standard, human-readable form.
//
// Concerns:
//: 1 The 'print' method writes the value to the specified 'ostream'.
//:
//: 2 The 'print' method writes the value in the intended format.
//:
//: 3 The output using 's << obj' is the same as 'obj.print(s, 0, -1)',
//: but with each "attributeName = " elided.
//:
//: 4 The 'print' method signature and return type are standard.
//:
//: 5 The 'print' method returns the supplied 'ostream'.
//:
//: 6 The optional 'level' and 'spacesPerLevel' parameters have the
//: correct default values.
//:
//: 7 The output 'operator<<' signature and return type are standard.
//:
//: 8 The output 'operator<<' returns the supplied 'ostream'.
//
// Plan:
//: 1 Use the addresses of the 'print' member function and 'operator<<'
//: free function defined in this component to initialize,
//: respectively, member-function and free-function pointers having
//: the appropriate signatures and return types. (C-4, 7)
//:
//: 2 Using the table-driven technique: (C-1..3, 5..6, 8)
//:
//: 1 Define fourteen carefully selected combinations of (two) object
//: values ('A' and 'B'), having distinct values for each
//: corresponding salient attribute, and various values for the
//: two formatting parameters, along with the expected output
//: ( 'value' x 'level' x 'spacesPerLevel' ):
//: 1 { A } x { 0 } x { 0, 1, -1, -8 } --> 3 expected o/ps
//: 2 { A } x { 3, -3 } x { 0, 2, -2, -8 } --> 8 expected o/ps
//: 3 { B } x { 2 } x { 3 } --> 1 expected op
//: 4 { A B } x { -8 } x { -8 } --> 2 expected o/ps
//: 4 { A B } x { -9 } x { -9 } --> 2 expected o/ps
//:
//: 2 For each row in the table defined in P-2.1: (C-1..3, 5, 7)
//:
//: 1 Using a 'const' 'Obj', supply each object value and pair of
//: formatting parameters to 'print', omitting the 'level' or
//: 'spacesPerLevel' parameter if the value of that argument is
//: '-8'. If the parameters are, arbitrarily, (-9, -9), then
//: invoke the 'operator<<' instead.
//:
//: 2 Use a standard 'ostringstream' to capture the actual output.
//:
//: 3 Verify the address of what is returned is that of the
//: supplied stream. (C-5, 8)
//:
//: 4 Compare the contents captured in P-2.2.2 with what is
//: expected. (C-1..3, 6)
//
// Testing:
// ostream& print(ostream& s, int level = 0, int sPL = 4) const;
// operator<<(ostream& s, const baltzo::LocalTimeDescriptor& d);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "PRINT AND OUTPUT OPERATOR" << endl
<< "=========================" << endl;
if (verbose) cout << "\nAssign the addresses of 'print' and "
"the output 'operator<<' to variables." << endl;
{
using namespace baltzo;
typedef ostream& (Obj::*funcPtr)(ostream&, int, int) const;
typedef ostream& (*operatorPtr)(ostream&, const Obj&);
// Verify that the signatures and return types are standard.
funcPtr printMember = &Obj::print;
operatorPtr operatorOp = operator<<;
(void)printMember; // quash potential compiler warnings
(void)operatorOp;
}
if (verbose) cout <<
"\nCreate a table of distinct value/format combinations." << endl;
static const Obj A(bdlt::DatetimeTz(bdlt::Datetime(2011, 5, 3, 15),
-4 * 60),
"EDT");
static const Obj B(bdlt::DatetimeTz(bdlt::Datetime(2011, 1, 9, 10),
2 * 60),
"IST");
static const struct {
int d_line; // source line number
int d_level;
int d_spacesPerLevel;
const Obj *d_object_p;
const char *d_expected_p;
} DATA[] = {
#define NL "\n"
#define SP " "
// -------------------------------------------------------------------
// P-2.1.1: { A } x { 0 } x { 0, 1, -1, -8 } --> 4 expected o/ps
// -------------------------------------------------------------------
//LINE L SPL OBJ EXPECTED
//---- - --- --- ---------------------------------------------------
{ L_, 0, 0, &A, "[" NL
"datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
"timeZoneId = \"EDT\"" NL
"]" NL
},
{ L_, 0, 1, &A, "[" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
"]" NL
},
{ L_, 0, -1, &A, "[" SP
"datetimeTz = 03MAY2011_15:00:00.000000-0400" SP
"timeZoneId = \"EDT\"" SP
"]"
},
{ L_, 0, -8, &A, "[" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
"]" NL
},
// -------------------------------------------------------------------
// P-2.1.2: { A } x { 3, -3 } x { 0, 2, -2 } --> 8 expected o/ps
// -------------------------------------------------------------------
//LINE L SPL OBJ EXPECTED
//---- - --- --- ---------------------------------------------------
{ L_, 3, 0, &A, "[" NL
"datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
"timeZoneId = \"EDT\"" NL
"]" NL
},
{ L_, 3, 2, &A,
" [" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
" ]" NL
},
{ L_, 3, -2, &A, " [" SP
"datetimeTz = 03MAY2011_15:00:00.000000-0400" SP
"timeZoneId = \"EDT\"" SP
"]"
},
{ L_, 3, -8, &A,
" [" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
" ]" NL
},
{ L_, -3, 0, &A, "[" NL
"datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
"timeZoneId = \"EDT\"" NL
"]" NL
},
{ L_, -3, 2, &A,
"[" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
" ]" NL
},
{ L_, -3, -2, &A, "[" SP
"datetimeTz = 03MAY2011_15:00:00.000000-0400" SP
"timeZoneId = \"EDT\"" SP
"]"
},
{ L_, -3, -8, &A,
"[" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
" ]" NL
},
// ------------------------------------------------------------------
// P-2.1.3: { B } x { 2 } x { 3 } --> 1 expected o/p
// ------------------------------------------------------------------
//LINE L SPL OBJ EXPECTED
//---- - --- --- ---------------------------------------------------
{ L_, 2, 3, &B,
" [" NL
" datetimeTz = 09JAN2011_10:00:00.000000+0200" NL
" timeZoneId = \"IST\"" NL
" ]" NL
},
// -------------------------------------------------------------------
// P-2.1.4: { A B } x { -8 } x { -8 } --> 2 expected o/ps
// -------------------------------------------------------------------
//LINE L SPL OBJ EXPECTED
//---- - --- --- ---------------------------------------------------
{ L_, -8, -8, &A,
"[" NL
" datetimeTz = 03MAY2011_15:00:00.000000-0400" NL
" timeZoneId = \"EDT\"" NL
"]" NL
},
{ L_, -8, -8, &B,
"[" NL
" datetimeTz = 09JAN2011_10:00:00.000000+0200" NL
" timeZoneId = \"IST\"" NL
"]" NL
},
// -------------------------------------------------------------------
// P-2.1.5: { A B } x { -9 } x { -9 } --> 2 expected o/ps
// -------------------------------------------------------------------
//LINE L SPL OBJ EXPECTED
//---- - --- --- ---------------------------------------------------
{ L_, -9, -9, &A, "[" SP
"03MAY2011_15:00:00.000000-0400" SP
"\"EDT\"" SP
"]"
},
{ L_, -9, -9, &B, "[" SP
"09JAN2011_10:00:00.000000+0200" SP
"\"IST\"" SP
"]"
},
#undef NL
#undef SP
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) cout << "\nTesting with various print specifications."
<< endl;
{
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const int L = DATA[ti].d_level;
const int SPL = DATA[ti].d_spacesPerLevel;
const Obj& OBJ = *DATA[ti].d_object_p;
const char *EXP = DATA[ti].d_expected_p;
if (veryVerbose) { T_ P_(L) P_(SPL) P(OBJ) }
if (veryVeryVerbose) { T_ T_ Q(EXP) cout << EXP; }
ostringstream os;
// Verify supplied stream is returned by reference.
if (-9 == L && -9 == SPL) {
LOOP_ASSERT(LINE, &os == &(os << OBJ));
if (veryVeryVerbose) { T_ T_ Q(operator<<) }
}
else {
LOOP_ASSERT(LINE, -8 == SPL || -8 != L);
if (-8 != SPL) {
LOOP_ASSERT(LINE, &os == &OBJ.print(os, L, SPL));
}
else if (-8 != L) {
LOOP_ASSERT(LINE, &os == &OBJ.print(os, L));
}
else {
LOOP_ASSERT(LINE, &os == &OBJ.print(os));
}
if (veryVeryVerbose) { T_ T_ Q(print) }
}
// Verify output is formatted as expected.
if (veryVeryVerbose) { P(os.str()) }
LOOP3_ASSERT(LINE, EXP, os.str(), EXP == os.str());
}
}
} break;
case 4: {
// --------------------------------------------------------------------
// BASIC ACCESSORS
// Ensure each basic accessor properly interprets object state.
//
// Concerns:
//: 1 Each accessor returns the value of the corresponding attribute
//: of the object.
//:
//: 2 Each accessor method is declared 'const'.
//:
//: 3 No accessor allocates any memory.
//:
//: 4 Accessors for attributes that can allocate memory (i.e., those
//: that take an allocator in their constructor) return a reference
//: providing only non-modifiable access.
//
// Plan:
// In case 3 we demonstrated that all basic accessors work properly
// with respect to attributes initialized by the value constructor.
// Here we use the default constructor and primary manipulators,
// which were fully tested in case 2, to further corroborate that
// these accessors are properly interpreting object state.
//
//: 1 Create two 'bslma::TestAllocator' objects, and install one as
//: the current default allocator (note that a ubiquitous test
//: allocator is already installed as the global allocator).
//:
//: 2 Use the default constructor, using the other test allocator
//: from P-1, to create an object (having default attribute values).
//:
//: 3 Verify that each basic accessor, invoked on a reference providing
//: non-modifiable access to the object created in P2, returns the
//: expected value. (C-2)
//:
//: 4 For each salient attribute (contributing to value): (C-1, 3..4)
//: 1 Use the corresponding primary manipulator to set the attribute
//: to a unique value, making sure to allocate memory if possible.
//:
//: 2 Use the corresponding basic accessor to verify the new
//: expected value. (C-1)
//:
//: 3 Monitor the memory allocated from both the default and object
//: allocators before and after calling the accessor; verify that
//: there is no change in total memory allocation. (C-3..4)
//
// Testing:
// bslma::Allocator *allocator() const;
// const bdlt::DatetimeTz& datetimeTz() const;
// const bsl::string& timeZoneId() const;
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "BASIC ACCESSORS" << endl
<< "===============" << endl;
if (verbose) cout << "\nEstablish suitable attribute values." << endl;
// Attribute Types
typedef bdlt::DatetimeTz T1; // 'datetimeTz'
typedef bsl::string T2; // 'timeZoneId'
// -----------------------------------------------------
// 'D' values: These are the default-constructed values.
// -----------------------------------------------------
const T1 D1; // default value
const T2 D2 = ""; // default value
// -------------------------------------------------------
// 'A' values: Should cause memory allocation if possible.
// -------------------------------------------------------
const T1 A1(bdlt::Datetime(2011, 5, 3, 15), -4 * 60);
const T2 A2 = "a_" SUFFICIENTLY_LONG_STRING;
if (verbose) cout <<
"\nCreate two test allocators; install one as the default." << endl;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
if (verbose) cout <<
"\nCreate an object, passing in the other allocator." << endl;
Obj mX(&oa); const Obj& X = mX;
if (verbose) cout <<
"\nVerify all basic accessors report expected values." << endl;
{
const T1& datetimeTz = X.datetimeTz();
LOOP2_ASSERT(D1, datetimeTz, D1 == datetimeTz);
const T2 timeZoneId = X.timeZoneId();
LOOP2_ASSERT(D2, timeZoneId, D2 == timeZoneId);
ASSERT(&oa == X.allocator());
}
if (verbose) cout <<
"\nApply primary manipulators and verify expected values." << endl;
if (veryVerbose) { T_ Q(datetimeTz) }
{
mX.setDatetimeTz(A1);
TestAllocatorMonitor oam(oa), dam(da);
const T1& datetimeTz = X.datetimeTz();
LOOP2_ASSERT(A1, datetimeTz, A1 == datetimeTz);
ASSERT(oam.isInUseSame()); ASSERT(dam.isInUseSame());
}
if (veryVerbose) { T_ Q(timeZoneId) }
{
mX.setTimeZoneId(A2);
TestAllocatorMonitor oam(oa), dam(da);
const T2& timeZoneId = X.timeZoneId();
LOOP2_ASSERT(A2, timeZoneId, A2 == timeZoneId);
ASSERT(oam.isTotalSame()); ASSERT(dam.isTotalSame());
}
// Double check that some object memory was allocated.
ASSERT(1 <= oa.numBlocksTotal());
// Note that memory should be independently allocated for each
// attribute capable of allocating memory.
LOOP_ASSERT(da.numBlocksTotal(), 0 == da.numBlocksTotal());
} break;
case 3: {
// --------------------------------------------------------------------
// VALUE CTOR
// Ensure that we can put an object into any initial state relevant
// for thorough testing.
//
// Concerns:
//: 1 The value constructor (with or without a supplied allocator) can
//: create an object having any value that does not violate the
//: constructor's documented preconditions.
//:
//: 2 Any string arguments can be of type 'char *' or 'string'.
//:
//: 3 Any argument can be 'const'.
//:
//: 4 If an allocator is NOT supplied to the value constructor, the
//: default allocator in effect at the time of construction becomes
//: the object allocator for the resulting object.
//:
//: 5 If an allocator IS supplied to the value constructor, that
//: allocator becomes the object allocator for the resulting object.
//:
//: 6 Supplying a null allocator address has the same effect as not
//: supplying an allocator.
//:
//: 7 Supplying an allocator to the value constructor has no effect
//: on subsequent object values.
//:
//: 8 Any memory allocation is from the object allocator.
//:
//: 9 There is no temporary memory allocation from any allocator.
//:
//:10 Every object releases any allocated memory at destruction.
//:
//:11 QoI: Creating an object having the default-constructed value
//: allocates no memory.
//:
//:12 Any memory allocation is exception neutral.
//
// Plan:
//: 1 Using the table-driven technique:
//:
//: 1 Specify a set of (unique) valid object values (one per row) in
//: terms of their individual attributes, including (a) first, the
//: default value, (b) boundary values corresponding to every range
//: of values that each individual attribute can independently
//: attain, and (c) values that should require allocation from each
//: individual attribute that can independently allocate memory.
//:
//: 2 Additionally, provide a (tri-valued) column, 'MEM', indicating
//: the expectation of memory allocation for all typical
//: implementations of individual attribute types: ('Y') "Yes",
//: ('N') "No", or ('?') "implementation-dependent".
//:
//: 2 For each row (representing a distinct object value, 'V') in the
//: table described in P-1: (C-1, 3..11)
//:
//: 1 Execute an inner loop creating three distinct objects, in turn,
//: each object having the same value, 'V', but configured
//: differently: (a) without passing an allocator, (b) passing a
//: null allocator address explicitly, and (c) passing the address
//: of a test allocator distinct from the default allocator.
//:
//: 2 For each of the three iterations in P-2.1: (C-1, 4..11)
//:
//: 1 Create three 'bslma::TestAllocator' objects, and install one
//: as the current default allocator (note that a ubiquitous test
//: allocator is already installed as the global allocator).
//:
//: 2 Use the value constructor to dynamically create an object
//: having the value 'V', with its object allocator configured
//: appropriately (see P-2.1), supplying all the arguments as
//: 'const' and representing any string arguments as 'char *';
//: use a distinct test allocator for the object's footprint.
//:
//: 3 Use the (as yet unproven) salient attribute accessors to
//: verify that all of the attributes of each object have their
//: expected values. (C-1, 7)
//:
//: 4 Use the 'allocator' accessor of each underlying attribute
//: capable of allocating memory to ensure that its object
//: allocator is properly installed; also invoke the (as yet
//: unproven) 'allocator' accessor of the object under test.
//: (C-8)
//:
//: 5 Use the appropriate test allocators to verify that: (C-4..6,
//: 9..11)
//:
//: 1 An object that IS expected to allocate memory does so
//: from the object allocator only (irrespective of the
//: specific number of allocations or the total amount of
//: memory allocated). (C-4, 6)
//:
//: 2 An object that is expected NOT to allocate memory doesn't.
//: (C-11)
//:
//: 3 If an allocator was supplied at construction (P-2.1c), the
//: default allocator doesn't allocate any memory. (C-5)
//:
//: 4 No temporary memory is allocated from the object allocator.
//: (C-9)
//:
//: 5 All object memory is released when the object is destroyed.
//: (C-10)
//:
//: 3 Repeat the steps in P-2 for the supplied allocator configuration
//: (P-2.1c) on the data of P-1, but this time create the object as
//: an automatic variable in the presence of injected exceptions
//: (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros);
//: represent any string arguments in terms of 'string' using a
//: "scratch" allocator. (C-2, 12)
//
// Testing:
// baltzo::LocalDatetime(DatetimeTz& d, const char *t, *bA = 0);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "VALUE CTOR" << endl
<< "==========" << endl;
if (verbose) cout <<
"\nUse a table of distinct object values and expected memory usage."
<< endl;
bdlt::DatetimeTz defaultDtz;
bdlt::Datetime smallDt; smallDt.addMilliseconds(1);
bdlt::Datetime someDt(2011, 5, 3, 15, 32);
bdlt::Datetime largeDt(9999, 12, 31, 23, 59, 59, 999);
bdlt::DatetimeTz smallDtz(smallDt, -(24 * 60 - 1));
bdlt::DatetimeTz someDtz( someDt, -( 4 * 60 - 0));
bdlt::DatetimeTz largeDtz(largeDt, (24 * 60 - 1));
const char *defaultTzId = "";
const char *smallTzId = "a";
const char *largeTzId = LONGEST_STRING;
const struct {
int d_line; // source line number
char d_mem; // expected allocation: 'Y', 'N', '?'
bdlt::DatetimeTz *d_datetimeTz;
const char *const d_timeZoneId;
} DATA[] = {
//LINE MEM DTTZ TZID
//---- --- ----------- -----------
// default (must be first)
{ L_, 'N', &defaultDtz, defaultTzId },
// 'datetimeTz'
{ L_, 'N', &smallDtz, defaultTzId },
{ L_, 'N', &someDtz, defaultTzId },
{ L_, 'N', &largeDtz, defaultTzId },
// 'timeZoneId'
{ L_, '?', &defaultDtz, smallTzId },
{ L_, 'Y', &defaultDtz, largeTzId },
// other
{ L_, '?', &someDtz, smallTzId },
{ L_, 'Y', &someDtz, largeTzId },
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
if (verbose) cout <<
"\nCreate objects with various allocator configurations." << endl;
{
bool anyObjectMemoryAllocatedFlag = false; // We later check that
// this test allocates
// some object memory.
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char MEM = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ = *DATA[ti].d_datetimeTz;
const char *const TZID = DATA[ti].d_timeZoneId;
if (veryVerbose) { T_ P_(MEM) P_(DTTZ) P(TZID) }
LOOP2_ASSERT(LINE, MEM, MEM && strchr("YN?", MEM));
for (char cfg = 'a'; cfg <= 'c'; ++cfg) {
const char CONFIG = cfg; // how we specify the allocator
if (veryVerbose) { T_ T_ P(CONFIG) }
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(DTTZ, TZID);
objAllocatorPtr = &da;
} break;
case 'b': {
objPtr = new (fa) Obj(DTTZ, TZID, 0);
objAllocatorPtr = &da;
} break;
case 'c': {
objPtr = new (fa) Obj(DTTZ, TZID, &sa);
objAllocatorPtr = &sa;
} break;
default: {
LOOP2_ASSERT(LINE, CONFIG, !"Bad allocator config.");
} break;
}
LOOP2_ASSERT(LINE, CONFIG,
sizeof(Obj) == fa.numBytesInUse());
Obj& mX = *objPtr; const Obj& X = mX;
if (veryVerbose) { T_ T_ P_(CONFIG) P(X) }
bslma::TestAllocator& oa = *objAllocatorPtr;
bslma::TestAllocator& noa = 'c' != CONFIG ? sa : da;
// Use untested functionality to help ensure the first row
// of the table contains the default-constructed value.
static bool firstFlag = true;
if (firstFlag) {
LOOP4_ASSERT(LINE, CONFIG, Obj(), *objPtr,
Obj() == *objPtr)
firstFlag = false;
}
// -------------------------------------
// Verify the object's attribute values.
// -------------------------------------
LOOP4_ASSERT(LINE, CONFIG, DTTZ, X.datetimeTz(),
DTTZ == X.datetimeTz());
LOOP4_ASSERT(LINE, CONFIG, TZID, X.timeZoneId(),
TZID == X.timeZoneId());
// -------------------------------------------------------
// Verify any attribute allocators are installed properly.
// -------------------------------------------------------
LOOP2_ASSERT(LINE, CONFIG,
&oa == X.timeZoneId().allocator());
// Also invoke the object's 'allocator' accessor.
LOOP4_ASSERT(LINE, CONFIG, &oa, X.allocator(),
&oa == X.allocator());
// Verify no allocation from the non-object allocator.
LOOP3_ASSERT(LINE, CONFIG, noa.numBlocksTotal(),
0 == noa.numBlocksTotal());
// Verify no temporary memory is allocated from the object
// allocator.
LOOP4_ASSERT(LINE, CONFIG, oa.numBlocksTotal(),
oa.numBlocksInUse(),
oa.numBlocksTotal() == oa.numBlocksInUse());
// Verify expected ('Y'/'N') object-memory allocations.
if ('?' != MEM) {
LOOP4_ASSERT(LINE, CONFIG, MEM, oa.numBlocksInUse(),
('N' == MEM) == (0 == oa.numBlocksInUse()));
}
// Record if some object memory was allocated.
anyObjectMemoryAllocatedFlag |= !!oa.numBlocksInUse();
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
LOOP3_ASSERT(LINE, CONFIG, da.numBlocksInUse(),
0 == da.numBlocksInUse());
LOOP3_ASSERT(LINE, CONFIG, fa.numBlocksInUse(),
0 == fa.numBlocksInUse());
LOOP3_ASSERT(LINE, CONFIG, sa.numBlocksInUse(),
0 == sa.numBlocksInUse());
} // end foreach configuration
} // end foreach row
// Double check that some object memory was allocated.
ASSERT(anyObjectMemoryAllocatedFlag);
// Note that memory should be independently allocated for each
// attribute capable of allocating memory.
}
if (verbose) cout << "\nTesting with injected exceptions." << endl;
{
// Note that any string arguments are now of type 'string', which
// require their own "scratch" allocator.
bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose);
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char MEM = DATA[ti].d_mem;
const bdlt::DatetimeTz& DTTZ = *DATA[ti].d_datetimeTz;
const char *const TZID = DATA[ti].d_timeZoneId;
if (veryVerbose) { T_ P_(MEM) P_(DTTZ) P(TZID) }
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(sa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
Obj obj(DTTZ, TZID, &sa);
LOOP3_ASSERT(LINE, DTTZ, obj.datetimeTz(),
DTTZ == obj.datetimeTz());
LOOP3_ASSERT(LINE, TZID, obj.timeZoneId(),
TZID == obj.timeZoneId());
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP2_ASSERT(LINE, da.numBlocksInUse(),
0 == da.numBlocksInUse());
LOOP2_ASSERT(LINE, sa.numBlocksInUse(),
0 == sa.numBlocksInUse());
}
}
} break;
case 2: {
// --------------------------------------------------------------------
// DEFAULT CTOR, PRIMARY MANIPULATORS, & DTOR
// Ensure that we can use the default constructor to create an
// object (having the default-constructed value), use the primary
// manipulators to put that object into any state relevant for
// thorough testing, and use the destructor to destroy it safely.
//
// Concerns:
//: 1 An object created with the default constructor (with or without
//: a supplied allocator) has the contractually specified default
//: value.
//:
//: 2 If an allocator is NOT supplied to the default constructor, the
//: default allocator in effect at the time of construction becomes
//: the object allocator for the resulting object.
//:
//: 3 If an allocator IS supplied to the default constructor, that
//: allocator becomes the object allocator for the resulting object.
//:
//: 4 Supplying a null allocator address has the same effect as not
//: supplying an allocator.
//:
//: 5 Supplying an allocator to the default constructor has no effect
//: on subsequent object values.
//:
//: 6 Any memory allocation is from the object allocator.
//:
//: 7 There is no temporary allocation from any allocator.
//:
//: 8 Every object releases any allocated memory at destruction.
//:
//: 9 QoI: The default constructor allocates no memory.
//:
//:10 Each attribute is modifiable independently.
//:
//:11 Each attribute can be set to represent any value that does not
//: violate that attribute's documented constraints.
//:
//:12 Any string arguments can be of type 'char *' or 'string'.
//:
//:13 Any argument can be 'const'.
//:
//:14 Any memory allocation is exception neutral.
//
// Plan:
//: 1 Create three sets of attribute values for the object: ('D')
//: values corresponding to the default-constructed object, ('A')
//: values that allocate memory if possible, and ('B') other values
//: that do not cause additional memory allocation beyond that which
//: may be incurred by 'A'. Both the 'A' and 'B' attribute values
//: should be chosen to be boundary values where possible. If an
//: attribute can be supplied via alternate C++ types (e.g., 'string'
//: instead of 'char *'), use the alternate type for 'B'.
//:
//: 2 Using a loop-based approach, default-construct three distinct
//: objects, in turn, but configured differently: (a) without passing
//: an allocator, (b) passing a null allocator address explicitly,
//: and (c) passing the address of a test allocator distinct from the
//: default. For each of these three iterations: (C-1..14)
//:
//: 1 Create three 'bslma::TestAllocator' objects, and install one as
//: as the current default allocator (note that a ubiquitous test
//: allocator is already installed as the global allocator).
//:
//: 2 Use the default constructor to dynamically create an object
//: 'X', with its object allocator configured appropriately (see
//: P-2); use a distinct test allocator for the object's footprint.
//:
//: 3 Use the 'allocator' accessor of each underlying attribute
//: capable of allocating memory to ensure that its object
//: allocator is properly installed; also invoke the (as yet
//: unproven) 'allocator' accessor of the object under test.
//: (C-2..4)
//:
//: 4 Use the appropriate test allocators to verify that no memory
//: is allocated by the default constructor. (C-9)
//:
//: 5 Use the individual (as yet unproven) salient attribute
//: accessors to verify the default-constructed value. (C-1)
//:
//: 6 For each attribute 'i', in turn, create a local block. Then
//: inside the block, using brute force, set that attribute's
//: value, passing a 'const' argument representing each of the
//: three test values, in turn (see P-1), first to 'Ai', then to
//: 'Bi', and finally back to 'Di'. If attribute 'i' can allocate
//: memory, verify that it does so on the first value transition
//: ('Di' -> 'Ai'), and that the corresponding primary manipulator
//: is exception neutral (using the
//: 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros). In all other
//: cases, verify that no memory allocation occurs. After each
//: transition, use the (as yet unproven) basic accessors to verify
//: that only the intended attribute value changed. (C-5..6,
//: 11..14)
//:
//: 7 Corroborate that attributes are modifiable independently by
//: first setting all of the attributes to their 'A' values. Then
//: incrementally set each attribute to it's corresponding 'B'
//: value and verify after each manipulation that only that
//: attribute's value changed. (C-10)
//:
//: 8 Verify that no temporary memory is allocated from the object
//: allocator. (C-7)
//:
//: 9 Verify that all object memory is released when the object is
//: destroyed. (C-8)
//:
//: 3 Verify that, in appropriate build modes, defensive checks are
//: triggered for invalid attribute values, but not triggered for
//: adjacent valid ones (using the 'BSLS_ASSERTTEST_*' macros).
//: (C-15)
//
// Testing:
// baltzo::LocalDatetime(bslma::Allocator *bA = 0);
// baltzo::LocalDatetime(DatetimeTz& d, const char *t, *bA = 0);
// setDatetimeTz(const bdlt::DatetimeTz& value);
// setTimeZoneId(const char *value);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "DEFAULT CTOR, PRIMARY MANIPULATORS, & DTOR" << endl
<< "==========================================" << endl;
if (verbose) cout << "\nEstablish suitable attribute values." << endl;
// 'D' values: These are the default-constructed values.
const bdlt::DatetimeTz D1 = bdlt::DatetimeTz(); // default value
const char D2[] = ""; // default value
// 'A' values: Should cause memory allocation if possible.
const bdlt::DatetimeTz A1(bdlt::Datetime(2011, 5, 3, 15), -4 * 60);
const char A2[] = "a_" SUFFICIENTLY_LONG_STRING;
// 'B' values: Should NOT cause allocation (use alternate string type).
const bdlt::Datetime maxDatetime(9999, 12, 31, 23, 59, 59, 999);
const bdlt::DatetimeTz B1 = bdlt::DatetimeTz(maxDatetime, 1440 - 1);
const char B2[] = "xyz";
if (verbose) cout << "\nTesting with various allocator configurations."
<< endl;
for (char cfg = 'a'; cfg <= 'c'; ++cfg) {
const char CONFIG = cfg; // how we specify the allocator
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj();
objAllocatorPtr = &da;
} break;
case 'b': {
objPtr = new (fa) Obj(0);
objAllocatorPtr = &da;
} break;
case 'c': {
objPtr = new (fa) Obj(&sa);
objAllocatorPtr = &sa;
} break;
default: {
LOOP_ASSERT(CONFIG, !"Bad allocator config.");
} break;
}
Obj& mX = *objPtr; const Obj& X = mX;
bslma::TestAllocator& oa = *objAllocatorPtr;
bslma::TestAllocator& noa = 'c' != CONFIG ? sa : da;
// -------------------------------------------------------
// Verify any attribute allocators are installed properly.
// -------------------------------------------------------
LOOP_ASSERT(CONFIG, &oa == X.timeZoneId().allocator());
// Also invoke the object's 'allocator' accessor.
LOOP3_ASSERT(CONFIG, &oa, X.allocator(), &oa == X.allocator());
// Verify no allocation from the object/non-object allocators.
LOOP2_ASSERT(CONFIG, oa.numBlocksTotal(),
0 == oa.numBlocksTotal());
LOOP2_ASSERT(CONFIG, noa.numBlocksTotal(),
0 == noa.numBlocksTotal());
// -------------------------------------
// Verify the object's attribute values.
// -------------------------------------
LOOP3_ASSERT(CONFIG, D1, X.datetimeTz(),
D1 == X.datetimeTz());
LOOP3_ASSERT(CONFIG, D2, X.timeZoneId(),
D2 == X.timeZoneId());
// -----------------------------------------------------
// Verify that each attribute is independently settable.
// -----------------------------------------------------
// 'datetimeTz'
{
TestAllocatorMonitor tam(oa);
mX.setDatetimeTz(A1);
LOOP_ASSERT(CONFIG, A1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, D2 == X.timeZoneId());
mX.setDatetimeTz(B1);
LOOP_ASSERT(CONFIG, B1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, D2 == X.timeZoneId());
mX.setDatetimeTz(D1);
LOOP_ASSERT(CONFIG, D1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, D2 == X.timeZoneId());
LOOP_ASSERT(CONFIG, tam.isTotalSame());
}
// 'timeZoneId'
{
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) {
if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) }
TestAllocatorMonitor tam(oa);
mX.setTimeZoneId(A2);
LOOP_ASSERT(CONFIG, tam.isInUseUp());
} BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
LOOP_ASSERT(CONFIG, D1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, A2 == X.timeZoneId());
TestAllocatorMonitor tam(oa);
mX.setTimeZoneId(B2);
LOOP_ASSERT(CONFIG, D1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, B2 == X.timeZoneId());
mX.setTimeZoneId(D2);
LOOP_ASSERT(CONFIG, D1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, D2 == X.timeZoneId());
LOOP_ASSERT(CONFIG, tam.isTotalSame());
}
// Corroborate attribute independence.
{
// Set all attributes to their 'A' values.
mX.setDatetimeTz(A1);
mX.setTimeZoneId(A2);
LOOP_ASSERT(CONFIG, A1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, A2 == X.timeZoneId());
// Set all attributes to their 'B' values.
mX.setDatetimeTz(B1);
LOOP_ASSERT(CONFIG, B1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, A2 == X.timeZoneId());
mX.setTimeZoneId(B2);
LOOP_ASSERT(CONFIG, B1 == X.datetimeTz());
LOOP_ASSERT(CONFIG, B2 == X.timeZoneId());
}
// Verify no temporary memory is allocated from the object
// allocator.
LOOP2_ASSERT(CONFIG, oa.numBlocksMax(), 1 == oa.numBlocksMax());
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
LOOP_ASSERT(fa.numBlocksInUse(), 0 == fa.numBlocksInUse());
LOOP_ASSERT(oa.numBlocksInUse(), 0 == oa.numBlocksInUse());
LOOP_ASSERT(noa.numBlocksTotal(), 0 == noa.numBlocksTotal());
// Double check that some object memory was allocated.
LOOP_ASSERT(CONFIG, 1 <= oa.numBlocksTotal());
// Note that memory should be independently allocated for each
// attribute capable of allocating memory.
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Create an object 'w' (default ctor). { w:D }
//: 2 Create an object 'x' (copy from 'w'). { w:D x:D }
//: 3 Set 'x' to 'A' (value distinct from 'D'). { w:D x:A }
//: 4 Create an object 'y' (init. to 'A'). { w:D x:A y:A }
//: 5 Create an object 'z' (copy from 'y'). { w:D x:A y:A z:A }
//: 6 Set 'z' to 'D' (the default value). { w:D x:A y:A z:D }
//: 7 Assign 'w' from 'x'. { w:A x:A y:A z:D }
//: 8 Assign 'w' from 'z'. { w:D x:A y:A z:D }
//: 9 Assign 'x' from 'x' (aliasing). { w:D x:A y:A z:D }
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "BREATHING TEST" << endl
<< "==============" << endl;
// Attribute Types
typedef bdlt::DatetimeTz T1; // 'datetimeTz'
typedef const char *T2; // 'timeZoneId'
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Values for testing
// Attribute 1 Values: 'datetimeTz'
const T1 D1; // default value
const T1 A1(bdlt::Datetime(2011, 5, 3, 15), -4 * 60);
// Attribute 2 Values: 'timeZoneId'
const T2 D2 = ""; // default value
const T2 A2 = "America/New_York";
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 1. Create an object 'w' (default ctor)."
"\t\t{ w:D }" << endl;
Obj mW; const Obj& W = mW;
if (veryVerbose) cout << "\ta. Check initial value of 'w'." << endl;
if (veryVeryVerbose) { T_ T_ P(W) }
ASSERT(D1 == W.datetimeTz());
ASSERT(D2 == W.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'w' <op> 'w'." << endl;
ASSERT(1 == (W == W)); ASSERT(0 == (W != W));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 2. Create an object 'x' (copy from 'w')."
"\t\t{ w:D x:D }" << endl;
Obj mX(W); const Obj& X = mX;
if (veryVerbose) cout << "\ta. Check initial value of 'x'." << endl;
if (veryVeryVerbose) { T_ T_ P(X) }
ASSERT(D1 == X.datetimeTz());
ASSERT(D2 == X.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'x' <op> 'w', 'x'." << endl;
ASSERT(1 == (X == W)); ASSERT(0 == (X != W));
ASSERT(1 == (X == X)); ASSERT(0 == (X != X));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 3. Set 'x' to 'A' (value distinct from 'D')."
"\t\t{ w:D x:A }" << endl;
mX.setDatetimeTz(A1);
mX.setTimeZoneId(A2);
if (veryVerbose) cout << "\ta. Check new value of 'x'." << endl;
if (veryVeryVerbose) { T_ T_ P(X) }
ASSERT(A1 == X.datetimeTz());
ASSERT(A2 == X.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'x' <op> 'w', 'x'." << endl;
ASSERT(0 == (X == W)); ASSERT(1 == (X != W));
ASSERT(1 == (X == X)); ASSERT(0 == (X != X));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 4. Create an object 'y' (init. to 'A')."
"\t\t{ w:D x:A y:A }" << endl;
Obj mY(A1, A2); const Obj& Y = mY;
if (veryVerbose) cout << "\ta. Check initial value of 'y'." << endl;
if (veryVeryVerbose) { T_ T_ P(Y) }
ASSERT(A1 == Y.datetimeTz());
ASSERT(A2 == Y.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'y' <op> 'w', 'x', 'y'" << endl;
ASSERT(0 == (Y == W)); ASSERT(1 == (Y != W));
ASSERT(1 == (Y == X)); ASSERT(0 == (Y != X));
ASSERT(1 == (Y == Y)); ASSERT(0 == (Y != Y));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 5. Create an object 'z' (copy from 'y')."
"\t\t{ w:D x:A y:A z:A }" << endl;
Obj mZ(Y); const Obj& Z = mZ;
if (veryVerbose) cout << "\ta. Check initial value of 'z'." << endl;
if (veryVeryVerbose) { T_ T_ P(Z) }
ASSERT(A1 == Z.datetimeTz());
ASSERT(A2 == Z.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'z' <op> 'w', 'x', 'y', 'z'." << endl;
ASSERT(0 == (Z == W)); ASSERT(1 == (Z != W));
ASSERT(1 == (Z == X)); ASSERT(0 == (Z != X));
ASSERT(1 == (Z == Y)); ASSERT(0 == (Z != Y));
ASSERT(1 == (Z == Z)); ASSERT(0 == (Z != Z));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 6. Set 'z' to 'D' (the default value)."
"\t\t\t{ w:D x:A y:A z:D }" << endl;
mZ.setDatetimeTz(D1);
mZ.setTimeZoneId(D2);
if (veryVerbose) cout << "\ta. Check new value of 'z'." << endl;
if (veryVeryVerbose) { T_ T_ P(Z) }
ASSERT(D1 == Z.datetimeTz());
ASSERT(D2 == Z.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'z' <op> 'w', 'x', 'y', 'z'." << endl;
ASSERT(1 == (Z == W)); ASSERT(0 == (Z != W));
ASSERT(0 == (Z == X)); ASSERT(1 == (Z != X));
ASSERT(0 == (Z == Y)); ASSERT(1 == (Z != Y));
ASSERT(1 == (Z == Z)); ASSERT(0 == (Z != Z));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 7. Assign 'w' from 'x'."
"\t\t\t\t{ w:A x:A y:A z:D }" << endl;
mW = X;
if (veryVerbose) cout << "\ta. Check new value of 'w'." << endl;
if (veryVeryVerbose) { T_ T_ P(W) }
ASSERT(A1 == W.datetimeTz());
ASSERT(A2 == W.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'w' <op> 'w', 'x', 'y', 'z'." << endl;
ASSERT(1 == (W == W)); ASSERT(0 == (W != W));
ASSERT(1 == (W == X)); ASSERT(0 == (W != X));
ASSERT(1 == (W == Y)); ASSERT(0 == (W != Y));
ASSERT(0 == (W == Z)); ASSERT(1 == (W != Z));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 8. Assign 'w' from 'z'."
"\t\t\t\t{ w:D x:A y:A z:D }" << endl;
mW = Z;
if (veryVerbose) cout << "\ta. Check new value of 'w'." << endl;
if (veryVeryVerbose) { T_ T_ P(W) }
ASSERT(D1 == W.datetimeTz());
ASSERT(D2 == W.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'x' <op> 'w', 'x', 'y', 'z'." << endl;
ASSERT(1 == (W == W)); ASSERT(0 == (W != W));
ASSERT(0 == (W == X)); ASSERT(1 == (W != X));
ASSERT(0 == (W == Y)); ASSERT(1 == (W != Y));
ASSERT(1 == (W == Z)); ASSERT(0 == (W != Z));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (verbose) cout << "\n 9. Assign 'x' from 'x' (aliasing)."
"\t\t\t{ w:D x:A y:A z:D }" << endl;
mX = X;
if (veryVerbose) cout << "\ta. Check (same) value of 'x'." << endl;
if (veryVeryVerbose) { T_ T_ P(X) }
ASSERT(A1 == X.datetimeTz());
ASSERT(A2 == X.timeZoneId());
if (veryVerbose) cout <<
"\tb. Try equality operators: 'x' <op> 'w', 'x', 'y', 'z'." << endl;
ASSERT(0 == (X == W)); ASSERT(1 == (X != W));
ASSERT(1 == (X == X)); ASSERT(0 == (X != X));
ASSERT(1 == (X == Y)); ASSERT(0 == (X != Y));
ASSERT(0 == (X == Z)); ASSERT(1 == (X != Z));
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
}
}
// CONCERN: In no case does memory come from the global allocator.
LOOP_ASSERT(globalAllocator.numBlocksTotal(),
0 == globalAllocator.numBlocksTotal());
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| {
"content_hash": "986f6eb8f92a430b64fa62553ecf0056",
"timestamp": "",
"source": "github",
"line_count": 3820,
"max_line_length": 79,
"avg_line_length": 42.758115183246076,
"alnum_prop": 0.4652250575500808,
"repo_name": "apaprocki/bde",
"id": "8a6b066309ed8feea47fc72292e759d9d8e2ce9d",
"size": "164291",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "groups/bal/baltzo/baltzo_localdatetime.t.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "156976"
},
{
"name": "C++",
"bytes": "98010158"
},
{
"name": "CMake",
"bytes": "5472"
},
{
"name": "Makefile",
"bytes": "6304"
},
{
"name": "Perl",
"bytes": "379933"
},
{
"name": "Python",
"bytes": "17049"
},
{
"name": "Roff",
"bytes": "65678"
},
{
"name": "Shell",
"bytes": "9762"
}
],
"symlink_target": ""
} |
package decor
import (
"fmt"
"math"
"time"
"github.com/VividCortex/ewma"
)
type TimeNormalizer func(time.Duration) time.Duration
// EwmaETA exponential-weighted-moving-average based ETA decorator.
//
// `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
//
// `age` is the previous N samples to average over.
//
// `wcc` optional WC config
func EwmaETA(style TimeStyle, age float64, wcc ...WC) Decorator {
return MovingAverageETA(style, ewma.NewMovingAverage(age), NopNormalizer(), wcc...)
}
// MovingAverageETA decorator relies on MovingAverage implementation to calculate its average.
//
// `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
//
// `average` available implementations of MovingAverage [ewma.MovingAverage|NewMedian|NewMedianEwma]
//
// `normalizer` available implementations are [NopNormalizer|FixedIntervalTimeNormalizer|MaxTolerateTimeNormalizer]
//
// `wcc` optional WC config
func MovingAverageETA(style TimeStyle, average MovingAverage, normalizer TimeNormalizer, wcc ...WC) Decorator {
var wc WC
for _, widthConf := range wcc {
wc = widthConf
}
wc.Init()
d := &movingAverageETA{
WC: wc,
style: style,
average: average,
normalizer: normalizer,
}
return d
}
type movingAverageETA struct {
WC
style TimeStyle
average ewma.MovingAverage
completeMsg *string
normalizer TimeNormalizer
}
func (d *movingAverageETA) Decor(st *Statistics) string {
if st.Completed && d.completeMsg != nil {
return d.FormatMsg(*d.completeMsg)
}
v := math.Round(d.average.Value())
remaining := d.normalizer(time.Duration((st.Total - st.Current) * int64(v)))
hours := int64((remaining / time.Hour) % 60)
minutes := int64((remaining / time.Minute) % 60)
seconds := int64((remaining / time.Second) % 60)
var str string
switch d.style {
case ET_STYLE_GO:
str = fmt.Sprint(time.Duration(remaining.Seconds()) * time.Second)
case ET_STYLE_HHMMSS:
str = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
case ET_STYLE_HHMM:
str = fmt.Sprintf("%02d:%02d", hours, minutes)
case ET_STYLE_MMSS:
if hours > 0 {
str = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
} else {
str = fmt.Sprintf("%02d:%02d", minutes, seconds)
}
}
return d.FormatMsg(str)
}
func (d *movingAverageETA) NextAmount(n int, wdd ...time.Duration) {
var workDuration time.Duration
for _, wd := range wdd {
workDuration = wd
}
lastItemEstimate := float64(workDuration) / float64(n)
if math.IsInf(lastItemEstimate, 0) || math.IsNaN(lastItemEstimate) {
return
}
d.average.Add(lastItemEstimate)
}
func (d *movingAverageETA) OnCompleteMessage(msg string) {
d.completeMsg = &msg
}
// AverageETA decorator.
//
// `style` one of [ET_STYLE_GO|ET_STYLE_HHMMSS|ET_STYLE_HHMM|ET_STYLE_MMSS]
//
// `wcc` optional WC config
func AverageETA(style TimeStyle, wcc ...WC) Decorator {
var wc WC
for _, widthConf := range wcc {
wc = widthConf
}
wc.Init()
d := &averageETA{
WC: wc,
style: style,
startTime: time.Now(),
}
return d
}
type averageETA struct {
WC
style TimeStyle
startTime time.Time
completeMsg *string
}
func (d *averageETA) Decor(st *Statistics) string {
if st.Completed && d.completeMsg != nil {
return d.FormatMsg(*d.completeMsg)
}
var str string
timeElapsed := time.Since(d.startTime)
v := math.Round(float64(timeElapsed) / float64(st.Current))
if math.IsInf(v, 0) || math.IsNaN(v) {
v = 0
}
remaining := time.Duration((st.Total - st.Current) * int64(v))
hours := int64((remaining / time.Hour) % 60)
minutes := int64((remaining / time.Minute) % 60)
seconds := int64((remaining / time.Second) % 60)
switch d.style {
case ET_STYLE_GO:
str = fmt.Sprint(time.Duration(remaining.Seconds()) * time.Second)
case ET_STYLE_HHMMSS:
str = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
case ET_STYLE_HHMM:
str = fmt.Sprintf("%02d:%02d", hours, minutes)
case ET_STYLE_MMSS:
if hours > 0 {
str = fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
} else {
str = fmt.Sprintf("%02d:%02d", minutes, seconds)
}
}
return d.FormatMsg(str)
}
func (d *averageETA) OnCompleteMessage(msg string) {
d.completeMsg = &msg
}
func MaxTolerateTimeNormalizer(maxTolerate time.Duration) TimeNormalizer {
var normalized time.Duration
var lastCall time.Time
return func(remaining time.Duration) time.Duration {
if diff := normalized - remaining; diff <= 0 || diff > maxTolerate || remaining < maxTolerate/2 {
normalized = remaining
lastCall = time.Now()
return remaining
}
normalized -= time.Since(lastCall)
lastCall = time.Now()
return normalized
}
}
func FixedIntervalTimeNormalizer(updInterval int) TimeNormalizer {
var normalized time.Duration
var lastCall time.Time
var count int
return func(remaining time.Duration) time.Duration {
if count == 0 || remaining <= time.Duration(15*time.Second) {
count = updInterval
normalized = remaining
lastCall = time.Now()
return remaining
}
count--
normalized -= time.Since(lastCall)
lastCall = time.Now()
if normalized > 0 {
return normalized
}
return remaining
}
}
func NopNormalizer() TimeNormalizer {
return func(remaining time.Duration) time.Duration {
return remaining
}
}
| {
"content_hash": "5ccee0fa2768a00d3175099c8efe24ab",
"timestamp": "",
"source": "github",
"line_count": 206,
"max_line_length": 115,
"avg_line_length": 25.601941747572816,
"alnum_prop": 0.6971937808115283,
"repo_name": "dcos/dcos-cli",
"id": "e8dc979b433ff1d163626ab2162097eaf0fadb92",
"size": "5274",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/github.com/vbauerster/mpb/decor/eta.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "468"
},
{
"name": "Dockerfile",
"bytes": "270"
},
{
"name": "Go",
"bytes": "219403"
},
{
"name": "Groovy",
"bytes": "16295"
},
{
"name": "HCL",
"bytes": "212"
},
{
"name": "HTML",
"bytes": "2583"
},
{
"name": "JavaScript",
"bytes": "18776"
},
{
"name": "Makefile",
"bytes": "1305"
},
{
"name": "Python",
"bytes": "41428"
},
{
"name": "Shell",
"bytes": "18870"
}
],
"symlink_target": ""
} |
FROM python:3.9 AS build
LABEL maintainer="EclecticIQ <opentaxii@eclecticiq.com>"
RUN apt-get update \
&& apt-get install -y libmariadb-dev-compat
RUN python3 -m venv /venv && /venv/bin/pip install -U pip setuptools
COPY ./requirements.txt ./requirements-docker.txt /opentaxii/
RUN /venv/bin/pip install -r /opentaxii/requirements.txt -r /opentaxii/requirements-docker.txt
COPY . /opentaxii
RUN /venv/bin/pip install /opentaxii
FROM python:3.9-slim AS prod
LABEL maintainer="EclecticIQ <opentaxii@eclecticiq.com>"
COPY --from=build /venv /venv
RUN apt-get update \
&& apt-get upgrade -y \
&& apt-get install -y mariadb-client postgresql-client \
&& apt-get autoremove \
&& apt-get autoclean \
&& mkdir /data /input
VOLUME ["/data", "/input"]
COPY ./docker/entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
EXPOSE 9000
ENV PATH "/venv/bin:${PATH}"
ENV PYTHONDONTWRITEBYTECODE "1"
CMD ["/venv/bin/gunicorn", "opentaxii.http:app", "--workers=2", \
"--log-level=info", "--log-file=-", "--timeout=300", \
"--config=python:opentaxii.http", "--bind=0.0.0.0:9000"]
| {
"content_hash": "a2880dd4712b15ee99b8aa0184f08f02",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 94,
"avg_line_length": 30.305555555555557,
"alnum_prop": 0.7076076993583869,
"repo_name": "EclecticIQ/OpenTAXII",
"id": "82486a696df04659190e787722f50419da345820",
"size": "1091",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "237268"
},
{
"name": "Shell",
"bytes": "3174"
}
],
"symlink_target": ""
} |
#!/usr/bin/env node
'use strict';
/*eslint no-console: 0, no-sync: 0*/
// UMD bundler
// simple and yet reusable system.js bundler
// bundles, minifies and gzips
const fs = require('fs');
const del = require('del');
const path = require('path');
const zlib = require('zlib');
const async = require('async');
const Builder = require('systemjs-builder');
const pkg = require('../package.json');
const name = pkg.name;
const targetFolder = path.resolve('./bundles');
async.waterfall([
cleanBundlesFolder,
getSystemJsBundleConfig,
buildSystemJs({minify: false, sourceMaps: true, mangle: false, noEmitHelpers: false, declaration: true}),
getSystemJsBundleConfig,
buildSystemJs({minify: true, sourceMaps: true, mangle: false, noEmitHelpers: false, declaration: true})
], err => {
if (err) {
throw err;
}
});
function getSystemJsBundleConfig(cb) {
const config = {
baseURL: '.',
transpiler: 'typescript',
typescriptOptions: {
module: 'cjs'
},
map: {
typescript: './node_modules/typescript/lib/typescript',
'@angular': './node_modules/@angular',
rxjs: './node_modules/rxjs'
},
paths: {
'*': '*.js'
},
meta: {
'./node_modules/@angular/*': {build: false},
'./node_modules/rxjs/*': {build: false},
moment: {build: false}
}
};
return cb(null, config);
}
function cleanBundlesFolder(cb) {
return del(targetFolder)
.then(paths => {
console.log('Deleted files and folders:\n', paths.join('\n'));
cb();
});
}
function buildSystemJs(options) {
return (config, cb) => {
const minPostFix = options && options.minify ? '.umd.min' : '.umd';
const fileName = `${name}${minPostFix}.js`;
const dest = path.resolve(__dirname, targetFolder, fileName);
const builder = new Builder();
console.log('Bundling system.js file:', fileName, options);
builder.config(config);
return builder
.buildStatic(name, dest, {format: 'umd'})
.then(() => {
console.log('Build complete.');
cb();
})
.catch(err => {
console.log('Error', err);
cb();
});
};
}
| {
"content_hash": "04f04de76823da221f260f8617e5379c",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 107,
"avg_line_length": 24.179775280898877,
"alnum_prop": 0.6096654275092936,
"repo_name": "travelist/angular2-fontawesome",
"id": "f7ee392086eae9edb89acb0b516a8ebc257c46e5",
"size": "2152",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".config/umd-bundler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "80"
},
{
"name": "HTML",
"bytes": "734"
},
{
"name": "JavaScript",
"bytes": "3797"
},
{
"name": "TypeScript",
"bytes": "16542"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.schema.descriptors;
import com.google.common.collect.Lists;
import org.hisp.dhis.dashboard.DashboardItem;
import org.hisp.dhis.schema.Authority;
import org.hisp.dhis.schema.AuthorityType;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaDescriptor;
import org.springframework.stereotype.Component;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@Component
public class DashboardItemSchemaDescriptor implements SchemaDescriptor
{
public static final String SINGULAR = "dashboardItem";
public static final String PLURAL = "dashboardItems";
public static final String API_ENDPOINT = "/" + PLURAL;
@Override
public Schema getSchema()
{
Schema schema = new Schema( DashboardItem.class, SINGULAR, PLURAL );
schema.setRelativeApiEndpoint( API_ENDPOINT );
schema.setShareable( false );
schema.setOrder( 1600 );
schema.getAuthorities().add( new Authority( AuthorityType.CREATE_PUBLIC, Lists.newArrayList( "F_DASHBOARD_PUBLIC_ADD" ) ) );
return schema;
}
}
| {
"content_hash": "687618f0756945e4cba9ac90b19dbc46",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 132,
"avg_line_length": 29.37837837837838,
"alnum_prop": 0.7322907083716651,
"repo_name": "kakada/dhis2",
"id": "ccf13c1b45a98a7c0b0c287e9a2ffb2fe703c5f4",
"size": "2643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dhis-api/src/main/java/org/hisp/dhis/schema/descriptors/DashboardItemSchemaDescriptor.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "396164"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "340997"
},
{
"name": "Java",
"bytes": "18116166"
},
{
"name": "JavaScript",
"bytes": "7103857"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "376"
},
{
"name": "XSLT",
"bytes": "24103"
}
],
"symlink_target": ""
} |
export = ZipFile;
declare function ZipFile(): void;
declare class ZipFile {
open(path: string, mode: string): void;
close(): void;
write(paths: string | any[]): void;
writeString(string: string, fileName: string): void;
extract(path: string, pathToExtract: string): void;
extractAll(path: string): void;
getFileNames(): any[];
}
| {
"content_hash": "5f82b491e878756222137a53b8df7bed",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 32.45454545454545,
"alnum_prop": 0.6666666666666666,
"repo_name": "markogresak/DefinitelyTyped",
"id": "07da53cdb895a9af85abbbe6e206b25a54c40f21",
"size": "357",
"binary": false,
"copies": "21",
"ref": "refs/heads/master",
"path": "types/nginstack__engine/lib/compress/ZipFile.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17426898"
}
],
"symlink_target": ""
} |
using Microsoft.WindowsAzure.Storage.Table;
namespace FunctionAppSample
{
public class BotStatus : EventSourceState
{
public string Location { get; set; }
public string CurrentApp { get; set; }
public BotStatus() { }
}
}
| {
"content_hash": "58dcee429ed59963a6209fb9955b5fd7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 46,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.65,
"repo_name": "pierre3/LineMessagingApi",
"id": "d7da16de82c680b480f8e5c2194ed3c2c25eafe1",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FunctionAppSample/Samples/Models/BotStatus.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "228"
},
{
"name": "C#",
"bytes": "500869"
},
{
"name": "CSS",
"bytes": "1868"
},
{
"name": "HTML",
"bytes": "3527"
}
],
"symlink_target": ""
} |
export { Action, createAction, Dispatch } from "./common";
export { editorAction, EditorActionTypes, EditorPayload } from "./editor";
export { parseAction, ParseActionTypes, ParsePayload } from "./parse";
export { partAction, PartActionTypes, PartPayload } from "./part";
export { partTreeAction, PartTreeActionTypes, PartTreePayload } from "./partTree";
export { tabAction, TabActionTypes, TabPayload } from "./tab";
| {
"content_hash": "24f81d1a72896fdb36b00dd8ef2bcd8b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 82,
"avg_line_length": 69.66666666666667,
"alnum_prop": 0.7559808612440191,
"repo_name": "defvar/toyctron",
"id": "2e239cbfe4853f4014e21a592449943f014b0bc4",
"size": "418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/renderer/actions/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3041"
},
{
"name": "HTML",
"bytes": "815"
},
{
"name": "JavaScript",
"bytes": "10594"
},
{
"name": "TypeScript",
"bytes": "141385"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: cpu/o3/decode.cc File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.7 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="classes.html"><span>Classes</span></a></li>
<li id="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul></div>
<h1>cpu/o3/decode.cc File Reference</h1><code>#include "<a class="el" href="decode__impl_8hh-source.html">cpu/o3/decode_impl.hh</a>"</code><br>
<code>#include "<a class="el" href="isa__specific_8hh-source.html">cpu/o3/isa_specific.hh</a>"</code><br>
<p>
<a href="o3_2decode_8cc-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
</table>
<hr size="1"><address style="align: right;"><small>
Generated on Fri Apr 17 12:39:08 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address>
</body>
</html>
| {
"content_hash": "d1aa08e7b2f6c1e3e59d0b7c7c7441ea",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 153,
"avg_line_length": 45.41860465116279,
"alnum_prop": 0.6175115207373272,
"repo_name": "wnoc-drexel/gem5-stable",
"id": "a6bfaf2820bb26be5780ad82b285736af808e63b",
"size": "1953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/doxygen/html/o3_2decode_8cc.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "239800"
},
{
"name": "C",
"bytes": "957228"
},
{
"name": "C++",
"bytes": "13915041"
},
{
"name": "CSS",
"bytes": "9813"
},
{
"name": "Emacs Lisp",
"bytes": "1969"
},
{
"name": "Groff",
"bytes": "11130043"
},
{
"name": "HTML",
"bytes": "132838214"
},
{
"name": "Java",
"bytes": "3096"
},
{
"name": "Makefile",
"bytes": "20709"
},
{
"name": "PHP",
"bytes": "10107"
},
{
"name": "Perl",
"bytes": "36183"
},
{
"name": "Protocol Buffer",
"bytes": "3246"
},
{
"name": "Python",
"bytes": "3739380"
},
{
"name": "Shell",
"bytes": "49333"
},
{
"name": "Visual Basic",
"bytes": "2884"
}
],
"symlink_target": ""
} |
import cgi
import unittest
from six.moves import xmlrpc_client as xmlrpclib
from six.moves.urllib.parse import urlparse
from pyrake.http import Request, FormRequest, XmlRpcRequest, Headers, HtmlResponse
class RequestTest(unittest.TestCase):
request_class = Request
default_method = 'GET'
default_headers = {}
default_meta = {}
def test_init(self):
# Request requires url in the constructor
self.assertRaises(Exception, self.request_class)
# url argument must be basestring
self.assertRaises(TypeError, self.request_class, 123)
r = self.request_class('http://www.example.com')
r = self.request_class("http://www.example.com")
assert isinstance(r.url, str)
self.assertEqual(r.url, "http://www.example.com")
self.assertEqual(r.method, self.default_method)
assert isinstance(r.headers, Headers)
self.assertEqual(r.headers, self.default_headers)
self.assertEqual(r.meta, self.default_meta)
meta = {"lala": "lolo"}
headers = {"caca": "coco"}
r = self.request_class("http://www.example.com", meta=meta, headers=headers, body="a body")
assert r.meta is not meta
self.assertEqual(r.meta, meta)
assert r.headers is not headers
self.assertEqual(r.headers["caca"], "coco")
def test_url_no_scheme(self):
self.assertRaises(ValueError, self.request_class, 'foo')
def test_headers(self):
# Different ways of setting headers attribute
url = 'http://www.pyrake.org'
headers = {'Accept':'gzip', 'Custom-Header':'nothing to tell you'}
r = self.request_class(url=url, headers=headers)
p = self.request_class(url=url, headers=r.headers)
self.assertEqual(r.headers, p.headers)
self.assertFalse(r.headers is headers)
self.assertFalse(p.headers is r.headers)
# headers must not be unicode
h = Headers({'key1': u'val1', u'key2': 'val2'})
h[u'newkey'] = u'newval'
for k, v in h.iteritems():
self.assert_(isinstance(k, str))
for s in v:
self.assert_(isinstance(s, str))
def test_eq(self):
url = 'http://www.pyrake.org'
r1 = self.request_class(url=url)
r2 = self.request_class(url=url)
self.assertNotEqual(r1, r2)
set_ = set()
set_.add(r1)
set_.add(r2)
self.assertEqual(len(set_), 2)
def test_url(self):
"""Request url tests"""
r = self.request_class(url="http://www.pyrake.org/path")
self.assertEqual(r.url, "http://www.pyrake.org/path")
# url quoting on creation
r = self.request_class(url="http://www.pyrake.org/blank%20space")
self.assertEqual(r.url, "http://www.pyrake.org/blank%20space")
r = self.request_class(url="http://www.pyrake.org/blank space")
self.assertEqual(r.url, "http://www.pyrake.org/blank%20space")
# url encoding
r1 = self.request_class(url=u"http://www.pyrake.org/price/\xa3", encoding="utf-8")
r2 = self.request_class(url=u"http://www.pyrake.org/price/\xa3", encoding="latin1")
self.assertEqual(r1.url, "http://www.pyrake.org/price/%C2%A3")
self.assertEqual(r2.url, "http://www.pyrake.org/price/%A3")
def test_body(self):
r1 = self.request_class(url="http://www.example.com/")
assert r1.body == ''
r2 = self.request_class(url="http://www.example.com/", body="")
assert isinstance(r2.body, str)
self.assertEqual(r2.encoding, 'utf-8') # default encoding
r3 = self.request_class(url="http://www.example.com/", body=u"Price: \xa3100", encoding='utf-8')
assert isinstance(r3.body, str)
self.assertEqual(r3.body, "Price: \xc2\xa3100")
r4 = self.request_class(url="http://www.example.com/", body=u"Price: \xa3100", encoding='latin1')
assert isinstance(r4.body, str)
self.assertEqual(r4.body, "Price: \xa3100")
def test_ajax_url(self):
# ascii url
r = self.request_class(url="http://www.example.com/ajax.html#!key=value")
self.assertEqual(r.url, "http://www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue")
# unicode url
r = self.request_class(url=u"http://www.example.com/ajax.html#!key=value")
self.assertEqual(r.url, "http://www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue")
def test_copy(self):
"""Test Request copy"""
def somecallback():
pass
r1 = self.request_class("http://www.example.com", callback=somecallback, errback=somecallback)
r1.meta['foo'] = 'bar'
r2 = r1.copy()
# make sure copy does not propagate callbacks
assert r1.callback is somecallback
assert r1.errback is somecallback
assert r2.callback is r1.callback
assert r2.errback is r2.errback
# make sure meta dict is shallow copied
assert r1.meta is not r2.meta, "meta must be a shallow copy, not identical"
self.assertEqual(r1.meta, r2.meta)
# make sure headers attribute is shallow copied
assert r1.headers is not r2.headers, "headers must be a shallow copy, not identical"
self.assertEqual(r1.headers, r2.headers)
self.assertEqual(r1.encoding, r2.encoding)
self.assertEqual(r1.dont_filter, r2.dont_filter)
# Request.body can be identical since it's an immutable object (str)
def test_copy_inherited_classes(self):
"""Test Request children copies preserve their class"""
class CustomRequest(self.request_class):
pass
r1 = CustomRequest('http://www.example.com')
r2 = r1.copy()
assert type(r2) is CustomRequest
def test_replace(self):
"""Test Request.replace() method"""
r1 = self.request_class("http://www.example.com", method='GET')
hdrs = Headers(dict(r1.headers, key='value'))
r2 = r1.replace(method="POST", body="New body", headers=hdrs)
self.assertEqual(r1.url, r2.url)
self.assertEqual((r1.method, r2.method), ("GET", "POST"))
self.assertEqual((r1.body, r2.body), ('', "New body"))
self.assertEqual((r1.headers, r2.headers), (self.default_headers, hdrs))
# Empty attributes (which may fail if not compared properly)
r3 = self.request_class("http://www.example.com", meta={'a': 1}, dont_filter=True)
r4 = r3.replace(url="http://www.example.com/2", body='', meta={}, dont_filter=False)
self.assertEqual(r4.url, "http://www.example.com/2")
self.assertEqual(r4.body, '')
self.assertEqual(r4.meta, {})
assert r4.dont_filter is False
def test_method_always_str(self):
r = self.request_class("http://www.example.com", method=u"POST")
assert isinstance(r.method, str)
def test_immutable_attributes(self):
r = self.request_class("http://example.com")
self.assertRaises(AttributeError, setattr, r, 'url', 'http://example2.com')
self.assertRaises(AttributeError, setattr, r, 'body', 'xxx')
class FormRequestTest(RequestTest):
request_class = FormRequest
def assertSortedEqual(self, first, second, msg=None):
return self.assertEqual(sorted(first), sorted(second), msg)
def test_empty_formdata(self):
r1 = self.request_class("http://www.example.com", formdata={})
self.assertEqual(r1.body, '')
def test_default_encoding(self):
# using default encoding (utf-8)
data = {'one': 'two', 'price': '\xc2\xa3 100'}
r2 = self.request_class("http://www.example.com", formdata=data)
self.assertEqual(r2.method, 'POST')
self.assertEqual(r2.encoding, 'utf-8')
self.assertSortedEqual(r2.body.split('&'),
'price=%C2%A3+100&one=two'.split('&'))
self.assertEqual(r2.headers['Content-Type'], 'application/x-www-form-urlencoded')
def test_custom_encoding(self):
data = {'price': u'\xa3 100'}
r3 = self.request_class("http://www.example.com", formdata=data, encoding='latin1')
self.assertEqual(r3.encoding, 'latin1')
self.assertEqual(r3.body, 'price=%A3+100')
def test_multi_key_values(self):
# using multiples values for a single key
data = {'price': u'\xa3 100', 'colours': ['red', 'blue', 'green']}
r3 = self.request_class("http://www.example.com", formdata=data)
self.assertSortedEqual(r3.body.split('&'),
'colours=red&colours=blue&colours=green&price=%C2%A3+100'.split('&'))
def test_from_response_post(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
<input type="hidden" name="test" value="val1">
<input type="hidden" name="test" value="val2">
<input type="hidden" name="test2" value="xxx">
</form>""",
url="http://www.example.com/this/list.html")
req = self.request_class.from_response(response,
formdata={'one': ['two', 'three'], 'six': 'seven'})
self.assertEqual(req.method, 'POST')
self.assertEqual(req.headers['Content-type'], 'application/x-www-form-urlencoded')
self.assertEqual(req.url, "http://www.example.com/this/post.php")
fs = _qs(req)
self.assertEqual(set(fs["test"]), set(["val1", "val2"]))
self.assertEqual(set(fs["one"]), set(["two", "three"]))
self.assertEqual(fs['test2'], ['xxx'])
self.assertEqual(fs['six'], ['seven'])
def test_from_response_extra_headers(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
<input type="hidden" name="test" value="val1">
<input type="hidden" name="test" value="val2">
<input type="hidden" name="test2" value="xxx">
</form>""")
req = self.request_class.from_response(response,
formdata={'one': ['two', 'three'], 'six': 'seven'},
headers={"Accept-Encoding": "gzip,deflate"})
self.assertEqual(req.method, 'POST')
self.assertEqual(req.headers['Content-type'], 'application/x-www-form-urlencoded')
self.assertEqual(req.headers['Accept-Encoding'], 'gzip,deflate')
def test_from_response_get(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="hidden" name="test" value="val1">
<input type="hidden" name="test" value="val2">
<input type="hidden" name="test2" value="xxx">
</form>""",
url="http://www.example.com/this/list.html")
r1 = self.request_class.from_response(response,
formdata={'one': ['two', 'three'], 'six': 'seven'})
self.assertEqual(r1.method, 'GET')
self.assertEqual(urlparse(r1.url).hostname, "www.example.com")
self.assertEqual(urlparse(r1.url).path, "/this/get.php")
fs = _qs(r1)
self.assertEqual(set(fs['test']), set(['val1', 'val2']))
self.assertEqual(set(fs['one']), set(['two', 'three']))
self.assertEqual(fs['test2'], ['xxx'])
self.assertEqual(fs['six'], ['seven'])
def test_from_response_override_params(self):
response = _buildresponse(
"""<form action="get.php" method="POST">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="3">
</form>""")
req = self.request_class.from_response(response, formdata={'two': '2'})
fs = _qs(req)
self.assertEqual(fs['one'], ['1'])
self.assertEqual(fs['two'], ['2'])
def test_from_response_override_method(self):
response = _buildresponse(
'''<html><body>
<form action="/app"></form>
</body></html>''')
request = FormRequest.from_response(response)
self.assertEqual(request.method, 'GET')
request = FormRequest.from_response(response, method='POST')
self.assertEqual(request.method, 'POST')
def test_from_response_override_url(self):
response = _buildresponse(
'''<html><body>
<form action="/app"></form>
</body></html>''')
request = FormRequest.from_response(response)
self.assertEqual(request.url, 'http://example.com/app')
request = FormRequest.from_response(response, url='http://foo.bar/absolute')
self.assertEqual(request.url, 'http://foo.bar/absolute')
request = FormRequest.from_response(response, url='/relative')
self.assertEqual(request.url, 'http://example.com/relative')
def test_from_response_submit_first_clickable(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="submit" name="clickable1" value="clicked1">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="3">
<input type="submit" name="clickable2" value="clicked2">
</form>""")
req = self.request_class.from_response(response, formdata={'two': '2'})
fs = _qs(req)
self.assertEqual(fs['clickable1'], ['clicked1'])
self.assertFalse('clickable2' in fs, fs)
self.assertEqual(fs['one'], ['1'])
self.assertEqual(fs['two'], ['2'])
def test_from_response_submit_not_first_clickable(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="submit" name="clickable1" value="clicked1">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="3">
<input type="submit" name="clickable2" value="clicked2">
</form>""")
req = self.request_class.from_response(response, formdata={'two': '2'}, \
clickdata={'name': 'clickable2'})
fs = _qs(req)
self.assertEqual(fs['clickable2'], ['clicked2'])
self.assertFalse('clickable1' in fs, fs)
self.assertEqual(fs['one'], ['1'])
self.assertEqual(fs['two'], ['2'])
def test_from_response_dont_submit_image_as_input(self):
response = _buildresponse(
"""<form>
<input type="hidden" name="i1" value="i1v">
<input type="image" name="i2" src="http://my.image.org/1.jpg">
<input type="submit" name="i3" value="i3v">
</form>""")
req = self.request_class.from_response(response, dont_click=True)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v']})
def test_from_response_dont_submit_reset_as_input(self):
response = _buildresponse(
"""<form>
<input type="hidden" name="i1" value="i1v">
<input type="text" name="i2" value="i2v">
<input type="reset" name="resetme">
<input type="submit" name="i3" value="i3v">
</form>""")
req = self.request_class.from_response(response, dont_click=True)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v'], 'i2': ['i2v']})
def test_from_response_multiple_clickdata(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="submit" name="clickable" value="clicked1">
<input type="submit" name="clickable" value="clicked2">
<input type="hidden" name="one" value="clicked1">
<input type="hidden" name="two" value="clicked2">
</form>""")
req = self.request_class.from_response(response, \
clickdata={'name': 'clickable', 'value': 'clicked2'})
fs = _qs(req)
self.assertEqual(fs['clickable'], ['clicked2'])
self.assertEqual(fs['one'], ['clicked1'])
self.assertEqual(fs['two'], ['clicked2'])
def test_from_response_unicode_clickdata(self):
response = _buildresponse(
u"""<form action="get.php" method="GET">
<input type="submit" name="price in \u00a3" value="\u00a3 1000">
<input type="submit" name="price in \u20ac" value="\u20ac 2000">
<input type="hidden" name="poundsign" value="\u00a3">
<input type="hidden" name="eurosign" value="\u20ac">
</form>""")
req = self.request_class.from_response(response, \
clickdata={'name': u'price in \u00a3'})
fs = _qs(req)
self.assertTrue(fs[u'price in \u00a3'.encode('utf-8')])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1">
<input type="submit" name="clickable" value="clicked1">
<input type="hidden" name="field1" value="value1">
</form>
<form name="form2">
<input type="submit" name="clickable" value="clicked2">
<input type="hidden" name="field2" value="value2">
</form>
""")
req = self.request_class.from_response(response, formname='form2', \
clickdata={'name': 'clickable'})
fs = _qs(req)
self.assertEqual(fs['clickable'], ['clicked2'])
self.assertEqual(fs['field2'], ['value2'])
self.assertFalse('field1' in fs, fs)
def test_from_response_override_clickable(self):
response = _buildresponse('''<form><input type="submit" name="clickme" value="one"> </form>''')
req = self.request_class.from_response(response, \
formdata={'clickme': 'two'}, clickdata={'name': 'clickme'})
fs = _qs(req)
self.assertEqual(fs['clickme'], ['two'])
def test_from_response_dont_click(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="submit" name="clickable1" value="clicked1">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="3">
<input type="submit" name="clickable2" value="clicked2">
</form>""")
r1 = self.request_class.from_response(response, dont_click=True)
fs = _qs(r1)
self.assertFalse('clickable1' in fs, fs)
self.assertFalse('clickable2' in fs, fs)
def test_from_response_ambiguous_clickdata(self):
response = _buildresponse(
"""
<form action="get.php" method="GET">
<input type="submit" name="clickable1" value="clicked1">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="3">
<input type="submit" name="clickable2" value="clicked2">
</form>""")
self.assertRaises(ValueError, self.request_class.from_response,
response, clickdata={'type': 'submit'})
def test_from_response_non_matching_clickdata(self):
response = _buildresponse(
"""<form>
<input type="submit" name="clickable" value="clicked">
</form>""")
self.assertRaises(ValueError, self.request_class.from_response,
response, clickdata={'nonexistent': 'notme'})
def test_from_response_nr_index_clickdata(self):
response = _buildresponse(
"""<form>
<input type="submit" name="clickable1" value="clicked1">
<input type="submit" name="clickable2" value="clicked2">
</form>
""")
req = self.request_class.from_response(response, clickdata={'nr': 1})
fs = _qs(req)
self.assertIn('clickable2', fs)
self.assertNotIn('clickable1', fs)
def test_from_response_invalid_nr_index_clickdata(self):
response = _buildresponse(
"""<form>
<input type="submit" name="clickable" value="clicked">
</form>
""")
self.assertRaises(ValueError, self.request_class.from_response,
response, clickdata={'nr': 1})
def test_from_response_errors_noform(self):
response = _buildresponse("""<html></html>""")
self.assertRaises(ValueError, self.request_class.from_response, response)
def test_from_response_invalid_html5(self):
response = _buildresponse("""<!DOCTYPE html><body></html><form>"""
"""<input type="text" name="foo" value="xxx">"""
"""</form></body></html>""")
req = self.request_class.from_response(response, formdata={'bar': 'buz'})
fs = _qs(req)
self.assertEqual(fs, {'foo': ['xxx'], 'bar': ['buz']})
def test_from_response_errors_formnumber(self):
response = _buildresponse(
"""<form action="get.php" method="GET">
<input type="hidden" name="test" value="val1">
<input type="hidden" name="test" value="val2">
<input type="hidden" name="test2" value="xxx">
</form>""")
self.assertRaises(IndexError, self.request_class.from_response, response, formnumber=1)
def test_from_response_noformname(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="2">
</form>""")
r1 = self.request_class.from_response(response, formdata={'two':'3'})
self.assertEqual(r1.method, 'POST')
self.assertEqual(r1.headers['Content-type'], 'application/x-www-form-urlencoded')
fs = _qs(r1)
self.assertEqual(fs, {'one': ['1'], 'two': ['3']})
def test_from_response_formname_exists(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="2">
</form>
<form name="form2" action="post.php" method="POST">
<input type="hidden" name="three" value="3">
<input type="hidden" name="four" value="4">
</form>""")
r1 = self.request_class.from_response(response, formname="form2")
self.assertEqual(r1.method, 'POST')
fs = _qs(r1)
self.assertEqual(fs, {'four': ['4'], 'three': ['3']})
def test_from_response_formname_notexist(self):
response = _buildresponse(
"""<form name="form1" action="post.php" method="POST">
<input type="hidden" name="one" value="1">
</form>
<form name="form2" action="post.php" method="POST">
<input type="hidden" name="two" value="2">
</form>""")
r1 = self.request_class.from_response(response, formname="form3")
self.assertEqual(r1.method, 'POST')
fs = _qs(r1)
self.assertEqual(fs, {'one': ['1']})
def test_from_response_formname_errors_formnumber(self):
response = _buildresponse(
"""<form name="form1" action="post.php" method="POST">
<input type="hidden" name="one" value="1">
</form>
<form name="form2" action="post.php" method="POST">
<input type="hidden" name="two" value="2">
</form>""")
self.assertRaises(IndexError, self.request_class.from_response, \
response, formname="form3", formnumber=2)
def test_from_response_select(self):
res = _buildresponse(
'''<form>
<select name="i1">
<option value="i1v1">option 1</option>
<option value="i1v2" selected>option 2</option>
</select>
<select name="i2">
<option value="i2v1">option 1</option>
<option value="i2v2">option 2</option>
</select>
<select>
<option value="i3v1">option 1</option>
<option value="i3v2">option 2</option>
</select>
<select name="i4" multiple>
<option value="i4v1">option 1</option>
<option value="i4v2" selected>option 2</option>
<option value="i4v3" selected>option 3</option>
</select>
<select name="i5" multiple>
<option value="i5v1">option 1</option>
<option value="i5v2">option 2</option>
</select>
<select name="i6"></select>
<select name="i7"/>
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v2'], 'i2': ['i2v1'], 'i4': ['i4v2', 'i4v3']})
def test_from_response_radio(self):
res = _buildresponse(
'''<form>
<input type="radio" name="i1" value="i1v1">
<input type="radio" name="i1" value="iv2" checked>
<input type="radio" name="i2" checked>
<input type="radio" name="i2">
<input type="radio" name="i3" value="i3v1">
<input type="radio" name="i3">
<input type="radio" value="i4v1">
<input type="radio">
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['iv2'], 'i2': ['on']})
def test_from_response_checkbox(self):
res = _buildresponse(
'''<form>
<input type="checkbox" name="i1" value="i1v1">
<input type="checkbox" name="i1" value="iv2" checked>
<input type="checkbox" name="i2" checked>
<input type="checkbox" name="i2">
<input type="checkbox" name="i3" value="i3v1">
<input type="checkbox" name="i3">
<input type="checkbox" value="i4v1">
<input type="checkbox">
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['iv2'], 'i2': ['on']})
def test_from_response_input_text(self):
res = _buildresponse(
'''<form>
<input type="text" name="i1" value="i1v1">
<input type="text" name="i2">
<input type="text" value="i3v1">
<input type="text">
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v1'], 'i2': ['']})
def test_from_response_input_hidden(self):
res = _buildresponse(
'''<form>
<input type="hidden" name="i1" value="i1v1">
<input type="hidden" name="i2">
<input type="hidden" value="i3v1">
<input type="hidden">
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v1'], 'i2': ['']})
def test_from_response_input_textarea(self):
res = _buildresponse(
'''<form>
<textarea name="i1">i1v</textarea>
<textarea name="i2"></textarea>
<textarea name="i3"/>
<textarea>i4v</textarea>
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(fs, {'i1': ['i1v'], 'i2': [''], 'i3': ['']})
def test_from_response_descendants(self):
res = _buildresponse(
'''<form>
<div>
<fieldset>
<input type="text" name="i1">
<select name="i2">
<option value="v1" selected>
</select>
</fieldset>
<input type="radio" name="i3" value="i3v2" checked>
<input type="checkbox" name="i4" value="i4v2" checked>
<textarea name="i5"></textarea>
<input type="hidden" name="h1" value="h1v">
</div>
<input type="hidden" name="h2" value="h2v">
</form>''')
req = self.request_class.from_response(res)
fs = _qs(req)
self.assertEqual(set(fs), set(['h2', 'i2', 'i1', 'i3', 'h1', 'i5', 'i4']))
def test_from_response_xpath(self):
response = _buildresponse(
"""<form action="post.php" method="POST">
<input type="hidden" name="one" value="1">
<input type="hidden" name="two" value="2">
</form>
<form action="post2.php" method="POST">
<input type="hidden" name="three" value="3">
<input type="hidden" name="four" value="4">
</form>""")
r1 = self.request_class.from_response(response, formxpath="//form[@action='post.php']")
fs = _qs(r1)
self.assertEqual(fs['one'], ['1'])
r1 = self.request_class.from_response(response, formxpath="//form/input[@name='four']")
fs = _qs(r1)
self.assertEqual(fs['three'], ['3'])
self.assertRaises(ValueError, self.request_class.from_response,
response, formxpath="//form/input[@name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault('encoding', 'utf-8')
return HtmlResponse(**kwargs)
def _qs(req):
if req.method == 'POST':
qs = req.body
else:
qs = req.url.partition('?')[2]
return cgi.parse_qs(qs, True)
class XmlRpcRequestTest(RequestTest):
request_class = XmlRpcRequest
default_method = 'POST'
default_headers = {'Content-Type': ['text/xml']}
def _test_request(self, **kwargs):
r = self.request_class('http://pyraketest.org/rpc2', **kwargs)
self.assertEqual(r.headers['Content-Type'], 'text/xml')
self.assertEqual(r.body, xmlrpclib.dumps(**kwargs))
self.assertEqual(r.method, 'POST')
self.assertEqual(r.encoding, kwargs.get('encoding', 'utf-8'))
self.assertTrue(r.dont_filter, True)
def test_xmlrpc_dumps(self):
self._test_request(params=('value',))
self._test_request(params=('username', 'password'), methodname='login')
self._test_request(params=('response', ), methodresponse='login')
self._test_request(params=(u'pas\xa3',), encoding='utf-8')
self._test_request(params=(u'pas\xa3',), encoding='latin')
self._test_request(params=(None,), allow_none=1)
self.assertRaises(TypeError, self._test_request)
self.assertRaises(TypeError, self._test_request, params=(None,))
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "e8db54eae46114c78c6b688aae43bab5",
"timestamp": "",
"source": "github",
"line_count": 716,
"max_line_length": 105,
"avg_line_length": 42.70670391061452,
"alnum_prop": 0.5660278631695991,
"repo_name": "elkingtowa/pyrake",
"id": "1ebae3156a1a7588fdbe54425a213895b31340f2",
"size": "30578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_http_request.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9681"
},
{
"name": "Perl",
"bytes": "1311"
},
{
"name": "Python",
"bytes": "1950905"
},
{
"name": "Shell",
"bytes": "3209"
}
],
"symlink_target": ""
} |
/* globals Engine, THREE, ObjectControls, $, THREEx, console */
'use strict';
Engine.createView = function( options ){
var that = {};
var renderWidth = window.innerWidth;
var renderHeight = window.innerHeight;
var camera = new THREE.PerspectiveCamera( 60, renderWidth/renderHeight, 0.1, 1000 );
// some default camera location
camera.position.set( 140, 130, 170 );
camera.position.normalize().multiplyScalar( 100 );
var rendererOptions = {
brightness: 1.0,
bloom: 0.5,
glowBlur: 1.0
};
if( options ){
rendererOptions = options;
}
var renderer = Engine.createRenderer( camera, rendererOptions );
var $render = $( '#render' );
if( $render.length === 0 ){
$render = $('<div>')
.attr( 'id', 'render' )
.addClass( ' unselectable' )
.appendTo( $( document.body ) );
}
$render.append( $( renderer.getDomElement() ) );
var scene = renderer.getScene();
var glowScene = renderer.getGlowScene();
var space = new THREE.Group();
scene.add( space );
var glowSpace = new THREE.Group();
glowScene.add( glowSpace );
// TODO
// place this elsewhere
// Engine.createDefaultLights().forEach( function( light ){
// scene.add( light );
// });
// TODO
// rewrite light engine for culling
var lights = [];
var deferredLightCount = 4096;
( function makeLights( count ){
do{
var light = new THREE.PointLight( 0xE0A075, 2.0, 2.0 );
// var light = new THREE.PointLight( 0x88aaff, 2.0, 2.0 );
light.visible = false;
light.enabled = false;
light.frustumCulled = true;
lights.push( light );
space.add( light );
}while( lights.length < count );
}( deferredLightCount ) );
that.setLight = function( idx, lightData ){
var light = lights[ idx ];
light.visible = true;
light.enabled = true;
light.position.set( lightData.x, lightData.y, lightData.z );
light.distance = lightData.distance;
light.intensity = lightData.intensity;
light.color.setHSL( lightData.h, lightData.s, lightData.l );
return light;
};
that.clearLights = function(){
lights.forEach( function( light ){
light.position.set( 0,0,0 );
light.visible = false;
light.enabled = false;
});
};
that.clearLightRange = function( start, count ){
var end = start + count;
for( var i=start; i<end; i++ ){
var light = lights[ i ];
light.position.set( 0,0,0 );
light.visible = false;
light.enabled = false;
}
};
var groupIdx = 0;
that.registerLightGroup = function( count ){
var current = groupIdx;
groupIdx += count;
if( groupIdx > deferredLightCount ){
console.warn( 'out of lights to register group' );
return 0;
}
return current;
};
var objectControls = new ObjectControls( camera );
var allowObjectControls = true;
objectControls.objectIntersected = function(){
if( this.intersected && allowObjectControls ){
var intersection = this.getIntersectionPoint( this.intersected );
if( this.intersected.hoverMove ){
var e = {
intersectionPoint: intersection
};
this.intersected.hoverMove( e );
}
}
};
function render(){
renderer.render();
}
THREEx.WindowResize( renderer.getForwardRenderer(), camera );
(function drawLoop( nowMsec )
{
if( allowObjectControls ){
objectControls.update();
}
render( nowMsec );
scene.traverse( function( o ){
if( o.update ){
if( o instanceof THREE.LOD ){
o.update( camera );
}
else{
o.update();
}
}
});
glowScene.traverse( function( o ){
if( o.update ){
if( o instanceof THREE.LOD ){
o.update( camera );
}
else{
o.update();
}
}
});
requestAnimationFrame( drawLoop );
})( Date.now() );
that.getRenderer = function(){
return renderer;
};
that.getSpace = function(){
return space;
};
that.getGlowSpace = function(){
return glowSpace;
};
that.getCamera = function(){
return camera;
};
that.getDomElement = function(){
return renderer.getDomElement();
};
return that;
};
Engine.createDefaultLights = function(){
var lights = [];
var light = new THREE.PointLight( 0xbbbbee, 7, 500 );
light.position.x = 40;
light.position.y = 70;
light.position.z = 300;
lights.push( light );
var light2 = new THREE.PointLight( 0x4477cc, 7, 500 );
light2.position.x = -140;
light2.position.y = -20;
light2.position.z = 170;
lights.push( light2 );
var light3 = new THREE.PointLight( 0xaaaaee, 5, 700 );
light3.position.x = -140;
light3.position.y = 160;
light3.position.z = -200;
lights.push( light3 );
return lights;
}; | {
"content_hash": "b5a8c9ad3231159c5da3e27d53cf5de5",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 86,
"avg_line_length": 22.781990521327014,
"alnum_prop": 0.6076555023923444,
"repo_name": "mflux/antler",
"id": "3fb9e5b5d4af67a8b4bf9ea57778cfd6b3da9a74",
"size": "4807",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/engine/view.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "366"
},
{
"name": "HTML",
"bytes": "643"
},
{
"name": "JavaScript",
"bytes": "23270"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "0260b67a5cef4af9373526a2c2ba3df8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f135e382a62ddaab38ecb706722473741172617c",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Malacothamnus/Malacothamnus densiflorus/Malvastrum densiflorum typicum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import unittest
from mock import mock
from oslo_utils import units
from cinder import coordination
from cinder.tests.unit.volume.drivers.dell_emc.unity \
import fake_exception as ex
from cinder.volume.drivers.dell_emc.unity import client
########################
#
# Start of Mocks
#
########################
class MockResource(object):
def __init__(self, name=None, _id=None):
self.name = name
self._id = _id
self.existed = True
self.size_total = 5 * units.Gi
self.size_subscribed = 6 * units.Gi
self.size_free = 2 * units.Gi
self.is_auto_delete = None
self.initiator_id = []
self.alu_hlu_map = {'already_attached': 99}
self.ip_address = None
self.is_logged_in = None
self.wwn = None
self.max_iops = None
self.max_kbps = None
self.pool_name = 'Pool0'
self._storage_resource = None
self.host_cache = []
@property
def id(self):
return self._id
def get_id(self):
return self._id
def delete(self):
if self.get_id() in ['snap_2']:
raise ex.SnapDeleteIsCalled()
elif self.get_id() == 'not_found':
raise ex.UnityResourceNotFoundError()
elif self.get_id() == 'snap_in_use':
raise ex.UnityDeleteAttachedSnapError()
elif self.name == 'empty_host':
raise ex.HostDeleteIsCalled()
@property
def pool(self):
return MockResource('pool0')
@property
def iscsi_host_initiators(self):
iscsi_initiator = MockResource('iscsi_initiator')
iscsi_initiator.initiator_id = ['iqn.1-1.com.e:c.host.0',
'iqn.1-1.com.e:c.host.1']
return iscsi_initiator
@property
def total_size_gb(self):
return self.size_total / units.Gi
@total_size_gb.setter
def total_size_gb(self, value):
if value == self.total_size_gb:
raise ex.UnityNothingToModifyError()
else:
self.size_total = value * units.Gi
def add_initiator(self, uid, force_create=None):
self.initiator_id.append(uid)
def attach(self, lun_or_snap, skip_hlu_0=True):
if lun_or_snap.get_id() == 'already_attached':
raise ex.UnityResourceAlreadyAttachedError()
self.alu_hlu_map[lun_or_snap.get_id()] = len(self.alu_hlu_map)
return self.get_hlu(lun_or_snap)
@staticmethod
def detach(lun_or_snap):
if lun_or_snap.name == 'detach_failure':
raise ex.DetachIsCalled()
@staticmethod
def detach_from(host):
if host is None:
raise ex.DetachFromIsCalled()
def get_hlu(self, lun):
return self.alu_hlu_map.get(lun.get_id(), None)
@staticmethod
def create_lun(lun_name, size_gb, description=None, io_limit_policy=None):
if lun_name == 'in_use':
raise ex.UnityLunNameInUseError()
ret = MockResource(lun_name, 'lun_2')
if io_limit_policy is not None:
ret.max_iops = io_limit_policy.max_iops
ret.max_kbps = io_limit_policy.max_kbps
return ret
@staticmethod
def create_snap(name, is_auto_delete=False):
if name == 'in_use':
raise ex.UnitySnapNameInUseError()
ret = MockResource(name)
ret.is_auto_delete = is_auto_delete
return ret
@staticmethod
def update(data=None):
pass
@property
def iscsi_node(self):
name = 'iqn.1-1.com.e:c.%s.0' % self.name
return MockResource(name)
@property
def fc_host_initiators(self):
init0 = MockResource('fhi_0')
init0.initiator_id = '00:11:22:33:44:55:66:77:88:99:AA:BB:CC:CD:EE:FF'
init1 = MockResource('fhi_1')
init1.initiator_id = '00:11:22:33:44:55:66:77:88:99:AA:BB:BC:CD:EE:FF'
return MockResourceList.create(init0, init1)
@property
def paths(self):
path0 = MockResource('%s_path_0' % self.name)
path0.is_logged_in = True
path1 = MockResource('%s_path_1' % self.name)
path1.is_logged_in = False
path2 = MockResource('%s_path_2' % self.name)
path2.is_logged_in = True
return MockResourceList.create(path0, path1)
@property
def fc_port(self):
ret = MockResource(_id='spa_iom_0_fc0')
ret.wwn = '00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF'
return ret
@property
def host_luns(self):
if self.name == 'host-no-host_luns':
return None
return []
@property
def storage_resource(self):
if self._storage_resource is None:
self._storage_resource = MockResource(_id='sr_%s' % self._id,
name='sr_%s' % self.name)
return self._storage_resource
@storage_resource.setter
def storage_resource(self, value):
self._storage_resource = value
def modify(self, name=None):
self.name = name
def thin_clone(self, name, io_limit_policy=None, description=None):
if name == 'thin_clone_name_in_use':
raise ex.UnityLunNameInUseError
return MockResource(_id=name, name=name)
def get_snap(self, name):
return MockResource(_id=name, name=name)
def restore(self, delete_backup):
return MockResource(_id='snap_1', name="internal_snap")
class MockResourceList(object):
def __init__(self, names=None, ids=None):
if names is not None:
self.resources = [MockResource(name=name) for name in names]
elif ids is not None:
self.resources = [MockResource(_id=_id) for _id in ids]
@staticmethod
def create(*rsc_list):
ret = MockResourceList([])
ret.resources = rsc_list
return ret
@property
def name(self):
return map(lambda i: i.name, self.resources)
def __iter__(self):
return self.resources.__iter__()
def __len__(self):
return len(self.resources)
def __getattr__(self, item):
return [getattr(i, item) for i in self.resources]
def shadow_copy(self, **kwargs):
if list(filter(None, kwargs.values())):
return MockResourceList.create(self.resources[0])
else:
return self
class MockSystem(object):
def __init__(self):
self.serial_number = 'SYSTEM_SERIAL'
self.system_version = '4.1.0'
@property
def info(self):
mocked_info = mock.Mock()
mocked_info.name = self.serial_number
return mocked_info
@staticmethod
def get_lun(_id=None, name=None):
if _id == 'not_found':
raise ex.UnityResourceNotFoundError()
if _id == 'tc_80': # for thin clone with extending size
lun = MockResource(name=_id, _id=_id)
lun.total_size_gb = 7
return lun
return MockResource(name, _id)
@staticmethod
def get_pool():
return MockResourceList(['Pool 1', 'Pool 2'])
@staticmethod
def get_snap(name):
if name == 'not_found':
raise ex.UnityResourceNotFoundError()
return MockResource(name)
@staticmethod
def create_host(name):
return MockResource(name)
@staticmethod
def get_host(name):
if name == 'not_found':
raise ex.UnityResourceNotFoundError()
if name == 'host1':
ret = MockResource(name)
ret.initiator_id = ['old-iqn']
return ret
return MockResource(name)
@staticmethod
def get_iscsi_portal():
portal0 = MockResource('p0')
portal0.ip_address = '1.1.1.1'
portal1 = MockResource('p1')
portal1.ip_address = '1.1.1.2'
return MockResourceList.create(portal0, portal1)
@staticmethod
def get_fc_port():
port0 = MockResource('fcp0')
port0.wwn = '00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF'
port1 = MockResource('fcp1')
port1.wwn = '00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:FF:EE'
return MockResourceList.create(port0, port1)
@staticmethod
def create_io_limit_policy(name, max_iops=None, max_kbps=None):
if name == 'in_use':
raise ex.UnityPolicyNameInUseError()
ret = MockResource(name)
ret.max_iops = max_iops
ret.max_kbps = max_kbps
return ret
@staticmethod
def get_io_limit_policy(name):
return MockResource(name=name)
@mock.patch.object(client, 'storops', new='True')
def get_client():
ret = client.UnityClient('1.2.3.4', 'user', 'pass')
ret._system = MockSystem()
return ret
########################
#
# Start of Tests
#
########################
@mock.patch.object(client, 'storops_ex', new=ex)
class ClientTest(unittest.TestCase):
def setUp(self):
self.client = get_client()
def test_get_serial(self):
self.assertEqual('SYSTEM_SERIAL', self.client.get_serial())
def test_create_lun_success(self):
name = 'LUN 3'
pool = MockResource('Pool 0')
lun = self.client.create_lun(name, 5, pool)
self.assertEqual(name, lun.name)
def test_create_lun_name_in_use(self):
name = 'in_use'
pool = MockResource('Pool 0')
lun = self.client.create_lun(name, 6, pool)
self.assertEqual('in_use', lun.name)
def test_create_lun_with_io_limit(self):
pool = MockResource('Pool 0')
limit = MockResource('limit')
limit.max_kbps = 100
lun = self.client.create_lun('LUN 4', 6, pool, io_limit_policy=limit)
self.assertEqual(100, lun.max_kbps)
def test_thin_clone_success(self):
name = 'tc_77'
src_lun = MockResource(_id='id_77')
lun = self.client.thin_clone(src_lun, name)
self.assertEqual(name, lun.name)
def test_thin_clone_name_in_used(self):
name = 'thin_clone_name_in_use'
src_lun = MockResource(_id='id_79')
lun = self.client.thin_clone(src_lun, name)
self.assertEqual(name, lun.name)
def test_thin_clone_extend_size(self):
name = 'tc_80'
src_lun = MockResource(_id='id_80')
lun = self.client.thin_clone(src_lun, name, io_limit_policy=None,
new_size_gb=7)
self.assertEqual(name, lun.name)
self.assertEqual(7, lun.total_size_gb)
def test_delete_lun_normal(self):
self.assertIsNone(self.client.delete_lun('lun3'))
def test_delete_lun_not_found(self):
try:
self.client.delete_lun('not_found')
except ex.StoropsException:
self.fail('not found error should be dealt with silently.')
def test_get_lun_with_id(self):
lun = self.client.get_lun('lun4')
self.assertEqual('lun4', lun.get_id())
def test_get_lun_with_name(self):
lun = self.client.get_lun(name='LUN 4')
self.assertEqual('LUN 4', lun.name)
def test_get_lun_not_found(self):
ret = self.client.get_lun(lun_id='not_found')
self.assertIsNone(ret)
def test_get_pools(self):
pools = self.client.get_pools()
self.assertEqual(2, len(pools))
def test_create_snap_normal(self):
snap = self.client.create_snap('lun_1', 'snap_1')
self.assertEqual('snap_1', snap.name)
def test_create_snap_in_use(self):
snap = self.client.create_snap('lun_1', 'in_use')
self.assertEqual('in_use', snap.name)
def test_delete_snap_error(self):
def f():
snap = MockResource(_id='snap_2')
self.client.delete_snap(snap)
self.assertRaises(ex.SnapDeleteIsCalled, f)
def test_delete_snap_not_found(self):
try:
snap = MockResource(_id='not_found')
self.client.delete_snap(snap)
except ex.StoropsException:
self.fail('snap not found should not raise exception.')
def test_delete_snap_none(self):
try:
ret = self.client.delete_snap(None)
self.assertIsNone(ret)
except ex.StoropsException:
self.fail('delete none should not raise exception.')
def test_delete_snap_in_use(self):
def f():
snap = MockResource(_id='snap_in_use')
self.client.delete_snap(snap)
self.assertRaises(ex.UnityDeleteAttachedSnapError, f)
def test_get_snap_found(self):
snap = self.client.get_snap('snap_2')
self.assertEqual('snap_2', snap.name)
def test_get_snap_not_found(self):
ret = self.client.get_snap('not_found')
self.assertIsNone(ret)
@mock.patch.object(coordination.Coordinator, 'get_lock')
def test_create_host_found(self, fake_coordination):
host = self.client.create_host('host1')
self.assertEqual('host1', host.name)
self.assertLessEqual(['iqn.1-1.com.e:c.a.a0'], host.initiator_id)
@mock.patch.object(coordination.Coordinator, 'get_lock')
def test_create_host_not_found(self, fake):
host = self.client.create_host('not_found')
self.assertEqual('not_found', host.name)
self.assertIn('not_found', self.client.host_cache)
def test_attach_lun(self):
lun = MockResource(_id='lun1', name='l1')
host = MockResource('host1')
self.assertEqual(1, self.client.attach(host, lun))
def test_attach_already_attached(self):
lun = MockResource(_id='already_attached')
host = MockResource('host1')
hlu = self.client.attach(host, lun)
self.assertEqual(99, hlu)
def test_detach_lun(self):
def f():
lun = MockResource('detach_failure')
host = MockResource('host1')
self.client.detach(host, lun)
self.assertRaises(ex.DetachIsCalled, f)
def test_detach_all(self):
def f():
lun = MockResource('lun_44')
self.client.detach_all(lun)
self.assertRaises(ex.DetachFromIsCalled, f)
@mock.patch.object(coordination.Coordinator, 'get_lock')
def test_create_host(self, fake):
self.assertEqual('host2', self.client.create_host('host2').name)
@mock.patch.object(coordination.Coordinator, 'get_lock')
def test_create_host_in_cache(self, fake):
self.client.host_cache['already_in'] = MockResource(name='already_in')
host = self.client.create_host('already_in')
self.assertIn('already_in', self.client.host_cache)
self.assertEqual('already_in', host.name)
def test_update_host_initiators(self):
host = MockResource(name='host_init')
host = self.client.update_host_initiators(host, 'fake-iqn-1')
def test_get_iscsi_target_info(self):
ret = self.client.get_iscsi_target_info()
expected = [{'iqn': 'iqn.1-1.com.e:c.p0.0', 'portal': '1.1.1.1:3260'},
{'iqn': 'iqn.1-1.com.e:c.p1.0', 'portal': '1.1.1.2:3260'}]
self.assertListEqual(expected, ret)
def test_get_iscsi_target_info_allowed_ports(self):
ret = self.client.get_iscsi_target_info(allowed_ports=['spa_eth0'])
expected = [{'iqn': 'iqn.1-1.com.e:c.p0.0', 'portal': '1.1.1.1:3260'}]
self.assertListEqual(expected, ret)
def test_get_fc_target_info_without_host(self):
ret = self.client.get_fc_target_info()
self.assertListEqual(['8899AABBCCDDEEFF', '8899AABBCCDDFFEE'],
sorted(ret))
def test_get_fc_target_info_without_host_but_allowed_ports(self):
ret = self.client.get_fc_target_info(allowed_ports=['spa_fc0'])
self.assertListEqual(['8899AABBCCDDEEFF'], ret)
def test_get_fc_target_info_with_host(self):
host = MockResource('host0')
ret = self.client.get_fc_target_info(host, True)
self.assertListEqual(['8899AABBCCDDEEFF'], ret)
def test_get_fc_target_info_with_host_and_allowed_ports(self):
host = MockResource('host0')
ret = self.client.get_fc_target_info(host, True,
allowed_ports=['spb_iom_0_fc0'])
self.assertListEqual([], ret)
def test_get_io_limit_policy_none(self):
ret = self.client.get_io_limit_policy(None)
self.assertIsNone(ret)
def test_get_io_limit_policy_create_new(self):
specs = {'maxBWS': 2, 'id': 'max_2_mbps', 'maxIOPS': None}
limit = self.client.get_io_limit_policy(specs)
self.assertEqual('max_2_mbps', limit.name)
self.assertEqual(2, limit.max_kbps)
def test_create_io_limit_policy_success(self):
limit = self.client.create_io_limit_policy('3kiops', max_iops=3000)
self.assertEqual('3kiops', limit.name)
self.assertEqual(3000, limit.max_iops)
def test_create_io_limit_policy_in_use(self):
limit = self.client.create_io_limit_policy('in_use', max_iops=100)
self.assertEqual('in_use', limit.name)
def test_expand_lun_success(self):
lun = self.client.extend_lun('ev_3', 6)
self.assertEqual(6, lun.total_size_gb)
def test_expand_lun_nothing_to_modify(self):
lun = self.client.extend_lun('ev_4', 5)
self.assertEqual(5, lun.total_size_gb)
def test_get_pool_name(self):
self.assertEqual('Pool0', self.client.get_pool_name('lun_0'))
def test_restore_snapshot(self):
back_snap = self.client.restore_snapshot('snap1')
self.assertEqual("internal_snap", back_snap.name)
def test_delete_host_wo_lock(self):
host = MockResource(name='empty-host')
self.client.host_cache['empty-host'] = host
self.assertRaises(ex.HostDeleteIsCalled,
self.client.delete_host_wo_lock(host))
def test_delete_host_wo_lock_remove_from_cache(self):
host = MockResource(name='empty-host-in-cache')
self.client.host_cache['empty-host-in-cache'] = host
self.client.delete_host_wo_lock(host)
self.assertNotIn(host.name, self.client.host_cache)
| {
"content_hash": "3abcb23719c71e0fca4816d2fb93affe",
"timestamp": "",
"source": "github",
"line_count": 547,
"max_line_length": 78,
"avg_line_length": 32.90859232175503,
"alnum_prop": 0.5978556746847398,
"repo_name": "phenoxim/cinder",
"id": "9a444dd5fc455e4a04d0625c11df28ecde2220c3",
"size": "18623",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cinder/tests/unit/volume/drivers/dell_emc/unity/test_client.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "621"
},
{
"name": "Python",
"bytes": "20325688"
},
{
"name": "Shell",
"bytes": "16353"
}
],
"symlink_target": ""
} |
<?php
namespace common\module\jrbac\backend\controllers;
use common\module\jrbac\src\RoleForm;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;
/**
* 角色管理
* Class RoleController
* @package jext\jrbac\controllers
*/
class RoleController extends ControllerJrbac
{
/** 角色列表 */
public function actionIndex()
{
$auth = \Yii::$app->getAuthManager();
$items = $auth->getRoles();
$dataProvider = new ArrayDataProvider();
$dataProvider->setModels($items);
return $this->render('index',[
'dataProvider' => $dataProvider,
]);
}
/** 创建角色 */
public function actionCreate()
{
$model = new RoleForm();
$model->isNewRecord = true;
if($model->load(\Yii::$app->getRequest()->post())) {
$auth = \Yii::$app->getAuthManager();
if($auth->getRole($model->name)) {
$model->addError('name','角色标识已存在');
} else {
$item = $auth->createRole($model->name);
$item->description = $model->description;
if($auth->add($item)) {
return $this->redirect(['index']);
}
}
}
return $this->render('create',[
'model'=>$model
]);
}
/** 删除角色 */
public function actionDelete($id = '')
{
$name = $id;
if (\Yii::$app->getRequest()->getIsPost()) {
$auth = \Yii::$app->getAuthManager();
if($name) {
$item = $auth->getRole($name);
if($item) $auth->remove($item);
} else {
if(isset($_POST['names']) && is_array($_POST['names'])) {
$flag = true;
try {
foreach($_POST['names'] as $name) {
if(!$auth->remove($auth->getRole(trim($name)))) $flag = false;
}
return $flag ? 1 : 0;
} catch(\Exception $e) {
return 0;
}
}
}
}
return $this->redirect(['index']);
}
/** 更新角色 */
public function actionUpdate($id)
{
$name = $id;
$model = new RoleForm();
$model->isNewRecord = false;
$auth = \Yii::$app->getAuthManager();
$item = $auth->getRole($name);
if($model->load(\Yii::$app->getRequest()->post())) {
$item->name = $model->name;
$item->description = $model->description;
if($auth->update($name,$item)) {
return $this->redirect(['index']);
}
}
$model->name = $name;
$model->description = $item->description;
return $this->render('update',[
'model' => $model
]);
}
/** 查看角色详细信息 */
public function actionView($id)
{
$name = $id;
$auth = \Yii::$app->getAuthManager();
$item = $auth->getRole($name);
return $this->render('view',[
'item' => $item
]);
}
/** 查看角色用户列表 */
public function actionUserindex($id)
{
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($id);
$roleUserIds = $auth->getUserIdsByRole($id);
$dataProvider = new ActiveDataProvider([
'query' => $auth->getUserQuery()->where('`status`!=9'),
'pagination' => [
'pageSize' => 20,
],
]);
return $this->render('userindex',[
'dataProvider' => $dataProvider,
'role' => $role,
'roleUserIds' => $roleUserIds
]);
}
/** 设置角色用户 */
public function actionSetuser($name)
{
if (\Yii::$app->getRequest()->getIsPost() && isset($_POST['act'],$_POST['val'])) {
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($name);
try {
$flag = true;
if($_POST['act'] == 'add') {
if(!$auth->assign($role,$_POST['val'])) $flag = false;
} else if($_POST['act'] == 'del') {
if(!$auth->revoke($role,$_POST['val'])) $flag = false;
} else {
$flag = false;
}
return $flag ? 1 : 0;
} catch(\Exception $e) {
return 0;
}
}
return $this->redirect(['index']);
}
/** 查看角色权限列表 */
public function actionPermissionindex($id)
{
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($id);
$allItems = $auth->getPermissions();
$roleItems = $auth->getPermissionsByRole($id);
$ownItems = $auth->getChildren($id);
// var_dump($roleItems);exit();
$dataProvider = new ArrayDataProvider();
$dataProvider->setModels($allItems);
return $this->render('permissionindex',[
'dataProvider' => $dataProvider,
'allItems' => $allItems,
'roleItems' => $roleItems,
'ownItems' => $ownItems,
'role' => $role
]);
}
/** 设置角色权限 */
public function actionSetpermission($name)
{
if (\Yii::$app->getRequest()->getIsPost() && isset($_POST['act'],$_POST['val'])) {
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($name);
$permission = $auth->getPermission($_POST['val']);
try {
$flag = true;
if($_POST['act'] == 'add') {
if(!$auth->addChild($role,$permission)) $flag = false;
} else if($_POST['act'] == 'del') {
if(!$auth->removeChild($role,$permission)) $flag = false;
} else {
$flag = false;
}
return $flag ? 1 : 0;
} catch(\Exception $e) {
return 0;
}
}
return $this->redirect(['index']);
}
/** 子角色列表 */
public function actionSubindex($id)
{
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($id);
$allItems = $auth->getRoles();
$subItems = $auth->getChildren($id);
$dataProvider = new ArrayDataProvider();
$dataProvider->setModels($allItems);
return $this->render('subindex',[
'dataProvider' => $dataProvider,
'allItems' => $allItems,
'subItems' => $subItems,
'role' => $role
]);
}
/** 子角色关联设置 */
public function actionSetsub($name)
{
if (\Yii::$app->getRequest()->getIsPost() && isset($_POST['act'],$_POST['val'])) {
$auth = \Yii::$app->getAuthManager();
$role = $auth->getRole($name);
$permission = $auth->getRole($_POST['val']);
try {
$flag = true;
if($_POST['act'] == 'add') {
if(!$auth->addChild($role,$permission)) $flag = false;
} else if($_POST['act'] == 'del') {
if(!$auth->removeChild($role,$permission)) $flag = false;
} else {
$flag = false;
}
return $flag ? 1 : 0;
} catch(\Exception $e) {
return 0;
}
}
return $this->redirect(['index']);
}
}
| {
"content_hash": "d6f93748f655c3c2275e1a02d1a2fe45",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 90,
"avg_line_length": 31.761702127659575,
"alnum_prop": 0.44560557341907825,
"repo_name": "JeanWolf/plat",
"id": "aa8e2b42c118e58a7bd2de50247f195f0480b277",
"size": "7614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/module/jrbac/backend/controllers/RoleController.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "452783"
},
{
"name": "HTML",
"bytes": "11626"
},
{
"name": "Hack",
"bytes": "7197"
},
{
"name": "JavaScript",
"bytes": "1241249"
},
{
"name": "PHP",
"bytes": "4545873"
}
],
"symlink_target": ""
} |
<?php
namespace Algolia\AlgoliaSearch\Model\Indexer;
use Algolia\AlgoliaSearch\Helper\ConfigHelper;
use Algolia\AlgoliaSearch\Helper\Data;
use Algolia\AlgoliaSearch\Model\Queue;
use Magento;
use Magento\Framework\Message\ManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
class AdditionalSection implements Magento\Framework\Indexer\ActionInterface, Magento\Framework\Mview\ActionInterface
{
private $fullAction;
private $storeManager;
private $queue;
private $configHelper;
private $messageManager;
private $output;
public function __construct(StoreManagerInterface $storeManager, Data $helper, Queue $queue, ConfigHelper $configHelper, ManagerInterface $messageManager, ConsoleOutput $output)
{
$this->fullAction = $helper;
$this->storeManager = $storeManager;
$this->queue = $queue;
$this->configHelper = $configHelper;
$this->messageManager = $messageManager;
$this->output = $output;
}
public function execute($ids)
{
}
public function executeFull()
{
if (!$this->configHelper->getApplicationID() || !$this->configHelper->getAPIKey() || !$this->configHelper->getSearchOnlyAPIKey()) {
$errorMessage = 'Algolia reindexing failed: You need to configure your Algolia credentials in Stores > Configuration > Algolia Search.';
if (php_sapi_name() === 'cli') {
$this->output->writeln($errorMessage);
return;
}
$this->messageManager->addErrorMessage($errorMessage);
return;
}
$storeIds = array_keys($this->storeManager->getStores());
foreach ($storeIds as $storeId) {
$this->queue->addToQueue($this->fullAction, 'rebuildStoreAdditionalSectionsIndex', ['store_id' => $storeId], 1);
}
}
public function executeList(array $ids)
{
}
public function executeRow($id)
{
}
}
| {
"content_hash": "880937647aaf20f02d8cf3f2d69ecf15",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 181,
"avg_line_length": 30.606060606060606,
"alnum_prop": 0.6658415841584159,
"repo_name": "aligent/algoliasearch-magento-2",
"id": "851b10c429a3d3f7923da9733b25d093d853c3f8",
"size": "2020",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Model/Indexer/AdditionalSection.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "30710"
},
{
"name": "HTML",
"bytes": "22148"
},
{
"name": "JavaScript",
"bytes": "35700"
},
{
"name": "PHP",
"bytes": "184277"
},
{
"name": "Shell",
"bytes": "8106"
}
],
"symlink_target": ""
} |
package elasticache_test
import (
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/elasticache"
)
var _ time.Duration
var _ strings.Reader
var _ aws.Config
func parseTime(layout, value string) *time.Time {
t, err := time.Parse(layout, value)
if err != nil {
panic(err)
}
return &t
}
// AddTagsToResource
//
// Adds up to 10 tags, key/value pairs, to a cluster or snapshot resource.
func ExampleElastiCache_AddTagsToResource_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.AddTagsToResourceInput{
ResourceName: aws.String("arn:aws:elasticache:us-east-1:1234567890:cluster:my-mem-cluster"),
Tags: []*elasticache.Tag{
{
Key: aws.String("APIVersion"),
Value: aws.String("20150202"),
},
{
Key: aws.String("Service"),
Value: aws.String("ElastiCache"),
},
},
}
result, err := svc.AddTagsToResource(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeTagQuotaPerResourceExceeded:
fmt.Println(elasticache.ErrCodeTagQuotaPerResourceExceeded, aerr.Error())
case elasticache.ErrCodeInvalidARNFault:
fmt.Println(elasticache.ErrCodeInvalidARNFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// AuthorizeCacheCacheSecurityGroupIngress
//
// Allows network ingress to a cache security group. Applications using ElastiCache
// must be running on Amazon EC2. Amazon EC2 security groups are used as the authorization
// mechanism.
func ExampleElastiCache_AuthorizeCacheSecurityGroupIngress_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.AuthorizeCacheSecurityGroupIngressInput{
CacheSecurityGroupName: aws.String("my-sec-grp"),
EC2SecurityGroupName: aws.String("my-ec2-sec-grp"),
EC2SecurityGroupOwnerId: aws.String("1234567890"),
}
result, err := svc.AuthorizeCacheSecurityGroupIngress(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheSecurityGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheSecurityGroupStateFault, aerr.Error())
case elasticache.ErrCodeAuthorizationAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeAuthorizationAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CopySnapshot
//
// Copies a snapshot to a specified name.
func ExampleElastiCache_CopySnapshot_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CopySnapshotInput{
SourceSnapshotName: aws.String("my-snapshot"),
TargetBucket: aws.String(""),
TargetSnapshotName: aws.String("my-snapshot-copy"),
}
result, err := svc.CopySnapshot(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidSnapshotStateFault:
fmt.Println(elasticache.ErrCodeInvalidSnapshotStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheCluster
//
// Creates a Memcached cluster with 2 nodes.
func ExampleElastiCache_CreateCacheCluster_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateCacheClusterInput{
AZMode: aws.String("cross-az"),
CacheClusterId: aws.String("my-memcached-cluster"),
CacheNodeType: aws.String("cache.r3.large"),
CacheSubnetGroupName: aws.String("default"),
Engine: aws.String("memcached"),
EngineVersion: aws.String("1.4.24"),
NumCacheNodes: aws.Int64(2),
Port: aws.Int64(11211),
}
result, err := svc.CreateCacheCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeCacheClusterAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeCacheClusterAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeClusterQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeClusterQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeTagQuotaPerResourceExceeded:
fmt.Println(elasticache.ErrCodeTagQuotaPerResourceExceeded, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheCluster
//
// Creates a Redis cluster with 1 node.
func ExampleElastiCache_CreateCacheCluster_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.CreateCacheClusterInput{
AutoMinorVersionUpgrade: aws.Bool(true),
CacheClusterId: aws.String("my-redis"),
CacheNodeType: aws.String("cache.r3.larage"),
CacheSubnetGroupName: aws.String("default"),
Engine: aws.String("redis"),
EngineVersion: aws.String("3.2.4"),
NumCacheNodes: aws.Int64(1),
Port: aws.Int64(6379),
PreferredAvailabilityZone: aws.String("us-east-1c"),
SnapshotRetentionLimit: aws.Int64(7),
}
result, err := svc.CreateCacheCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeCacheClusterAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeCacheClusterAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeClusterQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeClusterQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeTagQuotaPerResourceExceeded:
fmt.Println(elasticache.ErrCodeTagQuotaPerResourceExceeded, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheParameterGroup
//
// Creates the Amazon ElastiCache parameter group custom-redis2-8.
func ExampleElastiCache_CreateCacheParameterGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateCacheParameterGroupInput{
CacheParameterGroupFamily: aws.String("redis2.8"),
CacheParameterGroupName: aws.String("custom-redis2-8"),
Description: aws.String("Custom Redis 2.8 parameter group."),
}
result, err := svc.CreateCacheParameterGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheParameterGroupQuotaExceededFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheParameterGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheParameterGroupStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheSecurityGroup
//
// Creates an ElastiCache security group. ElastiCache security groups are only for clusters
// not running in an AWS VPC.
func ExampleElastiCache_CreateCacheSecurityGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateCacheSecurityGroupInput{
CacheSecurityGroupName: aws.String("my-cache-sec-grp"),
Description: aws.String("Example ElastiCache security group."),
}
result, err := svc.CreateCacheSecurityGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSecurityGroupAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupQuotaExceededFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheSubnet
//
// Creates a new cache subnet group.
func ExampleElastiCache_CreateCacheSubnetGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateCacheSubnetGroupInput{
CacheSubnetGroupDescription: aws.String("Sample subnet group"),
CacheSubnetGroupName: aws.String("my-sn-grp2"),
SubnetIds: []*string{
aws.String("subnet-6f28c982"),
aws.String("subnet-bcd382f3"),
aws.String("subnet-845b3e7c0"),
},
}
result, err := svc.CreateCacheSubnetGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSubnetGroupAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupQuotaExceededFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetQuotaExceededFault:
fmt.Println(elasticache.ErrCodeCacheSubnetQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidSubnet:
fmt.Println(elasticache.ErrCodeInvalidSubnet, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateCacheReplicationGroup
//
// Creates a Redis replication group with 3 nodes.
func ExampleElastiCache_CreateReplicationGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateReplicationGroupInput{
AutomaticFailoverEnabled: aws.Bool(true),
CacheNodeType: aws.String("cache.m3.medium"),
Engine: aws.String("redis"),
EngineVersion: aws.String("2.8.24"),
NumCacheClusters: aws.Int64(3),
ReplicationGroupDescription: aws.String("A Redis replication group."),
ReplicationGroupId: aws.String("my-redis-rg"),
SnapshotRetentionLimit: aws.Int64(30),
}
result, err := svc.CreateReplicationGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeReplicationGroupAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeClusterQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeClusterQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeTagQuotaPerResourceExceeded:
fmt.Println(elasticache.ErrCodeTagQuotaPerResourceExceeded, aerr.Error())
case elasticache.ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault:
fmt.Println(elasticache.ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateReplicationGroup
//
// Creates a Redis (cluster mode enabled) replication group with two shards. One shard
// has one read replica node and the other shard has two read replicas.
func ExampleElastiCache_CreateReplicationGroup_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.CreateReplicationGroupInput{
AutoMinorVersionUpgrade: aws.Bool(true),
CacheNodeType: aws.String("cache.m3.medium"),
CacheParameterGroupName: aws.String("default.redis3.2.cluster.on"),
Engine: aws.String("redis"),
EngineVersion: aws.String("3.2.4"),
NodeGroupConfiguration: []*elasticache.NodeGroupConfiguration{
{
PrimaryAvailabilityZone: aws.String("us-east-1c"),
ReplicaAvailabilityZones: []*string{
aws.String("us-east-1b"),
},
ReplicaCount: aws.Int64(1),
Slots: aws.String("0-8999"),
},
{
PrimaryAvailabilityZone: aws.String("us-east-1a"),
ReplicaAvailabilityZones: []*string{
aws.String("us-east-1a"),
aws.String("us-east-1c"),
},
ReplicaCount: aws.Int64(2),
Slots: aws.String("9000-16383"),
},
},
NumNodeGroups: aws.Int64(2),
ReplicationGroupDescription: aws.String("A multi-sharded replication group"),
ReplicationGroupId: aws.String("clustered-redis-rg"),
SnapshotRetentionLimit: aws.Int64(8),
}
result, err := svc.CreateReplicationGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeReplicationGroupAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeClusterQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeClusterQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeTagQuotaPerResourceExceeded:
fmt.Println(elasticache.ErrCodeTagQuotaPerResourceExceeded, aerr.Error())
case elasticache.ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault:
fmt.Println(elasticache.ErrCodeNodeGroupsPerReplicationGroupQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateSnapshot - NonClustered Redis, no read-replicas
//
// Creates a snapshot of a non-clustered Redis cluster that has only one node.
func ExampleElastiCache_CreateSnapshot_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.CreateSnapshotInput{
CacheClusterId: aws.String("onenoderedis"),
SnapshotName: aws.String("snapshot-1"),
}
result, err := svc.CreateSnapshot(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeSnapshotFeatureNotSupportedFault:
fmt.Println(elasticache.ErrCodeSnapshotFeatureNotSupportedFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateSnapshot - NonClustered Redis, 2 read-replicas
//
// Creates a snapshot of a non-clustered Redis cluster that has only three nodes, primary
// and two read-replicas. CacheClusterId must be a specific node in the cluster.
func ExampleElastiCache_CreateSnapshot_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.CreateSnapshotInput{
CacheClusterId: aws.String("threenoderedis-001"),
SnapshotName: aws.String("snapshot-2"),
}
result, err := svc.CreateSnapshot(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeSnapshotFeatureNotSupportedFault:
fmt.Println(elasticache.ErrCodeSnapshotFeatureNotSupportedFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// CreateSnapshot-clustered Redis
//
// Creates a snapshot of a clustered Redis cluster that has 2 shards, each with a primary
// and 4 read-replicas.
func ExampleElastiCache_CreateSnapshot_shared02() {
svc := elasticache.New(session.New())
input := &elasticache.CreateSnapshotInput{
ReplicationGroupId: aws.String("clusteredredis"),
SnapshotName: aws.String("snapshot-2x5"),
}
result, err := svc.CreateSnapshot(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeSnapshotFeatureNotSupportedFault:
fmt.Println(elasticache.ErrCodeSnapshotFeatureNotSupportedFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteCacheCluster
//
// Deletes an Amazon ElastiCache cluster.
func ExampleElastiCache_DeleteCacheCluster_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteCacheClusterInput{
CacheClusterId: aws.String("my-memcached"),
}
result, err := svc.DeleteCacheCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeSnapshotFeatureNotSupportedFault:
fmt.Println(elasticache.ErrCodeSnapshotFeatureNotSupportedFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteCacheParameterGroup
//
// Deletes the Amazon ElastiCache parameter group custom-mem1-4.
func ExampleElastiCache_DeleteCacheParameterGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteCacheParameterGroupInput{
CacheParameterGroupName: aws.String("custom-mem1-4"),
}
result, err := svc.DeleteCacheParameterGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidCacheParameterGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheParameterGroupStateFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteCacheSecurityGroup
//
// Deletes a cache security group.
func ExampleElastiCache_DeleteCacheSecurityGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteCacheSecurityGroupInput{
CacheSecurityGroupName: aws.String("my-sec-group"),
}
result, err := svc.DeleteCacheSecurityGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidCacheSecurityGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheSecurityGroupStateFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteCacheSubnetGroup
//
// Deletes the Amazon ElastiCache subnet group my-subnet-group.
func ExampleElastiCache_DeleteCacheSubnetGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteCacheSubnetGroupInput{
CacheSubnetGroupName: aws.String("my-subnet-group"),
}
result, err := svc.DeleteCacheSubnetGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSubnetGroupInUse:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupInUse, aerr.Error())
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteReplicationGroup
//
// Deletes the Amazon ElastiCache replication group my-redis-rg.
func ExampleElastiCache_DeleteReplicationGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteReplicationGroupInput{
ReplicationGroupId: aws.String("my-redis-rg"),
RetainPrimaryCluster: aws.Bool(false),
}
result, err := svc.DeleteReplicationGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeSnapshotAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeSnapshotAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeSnapshotFeatureNotSupportedFault:
fmt.Println(elasticache.ErrCodeSnapshotFeatureNotSupportedFault, aerr.Error())
case elasticache.ErrCodeSnapshotQuotaExceededFault:
fmt.Println(elasticache.ErrCodeSnapshotQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DeleteSnapshot
//
// Deletes the Redis snapshot snapshot-20160822.
func ExampleElastiCache_DeleteSnapshot_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DeleteSnapshotInput{
SnapshotName: aws.String("snapshot-20161212"),
}
result, err := svc.DeleteSnapshot(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidSnapshotStateFault:
fmt.Println(elasticache.ErrCodeInvalidSnapshotStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheClusters
//
// Lists the details for up to 50 cache clusters.
func ExampleElastiCache_DescribeCacheClusters_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheClustersInput{
CacheClusterId: aws.String("my-mem-cluster"),
}
result, err := svc.DescribeCacheClusters(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheClusters
//
// Lists the details for the cache cluster my-mem-cluster.
func ExampleElastiCache_DescribeCacheClusters_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheClustersInput{
CacheClusterId: aws.String("my-mem-cluster"),
ShowCacheNodeInfo: aws.Bool(true),
}
result, err := svc.DescribeCacheClusters(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheEngineVersions
//
// Lists the details for up to 25 Memcached and Redis cache engine versions.
func ExampleElastiCache_DescribeCacheEngineVersions_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheEngineVersionsInput{}
result, err := svc.DescribeCacheEngineVersions(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheEngineVersions
//
// Lists the details for up to 50 Redis cache engine versions.
func ExampleElastiCache_DescribeCacheEngineVersions_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheEngineVersionsInput{
DefaultOnly: aws.Bool(false),
Engine: aws.String("redis"),
MaxRecords: aws.Int64(50),
}
result, err := svc.DescribeCacheEngineVersions(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheParameterGroups
//
// Returns a list of cache parameter group descriptions. If a cache parameter group
// name is specified, the list contains only the descriptions for that group.
func ExampleElastiCache_DescribeCacheParameterGroups_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheParameterGroupsInput{
CacheParameterGroupName: aws.String("custom-mem1-4"),
}
result, err := svc.DescribeCacheParameterGroups(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheParameters
//
// Lists up to 100 user parameter values for the parameter group custom.redis2.8.
func ExampleElastiCache_DescribeCacheParameters_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheParametersInput{
CacheParameterGroupName: aws.String("custom-redis2-8"),
MaxRecords: aws.Int64(100),
Source: aws.String("user"),
}
result, err := svc.DescribeCacheParameters(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheSecurityGroups
//
// Returns a list of cache security group descriptions. If a cache security group name
// is specified, the list contains only the description of that group.
func ExampleElastiCache_DescribeCacheSecurityGroups_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheSecurityGroupsInput{
CacheSecurityGroupName: aws.String("my-sec-group"),
}
result, err := svc.DescribeCacheSecurityGroups(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheSubnetGroups
//
// Describes up to 25 cache subnet groups.
func ExampleElastiCache_DescribeCacheSubnetGroups_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeCacheSubnetGroupsInput{
MaxRecords: aws.Int64(25),
}
result, err := svc.DescribeCacheSubnetGroups(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeEngineDefaultParameters
//
// Returns the default engine and system parameter information for the specified cache
// engine.
func ExampleElastiCache_DescribeEngineDefaultParameters_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeEngineDefaultParametersInput{
CacheParameterGroupFamily: aws.String("redis2.8"),
MaxRecords: aws.Int64(25),
}
result, err := svc.DescribeEngineDefaultParameters(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeEvents
//
// Describes all the cache-cluster events for the past 120 minutes.
func ExampleElastiCache_DescribeEvents_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeEventsInput{
Duration: aws.Int64(360),
SourceType: aws.String("cache-cluster"),
}
result, err := svc.DescribeEvents(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeEvents
//
// Describes all the replication-group events from 3:00P to 5:00P on November 11, 2016.
func ExampleElastiCache_DescribeEvents_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeEventsInput{
StartTime: parseTime("2006-01-02T15:04:05.999999999Z", "2016-12-22T15:00:00.000Z"),
}
result, err := svc.DescribeEvents(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeReplicationGroups
//
// Returns information about the replication group myreplgroup.
func ExampleElastiCache_DescribeReplicationGroups_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeReplicationGroupsInput{}
result, err := svc.DescribeReplicationGroups(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeReservedCacheNodes
//
// Returns information about reserved cache nodes for this account, or about a specified
// reserved cache node. If the account has no reserved cache nodes, the operation returns
// an empty list, as shown here.
func ExampleElastiCache_DescribeReservedCacheNodes_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeReservedCacheNodesInput{
MaxRecords: aws.Int64(25),
}
result, err := svc.DescribeReservedCacheNodes(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReservedCacheNodeNotFoundFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodeNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeReseredCacheNodeOfferings
//
// Lists available reserved cache node offerings.
func ExampleElastiCache_DescribeReservedCacheNodesOfferings_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeReservedCacheNodesOfferingsInput{
MaxRecords: aws.Int64(20),
}
result, err := svc.DescribeReservedCacheNodesOfferings(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeReseredCacheNodeOfferings
//
// Lists available reserved cache node offerings for cache.r3.large nodes with a 3 year
// commitment.
func ExampleElastiCache_DescribeReservedCacheNodesOfferings_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeReservedCacheNodesOfferingsInput{
CacheNodeType: aws.String("cache.r3.large"),
Duration: aws.String("3"),
MaxRecords: aws.Int64(25),
OfferingType: aws.String("Light Utilization"),
ReservedCacheNodesOfferingId: aws.String(""),
}
result, err := svc.DescribeReservedCacheNodesOfferings(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeReseredCacheNodeOfferings
//
// Lists available reserved cache node offerings.
func ExampleElastiCache_DescribeReservedCacheNodesOfferings_shared02() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeReservedCacheNodesOfferingsInput{
CacheNodeType: aws.String(""),
Duration: aws.String(""),
Marker: aws.String(""),
MaxRecords: aws.Int64(25),
OfferingType: aws.String(""),
ProductDescription: aws.String(""),
ReservedCacheNodesOfferingId: aws.String("438012d3-4052-4cc7-b2e3-8d3372e0e706"),
}
result, err := svc.DescribeReservedCacheNodesOfferings(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeSnapshots
//
// Returns information about the snapshot mysnapshot. By default.
func ExampleElastiCache_DescribeSnapshots_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.DescribeSnapshotsInput{
SnapshotName: aws.String("snapshot-20161212"),
}
result, err := svc.DescribeSnapshots(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ListAllowedNodeTypeModifications
//
// Lists all available node types that you can scale your Redis cluster's or replication
// group's current node type up to.
func ExampleElastiCache_ListAllowedNodeTypeModifications_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ListAllowedNodeTypeModificationsInput{
ReplicationGroupId: aws.String("myreplgroup"),
}
result, err := svc.ListAllowedNodeTypeModifications(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ListAllowedNodeTypeModifications
//
// Lists all available node types that you can scale your Redis cluster's or replication
// group's current node type up to.
func ExampleElastiCache_ListAllowedNodeTypeModifications_shared01() {
svc := elasticache.New(session.New())
input := &elasticache.ListAllowedNodeTypeModificationsInput{
CacheClusterId: aws.String("mycluster"),
}
result, err := svc.ListAllowedNodeTypeModifications(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ListTagsForResource
//
// Lists all cost allocation tags currently on the named resource. A cost allocation
// tag is a key-value pair where the key is case-sensitive and the value is optional.
// You can use cost allocation tags to categorize and track your AWS costs.
func ExampleElastiCache_ListTagsForResource_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ListTagsForResourceInput{
ResourceName: aws.String("arn:aws:elasticache:us-west-2:<my-account-id>:cluster:mycluster"),
}
result, err := svc.ListTagsForResource(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidARNFault:
fmt.Println(elasticache.ErrCodeInvalidARNFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ModifyCacheCluster
//
// Copies a snapshot to a specified name.
func ExampleElastiCache_ModifyCacheCluster_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ModifyCacheClusterInput{
ApplyImmediately: aws.Bool(true),
CacheClusterId: aws.String("redis-cluster"),
SnapshotRetentionLimit: aws.Int64(14),
}
result, err := svc.ModifyCacheCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheSecurityGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheSecurityGroupStateFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ModifyCacheParameterGroup
//
// Modifies one or more parameter values in the specified parameter group. You cannot
// modify any default parameter group.
func ExampleElastiCache_ModifyCacheParameterGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ModifyCacheParameterGroupInput{
CacheParameterGroupName: aws.String("custom-mem1-4"),
ParameterNameValues: []*elasticache.ParameterNameValue{
{
ParameterName: aws.String("binding_protocol"),
ParameterValue: aws.String("ascii"),
},
{
ParameterName: aws.String("chunk_size"),
ParameterValue: aws.String("96"),
},
},
}
result, err := svc.ModifyCacheParameterGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheParameterGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheParameterGroupStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ModifyCacheSubnetGroup
//
// Modifies an existing ElastiCache subnet group.
func ExampleElastiCache_ModifyCacheSubnetGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ModifyCacheSubnetGroupInput{
CacheSubnetGroupName: aws.String("my-sn-grp"),
SubnetIds: []*string{
aws.String("subnet-bcde2345"),
},
}
result, err := svc.ModifyCacheSubnetGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheSubnetQuotaExceededFault:
fmt.Println(elasticache.ErrCodeCacheSubnetQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeSubnetInUse:
fmt.Println(elasticache.ErrCodeSubnetInUse, aerr.Error())
case elasticache.ErrCodeInvalidSubnet:
fmt.Println(elasticache.ErrCodeInvalidSubnet, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ModifyReplicationGroup
//
func ExampleElastiCache_ModifyReplicationGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ModifyReplicationGroupInput{
ApplyImmediately: aws.Bool(true),
ReplicationGroupDescription: aws.String("Modified replication group"),
ReplicationGroupId: aws.String("my-redis-rg"),
SnapshotRetentionLimit: aws.Int64(30),
SnapshottingClusterId: aws.String("my-redis-rg-001"),
}
result, err := svc.ModifyReplicationGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReplicationGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidReplicationGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheSecurityGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheSecurityGroupStateFault, aerr.Error())
case elasticache.ErrCodeInsufficientCacheClusterCapacityFault:
fmt.Println(elasticache.ErrCodeInsufficientCacheClusterCapacityFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForClusterExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForClusterExceededFault, aerr.Error())
case elasticache.ErrCodeNodeQuotaForCustomerExceededFault:
fmt.Println(elasticache.ErrCodeNodeQuotaForCustomerExceededFault, aerr.Error())
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidVPCNetworkStateFault:
fmt.Println(elasticache.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())
case elasticache.ErrCodeInvalidKMSKeyFault:
fmt.Println(elasticache.ErrCodeInvalidKMSKeyFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// PurchaseReservedCacheNodesOfferings
//
// Allows you to purchase a reserved cache node offering.
func ExampleElastiCache_PurchaseReservedCacheNodesOffering_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.PurchaseReservedCacheNodesOfferingInput{
ReservedCacheNodesOfferingId: aws.String("1ef01f5b-94ff-433f-a530-61a56bfc8e7a"),
}
result, err := svc.PurchaseReservedCacheNodesOffering(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodesOfferingNotFoundFault, aerr.Error())
case elasticache.ErrCodeReservedCacheNodeAlreadyExistsFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodeAlreadyExistsFault, aerr.Error())
case elasticache.ErrCodeReservedCacheNodeQuotaExceededFault:
fmt.Println(elasticache.ErrCodeReservedCacheNodeQuotaExceededFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// RebootCacheCluster
//
// Reboots the specified nodes in the names cluster.
func ExampleElastiCache_RebootCacheCluster_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.RebootCacheClusterInput{
CacheClusterId: aws.String("custom-mem1-4 "),
CacheNodeIdsToReboot: []*string{
aws.String("0001"),
aws.String("0002"),
},
}
result, err := svc.RebootCacheCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidCacheClusterStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheClusterStateFault, aerr.Error())
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// RemoveTagsFromResource
//
// Removes tags identified by a list of tag keys from the list of tags on the specified
// resource.
func ExampleElastiCache_RemoveTagsFromResource_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.RemoveTagsFromResourceInput{
ResourceName: aws.String("arn:aws:elasticache:us-east-1:1234567890:cluster:my-mem-cluster"),
TagKeys: []*string{
aws.String("A"),
aws.String("C"),
aws.String("E"),
},
}
result, err := svc.RemoveTagsFromResource(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheClusterNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
case elasticache.ErrCodeSnapshotNotFoundFault:
fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidARNFault:
fmt.Println(elasticache.ErrCodeInvalidARNFault, aerr.Error())
case elasticache.ErrCodeTagNotFoundFault:
fmt.Println(elasticache.ErrCodeTagNotFoundFault, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// ResetCacheParameterGroup
//
// Modifies the parameters of a cache parameter group to the engine or system default
// value.
func ExampleElastiCache_ResetCacheParameterGroup_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.ResetCacheParameterGroupInput{
CacheParameterGroupName: aws.String("custom-mem1-4"),
ResetAllParameters: aws.Bool(true),
}
result, err := svc.ResetCacheParameterGroup(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeInvalidCacheParameterGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheParameterGroupStateFault, aerr.Error())
case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// DescribeCacheSecurityGroups
//
// Returns a list of cache security group descriptions. If a cache security group name
// is specified, the list contains only the description of that group.
func ExampleElastiCache_RevokeCacheSecurityGroupIngress_shared00() {
svc := elasticache.New(session.New())
input := &elasticache.RevokeCacheSecurityGroupIngressInput{
CacheSecurityGroupName: aws.String("my-sec-grp"),
EC2SecurityGroupName: aws.String("my-ec2-sec-grp"),
EC2SecurityGroupOwnerId: aws.String("1234567890"),
}
result, err := svc.RevokeCacheSecurityGroupIngress(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
case elasticache.ErrCodeAuthorizationNotFoundFault:
fmt.Println(elasticache.ErrCodeAuthorizationNotFoundFault, aerr.Error())
case elasticache.ErrCodeInvalidCacheSecurityGroupStateFault:
fmt.Println(elasticache.ErrCodeInvalidCacheSecurityGroupStateFault, aerr.Error())
case elasticache.ErrCodeInvalidParameterValueException:
fmt.Println(elasticache.ErrCodeInvalidParameterValueException, aerr.Error())
case elasticache.ErrCodeInvalidParameterCombinationException:
fmt.Println(elasticache.ErrCodeInvalidParameterCombinationException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
| {
"content_hash": "8804da69ad4281cd0b993a08048cc0ec",
"timestamp": "",
"source": "github",
"line_count": 1953,
"max_line_length": 97,
"avg_line_length": 37.40552995391705,
"alnum_prop": 0.7637331800199855,
"repo_name": "ironcladlou/origin",
"id": "105b551579af59ed301b57edbec3e2733b5e1883",
"size": "73123",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/github.com/aws/aws-sdk-go/service/elasticache/examples_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "Dockerfile",
"bytes": "2240"
},
{
"name": "Go",
"bytes": "2321943"
},
{
"name": "Makefile",
"bytes": "6395"
},
{
"name": "Python",
"bytes": "14593"
},
{
"name": "Shell",
"bytes": "310343"
}
],
"symlink_target": ""
} |
To install in your home, just link (or copy) the language definition file in ~/.local/share/gtksourceview-2.0/language-specs
# syntaxhighlighter
Nit brush for the Alex Gorbatchev's JS syntaxhighlighter.
To install the JS syntaxhighlighter, please refer to http://alexgorbatchev.com/SyntaxHighlighter/
Then can add the brush to your html page:
<script type="text/javascript" src="shBrushNit.js"></script>
# Vim
Vim is a powerful text editor and a favorite of the Nit team.
The `misc/vim` directory provides Vim support for Nit source files.
## Install
The simpler way to install nit for vim is with [pathogen][1].
cd ~/.vim/bundle
ln -s /full/path/to/nit/misc/vim nit
Ensure that `~/.vimrc` contains
call pathogen#infect()
syntax on
filetype plugin indent on
[1]: https://github.com/tpope/vim-pathogen
## Features
* Syntax highlighting
* Automatic indentation
* Syntax checker (require [Syntastic][2]).
* Autocomplete for whole projects using module importations
* Show documentation in preview window
* Search declarations and usages of the word under the cursor
[2]: https://github.com/scrooloose/syntastic
## Autocomplete
The Nit plugin offers two kinds of autocompletion: complete and omnifunc.
You can use both completion at the same time. They each have their own strengths and weaknesses.
### Complete
The Nit plugin can configure the `complete` option by scanning all projects in the
current directory, and their dependencies.
Add the following code to `~/.vimrc`, then use `ctrl-n` to open the
autocomplete popup.
~~~
" Compute Nit module dependencies for autocomplete on loading our first Nit module
autocmd Filetype nit call NitComplete()
" Map reloading Nit module dependencies to F2
map <F2> :call ForceNitComplete()<enter>
~~~
The plugin is compatible with, and optimized for, [AutoComplPop][3].
Look at the functions defined in `misc/vim/plugin/nit.vim` for all possible
usages.
[3]: http://www.vim.org/scripts/script.php?script_id=1879
### Omnifunc
The Nit plugin also defines an omnifunc which uses metadata files produced by nitpick which
is called by syntastic.
It is activated by default when editing a Nit source file, launch it using `ctrl-x ctrl-o`.
It will suggest entities names from the current context and display the corresponding documentation.
Once the correct completion has been selected, you can close the documentation preview window with `:pc`.
The omnifunc applies a simple heuristic to recognize what kind of entities to display:
(This is a simplification some behaviors are missing.)
* If the cursor follows `import`, it will list known modules.
* If it follows `new` it will list known classes with their constructors.
* If it follows `super`, `class`, `isa` or `as` it will list known classes.
* If it follows a `.`, it will list properties.
* If on an extern method declaration, it will list classes and properties.
* Otherwise, it will list keywords and properties.
Make sure to save your Nit module if using syntastic or to manually call nitpick the generate
the metadata files before using the omnifunc. If there is no locally available metadata, it
will use general metadata in the plugin directory.
The metadata files from nitpick are stored in `~/.vim/nit/`. This location can be customized with
the environment variable `NIT_VIM_DIR`.
## Documentation in preview window
The command `:Nitdoc` searches the documentation for the word under the cursor.
The results are displayed in the preview window in order of relevance.
You can search for any word by passing it as an argument, as in `:Nitdoc modulo`.
The Nitdoc command uses the same metadata files as the omnifunc.
You may want to map the function to a shortcut by adding the following code to `~/.vimrc`.
~~~
" Map displaying Nitdoc to Ctrl-D
map <C-d> :Nitdoc<enter>
~~~
## Search declarations and usages of the word under the cursor
The function `NitGitGrep` calls `git grep` to find declarations and usages of the word under the cursor.
It displays the results in the preview window.
You may want to map the function to a shortcut by adding the following code to `~/.vimrc`.
~~~
" Map the NitGitGrep function to Ctrl-G
map <C-g> :call NitGitGrep()<enter>
~~~
| {
"content_hash": "dd47cf95ac9d7fff48796f37e234c45e",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 124,
"avg_line_length": 35.291666666666664,
"alnum_prop": 0.7629279811097993,
"repo_name": "ablondin/nit",
"id": "9b4bf06c21a6f51a41896b80a384b044740c532e",
"size": "4281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "misc/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8153"
},
{
"name": "Awk",
"bytes": "42973"
},
{
"name": "Batchfile",
"bytes": "3582"
},
{
"name": "Brainfuck",
"bytes": "4335"
},
{
"name": "C",
"bytes": "27886788"
},
{
"name": "C++",
"bytes": "84"
},
{
"name": "CMake",
"bytes": "13077"
},
{
"name": "CSS",
"bytes": "172394"
},
{
"name": "DIGITAL Command Language",
"bytes": "10718"
},
{
"name": "Groff",
"bytes": "273303"
},
{
"name": "HTML",
"bytes": "29883"
},
{
"name": "Haskell",
"bytes": "770"
},
{
"name": "Java",
"bytes": "34401"
},
{
"name": "JavaScript",
"bytes": "352165"
},
{
"name": "Makefile",
"bytes": "119259"
},
{
"name": "Module Management System",
"bytes": "2074"
},
{
"name": "Nit",
"bytes": "6442405"
},
{
"name": "Objective-C",
"bytes": "544748"
},
{
"name": "Perl",
"bytes": "21800"
},
{
"name": "Python",
"bytes": "761"
},
{
"name": "Shell",
"bytes": "477730"
},
{
"name": "VimL",
"bytes": "24522"
},
{
"name": "XSLT",
"bytes": "3225"
}
],
"symlink_target": ""
} |
<header>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="index.php">GP/FP SNOMED CT RefSet and ICPC-2 mapping project - Field Test</a>
<?php
if($_SESSION["logged"]){
?>
<ul class="nav pull-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" role="button" href="#"><?= ($_SESSION['title'] !== 'Other' ? $_SESSION['title'].' ' : ''); ?><?= $_SESSION['first_name'].' '.$_SESSION['last_name'] ?> <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li role="presentation"><a href="index.php" tabindex="-1" role="menuitem">Home</a></li>
<li role="presentation"><a href="profile.php" tabindex="-1" role="menuitem">Profile</a></li>
<li role="presentation"><a href="encounters.php" tabindex="-1" role="menuitem">Encounters</a></li>
<li role="presentation"><a href="userGuide.php" tabindex="-1" role="menuitem" target="_blank">User Guide</a></li>
<li role="presentation"><a href="logout.php" tabindex="-1" role="menuitem">Log out</a></li>
</ul>
</li>
</ul>
<?php
}
?>
</div>
</div>
</header> | {
"content_hash": "ac2b057a7adbce43998295603e625d98",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 236,
"avg_line_length": 46.92307692307692,
"alnum_prop": 0.55,
"repo_name": "IHTSDO/field-test-tool",
"id": "803b9199a2675af5073d03f57789699dd6afceea",
"size": "1220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "inc/header.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16111"
},
{
"name": "JavaScript",
"bytes": "18589"
},
{
"name": "PHP",
"bytes": "150580"
}
],
"symlink_target": ""
} |
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/sysfs.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/mutex.h>
#include <linux/mod_devicetable.h>
#include <linux/spi/spi.h>
#define DRVNAME "adcxx"
struct adcxx {
struct device *hwmon_dev;
struct mutex lock;
u32 channels;
u32 reference; /* in millivolts */
};
/* sysfs hook function */
static ssize_t adcxx_read(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adcxx *adc = spi_get_drvdata(spi);
u8 tx_buf[2];
u8 rx_buf[2];
int status;
u32 value;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
if (adc->channels == 1) {
status = spi_read(spi, rx_buf, sizeof(rx_buf));
} else {
tx_buf[0] = attr->index << 3; /* other bits are don't care */
status = spi_write_then_read(spi, tx_buf, sizeof(tx_buf),
rx_buf, sizeof(rx_buf));
}
if (status < 0) {
dev_warn(dev, "SPI synch. transfer failed with status %d\n",
status);
goto out;
}
value = (rx_buf[0] << 8) + rx_buf[1];
dev_dbg(dev, "raw value = 0x%x\n", value);
value = value * adc->reference >> 12;
status = sprintf(buf, "%d\n", value);
out:
mutex_unlock(&adc->lock);
return status;
}
static ssize_t adcxx_show_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
/* The minimum reference is 0 for this chip family */
return sprintf(buf, "0\n");
}
static ssize_t adcxx_show_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct adcxx *adc = spi_get_drvdata(spi);
u32 reference;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
reference = adc->reference;
mutex_unlock(&adc->lock);
return sprintf(buf, "%d\n", reference);
}
static ssize_t adcxx_set_max(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct adcxx *adc = spi_get_drvdata(spi);
unsigned long value;
if (kstrtoul(buf, 10, &value))
return -EINVAL;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
adc->reference = value;
mutex_unlock(&adc->lock);
return count;
}
static ssize_t adcxx_show_name(struct device *dev, struct device_attribute
*devattr, char *buf)
{
return sprintf(buf, "%s\n", to_spi_device(dev)->modalias);
}
static struct sensor_device_attribute ad_input[] = {
SENSOR_ATTR(name, S_IRUGO, adcxx_show_name, NULL, 0),
SENSOR_ATTR(in_min, S_IRUGO, adcxx_show_min, NULL, 0),
SENSOR_ATTR(in_max, S_IWUSR | S_IRUGO, adcxx_show_max,
adcxx_set_max, 0),
SENSOR_ATTR(in0_input, S_IRUGO, adcxx_read, NULL, 0),
SENSOR_ATTR(in1_input, S_IRUGO, adcxx_read, NULL, 1),
SENSOR_ATTR(in2_input, S_IRUGO, adcxx_read, NULL, 2),
SENSOR_ATTR(in3_input, S_IRUGO, adcxx_read, NULL, 3),
SENSOR_ATTR(in4_input, S_IRUGO, adcxx_read, NULL, 4),
SENSOR_ATTR(in5_input, S_IRUGO, adcxx_read, NULL, 5),
SENSOR_ATTR(in6_input, S_IRUGO, adcxx_read, NULL, 6),
SENSOR_ATTR(in7_input, S_IRUGO, adcxx_read, NULL, 7),
};
/*----------------------------------------------------------------------*/
static int adcxx_probe(struct spi_device *spi)
{
int channels = spi_get_device_id(spi)->driver_data;
struct adcxx *adc;
int status;
int i;
adc = devm_kzalloc(&spi->dev, sizeof(*adc), GFP_KERNEL);
if (!adc)
return -ENOMEM;
/* set a default value for the reference */
adc->reference = 3300;
adc->channels = channels;
mutex_init(&adc->lock);
mutex_lock(&adc->lock);
spi_set_drvdata(spi, adc);
for (i = 0; i < 3 + adc->channels; i++) {
status = device_create_file(&spi->dev, &ad_input[i].dev_attr);
if (status) {
dev_err(&spi->dev, "device_create_file failed.\n");
goto out_err;
}
}
adc->hwmon_dev = hwmon_device_register(&spi->dev);
if (IS_ERR(adc->hwmon_dev)) {
dev_err(&spi->dev, "hwmon_device_register failed.\n");
status = PTR_ERR(adc->hwmon_dev);
goto out_err;
}
mutex_unlock(&adc->lock);
return 0;
out_err:
for (i--; i >= 0; i--)
device_remove_file(&spi->dev, &ad_input[i].dev_attr);
mutex_unlock(&adc->lock);
return status;
}
static int adcxx_remove(struct spi_device *spi)
{
struct adcxx *adc = spi_get_drvdata(spi);
int i;
mutex_lock(&adc->lock);
hwmon_device_unregister(adc->hwmon_dev);
for (i = 0; i < 3 + adc->channels; i++)
device_remove_file(&spi->dev, &ad_input[i].dev_attr);
mutex_unlock(&adc->lock);
return 0;
}
static const struct spi_device_id adcxx_ids[] = {
{ "adcxx1s", 1 },
{ "adcxx2s", 2 },
{ "adcxx4s", 4 },
{ "adcxx8s", 8 },
{ },
};
MODULE_DEVICE_TABLE(spi, adcxx_ids);
static struct spi_driver adcxx_driver = {
.driver = {
.name = "adcxx",
},
.id_table = adcxx_ids,
.probe = adcxx_probe,
.remove = adcxx_remove,
};
module_spi_driver(adcxx_driver);
MODULE_AUTHOR("Marc Pignat");
MODULE_DESCRIPTION("National Semiconductor adcxx8sxxx Linux driver");
MODULE_LICENSE("GPL");
| {
"content_hash": "1b28b44a87e5008a9e2494d39d9cf7df",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 74,
"avg_line_length": 24.056338028169016,
"alnum_prop": 0.6539812646370023,
"repo_name": "AlbandeCrevoisier/ldd-athens",
"id": "69e0bb97e5973911e1fdbfba07a36420b585894b",
"size": "6576",
"binary": false,
"copies": "678",
"ref": "refs/heads/master",
"path": "linux-socfpga/drivers/hwmon/adcxx.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "10184236"
},
{
"name": "Awk",
"bytes": "40418"
},
{
"name": "Batchfile",
"bytes": "81753"
},
{
"name": "C",
"bytes": "566858455"
},
{
"name": "C++",
"bytes": "21399133"
},
{
"name": "Clojure",
"bytes": "971"
},
{
"name": "Cucumber",
"bytes": "5998"
},
{
"name": "FORTRAN",
"bytes": "11832"
},
{
"name": "GDB",
"bytes": "18113"
},
{
"name": "Groff",
"bytes": "2686457"
},
{
"name": "HTML",
"bytes": "34688334"
},
{
"name": "Lex",
"bytes": "56961"
},
{
"name": "Logos",
"bytes": "133810"
},
{
"name": "M4",
"bytes": "3325"
},
{
"name": "Makefile",
"bytes": "1685015"
},
{
"name": "Objective-C",
"bytes": "920162"
},
{
"name": "Perl",
"bytes": "752477"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "533352"
},
{
"name": "Shell",
"bytes": "468244"
},
{
"name": "SourcePawn",
"bytes": "2711"
},
{
"name": "UnrealScript",
"bytes": "12824"
},
{
"name": "XC",
"bytes": "33970"
},
{
"name": "XS",
"bytes": "34909"
},
{
"name": "Yacc",
"bytes": "113516"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MobiliTips.MvxPlugins.MvxAms.WindowsStore")]
[assembly: AssemblyDescription("MvvmCross - Azure Mobile Services plugin for Windows Store")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MobiliTips")]
[assembly: AssemblyProduct("MobiliTips.MvxPlugins.MvxAms.WindowsStore")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | {
"content_hash": "925d65143daaefa03b1fcb713bc4892c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 93,
"avg_line_length": 40.241379310344826,
"alnum_prop": 0.7566409597257926,
"repo_name": "MobiliTips/MvxPlugins",
"id": "ecb5c52e2033f538f15a762b44b57f84f9255636",
"size": "1170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MvxAms/MvxAms.WindowsStore/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "181090"
},
{
"name": "Pascal",
"bytes": "14799"
},
{
"name": "Puppet",
"bytes": "2195"
}
],
"symlink_target": ""
} |
package gov.hhs.fha.nhinc.docquery.xdsb.helper;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.docquery.xdsb.helper.XDSbConstants.RegistryStoredQueryParameter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import org.apache.commons.lang.StringUtils;
/**
*
* @author tjafri
*/
public class XDSbAdhocQueryRequestHelperImpl implements XDSbAdhocQueryRequestHelper {
/*
* (non-Javadoc)
*
* RegistryStoredQueryParameter, java.lang.String, oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest)
*/
@Override
public void createOrReplaceSlotValue(RegistryStoredQueryParameter slotName, String value, AdhocQueryRequest message) {
if (message != null && message.getAdhocQuery() != null && message.getAdhocQuery().getSlot() != null) {
for (SlotType1 slot : message.getAdhocQuery().getSlot()) {
if (slot != null) {
if (StringUtils.equalsIgnoreCase(slot.getName(), slotName.toString())) {
message.getAdhocQuery().getSlot().remove(slot);
break;
}
}
}
message.getAdhocQuery().getSlot().add(createSlot(slotName, value));
}
}
/**
* Creates a slot.
*
* @param slotName the slot name
* @param value the value
* @return the slot type1
*/
protected SlotType1 createSlot(RegistryStoredQueryParameter slotName, String value) {
SlotType1 slot = new SlotType1();
slot.setName(slotName.toString());
slot.setValueList(new ValueListType());
slot.getValueList().getValue().add(value);
return slot;
}
/**
* Creates a slot.
*
* @param slotName the slot name
* @param values
* @return the slot type1
*/
protected SlotType1 createSlot(RegistryStoredQueryParameter slotName, List<String> values) {
SlotType1 slot = new SlotType1();
slot.setName(slotName.toString());
slot.setValueList(new ValueListType());
slot.getValueList().getValue().addAll(values);
return null;
}
@Override
public String formatXDSbDate(Date date) {
String sFormattedDate = null;
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(NhincConstants.DATE_PARSE_FORMAT);
sFormattedDate = sdf.format(date);
sFormattedDate = StringUtils.stripEnd(sFormattedDate, "0000000000");
sFormattedDate = StringUtils.stripEnd(sFormattedDate, "00000000");
sFormattedDate = StringUtils.stripEnd(sFormattedDate, "000000");
sFormattedDate = StringUtils.stripEnd(sFormattedDate, "0000");
sFormattedDate = StringUtils.stripEnd(sFormattedDate, "00");
}
return sFormattedDate;
}
@Override
public String createSingleQuoteDelimitedValue(String value) {
if (!StringUtils.startsWith(value, "'")) {
value = "'".concat(value);
}
if (!StringUtils.endsWith(value, "'")) {
value = value.concat("'");
}
return value;
}
@Override
public String createSingleQuoteDelimitedListValue(List<String> values) {
StringBuilder builder = new StringBuilder();
builder.append("(");
for (String s : values) {
builder.append(createSingleQuoteDelimitedValue(s));
}
builder.append(")");
return builder.toString();
}
@Override
public List<String> createCodeSchemeValue(List<String> documentTypeCode, String schema) {
List<String> docType = new ArrayList<String>();
for (String docTypeCode : documentTypeCode) {
StringBuilder builder = new StringBuilder();
builder.append("('");
builder.append(docTypeCode);
builder.append("^^");
builder.append(schema);
builder.append("')");
docType.add(builder.toString());
}
return docType;
}
@Override
public void createOrReplaceSlotValue(RegistryStoredQueryParameter slotName, List<String> value, AdhocQueryRequest message) {
if (message != null && message.getAdhocQuery() != null && message.getAdhocQuery().getSlot() != null) {
for (SlotType1 slot : message.getAdhocQuery().getSlot()) {
if (slot != null) {
if (StringUtils.equalsIgnoreCase(slot.getName(), slotName.toString())) {
message.getAdhocQuery().getSlot().remove(slot);
break;
}
}
}
message.getAdhocQuery().getSlot().add(createSlot(slotName, value));
}
}
}
| {
"content_hash": "908cc75c35429a098fd4acdab10f7bab",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 128,
"avg_line_length": 36,
"alnum_prop": 0.6171063149480416,
"repo_name": "beiyuxinke/CONNECT",
"id": "0c35d767b895b7af8ae1bcb9d500a92c37fd5ae8",
"size": "6679",
"binary": false,
"copies": "2",
"ref": "refs/heads/CONNECT_integration",
"path": "Product/Production/Services/DocumentQueryCore/src/main/java/gov/hhs/fha/nhinc/docquery/xdsb/helper/XDSbAdhocQueryRequestHelperImpl.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "73091"
},
{
"name": "HTML",
"bytes": "178809"
},
{
"name": "Java",
"bytes": "14358905"
},
{
"name": "JavaScript",
"bytes": "6991"
},
{
"name": "PLSQL",
"bytes": "67148"
},
{
"name": "Python",
"bytes": "773"
},
{
"name": "SQLPL",
"bytes": "1363363"
},
{
"name": "Shell",
"bytes": "7384"
},
{
"name": "XSLT",
"bytes": "108247"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.ironmq.integrationtest;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@Disabled("Must be manually tested. Provide your own projectId and token!")
public class IronMQRackspaceComponentTest extends CamelTestSupport {
private String projectId = "myIronMQproject";
private String token = "myIronMQToken";
@EndpointInject("direct:start")
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void testIronMQ() throws Exception {
result.setExpectedMessageCount(1);
result.expectedBodiesReceived("some payload");
template.sendBody("some payload");
assertMockEndpointsSatisfied();
String id = result.getExchanges().get(0).getIn().getHeader("MESSAGE_ID", String.class);
assertNotNull(id);
}
@Override
protected RouteBuilder createRouteBuilder() {
final String ironMQEndpoint = "ironmq:testqueue?projectId=" + projectId + "&token=" + token
+ "&ironMQCloud=https://mq-rackspace-lon.iron.io";
return new RouteBuilder() {
public void configure() {
from("direct:start").to(ironMQEndpoint);
from(ironMQEndpoint + "&maxMessagesPerPoll=5").to("mock:result");
}
};
}
}
| {
"content_hash": "daabec0c797430ff901eb58514cd36fe",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 99,
"avg_line_length": 35.1875,
"alnum_prop": 0.6933096506808762,
"repo_name": "adessaigne/camel",
"id": "e763097b6b2a4990b858d8a11d48328e621a02bf",
"size": "2491",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "components/camel-ironmq/src/test/java/org/apache/camel/component/ironmq/integrationtest/IronMQRackspaceComponentTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "16123"
},
{
"name": "Groovy",
"bytes": "383919"
},
{
"name": "HTML",
"bytes": "209156"
},
{
"name": "Java",
"bytes": "109812609"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "19367"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
import {
GET_ALL_TEMPLATES,
SET_TEMPLATES,
TEMPLATE_GET_DISKS,
TEMPLATE_GET_NICS,
TEMPLATE_SET_DISKS,
TEMPLATE_SET_NICS,
} from '_/constants'
export function getTemplateDisks (templateId) {
return {
type: TEMPLATE_GET_DISKS,
payload: {
templateId,
},
}
}
export function getTemplateNics (templateId) {
return {
type: TEMPLATE_GET_NICS,
payload: {
templateId,
},
}
}
export function getAllTemplates () {
return { type: GET_ALL_TEMPLATES }
}
export function setTemplateDisks (templateId, disks) {
return {
type: TEMPLATE_SET_DISKS,
payload: {
templateId,
disks,
},
}
}
export function setTemplateNics (templateId, nics) {
return {
type: TEMPLATE_SET_NICS,
payload: {
templateId,
nics,
},
}
}
export function setTemplates (templates) {
return {
type: SET_TEMPLATES,
payload: {
templates,
},
}
}
| {
"content_hash": "1edb28f969e0e18a36d3e92f08034007",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 54,
"avg_line_length": 15.830508474576272,
"alnum_prop": 0.6220556745182013,
"repo_name": "mareklibra/userportal",
"id": "38d409d356691239efe84b599d460a8207f031d2",
"size": "934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/actions/templates.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "871"
},
{
"name": "CSS",
"bytes": "151"
},
{
"name": "HTML",
"bytes": "404"
},
{
"name": "Java",
"bytes": "974"
},
{
"name": "JavaScript",
"bytes": "80471"
},
{
"name": "M4",
"bytes": "1421"
},
{
"name": "Makefile",
"bytes": "3004"
},
{
"name": "Shell",
"bytes": "2245"
}
],
"symlink_target": ""
} |
package org.strangeforest.tcb.stats.model.core;
import java.util.*;
import static org.strangeforest.tcb.stats.model.core.SetRules.*;
public class MatchRules {
public static final MatchRules BEST_OF_3_MATCH = new MatchRules(3, COMMON_SET);
public static final MatchRules BEST_OF_5_MATCH = new MatchRules(5, COMMON_SET);
public static final MatchRules BEST_OF_5_NO_5TH_SET_TB_MATCH = new MatchRules(5, COMMON_SET, NO_TB_SET);
public static final MatchRules BEST_OF_5_AO_MATCH = new MatchRules(5, COMMON_SET, AO_5TH_SET);
public static final MatchRules BEST_OF_5_WB_MATCH = new MatchRules(5, COMMON_SET, WB_5TH_SET);
private final int bestOf;
private final SetRules set;
private final SetRules decidingSet;
public MatchRules(int bestOf, SetRules set) {
this(bestOf, set, set);
}
public MatchRules(int bestOf, SetRules set, SetRules decidingSet) {
this.bestOf = bestOf;
this.set = set;
this.decidingSet = decidingSet;
}
public int getSets() {
return (bestOf + 1) / 2;
}
public SetRules getSet() {
return set;
}
public SetRules getDecidingSet() {
return decidingSet;
}
public SetRules getSet(int set) {
return isDecidingSet(set) ? decidingSet : this.set;
}
public boolean isDecidingSet(int set) {
return set == bestOf;
}
public boolean hasDecidingSetSpecificRules() {
return !Objects.equals(set, decidingSet);
}
// Object Methods
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MatchRules)) return false;
var rules = (MatchRules) o;
return bestOf == rules.bestOf && Objects.equals(set, rules.set) && Objects.equals(decidingSet, rules.decidingSet);
}
@Override public int hashCode() {
return Objects.hash(bestOf, set, decidingSet);
}
}
| {
"content_hash": "a2f468a744ceec65387b2ad51522d302",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 116,
"avg_line_length": 26.5,
"alnum_prop": 0.7232704402515723,
"repo_name": "mcekovic/tennis-crystal-ball",
"id": "90aa7555b5b4f7b4be453bb61df0fae4f82a5efa",
"size": "1749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tennis-stats/src/main/java/org/strangeforest/tcb/stats/model/core/MatchRules.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7334"
},
{
"name": "Dockerfile",
"bytes": "821"
},
{
"name": "Groovy",
"bytes": "233228"
},
{
"name": "HTML",
"bytes": "1190999"
},
{
"name": "Java",
"bytes": "1605063"
},
{
"name": "JavaScript",
"bytes": "36603"
},
{
"name": "Kotlin",
"bytes": "12881"
},
{
"name": "PLpgSQL",
"bytes": "67620"
},
{
"name": "Shell",
"bytes": "681"
}
],
"symlink_target": ""
} |
'use strict';
/* global ace */
module.exports = function(keyMap) {
if (keyMap === 'default')
return this._Ace.setKeyboardHandler('ace/keyboard/hash_handler');
if (keyMap === 'vim') {
ace.config.loadModule('ace/keybinding/vim', () => {
const {CodeMirror} = ace.require('ace/keyboard/vim');
const {Vim} = CodeMirror;
Vim.defineEx('write', 'w', this.save.bind(this));
this._Ace.setOption('keyboardHandler', 'vim');
this._Ace.setKeyboardHandler('ace/keyboard/' + keyMap);
});
}
};
| {
"content_hash": "5146af33443323a3893e607c631e0f7c",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 73,
"avg_line_length": 30.3,
"alnum_prop": 0.5363036303630363,
"repo_name": "cloudcmd/edward",
"id": "4f24ee6875bd44626f896fd90cd5faa805e8f00c",
"size": "606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/set-key-map.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1556"
},
{
"name": "HCL",
"bytes": "193"
},
{
"name": "HTML",
"bytes": "823"
},
{
"name": "JavaScript",
"bytes": "35403"
}
],
"symlink_target": ""
} |
ZendFramework1-App-Skeleton
===========================
Composer Zend Framework 1.* App Skeletton with composer dependencies manager
| {
"content_hash": "8386c937286a6b6219f4bab3f7393a9b",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 76,
"avg_line_length": 33.5,
"alnum_prop": 0.6716417910447762,
"repo_name": "arzola/ZendFramework1-App-Skeleton",
"id": "9a38a4a131b52703b5cd2b3f14bd79e147617e7a",
"size": "134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "3941"
}
],
"symlink_target": ""
} |
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
<prerequisites>
<maven>3.0.4</maven>
</prerequisites>
<groupId>org.odlabs.wiquery</groupId>
<artifactId>wiquery-parent</artifactId>
<packaging>pom</packaging>
<version>7.0.0-SNAPSHOT</version>
<name>WiQuery Parent</name>
<licenses>
<license>
<name>MIT</name>
<url>http://choosealicense.com/licenses/mit/</url>
</license>
</licenses>
<url>https://github.com/wiquery/wiquery</url>
<scm>
<url>git://github.com/WiQuery/wiquery.git</url>
<connection>scm:git:git://github.com/WiQuery/wiquery.git</connection>
<developerConnection>scm:git:git@github.com:WiQuery/wiquery.git</developerConnection>
</scm>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<wicket.version>7.17.0</wicket.version>
<jackson.version>2.9.10.8</jackson.version>
<slf4j.version>[1.7,1.7.5]</slf4j.version>
<junit.version>4.13.1</junit.version>
<servlet-api.version>3.0.1</servlet-api.version>
<jetty.version>9.1.0.v20131115</jetty.version>
<maven-bundle-plugin.version>2.4.0</maven-bundle-plugin.version>
<maven-clean-plugin.version>2.5</maven-clean-plugin.version>
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven-deploy-plugin.version>2.8.1</maven-deploy-plugin.version>
<maven-eclipse-plugin.version>2.9</maven-eclipse-plugin.version>
<maven-gpg-plugin.version>1.4</maven-gpg-plugin.version>
<maven-install-plugin.version>2.5.1</maven-install-plugin.version>
<maven-jar-plugin.version>2.4</maven-jar-plugin.version>
<maven-javadoc-plugin.version>2.9.1</maven-javadoc-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<maven-site-plugin.version>3.3</maven-site-plugin.version>
<maven-source-plugin.version>2.2.1</maven-source-plugin.version>
<maven-surefire-plugin.version>2.16</maven-surefire-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
</properties>
<modules>
<module>wiquery-core</module>
<module>wiquery-jquery-ui</module>
<module>wiquery-demo</module>
</modules>
<dependencyManagement>
<dependencies>
<!-- WiQuery dependencies -->
<dependency>
<groupId>org.odlabs.wiquery</groupId>
<artifactId>wiquery-core</artifactId>
<version>${project.version}</version>
</dependency>
<!-- add wiquery-core also as test project so wiquery-jquery-ui can use
the abstract testcase class -->
<dependency>
<groupId>org.odlabs.wiquery</groupId>
<artifactId>wiquery-core</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.odlabs.wiquery</groupId>
<artifactId>wiquery-jquery-ui</artifactId>
<version>${project.version}</version>
</dependency>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- External dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<includes>
<include>**/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<includes>
<include>**/*</include>
</includes>
</testResource>
<testResource>
<directory>src/test/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<includes>
<include>**/*</include>
</includes>
</testResource>
</testResources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${maven-bundle-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven-clean-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>${maven-eclipse-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>${maven-gpg-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>${maven-install-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>${maven-site-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven-source-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.felix
</groupId>
<artifactId>
maven-bundle-plugin
</artifactId>
<versionRange>
[2.4.0,)
</versionRange>
<goals>
<goal>manifest</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<wtpmanifest>true</wtpmanifest>
<wtpapplicationxml>true</wtpapplicationxml>
<wtpversion>1.5</wtpversion>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<finalName>${project.artifactId}-${project.version}-r${buildNumber}-d${timestamp}</finalName>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>jar</supportedProjectType>
</supportedProjectTypes>
<instructions>
<Import-Package>
!org.odlabs.wiquery*,
!com.yahoo.platform.yui.compressor*,
!org.mozilla.javascript*,
com.fasterxml.jackson*;version="${jackson.version}",
org.apache.wicket*;version="${wicket.version}",
org.slf4j*;version="${slf4j.version}",
*
</Import-Package>
<Export-Package>
org.odlabs.wiquery*,
com.yahoo.platform.yui.compressor*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>nexus-owsi-core</id>
<name>Nexus OWSI Core</name>
<url>https://projects.openwide.fr/services/nexus/content/repositories/owsi-core</url>
</repository>
<snapshotRepository>
<id>nexus-owsi-core-snapshots</id>
<name>Nexus OWSI Core Snapshots</name>
<url>https://projects.openwide.fr/services/nexus/content/repositories/owsi-core-snapshots</url>
</snapshotRepository>
</distributionManagement>
</project>
| {
"content_hash": "220bbd3ebf02e4a073145d68c205e236",
"timestamp": "",
"source": "github",
"line_count": 432,
"max_line_length": 129,
"avg_line_length": 31.256944444444443,
"alnum_prop": 0.6649633414796712,
"repo_name": "WiQuery/wiquery",
"id": "6f8184754067a3a03e74b8696b529d45562fcab2",
"size": "13503",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "920"
},
{
"name": "HTML",
"bytes": "19559"
},
{
"name": "Java",
"bytes": "1323302"
},
{
"name": "JavaScript",
"bytes": "66989"
}
],
"symlink_target": ""
} |
// Copyright 2007 The Apache Software Foundation
//
// 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.
package org.apache.tapestry5.annotations;
import java.lang.annotation.*;
/**
* Allows for the inclusion of one or more JavaScript libraries. The libraries are assets, usually (but not always)
* stored on the classpath with the component.
*
* @see org.apache.tapestry5.annotations.IncludeStylesheet
* @see org.apache.tapestry5.annotations.Path
* @deprecated use {@link Import} instead.
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Deprecated
public @interface IncludeJavaScriptLibrary
{
/**
* The paths to the JavaScript library assets. Symbols in the paths are expanded. The library may be localized.
*/
String[] value();
}
| {
"content_hash": "9c9b2c91ab50cdda496ce2962f9c3bca",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 117,
"avg_line_length": 34.21052631578947,
"alnum_prop": 0.7446153846153846,
"repo_name": "safarijv/tapestry-compat",
"id": "382ad2356c3ce3f51a53d09f17cb36a5c7380137",
"size": "1300",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/apache/tapestry5/annotations/IncludeJavaScriptLibrary.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "48116"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.offline.off_policy_estimator import OffPolicyEstimator, \
OffPolicyEstimate
from ray.rllib.utils.annotations import override
class ImportanceSamplingEstimator(OffPolicyEstimator):
"""The step-wise IS estimator.
Step-wise IS estimator described in https://arxiv.org/pdf/1511.03722.pdf"""
def __init__(self, policy, gamma):
OffPolicyEstimator.__init__(self, policy, gamma)
@override(OffPolicyEstimator)
def estimate(self, batch):
self.check_can_estimate_for(batch)
rewards, old_prob = batch["rewards"], batch["action_prob"]
new_prob = self.action_prob(batch)
# calculate importance ratios
p = []
for t in range(batch.count - 1):
if t == 0:
pt_prev = 1.0
else:
pt_prev = p[t - 1]
p.append(pt_prev * new_prob[t] / old_prob[t])
# calculate stepwise IS estimate
V_prev, V_step_IS = 0.0, 0.0
for t in range(batch.count - 1):
V_prev += rewards[t] * self.gamma**t
V_step_IS += p[t] * rewards[t] * self.gamma**t
estimation = OffPolicyEstimate(
"is", {
"V_prev": V_prev,
"V_step_IS": V_step_IS,
"V_gain_est": V_step_IS / max(1e-8, V_prev),
})
return estimation
| {
"content_hash": "a2b8c204e3e4167f9ab1ec462afe5f6e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 79,
"avg_line_length": 31.91304347826087,
"alnum_prop": 0.5756130790190735,
"repo_name": "ujvl/ray-ng",
"id": "55678c9511c6708a37d91c499ec5cb7c99bc34eb",
"size": "1468",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rllib/offline/is_estimator.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "349753"
},
{
"name": "C++",
"bytes": "6547"
},
{
"name": "CMake",
"bytes": "4927"
},
{
"name": "Makefile",
"bytes": "5285"
},
{
"name": "Python",
"bytes": "260095"
},
{
"name": "Shell",
"bytes": "6666"
}
],
"symlink_target": ""
} |
from ctypes import *
import unittest
import struct
def valid_ranges(*types):
# given a sequence of numeric types, collect their _type_
# attribute, which is a single format character compatible with
# the struct module, use the struct module to calculate the
# minimum and maximum value allowed for this format.
# Returns a list of (min, max) values.
result = []
for t in types:
fmt = t._type_
size = struct.calcsize(fmt)
a = struct.unpack(fmt, (b"\x00"*32)[:size])[0]
b = struct.unpack(fmt, (b"\xFF"*32)[:size])[0]
c = struct.unpack(fmt, (b"\x7F"+b"\x00"*32)[:size])[0]
d = struct.unpack(fmt, (b"\x80"+b"\xFF"*32)[:size])[0]
result.append((min(a, b, c, d), max(a, b, c, d)))
return result
ArgType = type(byref(c_int(0)))
unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong]
signed_types = [c_byte, c_short, c_int, c_long, c_longlong]
bool_types = []
float_types = [c_double, c_float]
try:
c_ulonglong
c_longlong
except NameError:
pass
else:
unsigned_types.append(c_ulonglong)
signed_types.append(c_longlong)
try:
c_bool
except NameError:
pass
else:
bool_types.append(c_bool)
unsigned_ranges = valid_ranges(*unsigned_types)
signed_ranges = valid_ranges(*signed_types)
bool_values = [True, False, 0, 1, -1, 5000, 'test', [], [1]]
################################################################
class NumberTestCase(unittest.TestCase):
def test_default_init(self):
# default values are set to zero
for t in signed_types + unsigned_types + float_types:
self.failUnlessEqual(t().value, 0)
def test_unsigned_values(self):
# the value given to the constructor is available
# as the 'value' attribute
for t, (l, h) in zip(unsigned_types, unsigned_ranges):
self.failUnlessEqual(t(l).value, l)
self.failUnlessEqual(t(h).value, h)
def test_signed_values(self):
# see above
for t, (l, h) in zip(signed_types, signed_ranges):
self.failUnlessEqual(t(l).value, l)
self.failUnlessEqual(t(h).value, h)
def test_bool_values(self):
from operator import truth
for t, v in zip(bool_types, bool_values):
self.failUnlessEqual(t(v).value, truth(v))
def test_typeerror(self):
# Only numbers are allowed in the contructor,
# otherwise TypeError is raised
for t in signed_types + unsigned_types + float_types:
self.assertRaises(TypeError, t, "")
self.assertRaises(TypeError, t, None)
## def test_valid_ranges(self):
## # invalid values of the correct type
## # raise ValueError (not OverflowError)
## for t, (l, h) in zip(unsigned_types, unsigned_ranges):
## self.assertRaises(ValueError, t, l-1)
## self.assertRaises(ValueError, t, h+1)
def test_from_param(self):
# the from_param class method attribute always
# returns PyCArgObject instances
for t in signed_types + unsigned_types + float_types:
self.failUnlessEqual(ArgType, type(t.from_param(0)))
def test_byref(self):
# calling byref returns also a PyCArgObject instance
for t in signed_types + unsigned_types + float_types + bool_types:
parm = byref(t())
self.failUnlessEqual(ArgType, type(parm))
def test_floats(self):
# c_float and c_double can be created from
# Python int, long and float
class FloatLike(object):
def __float__(self):
return 2.0
f = FloatLike()
for t in float_types:
self.failUnlessEqual(t(2.0).value, 2.0)
self.failUnlessEqual(t(2).value, 2.0)
self.failUnlessEqual(t(2).value, 2.0)
self.failUnlessEqual(t(f).value, 2.0)
def test_integers(self):
class FloatLike(object):
def __float__(self):
return 2.0
f = FloatLike()
class IntLike(object):
def __int__(self):
return 2
i = IntLike()
# integers cannot be constructed from floats,
# but from integer-like objects
for t in signed_types + unsigned_types:
self.assertRaises(TypeError, t, 3.14)
self.assertRaises(TypeError, t, f)
self.failUnlessEqual(t(i).value, 2)
def test_sizes(self):
for t in signed_types + unsigned_types + float_types + bool_types:
try:
size = struct.calcsize(t._type_)
except struct.error:
continue
# sizeof of the type...
self.failUnlessEqual(sizeof(t), size)
# and sizeof of an instance
self.failUnlessEqual(sizeof(t()), size)
def test_alignments(self):
for t in signed_types + unsigned_types + float_types:
code = t._type_ # the typecode
align = struct.calcsize("c%c" % code) - struct.calcsize(code)
# alignment of the type...
self.failUnlessEqual((code, alignment(t)),
(code, align))
# and alignment of an instance
self.failUnlessEqual((code, alignment(t())),
(code, align))
def test_int_from_address(self):
from array import array
for t in signed_types + unsigned_types:
# the array module doesn't suppport all format codes
# (no 'q' or 'Q')
try:
array(t._type_)
except ValueError:
continue
a = array(t._type_, [100])
# v now is an integer at an 'external' memory location
v = t.from_address(a.buffer_info()[0])
self.failUnlessEqual(v.value, a[0])
self.failUnlessEqual(type(v), t)
# changing the value at the memory location changes v's value also
a[0] = 42
self.failUnlessEqual(v.value, a[0])
def test_float_from_address(self):
from array import array
for t in float_types:
a = array(t._type_, [3.14])
v = t.from_address(a.buffer_info()[0])
self.failUnlessEqual(v.value, a[0])
self.failUnless(type(v) is t)
a[0] = 2.3456e17
self.failUnlessEqual(v.value, a[0])
self.failUnless(type(v) is t)
def test_char_from_address(self):
from ctypes import c_char
from array import array
a = array('b', [0])
a[0] = ord('x')
v = c_char.from_address(a.buffer_info()[0])
self.failUnlessEqual(v.value, b'x')
self.failUnless(type(v) is c_char)
a[0] = ord('?')
self.failUnlessEqual(v.value, b'?')
# array does not support c_bool / 't'
# def test_bool_from_address(self):
# from ctypes import c_bool
# from array import array
# a = array(c_bool._type_, [True])
# v = t.from_address(a.buffer_info()[0])
# self.failUnlessEqual(v.value, a[0])
# self.failUnlessEqual(type(v) is t)
# a[0] = False
# self.failUnlessEqual(v.value, a[0])
# self.failUnlessEqual(type(v) is t)
def test_init(self):
# c_int() can be initialized from Python's int, and c_int.
# Not from c_long or so, which seems strange, abd should
# probably be changed:
self.assertRaises(TypeError, c_int, c_long(42))
## def test_perf(self):
## check_perf()
from ctypes import _SimpleCData
class c_int_S(_SimpleCData):
_type_ = "i"
__slots__ = []
def run_test(rep, msg, func, arg=None):
## items = [None] * rep
items = range(rep)
from time import clock
if arg is not None:
start = clock()
for i in items:
func(arg); func(arg); func(arg); func(arg); func(arg)
stop = clock()
else:
start = clock()
for i in items:
func(); func(); func(); func(); func()
stop = clock()
print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
def check_perf():
# Construct 5 objects
from ctypes import c_int
REP = 200000
run_test(REP, "int()", int)
run_test(REP, "int(999)", int)
run_test(REP, "c_int()", c_int)
run_test(REP, "c_int(999)", c_int)
run_test(REP, "c_int_S()", c_int_S)
run_test(REP, "c_int_S(999)", c_int_S)
# Python 2.3 -OO, win2k, P4 700 MHz:
#
# int(): 0.87 us
# int(999): 0.87 us
# c_int(): 3.35 us
# c_int(999): 3.34 us
# c_int_S(): 3.23 us
# c_int_S(999): 3.24 us
# Python 2.2 -OO, win2k, P4 700 MHz:
#
# int(): 0.89 us
# int(999): 0.89 us
# c_int(): 9.99 us
# c_int(999): 10.02 us
# c_int_S(): 9.87 us
# c_int_S(999): 9.85 us
if __name__ == '__main__':
## check_perf()
unittest.main()
| {
"content_hash": "e763cd7288b8710efe6f4a3863c1e77e",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 78,
"avg_line_length": 32.15523465703971,
"alnum_prop": 0.5564163017851128,
"repo_name": "MalloyPower/parsing-python",
"id": "c0732decd763c511d14d6db783278ec405d62088",
"size": "8907",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "front-end/testsuite-python-lib/Python-3.1/Lib/ctypes/test/test_numbers.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1963"
},
{
"name": "Lex",
"bytes": "238458"
},
{
"name": "Makefile",
"bytes": "4513"
},
{
"name": "OCaml",
"bytes": "412695"
},
{
"name": "Python",
"bytes": "17319"
},
{
"name": "Rascal",
"bytes": "523063"
},
{
"name": "Yacc",
"bytes": "429659"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">UseMediaStoreProvider</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
| {
"content_hash": "2c42d9cd5fc7f9392cd85d94bbfc55bb",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 58,
"avg_line_length": 28.875,
"alnum_prop": 0.6926406926406926,
"repo_name": "Android518-2015/week11-contentproviders",
"id": "bef7328e8d4b9e9852abbdbaddd4f42df969e018",
"size": "231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UseMediaStoreContentProvider/res/values/strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "Java",
"bytes": "15721"
}
],
"symlink_target": ""
} |
(function($) {
$.extend($, {lightBoxFu: {}});
$.extend($.lightBoxFu, {
initialize: function (o) {
if($('#lightboxfu').length == 0) {
options = {stylesheetsPath: '/stylesheets/', imagesPath: '/images/'};
jQuery.extend(options, o);
html = '<div id="lightboxfu" style="display: none"><div id="lOverlay"><div id="lWindow"><div id="lInner"></div></div></div></div>';
if ($.browser.msie && $.browser.version == '6.0') {
html += '<link rel="stylesheet" type="text/css" href="'+options.stylesheetsPath+'lightbox-fu-ie6.css" />';
$('body').css('background', 'url('+options.imagesPath+'blank.gif) fixed');
} else if($.browser.msie && $.browser.version == '7.0') {
html += '<link rel="stylesheet" type="text/css" href="'+options.stylesheetsPath+'lightbox-fu-ie7.css" />';
}
$('body').append(html);
if(!$.browser.msie) {
$('#lOverlay').css('background', 'url('+options.imagesPath+'overlay.png) fixed');
}
$.lightBoxFu.appendStyle();
}
},
open: function(options) {
options = options || {};
$('#lInner').html(options.html);
$('#lightboxfu').show();
var width = options.width || '250';
$('#lInner').css({'width': width});
if(options.closeOnClick != false) {
$('#lOverlay').one('click', $.lightBoxFu.close);
}
},
close: function() {
$('#lightboxfu').hide();
},
appendStyle: function() {
if(!$.browser.msie) {
$('#lOverlay').css({display: 'table'});
$('#lOverlay #lWindow').css({display: 'table-cell'});
}
$('#lOverlay').css({position: 'fixed', top: 0, left: 0, width: "100%", height: "100%"});
$('#lOverlay #lWindow').css({'vertical-align': 'middle'});
$('#lOverlay #lInner').css({width: '300px', 'background-color': '#fff', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', 'max-height': '550px', margin: '0 auto', padding: '15px', overflow: 'auto'});
}
});
$.extend($.fn, {
lightBoxFu: function(options){
return this.each(function() {
$(this).click(function() {
$.lightBoxFu.open(options);
return false;
});
});
}});
})(jQuery);
| {
"content_hash": "efe9da6ac6e3ed077b0dfad065cb8a38",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 218,
"avg_line_length": 36.65,
"alnum_prop": 0.5493406093678945,
"repo_name": "slawosz/content-slice",
"id": "756046f84ceb62d4ff3b93d4ad1f0a564ce5c9c1",
"size": "2371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/javascripts/jquery.lightBoxFu.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "7591"
},
{
"name": "ColdFusion",
"bytes": "169639"
},
{
"name": "JavaScript",
"bytes": "4811096"
},
{
"name": "PHP",
"bytes": "67590"
},
{
"name": "Perl",
"bytes": "38659"
},
{
"name": "Python",
"bytes": "47611"
},
{
"name": "Ruby",
"bytes": "121733"
}
],
"symlink_target": ""
} |
<?php
namespace Bolt\Storage\Entity;
/**
* Entity for relations.
*/
class Relations extends Entity
{
/** @var int */
protected $id;
/** @var string */
protected $from_contenttype;
/** @var int */
protected $from_id;
/** @var string */
protected $to_contenttype;
/** @var int */
protected $to_id;
private $invert = false;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getFromContenttype()
{
return $this->from_contenttype;
}
/**
* @param string $from_contenttype
*/
public function setFromContenttype($from_contenttype)
{
$this->from_contenttype = $from_contenttype;
}
/**
* @return int
*/
public function getFromId()
{
return $this->from_id;
}
/**
* @param int $from_id
*/
public function setFromId($from_id)
{
$this->from_id = $from_id;
}
/**
* @return string
*/
public function getToContenttype()
{
return $this->to_contenttype;
}
/**
* @return int
*/
public function getToId()
{
if ($this->invert === true) {
return $this->from_id;
}
return $this->to_id;
}
/**
* @param int $to_id
*/
public function setToId($to_id)
{
$this->to_id = $to_id;
}
/**
* @param string $to_contenttype
*/
public function setToContenttype($to_contenttype)
{
$this->to_contenttype = $to_contenttype;
}
/**
* @return boolean
*/
public function isInvert()
{
return $this->invert;
}
/**
* @param boolean $invert
*/
public function setInvert($invert)
{
$this->invert = $invert;
}
public function actAsInverse()
{
$this->invert = true;
}
public function isInverted()
{
return $this->invert;
}
}
| {
"content_hash": "3fd6993cadcc69f2310dcc2d47273787",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 57,
"avg_line_length": 16.21969696969697,
"alnum_prop": 0.4932274638019617,
"repo_name": "electrolinux/bolt",
"id": "47ca09b63e2bf1886c08d4f06034459048688310",
"size": "2141",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Storage/Entity/Relations.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3175"
},
{
"name": "CSS",
"bytes": "266671"
},
{
"name": "HTML",
"bytes": "445536"
},
{
"name": "JavaScript",
"bytes": "518082"
},
{
"name": "PHP",
"bytes": "2759857"
},
{
"name": "Shell",
"bytes": "2115"
}
],
"symlink_target": ""
} |
package io.renthell.eventstoresrv.web.events;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
/**
* Created by cfhernandez on 28/8/17.
*/
@Getter
@Setter
@ToString
public class PropertyTransactionConfirmEvent extends BaseEvent {
private String identifier;
private String transactionId;
public PropertyTransactionConfirmEvent() {
super();
}
}
| {
"content_hash": "8f4a184e5ede4e3c84901c9446f842fd",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 64,
"avg_line_length": 17.375,
"alnum_prop": 0.7410071942446043,
"repo_name": "charques/renthell",
"id": "cc45efe7cd3c60db1356c3cb42698a80d63a69b1",
"size": "417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "event-store-srv/src/main/java/io/renthell/eventstoresrv/web/events/PropertyTransactionConfirmEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "24970"
},
{
"name": "HTML",
"bytes": "20348"
},
{
"name": "Java",
"bytes": "248598"
},
{
"name": "JavaScript",
"bytes": "1406"
},
{
"name": "Shell",
"bytes": "40540"
}
],
"symlink_target": ""
} |
testA = "UDDDUDUU" #1
testB = "DDUUDDUDUUUD" #2
def countValleys(steps)
steps = steps.split("")
elevation = 0
lastStep = 0
valleys = 0
steps.each_with_index do |x, i|
## Track the current elevation from sea level (0)
if x == "U"
elevation += 1
elsif x == "D"
elevation -= 1
end
## ignore the first step where it will be zero, ensure last step was a valley, and that
## the slope of the valley reaches sea level
if i != 0 && lastStep < 0 && elevation === 0
valleys += 1
end
## track the previous step's elevation
lastStep = elevation
end
return valleys
end
puts countValleys(testA)
| {
"content_hash": "29a2adae50cbea8100defb32677ab1e5",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 91,
"avg_line_length": 21.258064516129032,
"alnum_prop": 0.6191198786039454,
"repo_name": "masharp/algorithm-challenges-n-stuff",
"id": "142ec96ca7ee2827b200d6a466d27e3d4c3e82b1",
"size": "659",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "coding-challenges/hacker-rank/algorithms/CountingValleys.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "24941"
},
{
"name": "JavaScript",
"bytes": "54737"
},
{
"name": "Python",
"bytes": "36150"
},
{
"name": "Ruby",
"bytes": "1744"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>checker: Error with dependencies</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 / extra-dev</a></li>
<li class="active"><a href="">dev / checker - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
checker
<small>
8.9.0
<span class="label label-warning">Error with dependencies</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-11-06 06:49:18 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-06 06:49:18 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 3 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/checker"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Checker"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: checker"
"keyword: dominos"
"keyword: puzzles"
"category: Miscellaneous/Logical Puzzles and Entertainment"
]
authors: [
"Gérard Huet"
]
bug-reports: "https://github.com/coq-contribs/checker/issues"
dev-repo: "git+https://github.com/coq-contribs/checker.git"
synopsis: "The Mutilated Checkerboard"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/checker/archive/v8.9.0.tar.gz"
checksum: "md5=dd97034f8e98abcb15c07471906588c5"
}
</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-checker.8.9.0 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
[ERROR] Package conflict!
Sorry, no solution found: there seems to be a problem with your request.
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-checker.8.9.0</code></dd>
<dt>Return code</dt>
<dd>512</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq dev
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
While removing coq.dev: these files have been modified since installation:
- share/texmf/tex/latex/misc/coqdoc.sty
- man/man1/coqwc.1
- man/man1/coqtop.opt.1
- man/man1/coqtop.byte.1
- man/man1/coqtop.1
- man/man1/coqnative.1
- man/man1/coqdoc.1
- man/man1/coqdep.1
- man/man1/coqchk.1
- man/man1/coqc.1
- man/man1/coq_makefile.1
- man/man1/coq-tex.1
- lib/stublibs/dllcoqrun_stubs.so
- lib/coqide-server/protocol/xmlprotocol.mli
- lib/coqide-server/protocol/xmlprotocol.ml
- lib/coqide-server/protocol/xmlprotocol.cmx
- lib/coqide-server/protocol/xmlprotocol.cmti
- lib/coqide-server/protocol/xmlprotocol.cmt
- lib/coqide-server/protocol/xmlprotocol.cmi
- lib/coqide-server/protocol/xml_printer.mli
- lib/coqide-server/protocol/xml_printer.ml
- lib/coqide-server/protocol/xml_printer.cmx
- lib/coqide-server/protocol/xml_printer.cmti
- lib/coqide-server/protocol/xml_printer.cmt
- lib/coqide-server/protocol/xml_printer.cmi
- lib/coqide-server/protocol/xml_parser.mli
- lib/coqide-server/protocol/xml_parser.ml
- lib/coqide-server/protocol/xml_parser.cmx
- lib/coqide-server/protocol/xml_parser.cmti
- lib/coqide-server/protocol/xml_parser.cmt
- lib/coqide-server/protocol/xml_parser.cmi
- lib/coqide-server/protocol/xml_lexer.mli
- lib/coqide-server/protocol/xml_lexer.ml
- lib/coqide-server/protocol/xml_lexer.cmx
- lib/coqide-server/protocol/xml_lexer.cmti
- lib/coqide-server/protocol/xml_lexer.cmt
- lib/coqide-server/protocol/xml_lexer.cmi
- lib/coqide-server/protocol/serialize.mli
- lib/coqide-server/protocol/serialize.ml
- lib/coqide-server/protocol/serialize.cmx
- lib/coqide-server/protocol/serialize.cmti
- lib/coqide-server/protocol/serialize.cmt
- lib/coqide-server/protocol/serialize.cmi
- lib/coqide-server/protocol/richpp.mli
- lib/coqide-server/protocol/richpp.ml
- lib/coqide-server/protocol/richpp.cmx
- lib/coqide-server/protocol/richpp.cmti
- lib/coqide-server/protocol/richpp.cmt
- lib/coqide-server/protocol/richpp.cmi
- lib/coqide-server/protocol/protocol.cmxs
- lib/coqide-server/protocol/protocol.cmxa
- lib/coqide-server/protocol/protocol.cma
- lib/coqide-server/protocol/protocol.a
- lib/coqide-server/protocol/interface.ml
- lib/coqide-server/protocol/interface.cmx
- lib/coqide-server/protocol/interface.cmt
- lib/coqide-server/protocol/interface.cmi
- lib/coqide-server/opam
- lib/coqide-server/dune-package
- lib/coqide-server/core/document.mli
- lib/coqide-server/core/document.ml
- lib/coqide-server/core/document.cmx
- lib/coqide-server/core/document.cmti
- lib/coqide-server/core/document.cmt
- lib/coqide-server/core/document.cmi
- lib/coqide-server/core/core.cmxs
- lib/coqide-server/core/core.cmxa
- lib/coqide-server/core/core.cma
- lib/coqide-server/core/core.a
- lib/coqide-server/META
- lib/coq/user-contrib/Ltac2/String.vos
- lib/coq/user-contrib/Ltac2/String.vo
- lib/coq/user-contrib/Ltac2/String.v
- lib/coq/user-contrib/Ltac2/String.glob
- lib/coq/user-contrib/Ltac2/Std.vos
- lib/coq/user-contrib/Ltac2/Std.vo
- lib/coq/user-contrib/Ltac2/Std.v
- lib/coq/user-contrib/Ltac2/Std.glob
- lib/coq/user-contrib/Ltac2/Printf.vos
- lib/coq/user-contrib/Ltac2/Printf.vo
- lib/coq/user-contrib/Ltac2/Printf.v
- lib/coq/user-contrib/Ltac2/Printf.glob
- lib/coq/user-contrib/Ltac2/Pattern.vos
- lib/coq/user-contrib/Ltac2/Pattern.vo
- lib/coq/user-contrib/Ltac2/Pattern.v
- lib/coq/user-contrib/Ltac2/Pattern.glob
- lib/coq/user-contrib/Ltac2/Option.vos
- lib/coq/user-contrib/Ltac2/Option.vo
- lib/coq/user-contrib/Ltac2/Option.v
- lib/coq/user-contrib/Ltac2/Option.glob
- lib/coq/user-contrib/Ltac2/Notations.vos
- lib/coq/user-contrib/Ltac2/Notations.vo
- lib/coq/user-contrib/Ltac2/Notations.v
- lib/coq/user-contrib/Ltac2/Notations.glob
- lib/coq/user-contrib/Ltac2/Message.vos
- lib/coq/user-contrib/Ltac2/Message.vo
- lib/coq/user-contrib/Ltac2/Message.v
- lib/coq/user-contrib/Ltac2/Message.glob
- lib/coq/user-contrib/Ltac2/Ltac2.vos
- lib/coq/user-contrib/Ltac2/Ltac2.vo
- lib/coq/user-contrib/Ltac2/Ltac2.v
- lib/coq/user-contrib/Ltac2/Ltac2.glob
- lib/coq/user-contrib/Ltac2/Ltac1.vos
- lib/coq/user-contrib/Ltac2/Ltac1.vo
- lib/coq/user-contrib/Ltac2/Ltac1.v
- lib/coq/user-contrib/Ltac2/Ltac1.glob
- lib/coq/user-contrib/Ltac2/List.vos
- lib/coq/user-contrib/Ltac2/List.vo
- lib/coq/user-contrib/Ltac2/List.v
- lib/coq/user-contrib/Ltac2/List.glob
- lib/coq/user-contrib/Ltac2/Int.vos
- lib/coq/user-contrib/Ltac2/Int.vo
- lib/coq/user-contrib/Ltac2/Int.v
- lib/coq/user-contrib/Ltac2/Int.glob
- lib/coq/user-contrib/Ltac2/Init.vos
- lib/coq/user-contrib/Ltac2/Init.vo
- lib/coq/user-contrib/Ltac2/Init.v
- lib/coq/user-contrib/Ltac2/Init.glob
- lib/coq/user-contrib/Ltac2/Ind.vos
- lib/coq/user-contrib/Ltac2/Ind.vo
- lib/coq/user-contrib/Ltac2/Ind.v
- lib/coq/user-contrib/Ltac2/Ind.glob
- lib/coq/user-contrib/Ltac2/Ident.vos
- lib/coq/user-contrib/Ltac2/Ident.vo
- lib/coq/user-contrib/Ltac2/Ident.v
- lib/coq/user-contrib/Ltac2/Ident.glob
- lib/coq/user-contrib/Ltac2/Fresh.vos
- lib/coq/user-contrib/Ltac2/Fresh.vo
- lib/coq/user-contrib/Ltac2/Fresh.v
- lib/coq/user-contrib/Ltac2/Fresh.glob
- lib/coq/user-contrib/Ltac2/Env.vos
- lib/coq/user-contrib/Ltac2/Env.vo
- lib/coq/user-contrib/Ltac2/Env.v
- lib/coq/user-contrib/Ltac2/Env.glob
- lib/coq/user-contrib/Ltac2/Control.vos
- lib/coq/user-contrib/Ltac2/Control.vo
- lib/coq/user-contrib/Ltac2/Control.v
- lib/coq/user-contrib/Ltac2/Control.glob
- lib/coq/user-contrib/Ltac2/Constr.vos
- lib/coq/user-contrib/Ltac2/Constr.vo
- lib/coq/user-contrib/Ltac2/Constr.v
- lib/coq/user-contrib/Ltac2/Constr.glob
- lib/coq/user-contrib/Ltac2/Char.vos
- lib/coq/user-contrib/Ltac2/Char.vo
- lib/coq/user-contrib/Ltac2/Char.v
- lib/coq/user-contrib/Ltac2/Char.glob
- lib/coq/user-contrib/Ltac2/Bool.vos
- lib/coq/user-contrib/Ltac2/Bool.vo
- lib/coq/user-contrib/Ltac2/Bool.v
- lib/coq/user-contrib/Ltac2/Bool.glob
- lib/coq/user-contrib/Ltac2/Array.vos
- lib/coq/user-contrib/Ltac2/Array.vo
- lib/coq/user-contrib/Ltac2/Array.v
- lib/coq/user-contrib/Ltac2/Array.glob
- lib/coq/theories/ssrsearch/ssrsearch.vos
- lib/coq/theories/ssrsearch/ssrsearch.vo
- lib/coq/theories/ssrsearch/ssrsearch.v
- lib/coq/theories/ssrsearch/ssrsearch.glob
- lib/coq/theories/ssrmatching/ssrmatching.vos
- lib/coq/theories/ssrmatching/ssrmatching.vo
- lib/coq/theories/ssrmatching/ssrmatching.v
- lib/coq/theories/ssrmatching/ssrmatching.glob
- lib/coq/theories/ssr/ssrunder.vos
- lib/coq/theories/ssr/ssrunder.vo
- lib/coq/theories/ssr/ssrunder.v
- lib/coq/theories/ssr/ssrunder.glob
- lib/coq/theories/ssr/ssrsetoid.vos
- lib/coq/theories/ssr/ssrsetoid.vo
- lib/coq/theories/ssr/ssrsetoid.v
- lib/coq/theories/ssr/ssrsetoid.glob
- lib/coq/theories/ssr/ssrfun.vos
- lib/coq/theories/ssr/ssrfun.vo
- lib/coq/theories/ssr/ssrfun.v
- lib/coq/theories/ssr/ssrfun.glob
- lib/coq/theories/ssr/ssreflect.vos
- lib/coq/theories/ssr/ssreflect.vo
- lib/coq/theories/ssr/ssreflect.v
- lib/coq/theories/ssr/ssreflect.glob
- lib/coq/theories/ssr/ssrclasses.vos
- lib/coq/theories/ssr/ssrclasses.vo
- lib/coq/theories/ssr/ssrclasses.v
- lib/coq/theories/ssr/ssrclasses.glob
- lib/coq/theories/ssr/ssrbool.vos
- lib/coq/theories/ssr/ssrbool.vo
- lib/coq/theories/ssr/ssrbool.v
- lib/coq/theories/ssr/ssrbool.glob
- lib/coq/theories/setoid_ring/ZArithRing.vos
- lib/coq/theories/setoid_ring/ZArithRing.vo
- lib/coq/theories/setoid_ring/ZArithRing.v
- lib/coq/theories/setoid_ring/ZArithRing.glob
- lib/coq/theories/setoid_ring/Rings_Z.vos
- lib/coq/theories/setoid_ring/Rings_Z.vo
- lib/coq/theories/setoid_ring/Rings_Z.v
- lib/coq/theories/setoid_ring/Rings_Z.glob
- lib/coq/theories/setoid_ring/Rings_R.vos
- lib/coq/theories/setoid_ring/Rings_R.vo
- lib/coq/theories/setoid_ring/Rings_R.v
- lib/coq/theories/setoid_ring/Rings_R.glob
- lib/coq/theories/setoid_ring/Rings_Q.vos
- lib/coq/theories/setoid_ring/Rings_Q.vo
- lib/coq/theories/setoid_ring/Rings_Q.v
- lib/coq/theories/setoid_ring/Rings_Q.glob
- lib/coq/theories/setoid_ring/Ring_theory.vos
- lib/coq/theories/setoid_ring/Ring_theory.vo
- lib/coq/theories/setoid_ring/Ring_theory.v
- lib/coq/theories/setoid_ring/Ring_theory.glob
- lib/coq/theories/setoid_ring/Ring_tac.vos
- lib/coq/theories/setoid_ring/Ring_tac.vo
- lib/coq/theories/setoid_ring/Ring_tac.v
- lib/coq/theories/setoid_ring/Ring_tac.glob
- lib/coq/theories/setoid_ring/Ring_polynom.vos
- lib/coq/theories/setoid_ring/Ring_polynom.vo
- lib/coq/theories/setoid_ring/Ring_polynom.v
- lib/coq/theories/setoid_ring/Ring_polynom.glob
- lib/coq/theories/setoid_ring/Ring_base.vos
- lib/coq/theories/setoid_ring/Ring_base.vo
- lib/coq/theories/setoid_ring/Ring_base.v
- lib/coq/theories/setoid_ring/Ring_base.glob
- lib/coq/theories/setoid_ring/Ring.vos
- lib/coq/theories/setoid_ring/Ring.vo
- lib/coq/theories/setoid_ring/Ring.v
- lib/coq/theories/setoid_ring/Ring.glob
- lib/coq/theories/setoid_ring/RealField.vos
- lib/coq/theories/setoid_ring/RealField.vo
- lib/coq/theories/setoid_ring/RealField.v
- lib/coq/theories/setoid_ring/RealField.glob
- lib/coq/theories/setoid_ring/Ncring_tac.vos
- lib/coq/theories/setoid_ring/Ncring_tac.vo
- lib/coq/theories/setoid_ring/Ncring_tac.v
- lib/coq/theories/setoid_ring/Ncring_tac.glob
- lib/coq/theories/setoid_ring/Ncring_polynom.vos
- lib/coq/theories/setoid_ring/Ncring_polynom.vo
- lib/coq/theories/setoid_ring/Ncring_polynom.v
- lib/coq/theories/setoid_ring/Ncring_polynom.glob
- lib/coq/theories/setoid_ring/Ncring_initial.vos
- lib/coq/theor
[...] truncated
predicate.cmt
- lib/coq-core/clib/predicate.cmi
- lib/coq-core/clib/orderedType.mli
- lib/coq-core/clib/orderedType.ml
- lib/coq-core/clib/orderedType.cmx
- lib/coq-core/clib/orderedType.cmti
- lib/coq-core/clib/orderedType.cmt
- lib/coq-core/clib/orderedType.cmi
- lib/coq-core/clib/option.mli
- lib/coq-core/clib/option.ml
- lib/coq-core/clib/option.cmx
- lib/coq-core/clib/option.cmti
- lib/coq-core/clib/option.cmt
- lib/coq-core/clib/option.cmi
- lib/coq-core/clib/neList.mli
- lib/coq-core/clib/neList.ml
- lib/coq-core/clib/neList.cmx
- lib/coq-core/clib/neList.cmti
- lib/coq-core/clib/neList.cmt
- lib/coq-core/clib/neList.cmi
- lib/coq-core/clib/monad.mli
- lib/coq-core/clib/monad.ml
- lib/coq-core/clib/monad.cmx
- lib/coq-core/clib/monad.cmti
- lib/coq-core/clib/monad.cmt
- lib/coq-core/clib/monad.cmi
- lib/coq-core/clib/minisys.ml
- lib/coq-core/clib/minisys.cmx
- lib/coq-core/clib/minisys.cmt
- lib/coq-core/clib/minisys.cmi
- lib/coq-core/clib/int.mli
- lib/coq-core/clib/int.ml
- lib/coq-core/clib/int.cmx
- lib/coq-core/clib/int.cmti
- lib/coq-core/clib/int.cmt
- lib/coq-core/clib/int.cmi
- lib/coq-core/clib/iStream.mli
- lib/coq-core/clib/iStream.ml
- lib/coq-core/clib/iStream.cmx
- lib/coq-core/clib/iStream.cmti
- lib/coq-core/clib/iStream.cmt
- lib/coq-core/clib/iStream.cmi
- lib/coq-core/clib/heap.mli
- lib/coq-core/clib/heap.ml
- lib/coq-core/clib/heap.cmx
- lib/coq-core/clib/heap.cmti
- lib/coq-core/clib/heap.cmt
- lib/coq-core/clib/heap.cmi
- lib/coq-core/clib/hashset.mli
- lib/coq-core/clib/hashset.ml
- lib/coq-core/clib/hashset.cmx
- lib/coq-core/clib/hashset.cmti
- lib/coq-core/clib/hashset.cmt
- lib/coq-core/clib/hashset.cmi
- lib/coq-core/clib/hashcons.mli
- lib/coq-core/clib/hashcons.ml
- lib/coq-core/clib/hashcons.cmx
- lib/coq-core/clib/hashcons.cmti
- lib/coq-core/clib/hashcons.cmt
- lib/coq-core/clib/hashcons.cmi
- lib/coq-core/clib/hMap.mli
- lib/coq-core/clib/hMap.ml
- lib/coq-core/clib/hMap.cmx
- lib/coq-core/clib/hMap.cmti
- lib/coq-core/clib/hMap.cmt
- lib/coq-core/clib/hMap.cmi
- lib/coq-core/clib/exninfo.mli
- lib/coq-core/clib/exninfo.ml
- lib/coq-core/clib/exninfo.cmx
- lib/coq-core/clib/exninfo.cmti
- lib/coq-core/clib/exninfo.cmt
- lib/coq-core/clib/exninfo.cmi
- lib/coq-core/clib/dyn.mli
- lib/coq-core/clib/dyn.ml
- lib/coq-core/clib/dyn.cmx
- lib/coq-core/clib/dyn.cmti
- lib/coq-core/clib/dyn.cmt
- lib/coq-core/clib/dyn.cmi
- lib/coq-core/clib/diff2.mli
- lib/coq-core/clib/diff2.ml
- lib/coq-core/clib/diff2.cmx
- lib/coq-core/clib/diff2.cmti
- lib/coq-core/clib/diff2.cmt
- lib/coq-core/clib/diff2.cmi
- lib/coq-core/clib/clib.cmxs
- lib/coq-core/clib/clib.cmxa
- lib/coq-core/clib/clib.cma
- lib/coq-core/clib/clib.a
- lib/coq-core/clib/cUnix.mli
- lib/coq-core/clib/cUnix.ml
- lib/coq-core/clib/cUnix.cmx
- lib/coq-core/clib/cUnix.cmti
- lib/coq-core/clib/cUnix.cmt
- lib/coq-core/clib/cUnix.cmi
- lib/coq-core/clib/cThread.mli
- lib/coq-core/clib/cThread.ml
- lib/coq-core/clib/cThread.cmx
- lib/coq-core/clib/cThread.cmti
- lib/coq-core/clib/cThread.cmt
- lib/coq-core/clib/cThread.cmi
- lib/coq-core/clib/cString.mli
- lib/coq-core/clib/cString.ml
- lib/coq-core/clib/cString.cmx
- lib/coq-core/clib/cString.cmti
- lib/coq-core/clib/cString.cmt
- lib/coq-core/clib/cString.cmi
- lib/coq-core/clib/cSig.mli
- lib/coq-core/clib/cSig.cmti
- lib/coq-core/clib/cSig.cmi
- lib/coq-core/clib/cSet.mli
- lib/coq-core/clib/cSet.ml
- lib/coq-core/clib/cSet.cmx
- lib/coq-core/clib/cSet.cmti
- lib/coq-core/clib/cSet.cmt
- lib/coq-core/clib/cSet.cmi
- lib/coq-core/clib/cObj.mli
- lib/coq-core/clib/cObj.ml
- lib/coq-core/clib/cObj.cmx
- lib/coq-core/clib/cObj.cmti
- lib/coq-core/clib/cObj.cmt
- lib/coq-core/clib/cObj.cmi
- lib/coq-core/clib/cMap.mli
- lib/coq-core/clib/cMap.ml
- lib/coq-core/clib/cMap.cmx
- lib/coq-core/clib/cMap.cmti
- lib/coq-core/clib/cMap.cmt
- lib/coq-core/clib/cMap.cmi
- lib/coq-core/clib/cList.mli
- lib/coq-core/clib/cList.ml
- lib/coq-core/clib/cList.cmx
- lib/coq-core/clib/cList.cmti
- lib/coq-core/clib/cList.cmt
- lib/coq-core/clib/cList.cmi
- lib/coq-core/clib/cEphemeron.mli
- lib/coq-core/clib/cEphemeron.ml
- lib/coq-core/clib/cEphemeron.cmx
- lib/coq-core/clib/cEphemeron.cmti
- lib/coq-core/clib/cEphemeron.cmt
- lib/coq-core/clib/cEphemeron.cmi
- lib/coq-core/clib/cArray.mli
- lib/coq-core/clib/cArray.ml
- lib/coq-core/clib/cArray.cmx
- lib/coq-core/clib/cArray.cmti
- lib/coq-core/clib/cArray.cmt
- lib/coq-core/clib/cArray.cmi
- lib/coq-core/boot/util.ml
- lib/coq-core/boot/path.ml
- lib/coq-core/boot/env.mli
- lib/coq-core/boot/env.ml
- lib/coq-core/boot/boot__Util.cmx
- lib/coq-core/boot/boot__Util.cmt
- lib/coq-core/boot/boot__Util.cmi
- lib/coq-core/boot/boot__Path.cmx
- lib/coq-core/boot/boot__Path.cmt
- lib/coq-core/boot/boot__Path.cmi
- lib/coq-core/boot/boot__Env.cmx
- lib/coq-core/boot/boot__Env.cmti
- lib/coq-core/boot/boot__Env.cmt
- lib/coq-core/boot/boot__Env.cmi
- lib/coq-core/boot/boot.ml
- lib/coq-core/boot/boot.cmxs
- lib/coq-core/boot/boot.cmxa
- lib/coq-core/boot/boot.cmx
- lib/coq-core/boot/boot.cmt
- lib/coq-core/boot/boot.cmi
- lib/coq-core/boot/boot.cma
- lib/coq-core/boot/boot.a
- lib/coq-core/META
- doc/coqide-server/README.md
- doc/coqide-server/LICENSE
- doc/coq-core/README.md
- doc/coq-core/LICENSE
- bin/votour
- bin/ocamllibdep
- bin/csdpcert
- bin/coqworkmgr
- bin/coqwc
- bin/coqtop.opt
- bin/coqtop.byte
- bin/coqtop
- bin/coqtacticworker.opt
- bin/coqqueryworker.opt
- bin/coqproofworker.opt
- bin/coqpp
- bin/coqnative
- bin/coqidetop.opt
- bin/coqidetop.byte
- bin/coqdoc
- bin/coqdep
- bin/coqchk
- bin/coqc.byte
- bin/coqc
- bin/coq_makefile
- bin/coq-tex
Remove them anyway? [y/N] y
[NOTE] While removing coq.dev: not removing non-empty directories:
- share/texmf/tex/latex/misc
- lib/coqide-server/protocol
- lib/coqide-server/core
- lib/coq/user-contrib/Ltac2
- lib/coq/theories/ssrsearch
- lib/coq/theories/ssrmatching
- lib/coq/theories/setoid_ring
- lib/coq/theories/rtauto
- lib/coq/theories/omega
- lib/coq/theories/nsatz
- lib/coq/theories/micromega
- lib/coq/theories/funind
- lib/coq/theories/extraction
- lib/coq/theories/derive
- lib/coq/theories/btauto
- lib/coq/theories/ZArith
- lib/coq/theories/Wellfounded
- lib/coq/theories/Vectors
- lib/coq/theories/Unicode
- lib/coq/theories/Structures
- lib/coq/theories/Strings
- lib/coq/theories/Sorting
- lib/coq/theories/Sets
- lib/coq/theories/Setoids
- lib/coq/theories/Relations
- lib/coq/theories/Reals/Cauchy
- lib/coq/theories/Reals/Abstract
- lib/coq/theories/QArith
- lib/coq/theories/Program
- lib/coq/theories/PArith
- lib/coq/theories/Numbers/Natural/Peano
- lib/coq/theories/Numbers/Natural/Binary
- lib/coq/theories/Numbers/Natural/Abstract
- lib/coq/theories/Numbers/NatInt
- lib/coq/theories/Numbers/Integer/NatPairs
- lib/coq/theories/Numbers/Integer/Binary
- lib/coq/theories/Numbers/Integer/Abstract
- lib/coq/theories/Numbers/Cyclic/ZModulo
- lib/coq/theories/Numbers/Cyclic/Int63
- lib/coq/theories/Numbers/Cyclic/Int31
- lib/coq/theories/Numbers/Cyclic/Abstract
- lib/coq/theories/NArith
- lib/coq/theories/MSets
- lib/coq/theories/Logic
- lib/coq/theories/Lists
- lib/coq/theories/Init
- lib/coq/theories/Floats
- lib/coq/theories/FSets
- lib/coq/theories/Compat
- lib/coq/theories/Classes
- lib/coq/theories/Bool
- lib/coq/theories/Array
- lib/coq/theories/Arith
- lib/coq-core/vm
- lib/coq-core/vernac
- lib/coq-core/toplevel
- lib/coq-core/top_printers
- lib/coq-core/tools/coqdoc
- lib/coq-core/tactics
- lib/coq-core/sysinit
- lib/coq-core/stm
- lib/coq-core/proofs
- lib/coq-core/printing
- lib/coq-core/pretyping
- lib/coq-core/plugins/zify
- lib/coq-core/plugins/tutorial/p3
- lib/coq-core/plugins/tutorial/p2
- lib/coq-core/plugins/tutorial/p1
- lib/coq-core/plugins/tutorial/p0
- lib/coq-core/plugins/tauto
- lib/coq-core/plugins/ssrsearch
- lib/coq-core/plugins/ssrmatching
- lib/coq-core/plugins/ssreflect
- lib/coq-core/plugins/rtauto
- lib/coq-core/plugins/ring
- lib/coq-core/plugins/number_string_notation
- lib/coq-core/plugins/nsatz
- lib/coq-core/plugins/micromega
- lib/coq-core/plugins/ltac2
- lib/coq-core/plugins/funind
- lib/coq-core/plugins/firstorder
- lib/coq-core/plugins/extraction
- lib/coq-core/plugins/derive
- lib/coq-core/plugins/cc
- lib/coq-core/plugins/btauto
- lib/coq-core/parsing
- lib/coq-core/library
- lib/coq-core/kernel
- lib/coq-core/interp
- lib/coq-core/gramlib
- lib/coq-core/engine
- lib/coq-core/config
- lib/coq-core/clib
- lib/coq-core/boot
- doc/coqide-server
- doc/coq-core
-> removed coq.dev
Done.
# Run eval $(opam env) to update the current shell environment
opam: --unlock-base was removed in version 2.1 of the opam CLI, but version 2.1 has been requested. Use --update-invariant instead or set OPAMCLI environment variable to 2.0.
The middle of the output is truncated (maximum 20000 characters)
</pre></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">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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": "2e9d277848d2fe046d5b0e6b3cd80552",
"timestamp": "",
"source": "github",
"line_count": 708,
"max_line_length": 260,
"avg_line_length": 38.271186440677965,
"alnum_prop": 0.6562592264540892,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "b4655b0b51c936e06b3a0350c94087343e7579bc",
"size": "27099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.13.1-2.1.0/extra-dev/dev/checker/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.jgrades.security.service;
import org.jgrades.admin.api.accounts.UserMgntService;
import org.jgrades.data.api.entities.User;
import org.jgrades.security.api.dao.PasswordDataRepository;
import org.jgrades.security.api.entities.PasswordData;
import org.jgrades.security.api.service.PasswordMgntService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
@Service
public class PasswordMgntServiceImpl implements PasswordMgntService {
@Autowired
private PasswordDataRepository passwordDataRepository;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserMgntService userMgntService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
@Transactional("mainTransactionManager")
public void setPassword(String password, User user) {
User refreshedUser = userMgntService.getWithLogin(user.getLogin());
PasswordData pswdData = passwordDataRepository.findOne(refreshedUser.getId());
String encodedPassword = passwordEncoder.encode(password);
if (pswdData == null) {
pswdData = new PasswordData();
pswdData.setId(refreshedUser.getId());
pswdData.setUser(refreshedUser);
pswdData.setPassword(encodedPassword);
pswdData.setLastChange(LocalDateTime.now());
passwordDataRepository.save(pswdData);
} else {
pswdData.setPassword(encodedPassword);
pswdData.setLastChange(LocalDateTime.now());
}
}
@Override
public String getPassword(User user) {
return passwordDataRepository.getPasswordDataWithUser(user.getLogin()).getPassword();
}
@Override
public boolean isPasswordExpired(User user) {
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getLogin());
return !userDetails.isCredentialsNonExpired();
}
}
| {
"content_hash": "53870646224d556eba12dba4d4506306",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 93,
"avg_line_length": 36.596774193548384,
"alnum_prop": 0.753195240193918,
"repo_name": "jgrades/jgrades",
"id": "d8cec26bc724fadf1fdbb5e6bcf7a402cf6cc8fd",
"size": "2553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jg-backend/implementation/base/jg-security/implementation/src/main/java/org/jgrades/security/service/PasswordMgntServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "499"
},
{
"name": "Java",
"bytes": "731522"
},
{
"name": "Shell",
"bytes": "2288"
}
],
"symlink_target": ""
} |
<com.tle.beans.mime.MimeEntry>
<id>47953</id>
<institution>
<id>47824</id>
<uniqueId>0</uniqueId>
<enabled>true</enabled>
</institution>
<extensions class="list">
<string>aifc</string>
<string>aiff</string>
<string>aif</string>
</extensions>
<type>audio/x-aiff</type>
<description>Audio</description>
<attributes>
<entry>
<string>PluginIconPath</string>
<string>icons/sound.png</string>
</entry>
</attributes>
</com.tle.beans.mime.MimeEntry> | {
"content_hash": "ff7971e4413397ffd5300160ae294cf1",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 38,
"avg_line_length": 23.952380952380953,
"alnum_prop": 0.6461232604373758,
"repo_name": "equella/Equella",
"id": "3a07e18d6073f4b2468bc8b8cbe1c9d83ffe57c9",
"size": "503",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "autotest/Tests/tests/blackboard/institution/mimetypes/audio_x-aiff.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "402"
},
{
"name": "Batchfile",
"bytes": "38432"
},
{
"name": "CSS",
"bytes": "648823"
},
{
"name": "Dockerfile",
"bytes": "2055"
},
{
"name": "FreeMarker",
"bytes": "370046"
},
{
"name": "HTML",
"bytes": "865667"
},
{
"name": "Java",
"bytes": "27081020"
},
{
"name": "JavaScript",
"bytes": "1673995"
},
{
"name": "PHP",
"bytes": "821"
},
{
"name": "PLpgSQL",
"bytes": "1363"
},
{
"name": "PureScript",
"bytes": "307610"
},
{
"name": "Python",
"bytes": "79871"
},
{
"name": "Scala",
"bytes": "765981"
},
{
"name": "Shell",
"bytes": "64170"
},
{
"name": "TypeScript",
"bytes": "146564"
},
{
"name": "XSLT",
"bytes": "510113"
}
],
"symlink_target": ""
} |
python -m unittest discover -p "*_test.py" | {
"content_hash": "fb609cfd567bd021e5f93a21c1dfc12f",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 42,
"avg_line_length": 42,
"alnum_prop": 0.7142857142857143,
"repo_name": "y-usuzumi/survive-the-course",
"id": "2d8ff1ab2b8f52c4149478b6451ebfc0d958336d",
"size": "52",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "leetcode-cn/leetcode-py/runtests.sh",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "10933"
},
{
"name": "C#",
"bytes": "12308"
},
{
"name": "Haskell",
"bytes": "39589"
},
{
"name": "Java",
"bytes": "55330"
},
{
"name": "JavaScript",
"bytes": "123"
},
{
"name": "Kotlin",
"bytes": "1371"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "348020"
},
{
"name": "Racket",
"bytes": "21082"
},
{
"name": "Rust",
"bytes": "220778"
},
{
"name": "Scala",
"bytes": "5023"
},
{
"name": "Shell",
"bytes": "695"
},
{
"name": "Standard ML",
"bytes": "42393"
},
{
"name": "TypeScript",
"bytes": "83468"
}
],
"symlink_target": ""
} |
/* ---------------------------------------------------------------------------- */
/* Atmel Microcontroller Software Support */
/* SAM Software Package License */
/* ---------------------------------------------------------------------------- */
/* Copyright (c) 2014, Atmel Corporation */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following condition is met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, */
/* this list of conditions and the disclaimer below. */
/* */
/* Atmel's name may not be used to endorse or promote products derived from */
/* this software without specific prior written permission. */
/* */
/* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */
/* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */
/* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */
/* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, */
/* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* ---------------------------------------------------------------------------- */
#ifndef _SAM4C_RSTC_COMPONENT_
#define _SAM4C_RSTC_COMPONENT_
/* ============================================================================= */
/** SOFTWARE API DEFINITION FOR Reset Controller */
/* ============================================================================= */
/** \addtogroup SAM4C_RSTC Reset Controller */
/*@{*/
#if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
/** \brief Rstc hardware registers */
typedef struct {
__O uint32_t RSTC_CR; /**< \brief (Rstc Offset: 0x00) Control Register */
__I uint32_t RSTC_SR; /**< \brief (Rstc Offset: 0x04) Status Register */
__IO uint32_t RSTC_MR; /**< \brief (Rstc Offset: 0x08) Mode Register */
__IO uint32_t RSTC_CPMR; /**< \brief (Rstc Offset: 0x0C) Coprocessor Mode Register */
} Rstc;
#endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
/* -------- RSTC_CR : (RSTC Offset: 0x00) Control Register -------- */
#define RSTC_CR_PROCRST (0x1u << 0) /**< \brief (RSTC_CR) Processor Reset */
#define RSTC_CR_PERRST (0x1u << 2) /**< \brief (RSTC_CR) Peripheral Reset */
#define RSTC_CR_EXTRST (0x1u << 3) /**< \brief (RSTC_CR) External Reset */
#define RSTC_CR_KEY_Pos 24
#define RSTC_CR_KEY_Msk (0xffu << RSTC_CR_KEY_Pos) /**< \brief (RSTC_CR) System Reset Key */
#define RSTC_CR_KEY_PASSWD (0xA5u << 24) /**< \brief (RSTC_CR) Writing any other value in this field aborts the write operation. */
/* -------- RSTC_SR : (RSTC Offset: 0x04) Status Register -------- */
#define RSTC_SR_URSTS (0x1u << 0) /**< \brief (RSTC_SR) User Reset Status */
#define RSTC_SR_RSTTYP_Pos 8
#define RSTC_SR_RSTTYP_Msk (0x7u << RSTC_SR_RSTTYP_Pos) /**< \brief (RSTC_SR) Reset Type */
#define RSTC_SR_RSTTYP_GeneralReset (0x0u << 8) /**< \brief (RSTC_SR) First power-up Reset */
#define RSTC_SR_RSTTYP_BackupReset (0x1u << 8) /**< \brief (RSTC_SR) Return from Backup Mode */
#define RSTC_SR_RSTTYP_WatchdogReset (0x2u << 8) /**< \brief (RSTC_SR) Watchdog fault occurred */
#define RSTC_SR_RSTTYP_SoftwareReset (0x3u << 8) /**< \brief (RSTC_SR) Processor reset required by the software */
#define RSTC_SR_RSTTYP_UserReset (0x4u << 8) /**< \brief (RSTC_SR) NRST pin detected low */
#define RSTC_SR_NRSTL (0x1u << 16) /**< \brief (RSTC_SR) NRST Pin Level */
#define RSTC_SR_SRCMP (0x1u << 17) /**< \brief (RSTC_SR) Software Reset Command in Progress */
/* -------- RSTC_MR : (RSTC Offset: 0x08) Mode Register -------- */
#define RSTC_MR_URSTEN (0x1u << 0) /**< \brief (RSTC_MR) User Reset Enable */
#define RSTC_MR_URSTIEN (0x1u << 4) /**< \brief (RSTC_MR) User Reset Interrupt Enable */
#define RSTC_MR_ERSTL_Pos 8
#define RSTC_MR_ERSTL_Msk (0xfu << RSTC_MR_ERSTL_Pos) /**< \brief (RSTC_MR) External Reset Length */
#define RSTC_MR_ERSTL(value) ((RSTC_MR_ERSTL_Msk & ((value) << RSTC_MR_ERSTL_Pos)))
#define RSTC_MR_KEY_Pos 24
#define RSTC_MR_KEY_Msk (0xffu << RSTC_MR_KEY_Pos) /**< \brief (RSTC_MR) Write Access Password */
#define RSTC_MR_KEY_PASSWD (0xA5u << 24) /**< \brief (RSTC_MR) Writing any other value in this field aborts the write operation.Always reads as 0. */
/* -------- RSTC_CPMR : (RSTC Offset: 0x0C) Coprocessor Mode Register -------- */
#define RSTC_CPMR_CPROCEN (0x1u << 0) /**< \brief (RSTC_CPMR) Coprocessor (second processor) Enable */
#define RSTC_CPMR_CPEREN (0x1u << 4) /**< \brief (RSTC_CPMR) Coprocessor Peripheral Enable */
#define RSTC_CPMR_CPKEY_Pos 24
#define RSTC_CPMR_CPKEY_Msk (0xffu << RSTC_CPMR_CPKEY_Pos) /**< \brief (RSTC_CPMR) Coprocessor System Enable Key */
#define RSTC_CPMR_CPKEY(value) ((RSTC_CPMR_CPKEY_Msk & ((value) << RSTC_CPMR_CPKEY_Pos)))
/*@}*/
#endif /* _SAM4C_RSTC_COMPONENT_ */
| {
"content_hash": "9061d364f2952e029e13dcc31fdd3bcc",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 151,
"avg_line_length": 70.15294117647059,
"alnum_prop": 0.5483816870702667,
"repo_name": "LabAixBidouille/EmbeddedTeam",
"id": "041525cb38246bef37d04b870ed526e1780c15e8",
"size": "5963",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "courses/examples/CMSIS/Device/ATMEL/sam4c/include/component/rstc.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "805802"
},
{
"name": "Batchfile",
"bytes": "6043"
},
{
"name": "C",
"bytes": "58510590"
},
{
"name": "C++",
"bytes": "880518"
},
{
"name": "HTML",
"bytes": "536"
},
{
"name": "Makefile",
"bytes": "11257"
},
{
"name": "Python",
"bytes": "1158"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Loss of Sexual Innocence, The (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0126859">Loss of Sexual Innocence, The (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Mac+VerStandig">Mac VerStandig</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>
The Loss of Sexual Innocence
1/2 Star (Out of 4)
Reviewed by Mac VerStandig
<A HREF="mailto:critic@moviereviews.org">critic@moviereviews.org</A>
<A HREF="http://www.moviereviews.org">http://www.moviereviews.org</A>
June 17, 1999</PRE>
<P>Mike Figgis' The Loss of Sexual Innocence is a movie so confusing, so
boring, and so poorly done that the Better Business Bureau should step
in and stop any poor, unsuspecting citizen from wasting their money on
this sad excuse for a film.</P>
<P>The premise of this piece of junk production that is attempting to pass
itself off as art is nearly unrealizable. Figgis (best known for his
critically acclaimed film, Leaving Las Vegas) takes several small
stories involving Nic (John Cowey at age five, George Moktar at age
twelve, Jonathan Rhys-Meyers at age 16, and Julian Sands at adult age),
the film's central character, and interweaves them with the biblical
tale of Adam (Femi Ogumbanjo) and Eve's (Hanne Klintoe) descent from the
Garden of Eden. There is no apparent rhyme nor reason to the order of
assembly of these stories, nor any true connections other than a common
loss of innocence, notably not always of a sexual nature.</P>
<P>Making the plot even more difficult to follow is the film's resemblance
to many silent picture of the early 1900's, opting for a delightful
musical score in place of dialogue. The little speech in this film is
insignificant to the plot, or so you assume because it is almost
entirely drowned out by the background music.</P>
<P>The Loss of Sexual Innocence leaves its audience asking themselves
"Huh?" Not only is the viewer totally disillusioned, but it is works
like this that are constantly making the line between art and junk ever
more blurry. Perhaps a more fitting title would have been "The Loss of
Artistic Innocence."</P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "a55498bc9dbcba43bcd35f0eca2b8c1e",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 219,
"avg_line_length": 59.25,
"alnum_prop": 0.7510548523206751,
"repo_name": "xianjunzhengbackup/code",
"id": "bd0f065f5bb4f97b4f9d7c493926df4541a6b5b0",
"size": "3081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/18948.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
import requests
from bs4 import BeautifulSoup
import os
import string #for zfill
from PIL import ImageFont, Image, ImageDraw, ImageOps
import os
import sys
from image_utils import ImageText
#takes in the image source, and local filename then downloads the image to out/localname
def download(src, localname):
image = get_page(src, 5)
if not image:
return False
f = open('out/' + localname, 'wb')
f.write(image)
f.close()
return True
def make_page(infile, outfile, text = "", text2 = ""): # takes the inputfilename, outputfilename and text to put it in at the bottom
font = 'Aller_Rg.ttf' #some random font, just fine one that is legible enough
color = (50, 50, 50) # color of the text box
page = Image.open(infile) # opening original image
width, original_height = page.size # size of original image
temp = ImageText((1000, 500), background = (255, 255, 255, 200)) # making a large temp Image text object to put the text in.
height = temp.write_text_box((0, 0), text, box_width = width, font_filename = font, font_size = 16, color = color)[1] + 20 # +20 y offset writer leaves that much space at the top
textbox = temp.image.crop((0, 0, width, height)) #crop textbox
temp = ImageText((1000, 500), background = (255, 255, 255, 200)) # making a large temp Image text object to put the text in.
height2 = temp.write_text_box((0, 0), text2, box_width = width, font_filename = font, font_size = 16, color = color)[1] + 20# +20 y offset writer leaves that much space at the top
textbox2 = temp.image.crop((0, 0, width, height)) #crop textbox
output = Image.new("RGBA", (width, original_height + height + height2), (120, 20, 20)) # make new blank image with computed dimensions
output.paste(textbox2, (0,0))
output.paste(page, (0,height2)) # paste original
output.paste(textbox, (0, original_height + height2)) # paste textbox
output.save(outfile) # save file
#function to check if the requested page returns the correct page and did not time out.
def get_page(url, max_attempts):
for i in xrange(max_attempts):
print "attempt no.", i + 1
r = requests.get(url)
if r.status_code == 200:
return r.content
print r.status_code
return False
def extract_archive(link):
html = get_page(link, 5)
if html:
soup = BeautifulSoup(html)
comic = soup.findAll('a')
for i in comic:
# get can obtain data with a var=data format
address = i.get('href')
joiner = ""
new_addr = joiner.join(('http://oglaf.com/',address[1:]))
print new_addr
html_inner = get_page(new_addr, 5)
if html_inner:
soup_inner = BeautifulSoup(html_inner)
comic = soup_inner.find(id = 'strip')
print comic
src = comic.get('src')
alt = comic.get('alt')
title = comic.get('title')
filename = address[1:][:-1] + '-' + string.zfill(1, 3) + '.' + src[-3:].lower()
print filename
download(src, filename)
#okay so it works but i still have to study it so I can put the alt at the top
try:
make_page(os.path.join('out', filename), os.path.join(outpath, os.path.basename(filename)), title, alt) # process the page
except Exception, e:
print e
sys.stdout.flush() # printing is buffered by default and this makes the display as soon as it is encountered
comic = soup_inner.find(href = address + '2/')
if comic:
count = 2
while True:
new_addr_2 = new_addr + str(count) + '/'
new_page = get_page(new_addr_2,2)
if new_page:
new_page = BeautifulSoup(new_page)
comic2 = new_page.find(id = 'strip')
src = comic2.get('src')
alt = comic2.get('alt')
title = comic2.get('title')
filename = address[1:][:-1] + '-' + string.zfill(count, 3) + '.' + src[-3:].lower()
download(src, filename)
print filename
print os.path.join(outpath, os.path.basename(filename))
print title
print alt
try:
make_page(os.path.join('out', filename), os.path.join(outpath, os.path.basename(filename)), title, alt)
except Exception, e:
print e
sys.stdout.flush()
count = count + 1
comic2 = new_page.find(href = address + str(count) + '/')
if comic2:
continue
else:
break
if __name__ == "__main__":
for directory in ['out', 'final']:
if not os.path.exists(directory):
os.makedirs(directory)
outpath = os.path.join(os.getcwd(), 'final')
url = 'http://oglaf.com/archive/'
extract_archive(url)
| {
"content_hash": "cea49abd605c5ca8702f158bcc1eb57a",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 183,
"avg_line_length": 38.4375,
"alnum_prop": 0.5232158988256549,
"repo_name": "antoniocarlosortiz/webcomic-image-parser",
"id": "e5d4fdb43359e2d9a42bc11f9245ea264335bf31",
"size": "5535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "image-parser.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "5535"
}
],
"symlink_target": ""
} |
require 'adwords_api'
require 'date'
def add_site_links(campaign_id)
# AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
# when called without parameters.
adwords = AdwordsApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# adwords.logger = Logger.new('adwords_xml.log')
customer_srv = adwords.service(:CustomerService, API_VERSION)
# Find the matching customer and its time zone. The get_customers method will
# return a single customer corresponding to the configured client_customer_id.
customer = customer_srv.get_customers().first
customer_time_zone = customer[:date_time_zone]
puts 'Found customer ID %d with time zone "%s"' %
[customer[:customer_id], customer_time_zone]
if customer_time_zone.nil?
raise StandardError, 'Customer not found for customer ID: ' + customer_id
end
campaign_extension_setting_srv =
adwords.service(:CampaignExtensionSettingService, API_VERSION)
sitelink_1 = {
:xsi_type => "SitelinkFeedItem",
:sitelink_text => "Store Hours",
:sitelink_final_urls => {
:urls => ["http://www.example.com/storehours"]
}
}
sitelink_2 = {
:xsi_type => "SitelinkFeedItem",
:sitelink_text => "Thanksgiving Specials",
:sitelink_final_urls => {
:urls => ["http://www.example.com/thanksgiving"]
},
:start_time => DateTime.new(Date.today.year, 11, 20, 0, 0, 0).
strftime("%Y%m%d %H%M%S ") + customer_time_zone,
:end_time => DateTime.new(Date.today.year, 11, 27, 23, 59, 59).
strftime("%Y%m%d %H%M%S ") + customer_time_zone,
# Target this sitelink for United States only. See
# https://developers.google.com/adwords/api/docs/appendix/geotargeting
# for valid geolocation codes.
:geo_targeting => {
:id => 2840
},
# Restrict targeting only to people physically within the United States.
# Otherwise, this could also show to people interested in the United States
# but not physically located there.
:geo_targeting_restriction => {
:geo_restriction => 'LOCATION_OF_PRESENCE'
}
}
sitelink_3 = {
:xsi_type => "SitelinkFeedItem",
:sitelink_text => "Wifi available",
:sitelink_final_urls => {
:urls => ["http://www.example.com/mobile/wifi"]
},
:device_preference => {:device_preference => 30001},
# Target this sitelink only when the ad is triggered by the keyword
# "free wifi".
:keyword_targeting => {
:text => "free wifi",
:match_type => 'BROAD'
}
}
sitelink_4 = {
:xsi_type => "SitelinkFeedItem",
:sitelink_text => "Happy hours",
:sitelink_final_urls => {
:urls => ["http://www.example.com/happyhours"]
},
:scheduling => {
:feed_item_schedules => [
{
:day_of_week => 'MONDAY',
:start_hour => 18,
:start_minute => 'ZERO',
:end_hour => 21,
:end_minute => 'ZERO'
},
{
:day_of_week => 'TUESDAY',
:start_hour => 18,
:start_minute => 'ZERO',
:end_hour => 21,
:end_minute => 'ZERO'
},
{
:day_of_week => 'WEDNESDAY',
:start_hour => 18,
:start_minute => 'ZERO',
:end_hour => 21,
:end_minute => 'ZERO'
},
{
:day_of_week => 'THURSDAY',
:start_hour => 18,
:start_minute => 'ZERO',
:end_hour => 21,
:end_minute => 'ZERO'
},
{
:day_of_week => 'FRIDAY',
:start_hour => 18,
:start_minute => 'ZERO',
:end_hour => 21,
:end_minute => 'ZERO'
}
]
}
}
campaign_extension_setting = {
:campaign_id => campaign_id,
:extension_type => 'SITELINK',
:extension_setting => {
:extensions => [sitelink_1, sitelink_2, sitelink_3, sitelink_4]
}
}
operation = {
:operand => campaign_extension_setting,
:operator => 'ADD'
}
response = campaign_extension_setting_srv.mutate([operation])
if response and response[:value]
new_extension_setting = response[:value].first
puts "Extension setting with type = %s was added to campaign ID %d" % [
new_extension_setting[:extension_type],
new_extension_setting[:campaign_id]
]
elsif
puts "No extension settings were created."
end
end
if __FILE__ == $0
API_VERSION = :v201710
begin
# Campaign ID to add site link to.
campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i
add_site_links(campaign_id)
# Authorization error.
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
"OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
"to retrieve and store OAuth2 tokens."
puts "See this wiki page for more details:\n\n " +
'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdwordsApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| {
"content_hash": "c00c9aef38ad9ef5628c9ce93e528c3e",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 80,
"avg_line_length": 30.41899441340782,
"alnum_prop": 0.5963269054178145,
"repo_name": "Invoca/google-api-ads-ruby",
"id": "bd0d23a1b898698faa21ef01a1a20e7db3b6a834",
"size": "6267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "adwords_api/examples/v201710/extensions/add_site_links.rb",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1319"
},
{
"name": "HTML",
"bytes": "7882"
},
{
"name": "JavaScript",
"bytes": "757"
},
{
"name": "Ruby",
"bytes": "8088692"
}
],
"symlink_target": ""
} |
package gitattr
type MacroProcessor struct {
macros map[string][]*Attr
}
// NewMacroProcessor returns a new MacroProcessor object for parsing macros.
func NewMacroProcessor() *MacroProcessor {
macros := make(map[string][]*Attr)
// This is built into Git.
macros["binary"] = []*Attr{
&Attr{K: "diff", V: "false"},
&Attr{K: "merge", V: "false"},
&Attr{K: "text", V: "false"},
}
return &MacroProcessor{
macros: macros,
}
}
// ProcessLines reads the specified lines, returning a new set of lines which
// all have a valid pattern. If readMacros is true, it additionally loads any
// macro lines as it reads them.
func (mp *MacroProcessor) ProcessLines(lines []*Line, readMacros bool) []*Line {
result := make([]*Line, 0, len(lines))
for _, line := range lines {
if line.Pattern != nil {
resultLine := Line{
Pattern: line.Pattern,
Attrs: make([]*Attr, 0, len(line.Attrs)),
}
for _, attr := range line.Attrs {
macros := mp.macros[attr.K]
if attr.V == "true" && macros != nil {
resultLine.Attrs = append(
resultLine.Attrs,
macros...,
)
}
// Git copies through aliases as well as
// expanding them.
resultLine.Attrs = append(
resultLine.Attrs,
attr,
)
}
result = append(result, &resultLine)
} else if readMacros {
mp.macros[line.Macro] = line.Attrs
}
}
return result
}
| {
"content_hash": "0d6166d6c59a5eaebb2d6da2573622ed",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 80,
"avg_line_length": 24.660714285714285,
"alnum_prop": 0.6350470673425054,
"repo_name": "github/git-lfs",
"id": "6413ac6b4c1b28a109fb5d6a2932b8010d7fa39c",
"size": "1381",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "git/gitattr/macro.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "92"
},
{
"name": "Go",
"bytes": "683699"
},
{
"name": "Inno Setup",
"bytes": "4763"
},
{
"name": "Makefile",
"bytes": "1069"
},
{
"name": "Ruby",
"bytes": "2868"
},
{
"name": "Shell",
"bytes": "279695"
}
],
"symlink_target": ""
} |
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using RestSharp;
using System.Text;
using Gx.Conclusion;
using Gx.Rs.Api.Util;
using Gx.Links;
using System.Net;
using System.Linq;
using Gx.Records;
using Gx.Common;
using Gedcomx.Model;
using Gedcomx.Support;
using System.Diagnostics;
namespace Gx.Rs.Api
{
/// <summary>
/// This is the base class for all state instances.
/// </summary>
public abstract class GedcomxApplicationState : HypermediaEnabledData
{
/// <summary>
/// The factory responsible for creating new state instances from REST API response data.
/// </summary>
protected internal readonly StateFactory stateFactory;
/// <summary>
/// The default link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded.
/// </summary>
protected static readonly EmbeddedLinkLoader DEFAULT_EMBEDDED_LINK_LOADER = new EmbeddedLinkLoader();
private readonly String gzipSuffix = "-gzip";
/// <summary>
/// Gets or sets the main REST API client to use with all API calls.
/// </summary>
/// <value>
/// The REST API client to use with all API calls.
/// </value>
public IFilterableRestClient Client { get; protected set; }
/// <summary>
/// Gets or sets the current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource.
/// </summary>
/// <value>
/// The current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource.
/// </value>
public String CurrentAccessToken { get; set; }
/// <summary>
/// The link factory for managing RFC 5988 compliant hypermedia links.
/// </summary>
protected Tavis.LinkFactory linkFactory;
/// <summary>
/// The parser for extracting RFC 5988 compliant hypermedia links from a web response header.
/// </summary>
protected Tavis.LinkHeaderParser linkHeaderParser;
/// <summary>
/// Gets a value indicating whether this instance is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if this instance is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated { get { return CurrentAccessToken != null; } }
/// <summary>
/// Gets or sets the REST API request.
/// </summary>
/// <value>
/// The REST API request.
/// </value>
public IRestRequest Request { get; protected set; }
/// <summary>
/// Gets or sets the REST API response.
/// </summary>
/// <value>
/// The REST API response.
/// </value>
public IRestResponse Response { get; protected set; }
/// <summary>
/// Gets or sets the last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </summary>
/// <value>
/// The last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </value>
public IRestRequest LastEmbeddedRequest { get; set; }
/// <summary>
/// Gets or sets the last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </summary>
/// <value>
/// The last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </value>
public IRestResponse LastEmbeddedResponse { get; set; }
/// <summary>
/// Gets the entity tag of the entity represented by this instance.
/// </summary>
/// <value>
/// The entity tag of the entity represented by this instance.
/// </value>
public string ETag
{
get
{
var result = this.Response != null ? this.Response.Headers.Get("ETag").Select(x => x.Value.ToString()).FirstOrDefault() : null;
if (result != null && result.IndexOf(gzipSuffix) != -1)
{
result = result.Replace(gzipSuffix, String.Empty);
}
return result;
}
}
/// <summary>
/// Gets the last modified date of the entity represented by this instance.
/// </summary>
/// <value>
/// The last modified date of the entity represented by this instance.
/// </value>
public DateTime? LastModified
{
get
{
return this.Response != null ? this.Response.Headers.Get("Last-Modified").Select(x => (DateTime?)DateTime.Parse(x.Value.ToString())).FirstOrDefault() : null;
}
}
/// <summary>
/// Gets the link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded.
/// </summary>
/// <value>
/// This always returns the default embedded link loader.
/// </value>
protected EmbeddedLinkLoader EmbeddedLinkLoader
{
get
{
return DEFAULT_EMBEDDED_LINK_LOADER;
}
}
/// <summary>
/// Gets the main data element represented by this state instance.
/// </summary>
/// <value>
/// The main data element represented by this state instance.
/// </value>
protected abstract ISupportsLinks MainDataElement
{
get;
}
/// <summary>
/// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class.
/// </summary>
protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory)
{
linkFactory = new Tavis.LinkFactory();
linkHeaderParser = new Tavis.LinkHeaderParser(linkFactory);
this.Request = request;
this.Response = response;
this.Client = client;
this.CurrentAccessToken = accessToken;
this.stateFactory = stateFactory;
}
/// <summary>
/// Executes the specified link and embeds the response in the specified Gedcomx entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="link">The link to execute.</param>
/// <param name="entity">The entity which will embed the reponse data.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <exception cref="GedcomxApplicationException">Thrown when the server responds with HTTP status code >= 500 and < 600.</exception>
protected void Embed<T>(Link link, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
if (link.Href != null)
{
LastEmbeddedRequest = CreateRequestForEmbeddedResource(link.Rel).Build(link.Href, Method.GET);
LastEmbeddedResponse = Invoke(LastEmbeddedRequest, options);
if (LastEmbeddedResponse.StatusCode == HttpStatusCode.OK)
{
entity.Embed(LastEmbeddedResponse.ToIRestResponse<T>().Data);
}
else if (LastEmbeddedResponse.HasServerError())
{
throw new GedcomxApplicationException(String.Format("Unable to load embedded resources: server says \"{0}\" at {1}.", LastEmbeddedResponse.StatusDescription, LastEmbeddedRequest.Resource), LastEmbeddedResponse);
}
else
{
//todo: log a warning? throw an error?
}
}
}
/// <summary>
/// Creates a REST API request (with appropriate authentication headers).
/// </summary>
/// <param name="rel">This parameter is currently unused.</param>
/// <returns>A REST API requeset (with appropriate authentication headers).</returns>
protected virtual IRestRequest CreateRequestForEmbeddedResource(String rel)
{
return CreateAuthenticatedGedcomxRequest();
}
/// <summary>
/// Applies the specified options before calling IFilterableRestClient.Handle() which applies any filters before executing the request.
/// </summary>
/// <param name="request">The REST API request.</param>
/// <param name="options">The options to applying before the request is handled.</param>
/// <returns>The REST API response after being handled.</returns>
protected internal IRestResponse Invoke(IRestRequest request, params IStateTransitionOption[] options)
{
IRestResponse result;
foreach (IStateTransitionOption option in options)
{
option.Apply(request);
}
result = this.Client.Handle(request);
Debug.WriteLine(string.Format("\nRequest: {0}", request.Resource));
foreach (var header in request.Parameters)
{
Debug.WriteLine(string.Format("{0} {1}", header.Name, header.Value));
}
Debug.WriteLine(string.Format("\nResponse Status: {0} {1}", result.StatusCode, result.StatusDescription));
Debug.WriteLine(string.Format("\nResponse Content: {0}", result.Content));
return result;
}
/// <summary>
/// Clones the current state instance.
/// </summary>
/// <param name="request">The REST API request used to create this state instance.</param>
/// <param name="response">The REST API response used to create this state instance.</param>
/// <param name="client">The REST API client used to create this state instance.</param>
/// <returns>A cloned instance of the current state instance.</returns>
protected abstract GedcomxApplicationState Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client);
/// <summary>
/// Creates a REST API request with authentication.
/// </summary>
/// <returns>The REST API request with authentication.</returns>
/// <remarks>This also sets the accept and content type headers.</remarks>
protected internal IRestRequest CreateAuthenticatedGedcomxRequest()
{
return CreateAuthenticatedRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).ContentType(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE);
}
/// <summary>
/// Creates a REST API request with authentication.
/// </summary>
/// <returns>The REST API request with authentication.</returns>
protected IRestRequest CreateAuthenticatedRequest()
{
IRestRequest request = CreateRequest();
if (this.CurrentAccessToken != null)
{
request = request.AddHeader("Authorization", "Bearer " + this.CurrentAccessToken);
}
return request;
}
/// <summary>
/// Creates a basic REST API request.
/// </summary>
/// <returns>A basic REST API request</returns>
protected IRestRequest CreateRequest()
{
return new RedirectableRestRequest();
}
/// <summary>
/// Extracts embedded links from the specified entity, calls each one, and embeds the response into the specified entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="entity">The entity with links and which shall have the data loaded into.</param>
/// <param name="options">The options to apply before handling the REST API requests.</param>
protected void IncludeEmbeddedResources<T>(Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
Embed<T>(EmbeddedLinkLoader.LoadEmbeddedLinks(entity), entity, options);
}
/// <summary>
/// Executes the specified links and embeds the response into the specified entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="links">The links to call.</param>
/// <param name="entity">The entity which shall have the data loaded into.</param>
/// <param name="options">The options to apply before handling the REST API requests.</param>
protected void Embed<T>(IEnumerable<Link> links, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
foreach (Link link in links)
{
Embed<T>(link, entity, options);
}
}
/// <summary>
/// Gets the URI of the REST API request associated to this state instance.
/// </summary>
/// <returns>The URI of the REST API request associated to this state instance.</returns>
public string GetUri()
{
return this.Client.BaseUrl + this.Request.Resource;
}
/// <summary>
/// Determines whether this instance has error (server [code >= 500 and < 600] or client [code >= 400 and < 500]).
/// </summary>
/// <returns>True if a server or client error exists; otherwise, false.</returns>
public bool HasError()
{
return this.Response.HasClientError() || this.Response.HasServerError();
}
/// <summary>
/// Determines whether the current REST API response has the specified status.
/// </summary>
/// <param name="status">The status to evaluate.</param>
/// <returns>True if the current REST API response has the specified status; otherwise, false.</returns>
public bool HasStatus(HttpStatusCode status)
{
return this.Response.StatusCode == status;
}
/// <summary>
/// Returns the current state instance if there are no errors in the current REST API response; otherwise, it throws an exception with the response details.
/// </summary>
/// <returns>
/// A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response or throws an exception with the response details.
/// </returns>
/// <exception cref="GedcomxApplicationException">Thrown if <see cref="HasError()" /> returns true.</exception>
public virtual GedcomxApplicationState IfSuccessful()
{
if (HasError())
{
throw new GedcomxApplicationException(String.Format("Unsuccessful {0} to {1}", this.Request.Method, GetUri()), this.Response);
}
return this;
}
/// <summary>
/// Executes a HEAD verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Head(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.HEAD);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes an OPTIONS verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Options(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.OPTIONS);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a GET verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Get(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.GET);
IRestResponse response = Invoke(request, options);
return Clone(request, response, this.Client);
}
/// <summary>
/// Executes an DELETE verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Delete(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.DELETE);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a PUT verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be PUT.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Put(object entity, params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.SetEntity(entity).Build(GetSelfUri(), Method.PUT);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a POST verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be POST.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Post(object entity, params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.SetEntity(entity).Build(GetSelfUri(), Method.POST);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Gets the warning headers from the current REST API response.
/// </summary>
/// <value>
/// The warning headers from the current REST API response.
/// </value>
public List<HttpWarning> Warnings
{
get
{
List<HttpWarning> warnings = new List<HttpWarning>();
IEnumerable<Parameter> warningValues = this.Response.Headers.Get("Warning");
if (warningValues != null)
{
foreach (Parameter warningValue in warningValues)
{
warnings.AddRange(HttpWarning.Parse(warningValue));
}
}
return warnings;
}
}
/// <summary>
/// Authenticates this session via OAuth2 password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="clientId">The client identifier.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId)
{
return AuthenticateViaOAuth2Password(username, password, clientId, null);
}
/// <summary>
/// Authenticates this session via OAuth2 password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "password");
formData.Add("username", username);
formData.Add("password", password);
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Authenticates this session via OAuth2 authentication code.
/// </summary>
/// <param name="authCode">The authentication code.</param>
/// <param name="redirect">The redirect.</param>
/// <param name="clientId">The client identifier.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId)
{
return AuthenticateViaOAuth2Password(authCode, authCode, clientId, null);
}
/// <summary>
/// Authenticates this session via OAuth2 authentication code.
/// </summary>
/// <param name="authCode">The authentication code.</param>
/// <param name="redirect">The redirect.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "authorization_code");
formData.Add("code", authCode);
formData.Add("redirect_uri", redirect);
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Authenticates this session via OAuth2 client credentials.
/// </summary>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2ClientCredentials(String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "client_credentials");
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Creates a state instance without authentication. It will produce an access token, but only good for requests that do not need authentication.
/// </summary>
/// <param name="ipAddress">The ip address.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState UnauthenticatedAccess(string ipAddress, string clientId, string clientSecret = null)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "unauthenticated_session");
formData.Add("client_id", clientId);
formData.Add("ip_address", ipAddress);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Sets the current access token to the one specified. The server is not contacted during this operation.
/// </summary>
/// <param name="accessToken">The access token.</param>
/// <returns>Returns this instance.</returns>
public GedcomxApplicationState AuthenticateWithAccessToken(String accessToken)
{
this.CurrentAccessToken = accessToken;
return this;
}
/// <summary>
/// Authenticates this session via OAuth2.
/// </summary>
/// <param name="formData">The form data.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <exception cref="GedcomxApplicationException">
/// Illegal access token response: no access_token provided.
/// or
/// Unable to obtain an access token.
/// </exception>
public GedcomxApplicationState AuthenticateViaOAuth2(IDictionary<String, String> formData, params IStateTransitionOption[] options)
{
Link tokenLink = this.GetLink(Rel.OAUTH2_TOKEN);
if (tokenLink == null || tokenLink.Href == null)
{
throw new GedcomxApplicationException(String.Format("No OAuth2 token URI supplied for resource at {0}.", GetUri()));
}
IRestRequest request = CreateRequest()
.Accept(MediaTypes.APPLICATION_JSON_TYPE)
.ContentType(MediaTypes.APPLICATION_FORM_URLENCODED_TYPE)
.SetEntity(formData)
.Build(tokenLink.Href, Method.POST);
IRestResponse response = Invoke(request, options);
if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
{
var accessToken = JsonConvert.DeserializeObject<IDictionary<string, object>>(response.Content);
String access_token = null;
if (accessToken.ContainsKey("access_token"))
{
access_token = accessToken["access_token"] as string;
}
if (access_token == null && accessToken.ContainsKey("token"))
{
//workaround to accommodate providers that were built on an older version of the oauth2 specification.
access_token = accessToken["token"] as string;
}
if (access_token == null)
{
throw new GedcomxApplicationException("Illegal access token response: no access_token provided.", response);
}
return AuthenticateWithAccessToken(access_token);
}
else
{
throw new GedcomxApplicationException("Unable to obtain an access token.", response);
}
}
/// <summary>
/// Reads a page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="rel">The rel name to use when looking for the link.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public GedcomxApplicationState ReadPage(String rel, params IStateTransitionOption[] options)
{
Link link = GetLink(rel);
if (link == null || link.Href == null)
{
return null;
}
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.Build(link.Href, Method.GET);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Reads the next page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.NEXT.</remarks>
public GedcomxApplicationState ReadNextPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.NEXT, options);
}
/// <summary>
/// Reads the previous page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.PREVIOUS.</remarks>
public GedcomxApplicationState ReadPreviousPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.PREVIOUS, options);
}
/// <summary>
/// Reads the first page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.FIRST.</remarks>
public GedcomxApplicationState ReadFirstPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.FIRST, options);
}
/// <summary>
/// Reads the last page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.LAST.</remarks>
public GedcomxApplicationState ReadLastPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.LAST, options);
}
/// <summary>
/// Creates an authenticated feed request by attaching the authentication token and specifying the accept type.
/// </summary>
/// <returns>A REST API requeset (with appropriate authentication headers).</returns>
protected IRestRequest CreateAuthenticatedFeedRequest()
{
return CreateAuthenticatedRequest().Accept(MediaTypes.ATOM_GEDCOMX_JSON_MEDIA_TYPE);
}
/// <summary>
/// Reads the contributor for the current state instance.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(params IStateTransitionOption[] options)
{
var scope = MainDataElement;
if (scope is IAttributable)
{
return ReadContributor((IAttributable)scope, options);
}
else
{
return null;
}
}
/// <summary>
/// Reads the contributor for the specified <see cref="IAttributable"/>.
/// </summary>
/// <param name="attributable">The attributable.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(IAttributable attributable, params IStateTransitionOption[] options)
{
Attribution attribution = attributable.Attribution;
if (attribution == null)
{
return null;
}
return ReadContributor(attribution.Contributor, options);
}
/// <summary>
/// Reads the contributor for the specified <see cref="ResourceReference"/>.
/// </summary>
/// <param name="contributor">The contributor.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(ResourceReference contributor, params IStateTransitionOption[] options)
{
if (contributor == null || contributor.Resource == null)
{
return null;
}
IRestRequest request = CreateAuthenticatedGedcomxRequest().Build(contributor.Resource, Method.GET);
return this.stateFactory.NewAgentState(request, Invoke(request, options), this.Client, this.CurrentAccessToken);
}
/// <summary>
/// Gets the headers of the current REST API response.
/// </summary>
/// <value>
/// The headers of the current REST API response.
/// </value>
public IList<Parameter> Headers
{
get
{
return Response.Headers;
}
}
/// <summary>
/// Gets the URI representing this current state instance.
/// </summary>
/// <returns>The URI representing this current state instance</returns>
public string GetSelfUri()
{
String selfRel = SelfRel;
Link link = null;
if (selfRel != null)
{
link = this.GetLink(selfRel);
}
link = link == null ? this.GetLink(Rel.SELF) : link;
String self = link == null ? null : link.Href == null ? null : link.Href;
return self == null ? GetUri() : self;
}
/// <summary>
/// Gets the rel name for the current state instance. This is expected to be overridden.
/// </summary>
/// <value>
/// The rel name for the current state instance
/// </value>
public virtual String SelfRel
{
get
{
return null;
}
}
}
/// <summary>
/// This is the base class for all state instances with generic specific functionality.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
public abstract class GedcomxApplicationState<T> : GedcomxApplicationState where T : class, new()
{
/// <summary>
/// Gets the entity represented by this state (if applicable). Not all responses produce entities.
/// </summary>
/// <value>
/// The entity represented by this state.
/// </value>
public T Entity { get; private set; }
/// <summary>
/// Returns the entity from the REST API response.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <returns>The entity from the REST API response.</returns>
protected virtual T LoadEntity(IRestResponse response)
{
T result = null;
if (response != null)
{
result = response.ToIRestResponse<T>().Data;
}
return result;
}
/// <summary>
/// Gets the main data element represented by this state instance.
/// </summary>
/// <value>
/// The main data element represented by this state instance.
/// </value>
protected override ISupportsLinks MainDataElement
{
get
{
return (ISupportsLinks)Entity;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class.
/// </summary>
/// <param name="request">The REST API request.</param>
/// <param name="response">The REST API response.</param>
/// <param name="client">The REST API client.</param>
/// <param name="accessToken">The access token.</param>
/// <param name="stateFactory">The state factory.</param>
protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory)
: base(request, response, client, accessToken, stateFactory)
{
this.Entity = LoadEntityConditionally(this.Response);
List<Link> links = LoadLinks(this.Response, this.Entity, this.Request.RequestFormat);
this.Links = new List<Link>();
this.Links.AddRange(links);
}
/// <summary>
/// Loads the entity from the REST API response if the response should have data.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <returns>Conditional returns the entity from the REST API response if the response should have data.</returns>
/// <remarks>The REST API response should have data if the invoking request was not a HEAD or OPTIONS request and the response status is OK.</remarks>
protected virtual T LoadEntityConditionally(IRestResponse response)
{
if (Request.Method != Method.HEAD && Request.Method != Method.OPTIONS && response.StatusCode == HttpStatusCode.OK)
{
return LoadEntity(response);
}
else
{
return null;
}
}
/// <summary>
/// Invokes the specified REST API request and returns a state instance of the REST API response.
/// </summary>
/// <param name="request">The REST API request to execute.</param>
/// <returns>The state instance of the REST API response.</returns>
public GedcomxApplicationState Inject(IRestRequest request)
{
return Clone(request, Invoke(request), this.Client);
}
/// <summary>
/// Loads all links from a REST API response and entity object, whether from the header, response body, or any other properties available to extract useful links for this state instance.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <param name="entity">The entity to also consider for finding links.</param>
/// <param name="contentFormat">The content format (JSON or XML) of the REST API response data.</param>
/// <returns>A list of all links discovered from the REST API response and entity object.</returns>
protected List<Link> LoadLinks(IRestResponse response, T entity, DataFormat contentFormat)
{
List<Link> links = new List<Link>();
var location = response.Headers.FirstOrDefault(x => x.Name == "Location");
//if there's a location, we'll consider it a "self" link.
if (location != null && location.Value != null)
{
links.Add(new Link() { Rel = Rel.SELF, Href = location.Value.ToString() });
}
//initialize links with link headers
foreach (var header in response.Headers.Where(x => x.Name == "Link" && x.Value != null).SelectMany(x => linkHeaderParser.Parse(response.ResponseUri, x.Value.ToString())))
{
Link link = new Link() { Rel = header.Relation, Href = header.Target.ToString() };
link.Template = header.LinkExtensions.Any(x => x.Key == "template") ? header.GetLinkExtension("template") : null;
link.Title = header.Title;
link.Accept = header.LinkExtensions.Any(x => x.Key == "accept") ? header.GetLinkExtension("accept") : null;
link.Allow = header.LinkExtensions.Any(x => x.Key == "allow") ? header.GetLinkExtension("allow") : null;
link.Hreflang = header.HrefLang.Select(x => x.Name).FirstOrDefault();
link.Type = header.LinkExtensions.Any(x => x.Key == "type") ? header.GetLinkExtension("type") : null;
links.Add(link);
}
//load the links from the main data element
ISupportsLinks mainElement = MainDataElement;
if (mainElement != null && mainElement.Links != null)
{
links.AddRange(mainElement.Links);
}
//load links at the document level
var collection = entity as ISupportsLinks;
if (entity != mainElement && collection != null && collection.Links != null)
{
links.AddRange(collection.Links);
}
return links;
}
}
}
| {
"content_hash": "f2230ae2c45c68a74fabf517b1f1dd64",
"timestamp": "",
"source": "github",
"line_count": 977,
"max_line_length": 231,
"avg_line_length": 47.16069600818833,
"alnum_prop": 0.6033075787828804,
"repo_name": "weitzhandler/gedcomx-csharp",
"id": "ae34bcd684cc58850b8b3835840c807cf790d7a9",
"size": "46076",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gedcomx.Rs.Api/GedcomxApplicationState.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1965280"
}
],
"symlink_target": ""
} |
*Don't worry! Form Editor works right out of the box without any scheduled jobs running. At the time of writing, the only feature that requires a scheduled job to work is the [automatic deletion of expired submissions](install.md#automatic-deletion-of-expired-submissions).*
## Authenticating
When running scheduled jobs with the scheduler that's built into Umbraco, you need publicly available endpoints to do the work. To add a layer of safety, Form Editor scheduled jobs require you to pass an authentication token in the querystring parameter `authToken`.
The authentication token is configured in the `<Jobs>` section of */Config/FormEditor.config*:
```xml
<FormEditor>
<Jobs authToken="something-very-secret"></Jobs>
<!-- ... -->
</FormEditor>
```
## Invoking jobs
You can invoke the job that handles deletion of expired submissions by adding it to the Umbraco scheduler. This is done in the `<scheduledTasks>` section of */Config/umbracoSettings.config*:
```xml
<settings>
<!-- ... -->
<scheduledTasks>
<!-- run the PurgeExpiredSubmissions job every 6 hours (21600 seconds) -->
<task log="true" alias="FormEditorPurgeExpiredSubmissions" interval="21600" url="[your site host]/umbraco/FormEditorApi/Jobs/PurgeExpiredSubmissions/?authToken=[your authentication token]"/>
</scheduledTasks>
<!-- ... -->
</settings>
```
You can read more about the Umbraco scheduler [here](https://our.umbraco.org/documentation/Reference/Config/umbracoSettings/#scheduledtasks).
## Alternative job schedulers
If you don't want to use the Umbraco scheduler, you can invoke the Form Editor jobs with any other job scheduler that can reach the */umbraco/* section of your site.
The Form Editor jobs can be invoked with both GET and POST requests (though you must provide the `authToken` parameter in the querystring even for POST requests).
| {
"content_hash": "e08167891b634fb42880e006fb8e008d",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 274,
"avg_line_length": 50.2972972972973,
"alnum_prop": 0.7576571735626008,
"repo_name": "kjac/FormEditor",
"id": "3f4a95a60a26f61511e6bcdf83601d26b7c49b93",
"size": "1890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Docs/jobs.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "251512"
},
{
"name": "CSS",
"bytes": "14989"
},
{
"name": "HTML",
"bytes": "86824"
},
{
"name": "JavaScript",
"bytes": "125468"
}
],
"symlink_target": ""
} |
GoLearn
=======
<img src="http://talks.golang.org/2013/advconc/gopherhat.jpg" width=125><br>
[](https://godoc.org/github.com/sjwhitworth/golearn)
[](https://travis-ci.org/sjwhitworth/golearn)<br>
[](https://www.gittip.com/sjwhitworth/)
GoLearn is a 'batteries included' machine learning library for Go. **Simplicity**, paired with customisability, is the goal.
We are in active development, and would love comments from users out in the wild. Drop us a line on Twitter.
twitter: [@golearn_ml](http://www.twitter.com/golearn_ml)
Install
=======
See [here](https://github.com/sjwhitworth/golearn/wiki/Installation) for installation instructions.
Getting Started
=======
Data are loaded in as Instances. You can then perform matrix like operations on them, and pass them to estimators.
GoLearn implements the scikit-learn interface of Fit/Predict, so you can easily swap out estimators for trial and error.
GoLearn also includes helper functions for data, like cross validation, and train and test splitting.
```go
// Load in a dataset, with headers. Header attributes will be stored.
// Think of instances as a Data Frame structure in R or Pandas.
// You can also create instances from scratch.
data, err := base.ParseCSVToInstances("datasets/iris_headers.csv", true)
// Print a pleasant summary of your data.
fmt.Println(data)
// Split your dataframe into a training set, and a test set, with an 80/20 proportion.
trainTest := base.InstancesTrainTestSplit(rawData, 0.8)
trainData := trainTest[0]
testData := trainTest[1]
// Instantiate a new KNN classifier. Euclidean distance, with 2 neighbours.
cls := knn.NewKnnClassifier("euclidean", 2)
// Fit it on your training data.
cls.Fit(trainData)
// Get your predictions against test instances.
predictions := cls.Predict(testData)
// Print a confusion matrix with precision and recall metrics.
confusionMat := evaluation.GetConfusionMatrix(testData, predictions)
fmt.Println(evaluation.GetSummary(confusionMat))
```
```
Iris-virginica 28 2 56 0.9333 0.9333 0.9333
Iris-setosa 29 0 59 1.0000 1.0000 1.0000
Iris-versicolor 27 2 57 0.9310 0.9310 0.9310
Overall accuracy: 0.9545
```
Examples
========
GoLearn comes with practical examples. Dive in and see what is going on.
```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/knnclassifier
go run knnclassifier_iris.go
```
```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/instances
go run instances.go
```
```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/trees
go run trees.go
```
Join the team
=============
Please send me a mail at stephen dot whitworth at hailocab dot com.
| {
"content_hash": "4f9b09be87e1cd6a00c95df8c8a8ed26",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 127,
"avg_line_length": 34.63855421686747,
"alnum_prop": 0.7530434782608696,
"repo_name": "ghs11/golearn",
"id": "95e2038c673d92464c1e2819afe0da71b7b4ef0c",
"size": "2875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "23927"
},
{
"name": "C++",
"bytes": "61940"
},
{
"name": "Go",
"bytes": "285538"
}
],
"symlink_target": ""
} |
HpwRewrite.CategoryNames = HpwRewrite.CategoryNames or { }
HpwRewrite.CategoryNames.DestrExp = HpwRewrite.Language:GetWord("#category_destrexp")
HpwRewrite.CategoryNames.Fight = HpwRewrite.Language:GetWord("#category_fight")
HpwRewrite.CategoryNames.Generic = HpwRewrite.Language:GetWord("#category_generic")
HpwRewrite.CategoryNames.Healing = HpwRewrite.Language:GetWord("#category_healing")
HpwRewrite.CategoryNames.Lighting = HpwRewrite.Language:GetWord("#category_lighting")
HpwRewrite.CategoryNames.Physics = HpwRewrite.Language:GetWord("#category_physics")
HpwRewrite.CategoryNames.Protecting = HpwRewrite.Language:GetWord("#category_protecting")
HpwRewrite.CategoryNames.Special = HpwRewrite.Language:GetWord("#category_special")
HpwRewrite.CategoryNames.Unforgivable = HpwRewrite.Language:GetWord("#category_unforgivable") | {
"content_hash": "c1ea4e34a9676a3d85cb6ce6095ac115",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 93,
"avg_line_length": 75.54545454545455,
"alnum_prop": 0.8351383874849578,
"repo_name": "Ayditor/HPW_Rewrite",
"id": "fe711316f1876699bdf59369cdb0215e63aff91d",
"size": "831",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lua/hpwrewrite/categories.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "564044"
}
],
"symlink_target": ""
} |
require 'bicycle_orm/model/actions'
require 'bicycle_orm/model/attributes'
module BicycleOrm
class Model
include BicycleOrm::Connection
extend BicycleOrm::Model::Actions
extend BicycleOrm::Model::Attributes
def initialize(attributes = nil)
@attributes = attributes
end
def [](name)
@attributes[name]
end
def delete!
db_adapter.delete!(id)
@attributes = {}
end
end
end
| {
"content_hash": "8ba3a6e54d4e97bb9a3b43ce3f7e9fa5",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 40,
"avg_line_length": 18.956521739130434,
"alnum_prop": 0.6674311926605505,
"repo_name": "vaihtovirta/bicycle_orm",
"id": "1bca7290f6b13ca19c23ab0ecd70363fbe7cc1f5",
"size": "436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/bicycle_orm/model.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8273"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
/**
*/
package bpsim.impl;
import bpsim.BPSimDataType;
import bpsim.BpsimPackage;
import bpsim.Scenario;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.BasicFeatureMap;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>BP Sim Data Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link bpsim.impl.BPSimDataTypeImpl#getGroup <em>Group</em>}</li>
* <li>{@link bpsim.impl.BPSimDataTypeImpl#getScenario <em>Scenario</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class BPSimDataTypeImpl extends EObjectImpl implements BPSimDataType {
/**
* The cached value of the '{@link #getGroup() <em>Group</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getGroup()
* @generated
* @ordered
*/
protected FeatureMap group;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BPSimDataTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return BpsimPackage.Literals.BP_SIM_DATA_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureMap getGroup() {
if (group == null) {
group = new BasicFeatureMap(this, BpsimPackage.BP_SIM_DATA_TYPE__GROUP);
}
return group;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Scenario> getScenario() {
return getGroup().list(BpsimPackage.Literals.BP_SIM_DATA_TYPE__SCENARIO);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case BpsimPackage.BP_SIM_DATA_TYPE__GROUP:
return ((InternalEList<?>)getGroup()).basicRemove(otherEnd, msgs);
case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO:
return ((InternalEList<?>)getScenario()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BpsimPackage.BP_SIM_DATA_TYPE__GROUP:
if (coreType) return getGroup();
return ((FeatureMap.Internal)getGroup()).getWrapper();
case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO:
return getScenario();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case BpsimPackage.BP_SIM_DATA_TYPE__GROUP:
((FeatureMap.Internal)getGroup()).set(newValue);
return;
case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO:
getScenario().clear();
getScenario().addAll((Collection<? extends Scenario>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case BpsimPackage.BP_SIM_DATA_TYPE__GROUP:
getGroup().clear();
return;
case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO:
getScenario().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BpsimPackage.BP_SIM_DATA_TYPE__GROUP:
return group != null && !group.isEmpty();
case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO:
return !getScenario().isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (group: ");
result.append(group);
result.append(')');
return result.toString();
}
} //BPSimDataTypeImpl
| {
"content_hash": "1e7b0e9f5a3223d3193538c306f1558b",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 107,
"avg_line_length": 23.29381443298969,
"alnum_prop": 0.6483735339676919,
"repo_name": "romartin/jbpm",
"id": "44afd8073cd6dcbbe1d30ccb9f6efc8273252d50",
"size": "5138",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "jbpm-bpmn2-emfextmodel/src/main/java/bpsim/impl/BPSimDataTypeImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "24447"
},
{
"name": "HTML",
"bytes": "39465"
},
{
"name": "Java",
"bytes": "16273485"
},
{
"name": "JavaScript",
"bytes": "20"
},
{
"name": "PLSQL",
"bytes": "35527"
},
{
"name": "PLpgSQL",
"bytes": "14108"
},
{
"name": "Shell",
"bytes": "98"
},
{
"name": "Smalltalk",
"bytes": "1062"
},
{
"name": "TSQL",
"bytes": "606095"
},
{
"name": "Visual Basic",
"bytes": "2545"
}
],
"symlink_target": ""
} |
package main_test
import (
"testing"
"github.com/neofight/govps"
"github.com/neofight/govps/io"
"github.com/neofight/govps/mock"
)
func setupMockFile(file string) {
mockFS := mock.NewFileSystem()
mockFS.DirectoryEntries = append(mockFS.DirectoryEntries, mock.FileInfo{FileName: file})
io.FileSystem = mockFS
}
func TestIdentifyProjectTypeMvc(t *testing.T) {
setupMockFile("Web.config")
pType, err := main.IdentifyProjectType()
if err != nil {
t.Error("Expected project to be identfied but it was not")
}
if pType != main.Mvc {
t.Error("Expected project to be identfied as MVC but it was not")
}
}
func TestIdentifyProjectTypeStatic(t *testing.T) {
setupMockFile("index.html")
pType, err := main.IdentifyProjectType()
if err != nil {
t.Error("Expected project to be identfied but it was not")
}
if pType != main.Static {
t.Error("Expected project to be identfied as MVC but it was not")
}
}
func TestIdentifyProjectTypeUnknown(t *testing.T) {
setupMockFile("xxx.xxx")
pType, err := main.IdentifyProjectType()
if err == nil {
t.Error("Expected unknown project type to return an error but it did not")
}
if pType != main.Unknown {
t.Error("Expected project to be identfied as Unknown but it was not")
}
}
func TestIdentifyProjectTypeDirectoryError(t *testing.T) {
io.FileSystem = mock.FileSystem{}
pType, err := main.IdentifyProjectType()
if err == nil {
t.Error("Expected unknown project type to return an error but it did not")
}
if pType != main.Unknown {
t.Error("Expected project to be identfied as Unknown but it was not")
}
}
func TestCreatePipelineMvcErrorReadingPassword(t *testing.T) {
io.Terminal = mock.Terminal{}
pipeline, err := main.CreatePipeline(main.Mvc)
if err == nil {
t.Error("Expected failure to read password to return error but it did not")
}
if pipeline != nil {
t.Error("Expected failure to read password to return a nil pipeline but it did not")
}
}
func TestCreatePipelineMvcHappyPath(t *testing.T) {
io.Terminal = mock.Terminal{Password: "password"}
pipeline, err := main.CreatePipeline(main.Mvc)
if err != nil {
t.Error("Expected pipeline to be created without error but it was not")
}
if pipeline == nil {
t.Error("Expected pipeline to be created but it was not")
}
}
func TestCreatePipelineStaticHappyPath(t *testing.T) {
pipeline, err := main.CreatePipeline(main.Static)
if err != nil {
t.Error("Expected pipeline to be created without error but it was not")
}
if pipeline == nil {
t.Error("Expected pipeline to be created but it was not")
}
}
func TestCreatePipelineUnknown(t *testing.T) {
pipeline, err := main.CreatePipeline(main.Unknown)
if err == nil {
t.Error("Expected unknown project type to return error it but did not")
}
if pipeline != nil {
t.Error("Expected unknown project type to return a nil pipeline but it did not")
}
}
| {
"content_hash": "7766e43a57f5d64a1dfa672974099f79",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 89,
"avg_line_length": 21.619402985074625,
"alnum_prop": 0.7117707973765964,
"repo_name": "neofight/govps",
"id": "9c08c00093a718562eb33f6ec866ab033a7455a5",
"size": "2897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projectTypes_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "42558"
}
],
"symlink_target": ""
} |
<?php
namespace Gnugat\SearchEngine\Criteria;
class Embeding
{
public $relations;
public function __construct(array $relations)
{
$this->relations = $relations;
}
public static function fromQueryParameters(array $queryParameters) : self
{
if (false === isset($queryParameters['embed'])) {
return new self([]);
}
return new self(explode(',', $queryParameters['embed']));
}
public function has(string $relation) : bool
{
return in_array($relation, $this->relations, true);
}
}
| {
"content_hash": "934f21c07dd86e088fc41d23cedcb116",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 77,
"avg_line_length": 19.82758620689655,
"alnum_prop": 0.6017391304347826,
"repo_name": "gnugat/search-engine",
"id": "0a0348bddd3a4765f03b854ed5e81ee9314234c9",
"size": "824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Gnugat/SearchEngine/Criteria/Embeding.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "97899"
},
{
"name": "Shell",
"bytes": "499"
}
],
"symlink_target": ""
} |
/* $OpenBSD: msdosfs_lookup.c,v 1.11 1999/02/19 17:26:17 art Exp $ */
/* $NetBSD: msdosfs_lookup.c,v 1.34 1997/10/18 22:12:27 ws Exp $ */
/*-
* Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
* Copyright (C) 1994, 1995, 1997 TooLs GmbH.
* All rights reserved.
* Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by TooLs GmbH.
* 4. The name of TooLs GmbH may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Written by Paul Popelka (paulp@uts.amdahl.com)
*
* You can do anything you want with this software, just don't say you wrote
* it, and don't remove this notice.
*
* This software is provided "as is".
*
* The author supplies this software to be publicly redistributed on the
* understanding that the author is not responsible for the correct
* functioning of this software in any circumstances and is not liable for
* any damages caused by this software.
*
* October 1992
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/namei.h>
#include <sys/buf.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/dirent.h>
#include <msdosfs/bpb.h>
#include <msdosfs/direntry.h>
#include <msdosfs/denode.h>
#include <msdosfs/msdosfsmount.h>
#include <msdosfs/fat.h>
/*
* When we search a directory the blocks containing directory entries are
* read and examined. The directory entries contain information that would
* normally be in the inode of a unix filesystem. This means that some of
* a directory's contents may also be in memory resident denodes (sort of
* an inode). This can cause problems if we are searching while some other
* process is modifying a directory. To prevent one process from accessing
* incompletely modified directory information we depend upon being the
* sole owner of a directory block. bread/brelse provide this service.
* This being the case, when a process modifies a directory it must first
* acquire the disk block that contains the directory entry to be modified.
* Then update the disk block and the denode, and then write the disk block
* out to disk. This way disk blocks containing directory entries and in
* memory denode's will be in synch.
*/
int
msdosfs_lookup(v)
void *v;
{
struct vop_lookup_args /* {
struct vnode *a_dvp;
struct vnode **a_vpp;
struct componentname *a_cnp;
} */ *ap = v;
struct vnode *vdp = ap->a_dvp;
struct vnode **vpp = ap->a_vpp;
struct componentname *cnp = ap->a_cnp;
struct proc *p = cnp->cn_proc;
daddr_t bn;
int error;
int lockparent;
int wantparent;
int slotcount;
int slotoffset = 0;
int frcn;
u_long cluster;
int blkoff;
int diroff;
int blsize;
int isadir; /* ~0 if found direntry is a directory */
u_long scn; /* starting cluster number */
struct vnode *pdp;
struct denode *dp;
struct denode *tdp;
struct msdosfsmount *pmp;
struct buf *bp = 0;
struct direntry *dep;
u_char dosfilename[12];
int flags = cnp->cn_flags;
int nameiop = cnp->cn_nameiop;
int wincnt = 1;
int chksum = -1;
int olddos = 1;
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): looking for %s\n", cnp->cn_nameptr);
#endif
dp = VTODE(vdp);
pmp = dp->de_pmp;
*vpp = NULL;
lockparent = flags & LOCKPARENT;
wantparent = flags & (LOCKPARENT | WANTPARENT);
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): vdp %08x, dp %08x, Attr %02x\n",
vdp, dp, dp->de_Attributes);
#endif
/*
* Check accessiblity of directory.
*/
if ((dp->de_Attributes & ATTR_DIRECTORY) == 0)
return (ENOTDIR);
if ((error = VOP_ACCESS(vdp, VEXEC, cnp->cn_cred, cnp->cn_proc)) != 0)
return (error);
/*
* We now have a segment name to search for, and a directory to search.
*
* Before tediously performing a linear scan of the directory,
* check the name cache to see if the directory/name pair
* we are looking for is known already.
*/
if ((error = cache_lookup(vdp, vpp, cnp)) != 0) {
int vpid;
if (error == ENOENT)
return (error);
/*
* Get the next vnode in the path.
* See comment below starting `Step through' for
* an explaination of the locking protocol.
*/
pdp = vdp;
dp = VTODE(*vpp);
vdp = *vpp;
vpid = vdp->v_id;
if (pdp == vdp) { /* lookup on "." */
VREF(vdp);
error = 0;
} else if (flags & ISDOTDOT) {
VOP_UNLOCK(pdp, 0, p);
error = vget(vdp, LK_EXCLUSIVE, p);
if (!error && lockparent && (flags & ISLASTCN))
error =
vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, p);
} else {
error = vget(vdp, LK_EXCLUSIVE, p);
if (!lockparent || error || !(flags & ISLASTCN))
VOP_UNLOCK(pdp, 0, p);
}
/*
* Check that the capability number did not change
* while we were waiting for the lock.
*/
if (!error) {
if (vpid == vdp->v_id) {
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): cache hit, vnode %08x, file %s\n",
vdp, dp->de_Name);
#endif
return (0);
}
vput(vdp);
if (lockparent && pdp != vdp && (flags & ISLASTCN))
VOP_UNLOCK(pdp, 0, p);
}
if ((error = vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, p)) != 0)
return (error);
vdp = pdp;
dp = VTODE(vdp);
*vpp = NULL;
}
/*
* If they are going after the . or .. entry in the root directory,
* they won't find it. DOS filesystems don't have them in the root
* directory. So, we fake it. deget() is in on this scam too.
*/
if ((vdp->v_flag & VROOT) && cnp->cn_nameptr[0] == '.' &&
(cnp->cn_namelen == 1 ||
(cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.'))) {
isadir = ATTR_DIRECTORY;
scn = MSDOSFSROOT;
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): looking for . or .. in root directory\n");
#endif
cluster = MSDOSFSROOT;
blkoff = MSDOSFSROOT_OFS;
goto foundroot;
}
switch (unix2dosfn((u_char *)cnp->cn_nameptr, dosfilename, cnp->cn_namelen, 0)) {
case 0:
return (EINVAL);
case 1:
break;
case 2:
wincnt = winSlotCnt((u_char *)cnp->cn_nameptr, cnp->cn_namelen) + 1;
break;
case 3:
olddos = 0;
wincnt = winSlotCnt((u_char *)cnp->cn_nameptr, cnp->cn_namelen) + 1;
break;
}
if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
wincnt = 1;
/*
* Suppress search for slots unless creating
* file and at end of pathname, in which case
* we watch for a place to put the new file in
* case it doesn't already exist.
*/
slotcount = wincnt;
if ((nameiop == CREATE || nameiop == RENAME) &&
(flags & ISLASTCN))
slotcount = 0;
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): dos version of filename %s, length %d\n",
dosfilename, cnp->cn_namelen);
#endif
/*
* Search the directory pointed at by vdp for the name pointed at
* by cnp->cn_nameptr.
*/
tdp = NULL;
/*
* The outer loop ranges over the clusters that make up the
* directory. Note that the root directory is different from all
* other directories. It has a fixed number of blocks that are not
* part of the pool of allocatable clusters. So, we treat it a
* little differently. The root directory starts at "cluster" 0.
*/
diroff = 0;
for (frcn = 0;; frcn++) {
if ((error = pcbmap(dp, frcn, &bn, &cluster, &blsize)) != 0) {
if (error == E2BIG)
break;
return (error);
}
error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
if (error) {
brelse(bp);
return (error);
}
for (blkoff = 0; blkoff < blsize;
blkoff += sizeof(struct direntry),
diroff += sizeof(struct direntry)) {
dep = (struct direntry *)(bp->b_data + blkoff);
/*
* If the slot is empty and we are still looking
* for an empty then remember this one. If the
* slot is not empty then check to see if it
* matches what we are looking for. If the slot
* has never been filled with anything, then the
* remainder of the directory has never been used,
* so there is no point in searching it.
*/
if (dep->deName[0] == SLOT_EMPTY ||
dep->deName[0] == SLOT_DELETED) {
/*
* Drop memory of previous long matches
*/
chksum = -1;
if (slotcount < wincnt) {
slotcount++;
slotoffset = diroff;
}
if (dep->deName[0] == SLOT_EMPTY) {
brelse(bp);
goto notfound;
}
} else {
/*
* If there wasn't enough space for our winentries,
* forget about the empty space
*/
if (slotcount < wincnt)
slotcount = 0;
/*
* Check for Win95 long filename entry
*/
if (dep->deAttributes == ATTR_WIN95) {
if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
continue;
chksum = winChkName((u_char *)cnp->cn_nameptr,
cnp->cn_namelen,
(struct winentry *)dep,
chksum);
continue;
}
/*
* Ignore volume labels (anywhere, not just
* the root directory).
*/
if (dep->deAttributes & ATTR_VOLUME) {
chksum = -1;
continue;
}
/*
* Check for a checksum or name match
*/
if (chksum != winChksum(dep->deName)
&& (!olddos || bcmp(dosfilename, dep->deName, 11))) {
chksum = -1;
continue;
}
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): match blkoff %d, diroff %d\n",
blkoff, diroff);
#endif
/*
* Remember where this directory
* entry came from for whoever did
* this lookup.
*/
dp->de_fndoffset = diroff;
dp->de_fndcnt = 0; /* unused anyway */
goto found;
}
} /* for (blkoff = 0; .... */
/*
* Release the buffer holding the directory cluster just
* searched.
*/
brelse(bp);
} /* for (frcn = 0; ; frcn++) */
notfound:;
/*
* We hold no disk buffers at this point.
*/
/*
* Fixup the slot description to point to the place where
* we might put the new DOS direntry (putting the Win95
* long name entries before that)
*/
if (!slotcount) {
slotcount = 1;
slotoffset = diroff;
}
if (wincnt > slotcount)
slotoffset += sizeof(struct direntry) * (wincnt - slotcount);
/*
* If we get here we didn't find the entry we were looking for. But
* that's ok if we are creating or renaming and are at the end of
* the pathname and the directory hasn't been removed.
*/
#ifdef MSDOSFS_DEBUG
printf("msdosfs_lookup(): op %d, refcnt %d\n",
nameiop, dp->de_refcnt);
printf(" slotcount %d, slotoffset %d\n",
slotcount, slotoffset);
#endif
if ((nameiop == CREATE || nameiop == RENAME) &&
(flags & ISLASTCN) && dp->de_refcnt != 0) {
/*
* Access for write is interpreted as allowing
* creation of files in the directory.
*/
error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc);
if (error)
return (error);
/*
* Return an indication of where the new directory
* entry should be put.
*/
dp->de_fndoffset = slotoffset;
dp->de_fndcnt = wincnt - 1;
/*
* We return with the directory locked, so that
* the parameters we set up above will still be
* valid if we actually decide to do a direnter().
* We return ni_vp == NULL to indicate that the entry
* does not currently exist; we leave a pointer to
* the (locked) directory inode in ndp->ni_dvp.
* The pathname buffer is saved so that the name
* can be obtained later.
*
* NB - if the directory is unlocked, then this
* information cannot be used.
*/
cnp->cn_flags |= SAVENAME;
if (!lockparent)
VOP_UNLOCK(vdp, 0, p);
return (EJUSTRETURN);
}
/*
* Insert name into cache (as non-existent) if appropriate.
*/
if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
cache_enter(vdp, *vpp, cnp);
return (ENOENT);
found:;
/*
* NOTE: We still have the buffer with matched directory entry at
* this point.
*/
isadir = dep->deAttributes & ATTR_DIRECTORY;
scn = getushort(dep->deStartCluster);
if (FAT32(pmp)) {
scn |= getushort(dep->deHighClust) << 16;
if (scn == pmp->pm_rootdirblk) {
/*
* There should actually be 0 here.
* Just ignore the error.
*/
scn = MSDOSFSROOT;
}
}
if (cluster == MSDOSFSROOT)
blkoff = diroff;
if (isadir) {
cluster = scn;
if (cluster == MSDOSFSROOT)
blkoff = MSDOSFSROOT_OFS;
else
blkoff = 0;
}
/*
* Now release buf to allow deget to read the entry again.
* Reserving it here and giving it to deget could result
* in a deadlock.
*/
brelse(bp);
foundroot:;
/*
* If we entered at foundroot, then we are looking for the . or ..
* entry of the filesystems root directory. isadir and scn were
* setup before jumping here. And, bp is already null.
*/
if (FAT32(pmp) && scn == MSDOSFSROOT)
scn = pmp->pm_rootdirblk;
/*
* If deleting, and at end of pathname, return
* parameters which can be used to remove file.
* If the wantparent flag isn't set, we return only
* the directory (in ndp->ni_dvp), otherwise we go
* on and lock the inode, being careful with ".".
*/
if (nameiop == DELETE && (flags & ISLASTCN)) {
/*
* Don't allow deleting the root.
*/
if (blkoff == MSDOSFSROOT_OFS)
return EROFS; /* really? XXX */
/*
* Write access to directory required to delete files.
*/
error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc);
if (error)
return (error);
/*
* Return pointer to current entry in dp->i_offset.
* Save directory inode pointer in ndp->ni_dvp for dirremove().
*/
if (dp->de_StartCluster == scn && isadir) { /* "." */
VREF(vdp);
*vpp = vdp;
return (0);
}
if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
return (error);
*vpp = DETOV(tdp);
if (!lockparent)
VOP_UNLOCK(vdp, 0, p);
return (0);
}
/*
* If rewriting (RENAME), return the inode and the
* information required to rewrite the present directory
* Must get inode of directory entry to verify it's a
* regular file, or empty directory.
*/
if (nameiop == RENAME && wantparent &&
(flags & ISLASTCN)) {
if (blkoff == MSDOSFSROOT_OFS)
return EROFS; /* really? XXX */
error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_proc);
if (error)
return (error);
/*
* Careful about locking second inode.
* This can only occur if the target is ".".
*/
if (dp->de_StartCluster == scn && isadir)
return (EISDIR);
if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
return (error);
*vpp = DETOV(tdp);
cnp->cn_flags |= SAVENAME;
if (!lockparent)
VOP_UNLOCK(vdp, 0, p);
return (0);
}
/*
* Step through the translation in the name. We do not `vput' the
* directory because we may need it again if a symbolic link
* is relative to the current directory. Instead we save it
* unlocked as "pdp". We must get the target inode before unlocking
* the directory to insure that the inode will not be removed
* before we get it. We prevent deadlock by always fetching
* inodes from the root, moving down the directory tree. Thus
* when following backward pointers ".." we must unlock the
* parent directory before getting the requested directory.
* There is a potential race condition here if both the current
* and parent directories are removed before the VFS_VGET for the
* inode associated with ".." returns. We hope that this occurs
* infrequently since we cannot avoid this race condition without
* implementing a sophisticated deadlock detection algorithm.
* Note also that this simple deadlock detection scheme will not
* work if the file system has any hard links other than ".."
* that point backwards in the directory structure.
*/
pdp = vdp;
if (flags & ISDOTDOT) {
VOP_UNLOCK(pdp, 0, p); /* race to get the inode */
if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0) {
vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, p);
return (error);
}
if (lockparent && (flags & ISLASTCN) &&
(error = vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, p))) {
vput(DETOV(tdp));
return (error);
}
*vpp = DETOV(tdp);
} else if (dp->de_StartCluster == scn && isadir) {
VREF(vdp); /* we want ourself, ie "." */
*vpp = vdp;
} else {
if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
return (error);
if (!lockparent || !(flags & ISLASTCN))
VOP_UNLOCK(pdp, 0, p);
*vpp = DETOV(tdp);
}
/*
* Insert name into cache if appropriate.
*/
if (cnp->cn_flags & MAKEENTRY)
cache_enter(vdp, *vpp, cnp);
return (0);
}
/*
* dep - directory entry to copy into the directory
* ddep - directory to add to
* depp - return the address of the denode for the created directory entry
* if depp != 0
* cnp - componentname needed for Win95 long filenames
*/
int
createde(dep, ddep, depp, cnp)
struct denode *dep;
struct denode *ddep;
struct denode **depp;
struct componentname *cnp;
{
int error;
u_long dirclust, diroffset;
struct direntry *ndep;
struct msdosfsmount *pmp = ddep->de_pmp;
struct buf *bp;
daddr_t bn;
int blsize;
#ifdef MSDOSFS_DEBUG
printf("createde(dep %08x, ddep %08x, depp %08x, cnp %08x)\n",
dep, ddep, depp, cnp);
#endif
/*
* If no space left in the directory then allocate another cluster
* and chain it onto the end of the file. There is one exception
* to this. That is, if the root directory has no more space it
* can NOT be expanded. extendfile() checks for and fails attempts
* to extend the root directory. We just return an error in that
* case.
*/
if (ddep->de_fndoffset >= ddep->de_FileSize) {
diroffset = ddep->de_fndoffset + sizeof(struct direntry)
- ddep->de_FileSize;
dirclust = de_clcount(pmp, diroffset);
if ((error = extendfile(ddep, dirclust, 0, 0, DE_CLEAR)) != 0) {
(void)detrunc(ddep, ddep->de_FileSize, 0, NOCRED, NULL);
return error;
}
/*
* Update the size of the directory
*/
ddep->de_FileSize += de_cn2off(pmp, dirclust);
}
/*
* We just read in the cluster with space. Copy the new directory
* entry in. Then write it to disk. NOTE: DOS directories
* do not get smaller as clusters are emptied.
*/
error = pcbmap(ddep, de_cluster(pmp, ddep->de_fndoffset),
&bn, &dirclust, &blsize);
if (error)
return error;
diroffset = ddep->de_fndoffset;
if (dirclust != MSDOSFSROOT)
diroffset &= pmp->pm_crbomask;
if ((error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) != 0) {
brelse(bp);
return error;
}
ndep = bptoep(pmp, bp, ddep->de_fndoffset);
DE_EXTERNALIZE(ndep, dep);
/*
* Now write the Win95 long name
*/
if (ddep->de_fndcnt > 0) {
u_int8_t chksum = winChksum(ndep->deName);
u_char *un = (u_char *)cnp->cn_nameptr;
int unlen = cnp->cn_namelen;
int cnt = 1;
while (--ddep->de_fndcnt >= 0) {
if (!(ddep->de_fndoffset & pmp->pm_crbomask)) {
if ((error = bwrite(bp)) != 0)
return error;
ddep->de_fndoffset -= sizeof(struct direntry);
error = pcbmap(ddep,
de_cluster(pmp,
ddep->de_fndoffset),
&bn, 0, &blsize);
if (error)
return error;
error = bread(pmp->pm_devvp, bn, blsize,
NOCRED, &bp);
if (error) {
brelse(bp);
return error;
}
ndep = bptoep(pmp, bp, ddep->de_fndoffset);
} else {
ndep--;
ddep->de_fndoffset -= sizeof(struct direntry);
}
if (!unix2winfn(un, unlen, (struct winentry *)ndep, cnt++, chksum))
break;
}
}
if ((error = bwrite(bp)) != 0)
return error;
/*
* If they want us to return with the denode gotten.
*/
if (depp) {
if (dep->de_Attributes & ATTR_DIRECTORY) {
dirclust = dep->de_StartCluster;
if (FAT32(pmp) && dirclust == pmp->pm_rootdirblk)
dirclust = MSDOSFSROOT;
if (dirclust == MSDOSFSROOT)
diroffset = MSDOSFSROOT_OFS;
else
diroffset = 0;
}
return deget(pmp, dirclust, diroffset, depp);
}
return 0;
}
/*
* Be sure a directory is empty except for "." and "..". Return 1 if empty,
* return 0 if not empty or error.
*/
int
dosdirempty(dep)
struct denode *dep;
{
int blsize;
int error;
u_long cn;
daddr_t bn;
struct buf *bp;
struct msdosfsmount *pmp = dep->de_pmp;
struct direntry *dentp;
/*
* Since the filesize field in directory entries for a directory is
* zero, we just have to feel our way through the directory until
* we hit end of file.
*/
for (cn = 0;; cn++) {
if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
if (error == E2BIG)
return (1); /* it's empty */
return (0);
}
error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
if (error) {
brelse(bp);
return (0);
}
for (dentp = (struct direntry *)bp->b_data;
(char *)dentp < bp->b_data + blsize;
dentp++) {
if (dentp->deName[0] != SLOT_DELETED &&
(dentp->deAttributes & ATTR_VOLUME) == 0) {
/*
* In dos directories an entry whose name
* starts with SLOT_EMPTY (0) starts the
* beginning of the unused part of the
* directory, so we can just return that it
* is empty.
*/
if (dentp->deName[0] == SLOT_EMPTY) {
brelse(bp);
return (1);
}
/*
* Any names other than "." and ".." in a
* directory mean it is not empty.
*/
if (bcmp(dentp->deName, ". ", 11) &&
bcmp(dentp->deName, ".. ", 11)) {
brelse(bp);
#ifdef MSDOSFS_DEBUG
printf("dosdirempty(): entry found %02x, %02x\n",
dentp->deName[0], dentp->deName[1]);
#endif
return (0); /* not empty */
}
}
}
brelse(bp);
}
/* NOTREACHED */
}
/*
* Check to see if the directory described by target is in some
* subdirectory of source. This prevents something like the following from
* succeeding and leaving a bunch or files and directories orphaned. mv
* /a/b/c /a/b/c/d/e/f Where c and f are directories.
*
* source - the inode for /a/b/c
* target - the inode for /a/b/c/d/e/f
*
* Returns 0 if target is NOT a subdirectory of source.
* Otherwise returns a non-zero error number.
* The target inode is always unlocked on return.
*/
int
doscheckpath(source, target)
struct denode *source;
struct denode *target;
{
daddr_t scn;
struct msdosfsmount *pmp;
struct direntry *ep;
struct denode *dep;
struct buf *bp = NULL;
int error = 0;
dep = target;
if ((target->de_Attributes & ATTR_DIRECTORY) == 0 ||
(source->de_Attributes & ATTR_DIRECTORY) == 0) {
error = ENOTDIR;
goto out;
}
if (dep->de_StartCluster == source->de_StartCluster) {
error = EEXIST;
goto out;
}
if (dep->de_StartCluster == MSDOSFSROOT)
goto out;
pmp = dep->de_pmp;
#ifdef DIAGNOSTIC
if (pmp != source->de_pmp)
panic("doscheckpath: source and target on different filesystems");
#endif
if (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)
goto out;
for (;;) {
if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) {
error = ENOTDIR;
break;
}
scn = dep->de_StartCluster;
error = bread(pmp->pm_devvp, cntobn(pmp, scn),
pmp->pm_bpcluster, NOCRED, &bp);
if (error)
break;
ep = (struct direntry *) bp->b_data + 1;
if ((ep->deAttributes & ATTR_DIRECTORY) == 0 ||
bcmp(ep->deName, ".. ", 11) != 0) {
error = ENOTDIR;
break;
}
scn = getushort(ep->deStartCluster);
if (FAT32(pmp))
scn |= getushort(ep->deHighClust) << 16;
if (scn == source->de_StartCluster) {
error = EINVAL;
break;
}
if (scn == MSDOSFSROOT)
break;
if (FAT32(pmp) && scn == pmp->pm_rootdirblk) {
/*
* scn should be 0 in this case,
* but we silently ignore the error.
*/
break;
}
vput(DETOV(dep));
brelse(bp);
bp = NULL;
/* NOTE: deget() clears dep on error */
if ((error = deget(pmp, scn, 0, &dep)) != 0)
break;
}
out:;
if (bp)
brelse(bp);
if (error == ENOTDIR)
printf("doscheckpath(): .. not a directory?\n");
if (dep != NULL)
vput(DETOV(dep));
return (error);
}
/*
* Read in the disk block containing the directory entry (dirclu, dirofs)
* and return the address of the buf header, and the address of the
* directory entry within the block.
*/
int
readep(pmp, dirclust, diroffset, bpp, epp)
struct msdosfsmount *pmp;
u_long dirclust, diroffset;
struct buf **bpp;
struct direntry **epp;
{
int error;
daddr_t bn;
int blsize;
u_long boff;
boff = diroffset & ~pmp->pm_crbomask;
blsize = pmp->pm_bpcluster;
if (dirclust == MSDOSFSROOT
&& de_blk(pmp, diroffset + blsize) > pmp->pm_rootdirsize)
blsize = de_bn2off(pmp, pmp->pm_rootdirsize) & pmp->pm_crbomask;
bn = detobn(pmp, dirclust, diroffset);
if ((error = bread(pmp->pm_devvp, bn, blsize, NOCRED, bpp)) != 0) {
brelse(*bpp);
*bpp = NULL;
return (error);
}
if (epp)
*epp = bptoep(pmp, *bpp, diroffset);
return (0);
}
/*
* Read in the disk block containing the directory entry dep came from and
* return the address of the buf header, and the address of the directory
* entry within the block.
*/
int
readde(dep, bpp, epp)
struct denode *dep;
struct buf **bpp;
struct direntry **epp;
{
return (readep(dep->de_pmp, dep->de_dirclust, dep->de_diroffset,
bpp, epp));
}
/*
* Remove a directory entry. At this point the file represented by the
* directory entry to be removed is still full length until noone has it
* open. When the file no longer being used msdosfs_inactive() is called
* and will truncate the file to 0 length. When the vnode containing the
* denode is needed for some other purpose by VFS it will call
* msdosfs_reclaim() which will remove the denode from the denode cache.
*/
int
removede(pdep, dep)
struct denode *pdep; /* directory where the entry is removed */
struct denode *dep; /* file to be removed */
{
int error;
struct direntry *ep;
struct buf *bp;
daddr_t bn;
int blsize;
struct msdosfsmount *pmp = pdep->de_pmp;
u_long offset = pdep->de_fndoffset;
#ifdef MSDOSFS_DEBUG
printf("removede(): filename %s, dep %08x, offset %08x\n",
dep->de_Name, dep, offset);
#endif
dep->de_refcnt--;
offset += sizeof(struct direntry);
do {
offset -= sizeof(struct direntry);
error = pcbmap(pdep, de_cluster(pmp, offset), &bn, 0, &blsize);
if (error)
return error;
error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
if (error) {
brelse(bp);
return error;
}
ep = bptoep(pmp, bp, offset);
/*
* Check whether, if we came here the second time, i.e.
* when underflowing into the previous block, the last
* entry in this block is a longfilename entry, too.
*/
if (ep->deAttributes != ATTR_WIN95
&& offset != pdep->de_fndoffset) {
brelse(bp);
break;
}
offset += sizeof(struct direntry);
while (1) {
/*
* We are a bit agressive here in that we delete any Win95
* entries preceding this entry, not just the ones we "own".
* Since these presumably aren't valid anyway,
* there should be no harm.
*/
offset -= sizeof(struct direntry);
ep--->deName[0] = SLOT_DELETED;
if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95)
|| !(offset & pmp->pm_crbomask)
|| ep->deAttributes != ATTR_WIN95)
break;
}
if ((error = bwrite(bp)) != 0)
return error;
} while (!(pmp->pm_flags & MSDOSFSMNT_NOWIN95)
&& !(offset & pmp->pm_crbomask)
&& offset);
return 0;
}
/*
* Create a unique DOS name in dvp
*/
int
uniqdosname(dep, cnp, cp)
struct denode *dep;
struct componentname *cnp;
u_char *cp;
{
struct msdosfsmount *pmp = dep->de_pmp;
struct direntry *dentp;
int gen;
int blsize;
u_long cn;
daddr_t bn;
struct buf *bp;
int error;
for (gen = 1;; gen++) {
/*
* Generate DOS name with generation number
*/
if (!unix2dosfn((u_char *)cnp->cn_nameptr, cp, cnp->cn_namelen, gen))
return gen == 1 ? EINVAL : EEXIST;
/*
* Now look for a dir entry with this exact name
*/
for (cn = error = 0; !error; cn++) {
if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
if (error == E2BIG) /* EOF reached and not found */
return 0;
return error;
}
error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
if (error) {
brelse(bp);
return error;
}
for (dentp = (struct direntry *)bp->b_data;
(char *)dentp < bp->b_data + blsize;
dentp++) {
if (dentp->deName[0] == SLOT_EMPTY) {
/*
* Last used entry and not found
*/
brelse(bp);
return 0;
}
/*
* Ignore volume labels and Win95 entries
*/
if (dentp->deAttributes & ATTR_VOLUME)
continue;
if (!bcmp(dentp->deName, cp, 11)) {
error = EEXIST;
break;
}
}
brelse(bp);
}
}
return (EEXIST);
}
/*
* Find any Win'95 long filename entry in directory dep
*/
int
findwin95(dep)
struct denode *dep;
{
struct msdosfsmount *pmp = dep->de_pmp;
struct direntry *dentp;
int blsize;
u_long cn;
daddr_t bn;
struct buf *bp;
/*
* Read through the directory looking for Win'95 entries
* Note: Error currently handled just as EOF XXX
*/
for (cn = 0;; cn++) {
if (pcbmap(dep, cn, &bn, 0, &blsize))
return 0;
if (bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) {
brelse(bp);
return 0;
}
for (dentp = (struct direntry *)bp->b_data;
(char *)dentp < bp->b_data + blsize;
dentp++) {
if (dentp->deName[0] == SLOT_EMPTY) {
/*
* Last used entry and not found
*/
brelse(bp);
return 0;
}
if (dentp->deName[0] == SLOT_DELETED) {
/*
* Ignore deleted files
* Note: might be an indication of Win'95 anyway XXX
*/
continue;
}
if (dentp->deAttributes == ATTR_WIN95) {
brelse(bp);
return 1;
}
}
brelse(bp);
}
}
| {
"content_hash": "6f256dc46467b93af97c3ea2221bb8f3",
"timestamp": "",
"source": "github",
"line_count": 1125,
"max_line_length": 82,
"avg_line_length": 27.165333333333333,
"alnum_prop": 0.633683452766598,
"repo_name": "MarginC/kame",
"id": "1a6baa0233b8bd229f7144a776728e4a96fbe3b8",
"size": "30561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "openbsd/sys/msdosfs/msdosfs_lookup.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
using System;
namespace GitMind.Utils.UI
{
internal class BusyProgress : IDisposable
{
private readonly BusyIndicator busyIndicator;
private readonly string statusText;
private Timing timing;
public BusyProgress(BusyIndicator busyIndicator, string statusText)
{
timing = new Timing();
timing.Log("Start busy indicator ...");
this.busyIndicator = busyIndicator;
this.statusText = statusText;
}
public void Dispose()
{
timing.Log("Done busy indicator");
busyIndicator.Done(statusText);
}
}
} | {
"content_hash": "57e7761171852fb2709947ccd2493fca",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 69,
"avg_line_length": 19.74074074074074,
"alnum_prop": 0.726078799249531,
"repo_name": "michael-reichenauer/GitMind",
"id": "c109697ebcfdc7edb08fb6f2ecc2c09a7e27e664",
"size": "533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GitMind/Utils/UI/BusyProgress.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "133"
},
{
"name": "C#",
"bytes": "991116"
},
{
"name": "PowerShell",
"bytes": "7436"
}
],
"symlink_target": ""
} |
#import <Foundation/Foundation.h>
#import "TiUtils.h"
#import "ApplicationDefaults.h"
@implementation ApplicationDefaults
+ (NSMutableDictionary*) copyDefaults
{
NSMutableDictionary * _property = [[NSMutableDictionary alloc] init];
[_property setObject:[TiUtils stringValue:@"system"] forKey:@"ti.ui.defaultunit"];
[_property setObject:[TiUtils stringValue:@"514307815249030"] forKey:@"ti.facebook.appid"];
return _property;
}
@end
| {
"content_hash": "ae19497791467eceaee91da28df9e26c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 95,
"avg_line_length": 26.823529411764707,
"alnum_prop": 0.7368421052631579,
"repo_name": "markofevil3/truyenClient",
"id": "c81f90989f5dca972f7f873be52a482156fea94d",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/iphone/Classes/ApplicationDefaults.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "144389"
},
{
"name": "C++",
"bytes": "52728"
},
{
"name": "D",
"bytes": "782892"
},
{
"name": "JavaScript",
"bytes": "73013"
},
{
"name": "Matlab",
"bytes": "1951"
},
{
"name": "Objective-C",
"bytes": "3303829"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
package org.springframework.boot.devtools.restart;
/**
* Strategy used to handle launch failures.
*
* @author Phillip Webb
* @since 1.3.0
*/
@FunctionalInterface
public interface FailureHandler {
/**
* {@link FailureHandler} that always aborts.
*/
FailureHandler NONE = (failure) -> Outcome.ABORT;
/**
* Handle a run failure. Implementations may block, for example to wait until specific
* files are updated.
* @param failure the exception
* @return the outcome
*/
Outcome handle(Throwable failure);
/**
* Various outcomes for the handler.
*/
enum Outcome {
/**
* Abort the relaunch.
*/
ABORT,
/**
* Try again to relaunch the application.
*/
RETRY
}
}
| {
"content_hash": "f7a87839b12b513b4225a837509ae5f2",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 87,
"avg_line_length": 16.181818181818183,
"alnum_prop": 0.6629213483146067,
"repo_name": "lburgazzoli/spring-boot",
"id": "84c490405df1d88f1793dee56f927cca592b81d7",
"size": "1333",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/FailureHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6954"
},
{
"name": "CSS",
"bytes": "5769"
},
{
"name": "FreeMarker",
"bytes": "2134"
},
{
"name": "Groovy",
"bytes": "49512"
},
{
"name": "HTML",
"bytes": "69689"
},
{
"name": "Java",
"bytes": "11602150"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1307"
},
{
"name": "Shell",
"bytes": "27916"
},
{
"name": "Smarty",
"bytes": "3276"
},
{
"name": "XSLT",
"bytes": "34105"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ren.CMS.CORE.Helper
{
public static class ArrayHelper
{
public static int IndexOfElement<T>(this IEnumerable<T> source, T value)
{
int index = 0;
var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
foreach (T item in source)
{
if (comparer.Equals(item, value)) return index;
index++;
}
return -1;
}
}
}
| {
"content_hash": "6792d743060708c52b968d80fa519f8f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 84,
"avg_line_length": 25.73913043478261,
"alnum_prop": 0.5709459459459459,
"repo_name": "nfMalde/Ren.CMS.NET",
"id": "95081ef37cbcd656530afb852717d64ec66911df",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/Release-Candidate",
"path": "Ren.CMS.Net/Source/Ren.CMS.Net-Libraries/Ren.CMS.CORE/Helper/ArrayHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1062"
},
{
"name": "C#",
"bytes": "1322575"
},
{
"name": "CSS",
"bytes": "495600"
},
{
"name": "HTML",
"bytes": "4028925"
},
{
"name": "JavaScript",
"bytes": "8580472"
},
{
"name": "PHP",
"bytes": "2199"
},
{
"name": "Shell",
"bytes": "66"
}
],
"symlink_target": ""
} |
from parsl.app.app import bash_app, python_app
from parsl.data_provider.files import File
import os
@bash_app
def echo(message, outputs=[]):
return 'echo {m} &> {o}'.format(m=message, o=outputs[0])
@python_app
def cat(inputs=[]):
with open(inputs[0].filepath) as f:
return f.readlines()
def test_slides():
"""Testing code snippet from slides """
if os.path.exists('hello1.txt'):
os.remove('hello1.txt')
hello = echo("Hello World!", outputs=[File('hello1.txt')])
message = cat(inputs=[hello.outputs[0]])
# Waits. This need not be in the slides.
print(hello.result())
print(message.result())
| {
"content_hash": "efbcec8947552a03d8aea377f833e4e7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 62,
"avg_line_length": 21.766666666666666,
"alnum_prop": 0.6416539050535988,
"repo_name": "Parsl/parsl",
"id": "09f5e86f938749c6b1d9a31077034397b137bea8",
"size": "653",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parsl/tests/test_docs/test_from_slides.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1263"
},
{
"name": "CSS",
"bytes": "337"
},
{
"name": "HTML",
"bytes": "12706"
},
{
"name": "Makefile",
"bytes": "4908"
},
{
"name": "Python",
"bytes": "1173869"
},
{
"name": "Shell",
"bytes": "12057"
}
],
"symlink_target": ""
} |
package io.dropwizard.testing;
import io.dropwizard.configuration.UrlConfigurationSourceProvider;
import io.dropwizard.setup.Environment;
import io.dropwizard.testing.app.TestApplication;
import io.dropwizard.testing.app.TestConfiguration;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class DropwizardTestSupportWithUrlConfigProviderTest {
private static final String CONFIG_PATH = DropwizardTestSupportWithUrlConfigProviderTest.class.getResource("/test-config.yaml").toString();
private static final DropwizardTestSupport<TestConfiguration> TEST_SUPPORT = new DropwizardTestSupport<>(
TestApplication.class, CONFIG_PATH, new UrlConfigurationSourceProvider());
@BeforeAll
static void setUp() throws Exception {
TEST_SUPPORT.before();
}
@AfterAll
static void tearDown() {
TEST_SUPPORT.after();
}
@Test
void returnsConfiguration() {
final TestConfiguration config = TEST_SUPPORT.getConfiguration();
assertThat(config.getMessage()).isEqualTo("Yes, it's here");
}
@Test
void returnsApplication() {
final TestApplication application = TEST_SUPPORT.getApplication();
assertThat(application).isNotNull();
}
@Test
void returnsEnvironment() {
final Environment environment = TEST_SUPPORT.getEnvironment();
assertThat(environment.getName()).isEqualTo("TestApplication");
}
}
| {
"content_hash": "908b58466e23a9eba63866174e9cce40",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 143,
"avg_line_length": 34.31111111111111,
"alnum_prop": 0.7396373056994818,
"repo_name": "dropwizard/dropwizard",
"id": "ee8c1ba3135a5816a9ff58d2f8acfacbf5583c55",
"size": "1544",
"binary": false,
"copies": "2",
"ref": "refs/heads/release/2.1.x",
"path": "dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportWithUrlConfigProviderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "992"
},
{
"name": "HTML",
"bytes": "111"
},
{
"name": "Java",
"bytes": "2956263"
},
{
"name": "Mustache",
"bytes": "569"
},
{
"name": "Shell",
"bytes": "6214"
}
],
"symlink_target": ""
} |
cask 'textmate' do
version '2.0-beta.12.20'
sha256 '332fb7b30a07a8cbaad9d8fb6893c8eae9f65e1397fd3b4c7781ed066f2df7f9'
# github.com/textmate/textmate was verified as official when first introduced to the cask
url "https://github.com/textmate/textmate/releases/download/v#{version}/TextMate_#{version}.tbz"
appcast 'https://github.com/textmate/textmate/releases.atom',
checkpoint: 'd772d70c6c408609b20a6d0cffcd2cab4c5a3fc8c577e542a7054e1eea185c73'
name 'TextMate'
homepage 'https://macromates.com/'
license :gpl
app 'TextMate.app'
binary "#{appdir}/TextMate.app/Contents/Resources/mate"
zap delete: [
'~/Library/Application Support/Avian',
'~/Library/Application Support/TextMate',
'~/Library/Preferences/com.macromates.TextMate.preview.LSSharedFileList.plist',
'~/Library/Preferences/com.macromates.TextMate.preview.plist',
'~/Library/Preferences/com.macromates.textmate.webpreview.plist',
'~/Library/Preferences/com.macromates.textmate.plist',
'~/Library/Preferences/com.macromates.textmate.latex_config.plist',
]
end
| {
"content_hash": "b53d7e02526e8309e5d72d16c7be0ae1",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 98,
"avg_line_length": 47.16,
"alnum_prop": 0.6997455470737913,
"repo_name": "forevergenin/homebrew-cask",
"id": "4e75cf5905cf6935be26a905aae505c1b00e5664",
"size": "1179",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Casks/textmate.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "1786985"
},
{
"name": "Shell",
"bytes": "70391"
}
],
"symlink_target": ""
} |
describe('MockWebServer', function () {
const base = this;
beforeEach(() => {
injector().inject(function (MockWebServer) {
base.MockWebServer = MockWebServer;
});
});
it('should exist', () => {
expect(this.MockWebServer).to.exist;
});
});
| {
"content_hash": "4bcdca18290dc270528e97564811f8ad",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 48,
"avg_line_length": 20.692307692307693,
"alnum_prop": 0.5947955390334573,
"repo_name": "opentable/spur-mockserver",
"id": "c092804a8da6086ca6fbb480571a7ea3c4f3aaf1",
"size": "269",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "test/unit/webserver/MockWebServerSpec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10729"
}
],
"symlink_target": ""
} |
using System.Threading.Tasks;
using CrystalQuartz.Application;
using CrystalQuartz.Core;
using CrystalQuartz.Core.SchedulerProviders;
using CrystalQuartz.WebFramework;
using CrystalQuartz.WebFramework.HttpAbstractions;
using Microsoft.AspNetCore.Http;
namespace CrystalQuartz.AspNetCore
{
public class CrystalQuartzPanelMiddleware
{
private readonly RequestDelegate _next;
private readonly RunningApplication _runningApplication;
public CrystalQuartzPanelMiddleware(
RequestDelegate next,
ISchedulerProvider schedulerProvider,
Options options)
{
_next = next;
var application = new CrystalQuartzPanelApplication(schedulerProvider, options);
_runningApplication = application.Run();
}
public async Task Invoke(HttpContext httpContext)
{
IRequest request = new AspNetCoreRequest(httpContext.Request.Query, httpContext.Request.HasFormContentType ? httpContext.Request.Form : null);
IResponseRenderer responseRenderer = new AspNetCoreResponseRenderer(httpContext);
_runningApplication.Handle(request, responseRenderer);
}
}
} | {
"content_hash": "5eea1cfb3571a2203155306840077205",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 154,
"avg_line_length": 33.666666666666664,
"alnum_prop": 0.7186468646864687,
"repo_name": "guryanovev/CrystalQuartz",
"id": "6278b1a15d0cfee14c1d43d9d8fa7e6d64f977cf",
"size": "1214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CrystalQuartz.AspNetCore/CrystalQuartzPanelMiddleware.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "804"
},
{
"name": "Batchfile",
"bytes": "483"
},
{
"name": "C#",
"bytes": "391367"
},
{
"name": "CSS",
"bytes": "38954"
},
{
"name": "HTML",
"bytes": "44459"
},
{
"name": "JavaScript",
"bytes": "65551"
},
{
"name": "Pascal",
"bytes": "1374"
},
{
"name": "TypeScript",
"bytes": "247778"
}
],
"symlink_target": ""
} |
package publicsuffix // import "golang.org/x/net/publicsuffix"
// TODO: specify case sensitivity and leading/trailing dot behavior for
// func PublicSuffix and func EffectiveTLDPlusOne.
import (
"fmt"
"net/http/cookiejar"
"strings"
)
// List implements the cookiejar.PublicSuffixList interface by calling the
// PublicSuffix function.
var List cookiejar.PublicSuffixList = list{}
type list struct{}
func (list) PublicSuffix(domain string) string {
ps, _ := PublicSuffix(domain)
return ps
}
func (list) String() string {
return version
}
// PublicSuffix returns the public suffix of the domain using a copy of the
// publicsuffix.org database compiled into the library.
//
// icann is whether the public suffix is managed by the Internet Corporation
// for Assigned Names and Numbers. If not, the public suffix is privately
// managed. For example, foo.org and foo.co.uk are ICANN domains,
// foo.dyndns.org and foo.blogspot.co.uk are private domains.
//
// Use cases for distinguishing ICANN domains like foo.com from private
// domains like foo.appspot.com can be found at
// https://wiki.mozilla.org/Public_Suffix_List/Use_Cases
func PublicSuffix(domain string) (publicSuffix string, icann bool) {
lo, hi := uint32(0), uint32(numTLD)
s, suffix, wildcard := domain, len(domain), false
loop:
for {
dot := strings.LastIndex(s, ".")
if wildcard {
suffix = 1 + dot
}
if lo == hi {
break
}
f := find(s[1 + dot:], lo, hi)
if f == notFound {
break
}
u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength)
icann = u & (1 << nodesBitsICANN - 1) != 0
u >>= nodesBitsICANN
u = children[u & (1 << nodesBitsChildren - 1)]
lo = u & (1 << childrenBitsLo - 1)
u >>= childrenBitsLo
hi = u & (1 << childrenBitsHi - 1)
u >>= childrenBitsHi
switch u & (1 << childrenBitsNodeType - 1) {
case nodeTypeNormal:
suffix = 1 + dot
case nodeTypeException:
suffix = 1 + len(s)
break loop
}
u >>= childrenBitsNodeType
wildcard = u & (1 << childrenBitsWildcard - 1) != 0
if dot == -1 {
break
}
s = s[:dot]
}
if suffix == len(domain) {
// If no rules match, the prevailing rule is "*".
return domain[1 + strings.LastIndex(domain, "."):], icann
}
return domain[suffix:], icann
}
const notFound uint32 = 1 << 32 - 1
// find returns the index of the node in the range [lo, hi) whose label equals
// label, or notFound if there is no such node. The range is assumed to be in
// strictly increasing node label order.
func find(label string, lo, hi uint32) uint32 {
for lo < hi {
mid := lo + (hi - lo) / 2
s := nodeLabel(mid)
if s < label {
lo = mid + 1
} else if s == label {
return mid
} else {
hi = mid
}
}
return notFound
}
// nodeLabel returns the label for the i'th node.
func nodeLabel(i uint32) string {
x := nodes[i]
length := x & (1 << nodesBitsTextLength - 1)
x >>= nodesBitsTextLength
offset := x & (1 << nodesBitsTextOffset - 1)
return text[offset : offset + length]
}
// EffectiveTLDPlusOne returns the effective top level domain plus one more
// label. For example, the eTLD+1 for "foo.bar.golang.org" is "golang.org".
func EffectiveTLDPlusOne(domain string) (string, error) {
suffix, _ := PublicSuffix(domain)
if len(domain) <= len(suffix) {
return "", fmt.Errorf("publicsuffix: cannot derive eTLD+1 for domain %q", domain)
}
i := len(domain) - len(suffix) - 1
if domain[i] != '.' {
return "", fmt.Errorf("publicsuffix: invalid public suffix %q for domain %q", suffix, domain)
}
return domain[1 + strings.LastIndex(domain[:i], "."):], nil
}
| {
"content_hash": "7d95a648127a3ee47450eeef663a71ba",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 101,
"avg_line_length": 31.38888888888889,
"alnum_prop": 0.606826801517067,
"repo_name": "spacexnice/ctlplane",
"id": "8d9b86f333388bb8b5bf2eed5ea58bb9457c2945",
"size": "4299",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Godeps/_workspace/src/golang.org/x/net/publicsuffix/list.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1662"
},
{
"name": "Go",
"bytes": "53925"
},
{
"name": "HTML",
"bytes": "27450"
},
{
"name": "JavaScript",
"bytes": "484"
},
{
"name": "Makefile",
"bytes": "351"
},
{
"name": "Shell",
"bytes": "587"
}
],
"symlink_target": ""
} |
package pstoreds
import (
"context"
"fmt"
"io"
"time"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
pstore "github.com/libp2p/go-libp2p/p2p/host/peerstore"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
"github.com/multiformats/go-base32"
)
// Configuration object for the peerstore.
type Options struct {
// The size of the in-memory cache. A value of 0 or lower disables the cache.
CacheSize uint
// MaxProtocols is the maximum number of protocols we store for one peer.
MaxProtocols int
// Sweep interval to purge expired addresses from the datastore. If this is a zero value, GC will not run
// automatically, but it'll be available on demand via explicit calls.
GCPurgeInterval time.Duration
// Interval to renew the GC lookahead window. If this is a zero value, lookahead will be disabled and we'll
// traverse the entire datastore for every purge cycle.
GCLookaheadInterval time.Duration
// Initial delay before GC processes start. Intended to give the system breathing room to fully boot
// before starting GC.
GCInitialDelay time.Duration
Clock clock
}
// DefaultOpts returns the default options for a persistent peerstore, with the full-purge GC algorithm:
//
// * Cache size: 1024.
// * MaxProtocols: 1024.
// * GC purge interval: 2 hours.
// * GC lookahead interval: disabled.
// * GC initial delay: 60 seconds.
func DefaultOpts() Options {
return Options{
CacheSize: 1024,
MaxProtocols: 1024,
GCPurgeInterval: 2 * time.Hour,
GCLookaheadInterval: 0,
GCInitialDelay: 60 * time.Second,
Clock: realclock{},
}
}
type pstoreds struct {
peerstore.Metrics
*dsKeyBook
*dsAddrBook
*dsProtoBook
*dsPeerMetadata
}
var _ peerstore.Peerstore = &pstoreds{}
// NewPeerstore creates a peerstore backed by the provided persistent datastore.
// It's the caller's responsibility to call RemovePeer to ensure
// that memory consumption of the peerstore doesn't grow unboundedly.
func NewPeerstore(ctx context.Context, store ds.Batching, opts Options) (*pstoreds, error) {
addrBook, err := NewAddrBook(ctx, store, opts)
if err != nil {
return nil, err
}
keyBook, err := NewKeyBook(ctx, store, opts)
if err != nil {
return nil, err
}
peerMetadata, err := NewPeerMetadata(ctx, store, opts)
if err != nil {
return nil, err
}
protoBook, err := NewProtoBook(peerMetadata, WithMaxProtocols(opts.MaxProtocols))
if err != nil {
return nil, err
}
return &pstoreds{
Metrics: pstore.NewMetrics(),
dsKeyBook: keyBook,
dsAddrBook: addrBook,
dsPeerMetadata: peerMetadata,
dsProtoBook: protoBook,
}, nil
}
// uniquePeerIds extracts and returns unique peer IDs from database keys.
func uniquePeerIds(ds ds.Datastore, prefix ds.Key, extractor func(result query.Result) string) (peer.IDSlice, error) {
var (
q = query.Query{Prefix: prefix.String(), KeysOnly: true}
results query.Results
err error
)
if results, err = ds.Query(context.TODO(), q); err != nil {
log.Error(err)
return nil, err
}
defer results.Close()
idset := make(map[string]struct{})
for result := range results.Next() {
k := extractor(result)
idset[k] = struct{}{}
}
if len(idset) == 0 {
return peer.IDSlice{}, nil
}
ids := make(peer.IDSlice, 0, len(idset))
for id := range idset {
pid, _ := base32.RawStdEncoding.DecodeString(id)
id, _ := peer.IDFromBytes(pid)
ids = append(ids, id)
}
return ids, nil
}
func (ps *pstoreds) Close() (err error) {
var errs []error
weakClose := func(name string, c interface{}) {
if cl, ok := c.(io.Closer); ok {
if err = cl.Close(); err != nil {
errs = append(errs, fmt.Errorf("%s error: %s", name, err))
}
}
}
weakClose("keybook", ps.dsKeyBook)
weakClose("addressbook", ps.dsAddrBook)
weakClose("protobook", ps.dsProtoBook)
weakClose("peermetadata", ps.dsPeerMetadata)
if len(errs) > 0 {
return fmt.Errorf("failed while closing peerstore; err(s): %q", errs)
}
return nil
}
func (ps *pstoreds) Peers() peer.IDSlice {
set := map[peer.ID]struct{}{}
for _, p := range ps.PeersWithKeys() {
set[p] = struct{}{}
}
for _, p := range ps.PeersWithAddrs() {
set[p] = struct{}{}
}
pps := make(peer.IDSlice, 0, len(set))
for p := range set {
pps = append(pps, p)
}
return pps
}
func (ps *pstoreds) PeerInfo(p peer.ID) peer.AddrInfo {
return peer.AddrInfo{
ID: p,
Addrs: ps.dsAddrBook.Addrs(p),
}
}
// RemovePeer removes entries associated with a peer from:
// * the KeyBook
// * the ProtoBook
// * the PeerMetadata
// * the Metrics
// It DOES NOT remove the peer from the AddrBook.
func (ps *pstoreds) RemovePeer(p peer.ID) {
ps.dsKeyBook.RemovePeer(p)
ps.dsProtoBook.RemovePeer(p)
ps.dsPeerMetadata.RemovePeer(p)
ps.Metrics.RemovePeer(p)
}
| {
"content_hash": "94d2a997a2ae3df8d30e2c352956cb5f",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 118,
"avg_line_length": 25.272251308900522,
"alnum_prop": 0.6909053242179407,
"repo_name": "libp2p/go-libp2p",
"id": "bd5476812928cf516cebb5006e59a886285318b5",
"size": "4827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "p2p/host/peerstore/pstoreds/peerstore.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "1888245"
},
{
"name": "Makefile",
"bytes": "2313"
},
{
"name": "Shell",
"bytes": "7949"
},
{
"name": "Standard ML",
"bytes": "70"
}
],
"symlink_target": ""
} |
<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<div class="site-error">
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
</div>
| {
"content_hash": "b30d57febf8935253918e153e029e7fb",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 82,
"avg_line_length": 20.576923076923077,
"alnum_prop": 0.577570093457944,
"repo_name": "gcdong/basic",
"id": "9a49b8e5612165b6fab2670619da2f35d7550038",
"size": "535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/site/error.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "241"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "377043"
},
{
"name": "HTML",
"bytes": "2599"
},
{
"name": "JavaScript",
"bytes": "1502306"
},
{
"name": "PHP",
"bytes": "143276"
}
],
"symlink_target": ""
} |
<style>
.guides-banner {
display: block;
box-sizing: border-box;
padding: 20px 40px;
width: 1160px;
height: 150px;
background-color: #0066FF;
background-image: url({{ "/images/backgrounds/guides_banner.svg" }});
background-position: top right;
background-repeat: no-repeat;
color: #FFFFFF;
text-decoration: none;
margin-bottom: 25px;
}
.guides-banner__title {
display: block;
font-style: normal;
font-weight: bold;
font-size: 25px;
line-height: 30px;
margin-bottom: 20px;
}
</style>
<div class="page__container">
<a data-proofer-ignore href="{{ "/guides/?utm_campaign=werf_site" }}"
target="_blank" class="guides-banner">
<span class="guides-banner__title">
Online guides<br />
for beginners!
</span>
<span class="page__btn page__btn_w page__btn_small page__btn_inline">
Let's dive →
</span>
</a>
</div> | {
"content_hash": "dfe820c0caa96b5ddb4fff8169beec6d",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 77,
"avg_line_length": 27.736842105263158,
"alnum_prop": 0.5464895635673624,
"repo_name": "flant/dapp",
"id": "d46ece3b30cc3713067a8a80e984ee236baea828",
"size": "1054",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/site/_includes/en/guides_banner.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "12293"
},
{
"name": "Go",
"bytes": "532211"
},
{
"name": "Makefile",
"bytes": "1580"
},
{
"name": "Ruby",
"bytes": "24290"
},
{
"name": "Shell",
"bytes": "12999"
}
],
"symlink_target": ""
} |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
namespace MusicXMLUtils.Structure
{
[GeneratedCode("xsd", "4.0.30319.18020")]
[Serializable]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType("bracket")]
public class Bracket
{
#region -- Public Properties --
[XmlAttribute("type")]
public StartStopContinue Type { get; set; }
[XmlAttribute("number", DataType = "positiveInteger")]
public string Number { get; set; }
[XmlAttribute("line-end")]
public LineEnd LineEnd { get; set; }
[XmlAttribute("end-length")]
public decimal EndLength { get; set; }
[XmlIgnore]
public bool EndLengthSpecified { get; set; }
[XmlAttribute("line-type")]
public LineType LineType { get; set; }
[XmlIgnore]
public bool LineTypeSpecified { get; set; }
[XmlAttribute("dash-length")]
public decimal DashLength { get; set; }
[XmlIgnore]
public bool DashLengthSpecified { get; set; }
[XmlAttribute("space-length")]
public decimal SpaceLength { get; set; }
[XmlIgnore]
public bool SpaceLengthSpecified { get; set; }
[XmlAttribute("default-x")]
public decimal DefaultX { get; set; }
[XmlIgnore]
public bool DefaultXSpecified { get; set; }
[XmlAttribute("default-y")]
public decimal DefaultY { get; set; }
[XmlIgnore]
public bool DefaultYSpecified { get; set; }
[XmlAttribute("relative-x")]
public decimal RelativeX { get; set; }
[XmlIgnore]
public bool RelativeXSpecified { get; set; }
[XmlAttribute("relative-y")]
public decimal RelativeY { get; set; }
[XmlIgnore]
public bool RelativeYSpecified { get; set; }
[XmlAttribute("color", DataType = "token")]
public string Color { get; set; }
#endregion
}
}
| {
"content_hash": "ff3f830d916fd5e8d5b834dd6401ef0a",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 62,
"avg_line_length": 25.59259259259259,
"alnum_prop": 0.6015436565364206,
"repo_name": "nanase/MusicXMLUtils",
"id": "41e1db24e5ffae509387bb91742452704066172e",
"size": "3235",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MusicXMLUtils/Structure/Direction/Bracket.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "595011"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f9cc94c97ac4d0ee1ba44ac7c33d5300",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "fd6b1a9dc9bc866135f877b418e83950da401273",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Eulophia/Eulophia mumbwaensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
'use strict';
const graphql = require('graphql');
const expect = require('chai').expect;
const DB = require('../../support/db');
const SimpleType = require('../../support/types/simple');
const TestUser = require('../../support/types/user');
const TestGroup = require('../../support/types/group');
module.exports = function (Type) {
describe('@Type', function () {
describe('#constructor(rawType)', function () {
it('should only accept a POJO as parameter', function () {
expect(() => new Type('adsfa')).to.throw(TypeError, /GraysQL Error: Expected rawType to be an object/);
expect(() => new Type(x => x)).to.throw(TypeError, /GraysQL Error: Expected rawType to be an object/);
expect(() => new Type({})).to.not.throw(TypeError, /GraysQL Error: Expected rawType to be an object/);
});
});
describe('#generate(types, interfaces)', function () {
let User;
let Group;
let types;
let finalTypes;
let increaseOnParseTypeField = 1;
function onParseTypeField(payload) {
increaseOnParseTypeField += 1;
}
let increaseOnGenerateType = 1;
function onGenerateType(payload) {
increaseOnGenerateType += 1;
}
before(function () {
User = new graphql.GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: graphql.GraphQLInt },
nick: { type: graphql.GraphQLString },
group: { type: Group }
})
});
Group = new graphql.GraphQLObjectType({
name: 'Group',
fields: () => ({
id: { type: graphql.GraphQLInt },
name: { type: graphql.GraphQLString },
members: { type: new graphql.GraphQLList(User) }
})
});
types = {
User: new Type(TestUser({ options: { DB }}), { onParseTypeField: [onParseTypeField], onGenerateType: [onGenerateType] }),
Group: new Type(TestGroup({ options: { DB }})),
};
finalTypes = { User: {}, Group: {} };
finalTypes['User'] = types['User'].generate(finalTypes);
finalTypes['Group'] = types['Group'].generate(finalTypes);
});
it('should call onParseTypeField listeners', function () {
types['User'].generate(finalTypes)._typeConfig.fields();
expect(increaseOnParseTypeField).to.be.above(1);
});
it('should call onGenerateType listeners', function () {
expect(increaseOnGenerateType).to.be.above(1);
});
it('should generate a valid GraphQLObjectType', function () {
expect(finalTypes['User']).to.include.keys(Object.keys(User));
expect(finalTypes['User']._typeConfig.fields()).to.include.keys(Object.keys(User._typeConfig.fields()));
});
it('should parse args in fields', function () {
expect(finalTypes['User']._typeConfig.fields().dummy).to.include.keys(['args']);
expect(finalTypes['User']._typeConfig.fields().dummy.args).to.include.keys(['id']);
expect(finalTypes['User']._typeConfig.fields().dummy.args.id.type.name).to.equal('String');
});
it('should link to other GraphQLObjectTypes if specified', function () {
expect(finalTypes['User']._typeConfig.fields().group.type).to.equal(finalTypes['Group']);
expect(JSON.stringify(finalTypes['Group']._typeConfig.fields().members.type)).to.equal(JSON.stringify(new graphql.GraphQLList(finalTypes['User'])));
});
});
});
};
| {
"content_hash": "4f7661264cdaa29a068ee362bda35990",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 156,
"avg_line_length": 39.29213483146067,
"alnum_prop": 0.5993708893337146,
"repo_name": "larsbs/graysql",
"id": "3fa3a5a91e32f44115291911c7c8ed131373bad6",
"size": "3497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/graysql/type.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "54195"
}
],
"symlink_target": ""
} |
using namespace Lvd;
using namespace std;
using namespace TestSystem;
namespace Test {
namespace LinearEmbedding {
void AddTests1 (Directory &parent)
{
Directory &dir = parent.GetSubDirectory("linearembedding");
typedef float Scalar;
typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,1,Tenh::Generic>,Tenh::Basis_c<Tenh::Generic>> B1;
typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,2,Tenh::Generic>,Tenh::Basis_c<Tenh::Generic>> B2;
typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,3,Tenh::Generic>,Tenh::Basis_c<Tenh::Generic>> B3;
typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,4,Tenh::Generic>,Tenh::Basis_c<Tenh::Generic>> B4;
typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,5,Tenh::Generic>,Tenh::Basis_c<Tenh::Generic>> B5;
add_checks_for_two_spaces<B1,B2,double>(dir);
add_checks_for_two_spaces<B1,B3,double>(dir);
add_checks_for_two_spaces<B1,B4,double>(dir);
add_checks_for_two_spaces<B1,B5,double>(dir);
}
} // end of namespace LinearEmbedding
} // end of namespace Test
| {
"content_hash": "d66b4970eaa7fdd0df643da04a05e6b3",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 123,
"avg_line_length": 42.03703703703704,
"alnum_prop": 0.7330396475770925,
"repo_name": "leapmotion/tensorheaven",
"id": "0bb81be11f8cfe4ced1b2ed1b5931be020395279",
"size": "1425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorhell/standard/test_linearembedding1.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "1715954"
},
{
"name": "CMake",
"bytes": "8916"
},
{
"name": "Perl",
"bytes": "1898"
},
{
"name": "Shell",
"bytes": "2688"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<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>
<parent>
<groupId>org.apache.syncope.ext</groupId>
<artifactId>syncope-ext-flowable</artifactId>
<version>3.0.1-SNAPSHOT</version>
</parent>
<name>Apache Syncope Ext: Flowable REST CXF</name>
<description>Apache Syncope Ext: Flowable REST CXF</description>
<groupId>org.apache.syncope.ext.flowable</groupId>
<artifactId>syncope-ext-flowable-rest-cxf</artifactId>
<packaging>jar</packaging>
<properties>
<rootpom.basedir>${basedir}/../../..</rootpom.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.syncope.core.idm</groupId>
<artifactId>syncope-core-idm-rest-cxf</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.syncope.ext.flowable</groupId>
<artifactId>syncope-ext-flowable-rest-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.syncope.ext.flowable</groupId>
<artifactId>syncope-ext-flowable-rest-api</artifactId>
<version>${project.version}</version>
<classifier>javadoc</classifier>
</dependency>
<dependency>
<groupId>org.apache.syncope.ext.flowable</groupId>
<artifactId>syncope-ext-flowable-logic</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "5e5d0b6f55e2acb0c4c0639b031f0a20",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 204,
"avg_line_length": 36.263888888888886,
"alnum_prop": 0.7146687093067791,
"repo_name": "ilgrosso/syncope",
"id": "f3b7012e3c5be59306930483355a19afd68ee85c",
"size": "2611",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ext/flowable/rest-cxf/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1932"
},
{
"name": "Batchfile",
"bytes": "1044"
},
{
"name": "CSS",
"bytes": "44883"
},
{
"name": "Dockerfile",
"bytes": "8716"
},
{
"name": "Groovy",
"bytes": "78474"
},
{
"name": "HTML",
"bytes": "549487"
},
{
"name": "Java",
"bytes": "13523162"
},
{
"name": "JavaScript",
"bytes": "36620"
},
{
"name": "PLpgSQL",
"bytes": "20311"
},
{
"name": "SCSS",
"bytes": "65724"
},
{
"name": "Shell",
"bytes": "6231"
},
{
"name": "TSQL",
"bytes": "11632"
},
{
"name": "XSLT",
"bytes": "5158"
}
],
"symlink_target": ""
} |
package model;
public class Point {
public static final Point ZERO_ZERO = new Point(0, 0);
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point point = (Point) o;
if (x != point.x) return false;
return y == point.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
| {
"content_hash": "53c1ab8a0b9f76958358389e3e05cf19",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 58,
"avg_line_length": 17.9375,
"alnum_prop": 0.47038327526132406,
"repo_name": "patryk-imielinski/fusta",
"id": "28af19479da6d0624de1414024638a45e0d732b9",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/test/java/model/Point.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "9284"
}
],
"symlink_target": ""
} |
typedef void (^WVJBResponseCallback)(id responseData);
typedef void (^WVJBHandler)(id data, WVJBResponseCallback responseCallback);
typedef NSDictionary WVJBMessage;
@protocol WebViewJavascriptBridgeBaseDelegate <NSObject>
- (NSString*) _evaluateJavascript:(NSString*)javascriptCommand;
@end
// 提供了与js类似的一套交互的工具类
@interface WebViewJavascriptBridgeBase : NSObject
@property (assign) id <WebViewJavascriptBridgeBaseDelegate> delegate;
// 在jsbridge没有注入到HTML之前发送的消息都会保存在该队列,注入成功后会被执行,然后该队列设置为nil
@property (strong, nonatomic) NSMutableArray* startupMessageQueue;
// OC调用js之后 返回数据 应该调用的block
@property (strong, nonatomic) NSMutableDictionary* responseCallbacks;
// 注册给js使用的Handler
@property (strong, nonatomic) NSMutableDictionary* messageHandlers;
// 没有用
@property (strong, nonatomic) WVJBHandler messageHandler;
+ (void)enableLogging;
+ (void)setLogMaxLength:(int)length;
- (void)reset;
// 发送数据给js也就是OC执行js中的方法
- (void)sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName;
// 刷新js队列中的消息 即执行js对于OC的调用
- (void)flushMessageQueue:(NSString *)messageQueueString;
// 注入jsbridge
- (void)injectJavascriptFile;
// 判断js调用的scheme是否为 wvjbscheme
- (BOOL)isCorrectProcotocolScheme:(NSURL*)url;
// 判断是否为js发送的消息的url
- (BOOL)isQueueMessageURL:(NSURL*)urll;
// 判断是否为注入jsbridge的url
- (BOOL)isBridgeLoadedURL:(NSURL*)urll;
// url未知
- (void)logUnkownMessage:(NSURL*)url;
// 判断WebViewJavascriptBridge是否为object 没有地方调用
- (NSString *)webViewJavascriptCheckCommand;
// 返回获取js队列中消息的js代码 WebViewJavascriptBridge._fetchQueue();
- (NSString *)webViewJavascriptFetchQueyCommand;
@end | {
"content_hash": "078e367f9cfb98163e612eb38ee4e5e5",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 117,
"avg_line_length": 28.473684210526315,
"alnum_prop": 0.8102279728897104,
"repo_name": "mengxiangyue/MShare_Salon",
"id": "55d2d774df8ca4bb3754e0c789d8976192a734b5",
"size": "2275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "第一期:iOS专场/JS与Swift的交互/WebViewJavascriptBridge-master/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1573620"
},
{
"name": "C++",
"bytes": "98860"
},
{
"name": "HTML",
"bytes": "4975"
},
{
"name": "Java",
"bytes": "53924"
},
{
"name": "JavaScript",
"bytes": "28717"
},
{
"name": "Makefile",
"bytes": "312"
},
{
"name": "Objective-C",
"bytes": "262162"
},
{
"name": "PHP",
"bytes": "1784"
},
{
"name": "Ruby",
"bytes": "2486"
},
{
"name": "Shell",
"bytes": "319"
},
{
"name": "Swift",
"bytes": "6523"
}
],
"symlink_target": ""
} |
layout: posts
title: Api - IMeasureMap Interface
---
<div class="container container-main toggle-visibilityprivate toggle-public">
<section class="tsd-panel tsd-comment">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A map of measurements.</p>
</div>
</div>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">IMeasureMap</span>
</li>
</ul>
</section>
<section class="tsd-panel tsd-kind-interface tsd-parent-kind-namespace">
<h3 class="tsd-before-signature">Indexable</h3>
<div class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">[</span>key: <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">]: </span><a href="makerjs.imeasure.html" class="tsd-signature-type">IMeasure</a></div>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A map of measurements.</p>
</div>
</div>
</section>
</div>
<footer class="tsd-panel with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div> | {
"content_hash": "a111cabc8d7543cc4318f8e8aa9bcd13",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 258,
"avg_line_length": 60.0989010989011,
"alnum_prop": 0.7039678186140063,
"repo_name": "Microsoft/maker.js",
"id": "1ec127de87523ebbd3520ebc4198a8f7475aa5eb",
"size": "5473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/docs/api/interfaces/makerjs.imeasuremap.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1681"
},
{
"name": "HTML",
"bytes": "42070"
},
{
"name": "JavaScript",
"bytes": "106705"
},
{
"name": "TypeScript",
"bytes": "578815"
}
],
"symlink_target": ""
} |
package mr.chaining;
import static mr.chaining.support.SampleJobFactory.createGrep;
import static mr.chaining.support.SampleJobFactory.createWordCount;
import static mr.chaining.support.SampleJobFactory.randomTextWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import utils.FsUtil;
/**
yarn jar $PLAY_AREA/HadoopSamples.jar mr.chaining.SimpleLinearDriver /training/playArea/SimpleLinearDriver/
*
*/
public class SimpleLinearDriver extends Configured implements Tool {
public int run(String[] args) throws Exception {
Path workingDir = new Path(args[0]);
Configuration conf = getConf();
FileSystem fs = FileSystem.get(conf);
FsUtil.delete(fs, workingDir);
Path intermediateOutput = new Path(workingDir, "intermediate_output");
Path countOutput = new Path(workingDir, "count_result");
Path grepOutput = new Path(workingDir, "grep_result");
Job genText = randomTextWriter(conf, "job1-WriteText", intermediateOutput);
boolean status = genText.waitForCompletion(true);
if ( status ){
Job countWords = createWordCount(conf, "job2-WordCount", intermediateOutput, countOutput);
status = countWords.waitForCompletion(true);
}
if ( status ){
Job grep = createGrep(conf, "job3-Grep", intermediateOutput, grepOutput, ".*au.*");
status = grep.waitForCompletion(true);
}
FsUtil.delete(fs, intermediateOutput);
return status ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new SimpleLinearDriver(), args);
System.exit(exitCode);
}
}
| {
"content_hash": "261690cf41b3559abd2b1ec644192914",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 107,
"avg_line_length": 38.74,
"alnum_prop": 0.6974703149199794,
"repo_name": "gliptak/hadoop-course",
"id": "7461bc39dcff332f6686dbab9ececc71aa2171fa",
"size": "1937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JHU605.788/HadoopSamples/src/main/java/mr/chaining/SimpleLinearDriver.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "5246"
},
{
"name": "Java",
"bytes": "547523"
},
{
"name": "PigLatin",
"bytes": "14723"
},
{
"name": "Python",
"bytes": "1878"
},
{
"name": "Shell",
"bytes": "53003"
}
],
"symlink_target": ""
} |
'use strict';
var express = require('express');
var api = require('../../api/api');
var router = express.Router();
router.post('/', api.tictactoe);
router.post('/fourbyfour', api.fourbyfour);
module.exports = router; | {
"content_hash": "bacd030674b3ce95cb7d10cb389c74f2",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 43,
"avg_line_length": 18.416666666666668,
"alnum_prop": 0.669683257918552,
"repo_name": "nongaap/minimax",
"id": "3e4e5c229357a39c8474599d6607c57b6cbb6ff4",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/server/routes/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1224"
},
{
"name": "HTML",
"bytes": "161"
},
{
"name": "JavaScript",
"bytes": "49227"
}
],
"symlink_target": ""
} |
@extends('layouts.main')
@section('title', '基本信息 - 为生活添欢乐')
@section('styles')
{{HTML::style('css/user.setting.css')}}
@stop
@section('header_type')
navbar-fixed-top
@stop
@section('content')
<div class="col-xs-3" id="sidebar" role="navigation">
<div class="list-group">
<a href="{{URL::to('/user/setting')}}" class="list-group-item active">基本信息</a>
<a href="{{URL::to('/user/setting/icon')}}" class="list-group-item ">头像设置</a>
<a href="{{URL::to('/user/setting/security')}}" class="list-group-item">账号安全</a>
</div>
</div>
<!--/span-->
<div class="col-xs-9">
<h3>基本信息</h3>
<div>
<form role="form" class="settingfrm" id="basicForm" action="{{URL::to('/user/basic/save')}}" method="post">
<div class="form-group">
<label for="inputName">尊称</label>
<input type="text" class="form-control" name="username" id="username" value="{{Auth::user()->name}}" placeholder="尊称" disabled />
<!-- <span class="help-block">建议使用实名、或您常用的昵称注册</span>-->
</div>
<div class="form-group">
<label for="inputEmail1">一句话介绍</label>
<textarea class="form-control" rows="3" name="introduction" id="introduction" placeholder="让人们认识你">{{Auth::user()->introduction}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
@stop
@section('container-bottom')
@include('includes/cfooter')
@stop
@section('scripts')
<script type="text/javascript">
$(function(){
$("#basicForm").validate({
rules: {
username: {
required: true
},
introduction: {
maxlength: 200
}
},
messages:{
username:{
required:'用户名不能为空'
},
introduction:{
maxlength:'自我介绍不能超过200个字'
}
}
});
});
</script>
@if(Session::get('message'))
<script type="text/javascript">
noty({
text : "{{Session::get('message')}}",
type : "information",
dismissQueue: true,
killer: true,
layout : 'topCenter',
theme : 'defaultTheme',
timeout: 2000
});
</script>
@endif
@stop | {
"content_hash": "7ef1172615a1e21332b31a8f7718b0f1",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 156,
"avg_line_length": 30.012048192771083,
"alnum_prop": 0.49779205138498595,
"repo_name": "kimhwawoon/xiaoxiao",
"id": "022b71b000d5aa67fa62e176b7acc387bcd13e71",
"size": "2643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/user/setting/basic.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20521"
},
{
"name": "JavaScript",
"bytes": "215723"
},
{
"name": "PHP",
"bytes": "185145"
}
],
"symlink_target": ""
} |
<?php
$docPath = realpath(getcwd() . '/doc');
$rdi = new RecursiveDirectoryIterator($docPath . '/html');
$rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST);
$files = new RegexIterator($rii, '/\.html$/', RecursiveRegexIterator::GET_MATCH);
$process = function () use ($files) {
$fileInfo = $files->getInnerIterator()->current();
if (! $fileInfo->isFile()) {
return true;
}
if ($fileInfo->getBasename('.html') === $fileInfo->getBasename()) {
return true;
}
$file = $fileInfo->getRealPath();
$html = file_get_contents($file);
if (! preg_match('#<p><img alt="[^"]*" src="[^"]+" \/><\/p>#s', $html)) {
return true;
}
$html = preg_replace(
'#(<p><img alt="[^"]*" src="[^"]+" )(\/><\/p>)#s',
'$1class="img-responsive"$2',
$html
);
file_put_contents($file, $html);
return true;
};
iterator_apply($files, $process);
| {
"content_hash": "24060e1409f2183740cf5518937b49c0",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 82,
"avg_line_length": 27.02857142857143,
"alnum_prop": 0.5570824524312896,
"repo_name": "weierophinney/zf-mkdoc-theme",
"id": "210dd60d96aee8b820ac1fe4054a57cd2013cedf",
"size": "1177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "img_responsive.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34629"
},
{
"name": "HTML",
"bytes": "11796"
},
{
"name": "JavaScript",
"bytes": "300"
},
{
"name": "PHP",
"bytes": "1730"
},
{
"name": "Shell",
"bytes": "2689"
}
],
"symlink_target": ""
} |
package mockit;
import java.io.*;
import java.net.*;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
import mockit.internal.*;
public final class ExpectationsTest
{
static class Collaborator
{
private int value;
Collaborator() {}
Collaborator(int value) { this.value = value; }
private static String doInternal() { return "123"; }
void provideSomeService() {}
String doSomething(URL url) { return url.toString(); }
int getValue() { return value; }
void setValue(int value) { this.value = value; }
}
@Test(expected = UnexpectedInvocation.class)
public void expectOnlyOneInvocationOnLocalMockedTypeButExerciseOthersDuringReplay()
{
Collaborator collaborator = new Collaborator();
new Expectations() {
Collaborator mock;
{
mock.provideSomeService();
}
};
collaborator.provideSomeService();
collaborator.setValue(1);
}
@Test(expected = UnexpectedInvocation.class)
public void expectOnlyOneInvocationOnTestScopedMockedTypeButExerciseOthersDuringReplay(final Collaborator mock)
{
new Expectations() {{ mock.provideSomeService(); }};
mock.provideSomeService();
mock.setValue(1);
}
@Test
public void recordNothingOnLocalMockedTypeAndExerciseItDuringReplay()
{
Collaborator collaborator = new Collaborator();
new Expectations() { @Mocked Collaborator mock; };
collaborator.provideSomeService();
}
@Test
public void recordNothingOnTestScopedMockedTypeAndExerciseItDuringReplay(Collaborator mock)
{
new Expectations() {};
mock.provideSomeService();
}
@Test(expected = UnexpectedInvocation.class)
public void expectNothingOnLocalMockedTypeButExerciseItDuringReplay()
{
Collaborator collaborator = new Collaborator();
new Expectations() {
Collaborator mock;
{
mock.provideSomeService(); times = 0;
}
};
collaborator.setValue(2);
}
@Test(expected = UnexpectedInvocation.class)
public void expectNothingOnTestScopedMockedTypeButExerciseItDuringReplay(final Collaborator mock)
{
new Expectations() {{
mock.setValue(anyInt); times = 0;
}};
mock.setValue(2);
}
@Test
public void mockInterface(final Runnable mock)
{
new Expectations() {{ mock.run(); }};
mock.run();
}
public interface IA {}
public interface IB extends IA {}
public interface IC { boolean doSomething(IB b); }
@Test
public void mockInterfaceWhichExtendsAnother(final IB b, final IC c)
{
new Expectations() {{
c.doSomething(b); result = false;
invoke(c, "doSomething", b); result = true;
}};
assertFalse(c.doSomething(b));
assertTrue(c.doSomething(b));
}
public abstract static class AbstractCollaborator
{
String doSomethingConcrete() { return "test"; }
protected abstract void doSomethingAbstract();
}
@Test
public void mockAbstractClass(final AbstractCollaborator mock)
{
new Expectations() {{
mock.doSomethingConcrete();
mock.doSomethingAbstract();
}};
mock.doSomethingConcrete();
mock.doSomethingAbstract();
}
@Test
public void mockFinalField()
{
new Expectations() {
final Collaborator mock = new Collaborator();
{
mock.getValue();
}
};
new Collaborator().getValue();
}
@Test
public void mockClassWithoutDefaultConstructor()
{
new Expectations() { @Mocked Dummy mock; };
}
static class Dummy
{
@SuppressWarnings("UnusedDeclaration")
Dummy(int i) {}
}
static final class SubCollaborator extends Collaborator
{
@Override int getValue() { return 1 + super.getValue(); }
int getValue(int i) { return i + super.getValue(); }
}
@Test
public void mockSubclass()
{
new Expectations() {
final SubCollaborator mock = new SubCollaborator();
{
mock.provideSomeService();
mock.getValue(); result = 1;
}
};
SubCollaborator collaborator = new SubCollaborator();
collaborator.provideSomeService();
assertEquals(1, collaborator.getValue());
}
@Test
public void mockSuperClassUsingLocalMockField()
{
new Expectations() {
Collaborator mock;
{
mock.getValue(); result = 1;
mock.getValue(); result = 2;
}
};
SubCollaborator collaborator = new SubCollaborator();
assertEquals(2, collaborator.getValue());
assertEquals(3, collaborator.getValue(1));
}
@Test
public void mockSuperClassUsingMockParameter(@NonStrict final Collaborator mock)
{
new Expectations() {{
mock.getValue(); times = 2; returns(1, 2);
}};
SubCollaborator collaborator = new SubCollaborator();
assertEquals(2, collaborator.getValue());
assertEquals(3, collaborator.getValue(1));
}
@Test(expected = IllegalStateException.class)
public void attemptToRecordExpectedReturnValueForNoCurrentInvocation()
{
new Expectations() {
@Mocked Collaborator mock;
{
result = 42;
}
};
}
@Test(expected = IllegalStateException.class)
public void attemptToAddArgumentMatcherWhenNotRecording()
{
new Expectations() {
@Mocked Collaborator mock;
}.withNotEqual(5);
}
@Test
public void mockClassWithMethodsOfAllReturnTypesReturningDefaultValues()
{
ClassWithMethodsOfEveryReturnType realObject = new ClassWithMethodsOfEveryReturnType();
new Expectations() {
ClassWithMethodsOfEveryReturnType mock;
{
mock.getBoolean();
mock.getChar();
mock.getByte();
mock.getShort();
mock.getInt();
mock.getLong();
mock.getFloat();
mock.getDouble();
mock.getObject();
mock.getElements();
}
};
assertFalse(realObject.getBoolean());
assertEquals('\0', realObject.getChar());
assertEquals(0, realObject.getByte());
assertEquals(0, realObject.getShort());
assertEquals(0, realObject.getInt());
assertEquals(0L, realObject.getLong());
assertEquals(0.0, realObject.getFloat(), 0.0);
assertEquals(0.0, realObject.getDouble(), 0.0);
assertNull(realObject.getObject());
assertFalse(realObject.getElements().hasMoreElements());
}
static class ClassWithMethodsOfEveryReturnType
{
boolean getBoolean() { return true; }
char getChar() { return 'A' ; }
byte getByte() { return 1; }
short getShort() { return 1; }
int getInt() { return 1; }
long getLong() { return 1; }
float getFloat() { return 1.0F; }
double getDouble() { return 1.0; }
Object getObject() { return new Object(); }
Enumeration<?> getElements() { return null; }
}
@Test(expected = UnexpectedInvocation.class)
public void replayWithUnexpectedStaticMethodInvocation()
{
new Expectations() {
Collaborator mock;
{
mock.getValue();
}
};
Collaborator.doInternal();
}
@Test(expected = MissingInvocation.class)
public void replayWithMissingExpectedMethodInvocation()
{
new Expectations() {
Collaborator mock;
{
mock.setValue(123);
}
};
}
@Test
public void defineTwoConsecutiveReturnValues(final Collaborator mock)
{
new Expectations() {{
mock.getValue(); result = 1; result = 2;
}};
assertEquals(1, mock.getValue());
assertEquals(2, mock.getValue());
}
@Test // Note: this test only works under JDK 1.6+; JDK 1.5 does not support redefining natives.
public void mockNativeMethod()
{
new Expectations() {
@Mocked final System system = null;
{
System.nanoTime(); result = 0L;
}
};
assertEquals(0, System.nanoTime());
}
@Test
public void mockSystemGetenvMethod()
{
new Expectations() {
@Mocked System mockedSystem;
{
System.getenv("envVar"); result = ".";
}
};
assertEquals(".", System.getenv("envVar"));
}
@Test
public void mockConstructorsInJREClassHierarchies() throws Exception
{
new Expectations() {
final FileWriter fileWriter;
@Mocked PrintWriter printWriter;
{
fileWriter = new FileWriter("no.file");
}
};
new FileWriter("no.file");
}
@Test(expected = UnexpectedInvocation.class)
public void failureFromUnexpectedInvocationInAnotherThread() throws Exception
{
final Collaborator collaborator = new Collaborator();
Thread t = new Thread() {
@Override
public void run() { collaborator.provideSomeService(); }
};
new Expectations() {
Collaborator mock;
{
mock.getValue();
}
};
collaborator.getValue();
t.start();
t.join();
}
public interface InterfaceWithStaticInitializer { Object X = "x"; }
@Test
public void mockInterfaceWithStaticInitializer(InterfaceWithStaticInitializer mock)
{
assertNotNull(mock);
assertEquals("x", InterfaceWithStaticInitializer.X);
}
@Test
public void recordStrictExpectationsAllowingZeroInvocationsAndReplayNone(final Collaborator mock)
{
new Expectations() {{
mock.provideSomeService(); minTimes = 0;
mock.setValue(1); minTimes = 0;
}};
// Don't exercise anything.
}
@Test
public void recordingExpectationOnMethodWithOneArgumentButReplayingWithAnotherShouldProduceUsefulErrorMessage(
final Collaborator mock) throws Exception
{
final URL expectedURL = new URL("http://expected");
new Expectations() {{ mock.doSomething(expectedURL); }};
mock.doSomething(expectedURL);
URL anotherURL = new URL("http://another");
try {
mock.doSomething(anotherURL);
fail();
}
catch (UnexpectedInvocation e) {
assertTrue(e.getMessage().contains(anotherURL.toString()));
}
}
@Test
public void recordExpectationInMethodOfExpectationBlockInsteadOfConstructor(@Mocked final Collaborator mock)
{
new Expectations() {
{
recordExpectation();
}
private void recordExpectation()
{
mock.getValue();
result = 123;
}
};
assertEquals(123, mock.getValue());
}
}
| {
"content_hash": "1719bdfc79ebf25f8fca9c79352b7de1",
"timestamp": "",
"source": "github",
"line_count": 451,
"max_line_length": 114,
"avg_line_length": 25.024390243902438,
"alnum_prop": 0.5904660641502747,
"repo_name": "royosherove/javatdddemo",
"id": "f01e9cc31310d3c4135b6b93d9972c538ca666c0",
"size": "11417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/jmockit/main/test/mockit/ExpectationsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22995"
},
{
"name": "Java",
"bytes": "3164211"
},
{
"name": "JavaScript",
"bytes": "7998"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Lichen dispersus Pers.
### Remarks
null | {
"content_hash": "82e7891b69e00de90b065d088e811440",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 22,
"avg_line_length": 9.76923076923077,
"alnum_prop": 0.7007874015748031,
"repo_name": "mdoering/backbone",
"id": "6e0154a7bdf2ae78e3e1a0990a93c2f701b3a3ec",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Eurotiomycetes/Verrucariales/Verrucariaceae/Verrucaria/Verrucaria dispersa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/* InventarisatiesVerslag Fixture generated on: 2011-04-15 15:04:13 : 1302873493 */
class InventarisatiesVerslagFixture extends CakeTestFixture
{
public $name = 'InventarisatiesVerslag';
public $table = 'inventarisaties_verslagen';
public $import = array(
'model' => 'InventarisatiesVerslag',
'records' => true,
'table' => 'inventarisaties_verslagen',
);
}
| {
"content_hash": "471e149a87321f1743ca1a104addbf25",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 83,
"avg_line_length": 32,
"alnum_prop": 0.6586538461538461,
"repo_name": "accelcloud/ecd",
"id": "2a764163aa7c318759daf2d48d06357f56884ab9",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/tests/fixtures/inventarisaties_verslag_fixture.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "821"
},
{
"name": "Batchfile",
"bytes": "1013"
},
{
"name": "CSS",
"bytes": "50508"
},
{
"name": "JavaScript",
"bytes": "144685"
},
{
"name": "PHP",
"bytes": "9465186"
},
{
"name": "Python",
"bytes": "3979"
},
{
"name": "Shell",
"bytes": "3551"
}
],
"symlink_target": ""
} |
<Type Name="QTCaptureInput" FullName="MonoMac.QTKit.QTCaptureInput">
<TypeSignature Language="C#" Value="public class QTCaptureInput : MonoMac.Foundation.NSObject" />
<TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit QTCaptureInput extends MonoMac.Foundation.NSObject" />
<AssemblyInfo>
<AssemblyName>MonoMac</AssemblyName>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Base>
<BaseTypeName>MonoMac.Foundation.NSObject</BaseTypeName>
</Base>
<Interfaces />
<Attributes>
<Attribute>
<AttributeName>MonoMac.Foundation.Register("QTCaptureInput", true)</AttributeName>
</Attribute>
</Attributes>
<Docs>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
</Docs>
<Members>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public QTCaptureInput (MonoMac.Foundation.NSCoder coder);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.Foundation.NSCoder coder) cil managed" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>MonoMac.Foundation.Export("initWithCoder:")</AttributeName>
</Attribute>
<Attribute>
<AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
</Attribute>
</Attributes>
<Parameters>
<Parameter Name="coder" Type="MonoMac.Foundation.NSCoder" />
</Parameters>
<Docs>
<param name="coder">The unarchiver object.</param>
<summary>A constructor that initializes the object from the data stored in the unarchiver object.</summary>
<remarks>This constructor is provided to allow the class to be initialized from an unarchiver (for example, during NIB deserialization).</remarks>
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public QTCaptureInput (MonoMac.Foundation.NSObjectFlag t);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.Foundation.NSObjectFlag t) cil managed" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
</Attribute>
</Attributes>
<Parameters>
<Parameter Name="t" Type="MonoMac.Foundation.NSObjectFlag" />
</Parameters>
<Docs>
<param name="t">Unused sentinel value, pass NSObjectFlag.Empty.</param>
<summary>Constructor to call on derived classes when the derived class has an [Export] constructor.</summary>
<remarks>
<para>This constructor should be called by derived classes when they are initialized using an [Export] attribute. The argument value is ignore, typically the chaining would look like this:</para>
<example>
<code lang="C#">
public class MyClass : BaseClass {
[Export ("initWithFoo:")]
public MyClass (string foo) : base (NSObjectFlag.Empty)
{
...
}
</code>
</example>
</remarks>
</Docs>
</Member>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="public QTCaptureInput (IntPtr handle);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int handle) cil managed" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
</Attribute>
</Attributes>
<Parameters>
<Parameter Name="handle" Type="System.IntPtr" />
</Parameters>
<Docs>
<param name="handle">Pointer (handle) to the unmanaged object.</param>
<summary>A constructor used when creating managed representations of unmanaged objects; Called by the runtime.</summary>
<remarks>
<para>This constructor is invoked by the runtime infrastructure (<see cref="M:MonoMac.ObjCRuntime.GetNSObject (System.IntPtr)" />) to create a new managed representation for a pointer to an unmanaged Objective-C object. You should not invoke this method directly, instead you should call the GetNSObject method as it will prevent two instances of a managed object to point to the same native object.</para>
</remarks>
</Docs>
</Member>
<Member MemberName="ClassHandle">
<MemberSignature Language="C#" Value="public override IntPtr ClassHandle { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance native int ClassHandle" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.IntPtr</ReturnType>
</ReturnValue>
<Docs>
<summary>The handle for this class.</summary>
<value>The pointer to the Objective-C class.</value>
<remarks>Each MonoMac class mirrors an unmanaged Objective-C class. This value contains the pointer to the Objective-C class, it is similar to calling objc_getClass with the object name.</remarks>
</Docs>
</Member>
<Member MemberName="Connections">
<MemberSignature Language="C#" Value="public virtual MonoMac.QTKit.QTCaptureConnection[] Connections { get; }" />
<MemberSignature Language="ILAsm" Value=".property instance class MonoMac.QTKit.QTCaptureConnection[] Connections" />
<MemberType>Property</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute>
<AttributeName>get: MonoMac.Foundation.Export("connections")</AttributeName>
</Attribute>
</Attributes>
<ReturnValue>
<ReturnType>MonoMac.QTKit.QTCaptureConnection[]</ReturnType>
</ReturnValue>
<Docs>
<summary>To be added.</summary>
<value>To be added.</value>
<remarks>To be added.</remarks>
</Docs>
</Member>
<Member MemberName="Dispose">
<MemberSignature Language="C#" Value="protected override void Dispose (bool disposing);" />
<MemberSignature Language="ILAsm" Value=".method familyhidebysig virtual instance void Dispose(bool disposing) cil managed" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Void</ReturnType>
</ReturnValue>
<Parameters>
<Parameter Name="disposing" Type="System.Boolean" />
</Parameters>
<Docs>
<param name="disposing">
<para>If set to <see langword="true" />, the method is invoked directly and will dispose manage and unmanaged resources; If set to <see langword="false" /> the method is being called by the garbage collector finalizer and should only release unmanaged resources.</para>
</param>
<summary>Releases the resources used by the QTCaptureInput object.</summary>
<remarks>
<para>This Dispose method releases the resources used by the QTCaptureInput class.</para>
<para>This method is called by both the Dispose() method and the object finalizer (Finalize). When invoked by the Dispose method, the parameter disposting <paramref name="disposing" /> is set to <see langword="true" /> and any managed object references that this object holds are also disposed or released; when invoked by the object finalizer, on the finalizer thread the value is set to <see langword="false" />. </para>
<para>Calling the Dispose method when you are finished using the QTCaptureInput ensures that all external resources used by this managed object are released as soon as possible. Once you have invoked the Dispose method, the object is no longer useful and you should no longer make any calls to it.</para>
<para> For more information on how to override this method and on the Dispose/IDisposable pattern, read the ``Implementing a Dispose Method'' document at http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx</para>
</remarks>
</Docs>
</Member>
</Members>
</Type>
| {
"content_hash": "97f0944e9b8904636ca3f8d843d03089",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 436,
"avg_line_length": 52.93975903614458,
"alnum_prop": 0.6902594446973145,
"repo_name": "dlech/monomac",
"id": "a8ed1f8650752d0e38d48f06e6a6fdcb4a1fb3da",
"size": "8788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/en/MonoMac.QTKit/QTCaptureInput.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "8653888"
},
{
"name": "Makefile",
"bytes": "8973"
}
],
"symlink_target": ""
} |
// # label component
/*
Just the label for a field.
*/
'use strict';
import createReactClass from 'create-react-class';
import cx from 'classnames';
import HelperMixin from '@/src/mixins/helper';
/** @jsx jsx */
import jsx from '@/src/jsx';
export default createReactClass({
displayName: 'Label',
mixins: [HelperMixin],
render: function() {
return this.renderWithConfig();
},
renderDefault: function() {
const config = this.props.config;
const field = this.props.field;
const fieldLabel = config.fieldLabel(field);
const requiredLabel = config.createElement('required-label', {
typeName: this.props.typeName,
config,
field,
});
let label = null;
if (typeof this.props.index === 'number') {
label = '' + (this.props.index + 1) + '.';
if (fieldLabel) {
label = label + ' ' + fieldLabel;
}
}
if (fieldLabel || label) {
let text = label || fieldLabel;
if (this.props.onClick) {
text = (
<a
href={'JavaScript' + ':'}
onClick={this.props.onClick}
renderWith={this.renderWith('LabelLink')}
>
{text}
</a>
);
}
label = (
<label
htmlFor={this.props.id}
id={this.props.id ? `${this.props.id}_label` : undefined}
renderWith={this.renderWith('LabelText')}
>
{text}
</label>
);
}
return (
<div
className={cx(this.props.classes)}
renderWith={this.renderWith('Label')}
>
{label} {requiredLabel}
</div>
);
},
});
| {
"content_hash": "94bb48746fb69d42b5a430e7c516a99d",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 67,
"avg_line_length": 20.6125,
"alnum_prop": 0.537901758641601,
"repo_name": "zapier/formatic",
"id": "288537fd00165754458aff2ac409e821ff5d92a0",
"size": "1649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/helpers/label.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5435"
},
{
"name": "JavaScript",
"bytes": "257804"
}
],
"symlink_target": ""
} |
import React, { PureComponent } from 'react';
import classNames from 'classnames';
import AudioPlayer from '../../AudioPlayer/AudioPlayer';
import styles from './Voice.css';
export type Props = {
className?: string,
duration: number,
fileUrl: ?string,
isUploading: boolean,
maxWidth: number
};
class Voice extends PureComponent {
props: Props;
render() {
const { isUploading, maxWidth } = this.props;
const className = classNames(styles.container, {
[styles.uploading]: isUploading
}, this.props.className);
return (
<div className={className} style={{ width: maxWidth }}>
<AudioPlayer
src={this.props.fileUrl}
duration={this.props.duration}
pending={this.props.isUploading}
/>
</div>
);
}
}
export default Voice;
| {
"content_hash": "a91275da948e3e7313f2d03a517133ab",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 61,
"avg_line_length": 22.18918918918919,
"alnum_prop": 0.6443361753958587,
"repo_name": "nolawi/champs-dialog-sg",
"id": "950f53d17bd7e7f949a6e723b292cbca7ca93985",
"size": "880",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/MessageContent/Voice/Voice.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "208925"
},
{
"name": "JavaScript",
"bytes": "472063"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.