text
stringlengths
2
99.9k
meta
dict
/* * Copyright (C) 2020 The Android Open Source Project * * 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 com.android.systemui.controls.management import android.content.ComponentName import android.graphics.Rect import android.os.Bundle import android.service.controls.Control import android.service.controls.DeviceTypes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.accessibility.AccessibilityNodeInfo import android.widget.CheckBox import android.widget.ImageView import android.widget.Switch import android.widget.TextView import androidx.core.view.AccessibilityDelegateCompat import androidx.core.view.ViewCompat import androidx.core.view.accessibility.AccessibilityNodeInfoCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.systemui.R import com.android.systemui.controls.ControlInterface import com.android.systemui.controls.ui.RenderInfo private typealias ModelFavoriteChanger = (String, Boolean) -> Unit /** * Adapter for binding [Control] information to views. * * The model for this adapter is provided by a [ControlModel] that is set using * [changeFavoritesModel]. This allows for updating the model if there's a reload. * * @property elevation elevation of each control view */ class ControlAdapter( private val elevation: Float ) : RecyclerView.Adapter<Holder>() { companion object { const val TYPE_ZONE = 0 const val TYPE_CONTROL = 1 const val TYPE_DIVIDER = 2 } val spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (getItemViewType(position) != TYPE_CONTROL) 2 else 1 } } private var model: ControlsModel? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val layoutInflater = LayoutInflater.from(parent.context) return when (viewType) { TYPE_CONTROL -> { ControlHolder( layoutInflater.inflate(R.layout.controls_base_item, parent, false).apply { layoutParams.apply { width = ViewGroup.LayoutParams.MATCH_PARENT } elevation = this@ControlAdapter.elevation background = parent.context.getDrawable( R.drawable.control_background_ripple) }, model?.moveHelper // Indicates that position information is needed ) { id, favorite -> model?.changeFavoriteStatus(id, favorite) } } TYPE_ZONE -> { ZoneHolder(layoutInflater.inflate(R.layout.controls_zone_header, parent, false)) } TYPE_DIVIDER -> { DividerHolder(layoutInflater.inflate( R.layout.controls_horizontal_divider_with_empty, parent, false)) } else -> throw IllegalStateException("Wrong viewType: $viewType") } } fun changeModel(model: ControlsModel) { this.model = model notifyDataSetChanged() } override fun getItemCount() = model?.elements?.size ?: 0 override fun onBindViewHolder(holder: Holder, index: Int) { model?.let { holder.bindData(it.elements[index]) } } override fun onBindViewHolder(holder: Holder, position: Int, payloads: MutableList<Any>) { if (payloads.isEmpty()) { super.onBindViewHolder(holder, position, payloads) } else { model?.let { val el = it.elements[position] if (el is ControlInterface) { holder.updateFavorite(el.favorite) } } } } override fun getItemViewType(position: Int): Int { model?.let { return when (it.elements.get(position)) { is ZoneNameWrapper -> TYPE_ZONE is ControlStatusWrapper -> TYPE_CONTROL is ControlInfoWrapper -> TYPE_CONTROL is DividerWrapper -> TYPE_DIVIDER } } ?: throw IllegalStateException("Getting item type for null model") } } /** * Holder for binding views in the [RecyclerView]- * @param view the [View] for this [Holder] */ sealed class Holder(view: View) : RecyclerView.ViewHolder(view) { /** * Bind the data from the model into the view */ abstract fun bindData(wrapper: ElementWrapper) open fun updateFavorite(favorite: Boolean) {} } /** * Holder for using with [DividerWrapper] to display a divider between zones. * * The divider can be shown or hidden. It also has a view the height of a control, that can * be toggled visible or gone. */ private class DividerHolder(view: View) : Holder(view) { private val frame: View = itemView.requireViewById(R.id.frame) private val divider: View = itemView.requireViewById(R.id.divider) override fun bindData(wrapper: ElementWrapper) { wrapper as DividerWrapper frame.visibility = if (wrapper.showNone) View.VISIBLE else View.GONE divider.visibility = if (wrapper.showDivider) View.VISIBLE else View.GONE } } /** * Holder for using with [ZoneNameWrapper] to display names of zones. */ private class ZoneHolder(view: View) : Holder(view) { private val zone: TextView = itemView as TextView override fun bindData(wrapper: ElementWrapper) { wrapper as ZoneNameWrapper zone.text = wrapper.zoneName } } /** * Holder for using with [ControlStatusWrapper] to display names of zones. * @param moveHelper a helper interface to facilitate a11y rearranging. Null indicates no * rearranging * @param favoriteCallback this callback will be called whenever the favorite state of the * [Control] this view represents changes. */ internal class ControlHolder( view: View, val moveHelper: ControlsModel.MoveHelper?, val favoriteCallback: ModelFavoriteChanger ) : Holder(view) { private val favoriteStateDescription = itemView.context.getString(R.string.accessibility_control_favorite) private val notFavoriteStateDescription = itemView.context.getString(R.string.accessibility_control_not_favorite) private val icon: ImageView = itemView.requireViewById(R.id.icon) private val title: TextView = itemView.requireViewById(R.id.title) private val subtitle: TextView = itemView.requireViewById(R.id.subtitle) private val removed: TextView = itemView.requireViewById(R.id.status) private val favorite: CheckBox = itemView.requireViewById<CheckBox>(R.id.favorite).apply { visibility = View.VISIBLE } private val accessibilityDelegate = ControlHolderAccessibilityDelegate( this::stateDescription, this::getLayoutPosition, moveHelper ) init { ViewCompat.setAccessibilityDelegate(itemView, accessibilityDelegate) } // Determine the stateDescription based on favorite state and maybe position private fun stateDescription(favorite: Boolean): CharSequence? { if (!favorite) { return notFavoriteStateDescription } else if (moveHelper == null) { return favoriteStateDescription } else { val position = layoutPosition + 1 return itemView.context.getString( R.string.accessibility_control_favorite_position, position) } } override fun bindData(wrapper: ElementWrapper) { wrapper as ControlInterface val renderInfo = getRenderInfo(wrapper.component, wrapper.deviceType) title.text = wrapper.title subtitle.text = wrapper.subtitle updateFavorite(wrapper.favorite) removed.text = if (wrapper.removed) { itemView.context.getText(R.string.controls_removed) } else { "" } itemView.setOnClickListener { updateFavorite(!favorite.isChecked) favoriteCallback(wrapper.controlId, favorite.isChecked) } applyRenderInfo(renderInfo, wrapper) } override fun updateFavorite(favorite: Boolean) { this.favorite.isChecked = favorite accessibilityDelegate.isFavorite = favorite itemView.stateDescription = stateDescription(favorite) } private fun getRenderInfo( component: ComponentName, @DeviceTypes.DeviceType deviceType: Int ): RenderInfo { return RenderInfo.lookup(itemView.context, component, deviceType) } private fun applyRenderInfo(ri: RenderInfo, ci: ControlInterface) { val context = itemView.context val fg = context.getResources().getColorStateList(ri.foreground, context.getTheme()) ci.customIcon?.let { icon.setImageIcon(it) } ?: run { icon.setImageDrawable(ri.icon) // Do not color app icons if (ci.deviceType != DeviceTypes.TYPE_ROUTINE) { icon.setImageTintList(fg) } } } } /** * Accessibility delegate for [ControlHolder]. * * Provides the following functionality: * * Sets the state description indicating whether the controls is Favorited or Unfavorited * * Adds the position to the state description if necessary. * * Adds context action for moving (rearranging) a control. * * @param stateRetriever function to determine the state description based on the favorite state * @param positionRetriever function to obtain the position of this control. It only has to be * correct in controls that are currently favorites (and therefore can * be moved). * @param moveHelper helper interface to determine if a control can be moved and actually move it. */ private class ControlHolderAccessibilityDelegate( val stateRetriever: (Boolean) -> CharSequence?, val positionRetriever: () -> Int, val moveHelper: ControlsModel.MoveHelper? ) : AccessibilityDelegateCompat() { var isFavorite = false companion object { private val MOVE_BEFORE_ID = R.id.accessibility_action_controls_move_before private val MOVE_AFTER_ID = R.id.accessibility_action_controls_move_after } override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfoCompat) { super.onInitializeAccessibilityNodeInfo(host, info) info.isContextClickable = false addClickAction(host, info) maybeAddMoveBeforeAction(host, info) maybeAddMoveAfterAction(host, info) // Determine the stateDescription based on the holder information info.stateDescription = stateRetriever(isFavorite) // Remove the information at the end indicating row and column. info.setCollectionItemInfo(null) info.className = Switch::class.java.name } override fun performAccessibilityAction(host: View?, action: Int, args: Bundle?): Boolean { if (super.performAccessibilityAction(host, action, args)) { return true } return when (action) { MOVE_BEFORE_ID -> { moveHelper?.moveBefore(positionRetriever()) true } MOVE_AFTER_ID -> { moveHelper?.moveAfter(positionRetriever()) true } else -> false } } private fun addClickAction(host: View, info: AccessibilityNodeInfoCompat) { // Change the text for the double-tap action val clickActionString = if (isFavorite) { host.context.getString(R.string.accessibility_control_change_unfavorite) } else { host.context.getString(R.string.accessibility_control_change_favorite) } val click = AccessibilityNodeInfoCompat.AccessibilityActionCompat( AccessibilityNodeInfo.ACTION_CLICK, // “favorite/unfavorite” clickActionString) info.addAction(click) } private fun maybeAddMoveBeforeAction(host: View, info: AccessibilityNodeInfoCompat) { if (moveHelper?.canMoveBefore(positionRetriever()) ?: false) { val newPosition = positionRetriever() + 1 - 1 val moveBefore = AccessibilityNodeInfoCompat.AccessibilityActionCompat( MOVE_BEFORE_ID, host.context.getString(R.string.accessibility_control_move, newPosition) ) info.addAction(moveBefore) info.isContextClickable = true } } private fun maybeAddMoveAfterAction(host: View, info: AccessibilityNodeInfoCompat) { if (moveHelper?.canMoveAfter(positionRetriever()) ?: false) { val newPosition = positionRetriever() + 1 + 1 val moveAfter = AccessibilityNodeInfoCompat.AccessibilityActionCompat( MOVE_AFTER_ID, host.context.getString(R.string.accessibility_control_move, newPosition) ) info.addAction(moveAfter) info.isContextClickable = true } } } class MarginItemDecorator( private val topMargin: Int, private val sideMargins: Int ) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val position = parent.getChildAdapterPosition(view) if (position == RecyclerView.NO_POSITION) return val type = parent.adapter?.getItemViewType(position) if (type == ControlAdapter.TYPE_CONTROL) { outRect.apply { top = topMargin left = sideMargins right = sideMargins bottom = 0 } } else if (type == ControlAdapter.TYPE_ZONE && position == 0) { // add negative padding to the first zone to counteract the margin val margin = (view.layoutParams as ViewGroup.MarginLayoutParams).topMargin outRect.apply { top = -margin left = 0 right = 0 bottom = 0 } } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- /* * Copyright 2020, The Android Open Source Project * * 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. */ --> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@android:color/transparent"/> <corners android:radius="@dimen/control_corner_radius" /> </shape>
{ "pile_set_name": "Github" }
pic10f200 pic10f202 pic10f204 pic10f220 pic10f222 pic12c508 pic12c509 pic12ce518 pic12ce519 pic12f508 pic12f509 pic12f510 pic12f629 pic12f675 pic12f683 pic12f1822 pic16c54 pic16c55 pic16c56 pic16c61 pic16c62 pic16c62a pic16cr62 pic16c63 pic16c64 pic16c65 pic16c65a pic16c71 pic16c712 pic16c716 pic16c72 pic16c73 pic16c74 pic16c84 pic16cr83 pic16cr84 pic16f73 pic16f74 pic16f83 pic16f84 pic16f87 pic16f88 pic16f882 pic16f883 pic16f884 pic16f886 pic16f887 pic16f627 pic16f627a pic16f628 pic16f628a pic16f630 pic16f631 pic16f648 pic16f648a pic16f676 pic16f677 pic16f684 pic16f685 pic16f687 pic16f689 pic16f690 pic16f818 pic16f819 pic16f871 pic16f873 pic16f874 pic16f876 pic16f877 pic16f873a pic16f874a pic16f876a pic16f877a pic16f1823 pic18c242 pic18c252 pic18c442 pic18c452 pic18f242 pic18f248 pic18f252 pic18f442 pic18f448 pic18f452 pic18f1220 pic18f1320 pic18f2221 pic18f2321 pic18f2420 pic18f2520 pic18f2455 pic18f4221 pic18f4321 pic18f4420 pic18f4520 pic18f4455 pic18f4620 pic18f6520
{ "pile_set_name": "Github" }
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ // Pocket Gems Google Uber Facebook // Hide Tags Depth-first Search Breadth-first Search Graph // Hide Similar Problems (H) Copy List with Random Pointer /** * Definition for undirected graph. * function UndirectedGraphNode(label) { * this.label = label; * this.neighbors = []; // Array of UndirectedGraphNode * } */ /** * @param {UndirectedGraphNode} graph * @return {UndirectedGraphNode} */ var cloneGraph = function(graph) { var visited = {}; if(graph === null){ return graph; }else{ return dfs(graph); } function dfs(node){ var newNode = visited[node.label] ? visited[node.label] : new UndirectedGraphNode(node.label); visited[node.label] = newNode; for(var i = 0; i < node.neighbors.length; i++){ var newNeighbor = visited[node.neighbors[i].label] ? visited[node.neighbors[i].label] : dfs(node.neighbors[i]); newNode.neighbors.push(newNeighbor); } return newNode; } }; var cloneGraph = function(graph) { if(!graph) { return graph; } else { return dfs(graph, {}); } function dfs(node, visited) { var newNode = visited[node.label] = visited[node.label] || new UndirectedGraphNode(node.label); for(var i = 0; i < node.neighbors.length; i++) { var neighbor = node.neighbors[i]; newNode.neighbors[i] = visited[neighbor.label] = visited[neighbor.label] || dfs(neighbor, visited); } return newNode; } };
{ "pile_set_name": "Github" }
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 FLANN_INDEX_TESTING_H_ #define FLANN_INDEX_TESTING_H_ #include <cstring> #include <cassert> #include <cmath> #include "../util/matrix.h" #include "../algorithms/nn_index.h" #include "../util/result_set.h" #include "../util/logger.h" #include "../util/timer.h" namespace flann { inline int countCorrectMatches(size_t* neighbors, size_t* groundTruth, int n) { int count = 0; for (int i=0; i<n; ++i) { for (int k=0; k<n; ++k) { if (neighbors[i]==groundTruth[k]) { count++; break; } } } return count; } template <typename Distance> typename Distance::ResultType computeDistanceRaport(const Matrix<typename Distance::ElementType>& inputData, typename Distance::ElementType* target, size_t* neighbors, size_t* groundTruth, int veclen, int n, const Distance& distance) { typedef typename Distance::ResultType DistanceType; DistanceType ret = 0; for (int i=0; i<n; ++i) { DistanceType den = distance(inputData[groundTruth[i]], target, veclen); DistanceType num = distance(inputData[neighbors[i]], target, veclen); if ((den==0)&&(num==0)) { ret += 1; } else { ret += num/den; } } return ret; } template <typename Index, typename Distance> float search_with_ground_truth(Index& index, const Matrix<typename Distance::ElementType>& inputData, const Matrix<typename Distance::ElementType>& testData, const Matrix<size_t>& matches, int nn, int checks, float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) { typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; if (matches.cols<size_t(nn)) { Logger::info("matches.cols=%d, nn=%d\n",matches.cols,nn); throw FLANNException("Ground truth is not computed for as many neighbors as requested"); } SearchParams searchParams(checks); size_t* indices = new size_t[nn+skipMatches]; DistanceType* dists = new DistanceType[nn+skipMatches]; Matrix<size_t> indices_mat(indices, 1, nn+skipMatches); Matrix<DistanceType> dists_mat(dists, 1, nn+skipMatches); size_t* neighbors = indices + skipMatches; int correct = 0; DistanceType distR = 0; StartStopTimer t; int repeats = 0; while (t.value<0.2) { repeats++; t.start(); correct = 0; distR = 0; for (size_t i = 0; i < testData.rows; i++) { index.knnSearch(Matrix<ElementType>(testData[i], 1, testData.cols), indices_mat, dists_mat, nn+skipMatches, searchParams); correct += countCorrectMatches(neighbors,matches[i], nn); distR += computeDistanceRaport<Distance>(inputData, testData[i], neighbors, matches[i], testData.cols, nn, distance); } t.stop(); } time = float(t.value/repeats); delete[] indices; delete[] dists; float precicion = (float)correct/(nn*testData.rows); dist = distR/(testData.rows*nn); Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", checks, precicion, time, 1000.0 * time / testData.rows, dist); return precicion; } template <typename Index, typename Distance> float test_index_checks(Index& index, const Matrix<typename Distance::ElementType>& inputData, const Matrix<typename Distance::ElementType>& testData, const Matrix<size_t>& matches, int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) { typedef typename Distance::ResultType DistanceType; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); float time = 0; DistanceType dist = 0; precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); return time; } template <typename Index, typename Distance> float test_index_precision(Index& index, const Matrix<typename Distance::ElementType>& inputData, const Matrix<typename Distance::ElementType>& testData, const Matrix<size_t>& matches, float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) { typedef typename Distance::ResultType DistanceType; const float SEARCH_EPS = 0.001f; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); int c2 = 1; float p2; int c1 = 1; // float p1; float time; DistanceType dist; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); if (p2>precision) { Logger::info("Got as close as I can\n"); checks = c2; return time; } while (p2<precision) { c1 = c2; // p1 = p2; c2 *=2; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); } int cx; float realPrecision; if (fabs(p2-precision)>SEARCH_EPS) { Logger::info("Start linear estimation\n"); // after we got to values in the vecinity of the desired precision // use linear approximation get a better estimation cx = (c1+c2)/2; realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); while (fabs(realPrecision-precision)>SEARCH_EPS) { if (realPrecision<precision) { c1 = cx; } else { c2 = cx; } cx = (c1+c2)/2; if (cx==c1) { Logger::info("Got as close as I can\n"); break; } realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); } c2 = cx; p2 = realPrecision; } else { Logger::info("No need for linear estimation\n"); cx = c2; realPrecision = p2; } checks = cx; return time; } template <typename Index, typename Distance> void test_index_precisions(Index& index, const Matrix<typename Distance::ElementType>& inputData, const Matrix<typename Distance::ElementType>& testData, const Matrix<int>& matches, float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) { typedef typename Distance::ResultType DistanceType; const float SEARCH_EPS = 0.001; // make sure precisions array is sorted std::sort(precisions, precisions+precisions_length); int pindex = 0; float precision = precisions[pindex]; Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); Logger::info("---------------------------------------------------------\n"); int c2 = 1; float p2; int c1 = 1; float p1; float time; DistanceType dist; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); // if precision for 1 run down the tree is already // better then some of the requested precisions, then // skip those while (precisions[pindex]<p2 && pindex<precisions_length) { pindex++; } if (pindex==precisions_length) { Logger::info("Got as close as I can\n"); return; } for (int i=pindex; i<precisions_length; ++i) { precision = precisions[i]; while (p2<precision) { c1 = c2; p1 = p2; c2 *=2; p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); if ((maxTime> 0)&&(time > maxTime)&&(p2<precision)) return; } int cx; float realPrecision; if (fabs(p2-precision)>SEARCH_EPS) { Logger::info("Start linear estimation\n"); // after we got to values in the vecinity of the desired precision // use linear approximation get a better estimation cx = (c1+c2)/2; realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); while (fabs(realPrecision-precision)>SEARCH_EPS) { if (realPrecision<precision) { c1 = cx; } else { c2 = cx; } cx = (c1+c2)/2; if (cx==c1) { Logger::info("Got as close as I can\n"); break; } realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); } c2 = cx; p2 = realPrecision; } else { Logger::info("No need for linear estimation\n"); cx = c2; realPrecision = p2; } } } } #endif //FLANN_INDEX_TESTING_H_
{ "pile_set_name": "Github" }
{{/* vim: set filetype=mustache: */}} {{/* Expand the name of the chart. */}} {{- define "name" -}} {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} {{- end -}} {{/* Create a default fully qualified app name. We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). */}} {{- define "fullname" -}} {{- if .Values.fullnameOverride -}} {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} {{- else -}} {{- $name := default .Chart.Name .Values.nameOverride -}} {{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} {{- end -}} {{- end -}} {{- define "uname" -}} {{ .Values.clusterName }}-{{ .Values.nodeGroup }} {{- end -}} {{- define "masterService" -}} {{- if empty .Values.masterService -}} {{ .Values.clusterName }}-master {{- else -}} {{ .Values.masterService }} {{- end -}} {{- end -}} {{- define "endpoints" -}} {{- $replicas := .replicas | int }} {{- $uname := printf "%s-%s" .clusterName .nodeGroup }} {{- range $i, $e := untilStep 0 $replicas 1 -}} {{ $uname }}-{{ $i }}, {{- end -}} {{- end -}} {{- define "haproxyEndpoints" -}} {{- $replicas := .replicas | int }} {{- range $i, $e := untilStep 0 $replicas 1 -}} 127.0.0.1:970{{ $i }}, {{- end -}} {{- end -}}
{ "pile_set_name": "Github" }
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.7.12 if (typeof WeakMap === "undefined") { (function() { var defineProperty = Object.defineProperty; var counter = Date.now() % 1e9; var WeakMap = function() { this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__"); }; WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, { value: [ key, value ], writable: true }); return this; }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, "delete": function(key) { var entry = key[this.name]; if (!entry || entry[0] !== key) return false; entry[0] = entry[1] = undefined; return true; }, has: function(key) { var entry = key[this.name]; if (!entry) return false; return entry[0] === key; } }; window.WeakMap = WeakMap; })(); } (function(global) { var registrationsTable = new WeakMap(); var setImmediate; if (/Trident|Edge/.test(navigator.userAgent)) { setImmediate = setTimeout; } else if (window.setImmediate) { setImmediate = window.setImmediate; } else { var setImmediateQueue = []; var sentinel = String(Math.random()); window.addEventListener("message", function(e) { if (e.data === sentinel) { var queue = setImmediateQueue; setImmediateQueue = []; queue.forEach(function(func) { func(); }); } }); setImmediate = function(func) { setImmediateQueue.push(func); window.postMessage(sentinel, "*"); }; } var isScheduled = false; var scheduledObservers = []; function scheduleCallback(observer) { scheduledObservers.push(observer); if (!isScheduled) { isScheduled = true; setImmediate(dispatchCallbacks); } } function wrapIfNeeded(node) { return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(node) || node; } function dispatchCallbacks() { isScheduled = false; var observers = scheduledObservers; scheduledObservers = []; observers.sort(function(o1, o2) { return o1.uid_ - o2.uid_; }); var anyNonEmpty = false; observers.forEach(function(observer) { var queue = observer.takeRecords(); removeTransientObserversFor(observer); if (queue.length) { observer.callback_(queue, observer); anyNonEmpty = true; } }); if (anyNonEmpty) dispatchCallbacks(); } function removeTransientObserversFor(observer) { observer.nodes_.forEach(function(node) { var registrations = registrationsTable.get(node); if (!registrations) return; registrations.forEach(function(registration) { if (registration.observer === observer) registration.removeTransientObservers(); }); }); } function forEachAncestorAndObserverEnqueueRecord(target, callback) { for (var node = target; node; node = node.parentNode) { var registrations = registrationsTable.get(node); if (registrations) { for (var j = 0; j < registrations.length; j++) { var registration = registrations[j]; var options = registration.options; if (node !== target && !options.subtree) continue; var record = callback(options); if (record) registration.enqueue(record); } } } } var uidCounter = 0; function JsMutationObserver(callback) { this.callback_ = callback; this.nodes_ = []; this.records_ = []; this.uid_ = ++uidCounter; } JsMutationObserver.prototype = { observe: function(target, options) { target = wrapIfNeeded(target); if (!options.childList && !options.attributes && !options.characterData || options.attributeOldValue && !options.attributes || options.attributeFilter && options.attributeFilter.length && !options.attributes || options.characterDataOldValue && !options.characterData) { throw new SyntaxError(); } var registrations = registrationsTable.get(target); if (!registrations) registrationsTable.set(target, registrations = []); var registration; for (var i = 0; i < registrations.length; i++) { if (registrations[i].observer === this) { registration = registrations[i]; registration.removeListeners(); registration.options = options; break; } } if (!registration) { registration = new Registration(this, target, options); registrations.push(registration); this.nodes_.push(target); } registration.addListeners(); }, disconnect: function() { this.nodes_.forEach(function(node) { var registrations = registrationsTable.get(node); for (var i = 0; i < registrations.length; i++) { var registration = registrations[i]; if (registration.observer === this) { registration.removeListeners(); registrations.splice(i, 1); break; } } }, this); this.records_ = []; }, takeRecords: function() { var copyOfRecords = this.records_; this.records_ = []; return copyOfRecords; } }; function MutationRecord(type, target) { this.type = type; this.target = target; this.addedNodes = []; this.removedNodes = []; this.previousSibling = null; this.nextSibling = null; this.attributeName = null; this.attributeNamespace = null; this.oldValue = null; } function copyMutationRecord(original) { var record = new MutationRecord(original.type, original.target); record.addedNodes = original.addedNodes.slice(); record.removedNodes = original.removedNodes.slice(); record.previousSibling = original.previousSibling; record.nextSibling = original.nextSibling; record.attributeName = original.attributeName; record.attributeNamespace = original.attributeNamespace; record.oldValue = original.oldValue; return record; } var currentRecord, recordWithOldValue; function getRecord(type, target) { return currentRecord = new MutationRecord(type, target); } function getRecordWithOldValue(oldValue) { if (recordWithOldValue) return recordWithOldValue; recordWithOldValue = copyMutationRecord(currentRecord); recordWithOldValue.oldValue = oldValue; return recordWithOldValue; } function clearRecords() { currentRecord = recordWithOldValue = undefined; } function recordRepresentsCurrentMutation(record) { return record === recordWithOldValue || record === currentRecord; } function selectRecord(lastRecord, newRecord) { if (lastRecord === newRecord) return lastRecord; if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue; return null; } function Registration(observer, target, options) { this.observer = observer; this.target = target; this.options = options; this.transientObservedNodes = []; } Registration.prototype = { enqueue: function(record) { var records = this.observer.records_; var length = records.length; if (records.length > 0) { var lastRecord = records[length - 1]; var recordToReplaceLast = selectRecord(lastRecord, record); if (recordToReplaceLast) { records[length - 1] = recordToReplaceLast; return; } } else { scheduleCallback(this.observer); } records[length] = record; }, addListeners: function() { this.addListeners_(this.target); }, addListeners_: function(node) { var options = this.options; if (options.attributes) node.addEventListener("DOMAttrModified", this, true); if (options.characterData) node.addEventListener("DOMCharacterDataModified", this, true); if (options.childList) node.addEventListener("DOMNodeInserted", this, true); if (options.childList || options.subtree) node.addEventListener("DOMNodeRemoved", this, true); }, removeListeners: function() { this.removeListeners_(this.target); }, removeListeners_: function(node) { var options = this.options; if (options.attributes) node.removeEventListener("DOMAttrModified", this, true); if (options.characterData) node.removeEventListener("DOMCharacterDataModified", this, true); if (options.childList) node.removeEventListener("DOMNodeInserted", this, true); if (options.childList || options.subtree) node.removeEventListener("DOMNodeRemoved", this, true); }, addTransientObserver: function(node) { if (node === this.target) return; this.addListeners_(node); this.transientObservedNodes.push(node); var registrations = registrationsTable.get(node); if (!registrations) registrationsTable.set(node, registrations = []); registrations.push(this); }, removeTransientObservers: function() { var transientObservedNodes = this.transientObservedNodes; this.transientObservedNodes = []; transientObservedNodes.forEach(function(node) { this.removeListeners_(node); var registrations = registrationsTable.get(node); for (var i = 0; i < registrations.length; i++) { if (registrations[i] === this) { registrations.splice(i, 1); break; } } }, this); }, handleEvent: function(e) { e.stopImmediatePropagation(); switch (e.type) { case "DOMAttrModified": var name = e.attrName; var namespace = e.relatedNode.namespaceURI; var target = e.target; var record = new getRecord("attributes", target); record.attributeName = name; record.attributeNamespace = namespace; var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue; forEachAncestorAndObserverEnqueueRecord(target, function(options) { if (!options.attributes) return; if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) { return; } if (options.attributeOldValue) return getRecordWithOldValue(oldValue); return record; }); break; case "DOMCharacterDataModified": var target = e.target; var record = getRecord("characterData", target); var oldValue = e.prevValue; forEachAncestorAndObserverEnqueueRecord(target, function(options) { if (!options.characterData) return; if (options.characterDataOldValue) return getRecordWithOldValue(oldValue); return record; }); break; case "DOMNodeRemoved": this.addTransientObserver(e.target); case "DOMNodeInserted": var changedNode = e.target; var addedNodes, removedNodes; if (e.type === "DOMNodeInserted") { addedNodes = [ changedNode ]; removedNodes = []; } else { addedNodes = []; removedNodes = [ changedNode ]; } var previousSibling = changedNode.previousSibling; var nextSibling = changedNode.nextSibling; var record = getRecord("childList", e.target.parentNode); record.addedNodes = addedNodes; record.removedNodes = removedNodes; record.previousSibling = previousSibling; record.nextSibling = nextSibling; forEachAncestorAndObserverEnqueueRecord(e.relatedNode, function(options) { if (!options.childList) return; return record; }); } clearRecords(); } }; global.JsMutationObserver = JsMutationObserver; if (!global.MutationObserver) global.MutationObserver = JsMutationObserver; })(window); window.CustomElements = window.CustomElements || { flags: {} }; (function(scope) { var flags = scope.flags; var modules = []; var addModule = function(module) { modules.push(module); }; var initializeModules = function() { modules.forEach(function(module) { module(scope); }); }; scope.addModule = addModule; scope.initializeModules = initializeModules; scope.hasNative = Boolean(document.registerElement); scope.isIE = /Trident/.test(navigator.userAgent); scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative); })(window.CustomElements); window.CustomElements.addModule(function(scope) { var IMPORT_LINK_TYPE = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; function forSubtree(node, cb) { findAllElements(node, function(e) { if (cb(e)) { return true; } forRoots(e, cb); }); forRoots(node, cb); } function findAllElements(node, find, data) { var e = node.firstElementChild; if (!e) { e = node.firstChild; while (e && e.nodeType !== Node.ELEMENT_NODE) { e = e.nextSibling; } } while (e) { if (find(e, data) !== true) { findAllElements(e, find, data); } e = e.nextElementSibling; } return null; } function forRoots(node, cb) { var root = node.shadowRoot; while (root) { forSubtree(root, cb); root = root.olderShadowRoot; } } function forDocumentTree(doc, cb) { _forDocumentTree(doc, cb, []); } function _forDocumentTree(doc, cb, processingDocuments) { doc = window.wrap(doc); if (processingDocuments.indexOf(doc) >= 0) { return; } processingDocuments.push(doc); var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]"); for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) { if (n.import) { _forDocumentTree(n.import, cb, processingDocuments); } } cb(doc); } scope.forDocumentTree = forDocumentTree; scope.forSubtree = forSubtree; }); window.CustomElements.addModule(function(scope) { var flags = scope.flags; var forSubtree = scope.forSubtree; var forDocumentTree = scope.forDocumentTree; function addedNode(node, isAttached) { return added(node, isAttached) || addedSubtree(node, isAttached); } function added(node, isAttached) { if (scope.upgrade(node, isAttached)) { return true; } if (isAttached) { attached(node); } } function addedSubtree(node, isAttached) { forSubtree(node, function(e) { if (added(e, isAttached)) { return true; } }); } var hasPolyfillMutations = !window.MutationObserver || window.MutationObserver === window.JsMutationObserver; scope.hasPolyfillMutations = hasPolyfillMutations; var isPendingMutations = false; var pendingMutations = []; function deferMutation(fn) { pendingMutations.push(fn); if (!isPendingMutations) { isPendingMutations = true; setTimeout(takeMutations); } } function takeMutations() { isPendingMutations = false; var $p = pendingMutations; for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) { p(); } pendingMutations = []; } function attached(element) { if (hasPolyfillMutations) { deferMutation(function() { _attached(element); }); } else { _attached(element); } } function _attached(element) { if (element.__upgraded__ && !element.__attached) { element.__attached = true; if (element.attachedCallback) { element.attachedCallback(); } } } function detachedNode(node) { detached(node); forSubtree(node, function(e) { detached(e); }); } function detached(element) { if (hasPolyfillMutations) { deferMutation(function() { _detached(element); }); } else { _detached(element); } } function _detached(element) { if (element.__upgraded__ && element.__attached) { element.__attached = false; if (element.detachedCallback) { element.detachedCallback(); } } } function inDocument(element) { var p = element; var doc = window.wrap(document); while (p) { if (p == doc) { return true; } p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host; } } function watchShadow(node) { if (node.shadowRoot && !node.shadowRoot.__watched) { flags.dom && console.log("watching shadow-root for: ", node.localName); var root = node.shadowRoot; while (root) { observe(root); root = root.olderShadowRoot; } } } function handler(root, mutations) { if (flags.dom) { var mx = mutations[0]; if (mx && mx.type === "childList" && mx.addedNodes) { if (mx.addedNodes) { var d = mx.addedNodes[0]; while (d && d !== document && !d.host) { d = d.parentNode; } var u = d && (d.URL || d._URL || d.host && d.host.localName) || ""; u = u.split("/?").shift().split("/").pop(); } } console.group("mutations (%d) [%s]", mutations.length, u || ""); } var isAttached = inDocument(root); mutations.forEach(function(mx) { if (mx.type === "childList") { forEach(mx.addedNodes, function(n) { if (!n.localName) { return; } addedNode(n, isAttached); }); forEach(mx.removedNodes, function(n) { if (!n.localName) { return; } detachedNode(n); }); } }); flags.dom && console.groupEnd(); } function takeRecords(node) { node = window.wrap(node); if (!node) { node = window.wrap(document); } while (node.parentNode) { node = node.parentNode; } var observer = node.__observer; if (observer) { handler(node, observer.takeRecords()); takeMutations(); } } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); function observe(inRoot) { if (inRoot.__observer) { return; } var observer = new MutationObserver(handler.bind(this, inRoot)); observer.observe(inRoot, { childList: true, subtree: true }); inRoot.__observer = observer; } function upgradeDocument(doc) { doc = window.wrap(doc); flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop()); var isMainDocument = doc === window.wrap(document); addedNode(doc, isMainDocument); observe(doc); flags.dom && console.groupEnd(); } function upgradeDocumentTree(doc) { forDocumentTree(doc, upgradeDocument); } var originalCreateShadowRoot = Element.prototype.createShadowRoot; if (originalCreateShadowRoot) { Element.prototype.createShadowRoot = function() { var root = originalCreateShadowRoot.call(this); window.CustomElements.watchShadow(this); return root; }; } scope.watchShadow = watchShadow; scope.upgradeDocumentTree = upgradeDocumentTree; scope.upgradeDocument = upgradeDocument; scope.upgradeSubtree = addedSubtree; scope.upgradeAll = addedNode; scope.attached = attached; scope.takeRecords = takeRecords; }); window.CustomElements.addModule(function(scope) { var flags = scope.flags; function upgrade(node, isAttached) { if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) { var is = node.getAttribute("is"); var definition = scope.getRegisteredDefinition(node.localName) || scope.getRegisteredDefinition(is); if (definition) { if (is && definition.tag == node.localName || !is && !definition.extends) { return upgradeWithDefinition(node, definition, isAttached); } } } } function upgradeWithDefinition(element, definition, isAttached) { flags.upgrade && console.group("upgrade:", element.localName); if (definition.is) { element.setAttribute("is", definition.is); } implementPrototype(element, definition); element.__upgraded__ = true; created(element); if (isAttached) { scope.attached(element); } scope.upgradeSubtree(element, isAttached); flags.upgrade && console.groupEnd(); return element; } function implementPrototype(element, definition) { if (Object.__proto__) { element.__proto__ = definition.prototype; } else { customMixin(element, definition.prototype, definition.native); element.__proto__ = definition.prototype; } } function customMixin(inTarget, inSrc, inNative) { var used = {}; var p = inSrc; while (p !== inNative && p !== HTMLElement.prototype) { var keys = Object.getOwnPropertyNames(p); for (var i = 0, k; k = keys[i]; i++) { if (!used[k]) { Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k)); used[k] = 1; } } p = Object.getPrototypeOf(p); } } function created(element) { if (element.createdCallback) { element.createdCallback(); } } scope.upgrade = upgrade; scope.upgradeWithDefinition = upgradeWithDefinition; scope.implementPrototype = implementPrototype; }); window.CustomElements.addModule(function(scope) { var isIE = scope.isIE; var upgradeDocumentTree = scope.upgradeDocumentTree; var upgradeAll = scope.upgradeAll; var upgradeWithDefinition = scope.upgradeWithDefinition; var implementPrototype = scope.implementPrototype; var useNative = scope.useNative; function register(name, options) { var definition = options || {}; if (!name) { throw new Error("document.registerElement: first argument `name` must not be empty"); } if (name.indexOf("-") < 0) { throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'."); } if (isReservedTag(name)) { throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid."); } if (getRegisteredDefinition(name)) { throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered"); } if (!definition.prototype) { definition.prototype = Object.create(HTMLElement.prototype); } definition.__name = name.toLowerCase(); definition.lifecycle = definition.lifecycle || {}; definition.ancestry = ancestry(definition.extends); resolveTagName(definition); resolvePrototypeChain(definition); overrideAttributeApi(definition.prototype); registerDefinition(definition.__name, definition); definition.ctor = generateConstructor(definition); definition.ctor.prototype = definition.prototype; definition.prototype.constructor = definition.ctor; if (scope.ready) { upgradeDocumentTree(document); } return definition.ctor; } function overrideAttributeApi(prototype) { if (prototype.setAttribute._polyfilled) { return; } var setAttribute = prototype.setAttribute; prototype.setAttribute = function(name, value) { changeAttribute.call(this, name, value, setAttribute); }; var removeAttribute = prototype.removeAttribute; prototype.removeAttribute = function(name) { changeAttribute.call(this, name, null, removeAttribute); }; prototype.setAttribute._polyfilled = true; } function changeAttribute(name, value, operation) { name = name.toLowerCase(); var oldValue = this.getAttribute(name); operation.apply(this, arguments); var newValue = this.getAttribute(name); if (this.attributeChangedCallback && newValue !== oldValue) { this.attributeChangedCallback(name, oldValue, newValue); } } function isReservedTag(name) { for (var i = 0; i < reservedTagList.length; i++) { if (name === reservedTagList[i]) { return true; } } } var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ]; function ancestry(extnds) { var extendee = getRegisteredDefinition(extnds); if (extendee) { return ancestry(extendee.extends).concat([ extendee ]); } return []; } function resolveTagName(definition) { var baseTag = definition.extends; for (var i = 0, a; a = definition.ancestry[i]; i++) { baseTag = a.is && a.tag; } definition.tag = baseTag || definition.__name; if (baseTag) { definition.is = definition.__name; } } function resolvePrototypeChain(definition) { if (!Object.__proto__) { var nativePrototype = HTMLElement.prototype; if (definition.is) { var inst = document.createElement(definition.tag); nativePrototype = Object.getPrototypeOf(inst); } var proto = definition.prototype, ancestor; var foundPrototype = false; while (proto) { if (proto == nativePrototype) { foundPrototype = true; } ancestor = Object.getPrototypeOf(proto); if (ancestor) { proto.__proto__ = ancestor; } proto = ancestor; } if (!foundPrototype) { console.warn(definition.tag + " prototype not found in prototype chain for " + definition.is); } definition.native = nativePrototype; } } function instantiate(definition) { return upgradeWithDefinition(domCreateElement(definition.tag), definition); } var registry = {}; function getRegisteredDefinition(name) { if (name) { return registry[name.toLowerCase()]; } } function registerDefinition(name, definition) { registry[name] = definition; } function generateConstructor(definition) { return function() { return instantiate(definition); }; } var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; function createElementNS(namespace, tag, typeExtension) { if (namespace === HTML_NAMESPACE) { return createElement(tag, typeExtension); } else { return domCreateElementNS(namespace, tag); } } function createElement(tag, typeExtension) { if (tag) { tag = tag.toLowerCase(); } if (typeExtension) { typeExtension = typeExtension.toLowerCase(); } var definition = getRegisteredDefinition(typeExtension || tag); if (definition) { if (tag == definition.tag && typeExtension == definition.is) { return new definition.ctor(); } if (!typeExtension && !definition.is) { return new definition.ctor(); } } var element; if (typeExtension) { element = createElement(tag); element.setAttribute("is", typeExtension); return element; } element = domCreateElement(tag); if (tag.indexOf("-") >= 0) { implementPrototype(element, HTMLElement); } return element; } var domCreateElement = document.createElement.bind(document); var domCreateElementNS = document.createElementNS.bind(document); var isInstance; if (!Object.__proto__ && !useNative) { isInstance = function(obj, ctor) { if (obj instanceof ctor) { return true; } var p = obj; while (p) { if (p === ctor.prototype) { return true; } p = p.__proto__; } return false; }; } else { isInstance = function(obj, base) { return obj instanceof base; }; } function wrapDomMethodToForceUpgrade(obj, methodName) { var orig = obj[methodName]; obj[methodName] = function() { var n = orig.apply(this, arguments); upgradeAll(n); return n; }; } wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode"); wrapDomMethodToForceUpgrade(document, "importNode"); if (isIE) { (function() { var importNode = document.importNode; document.importNode = function() { var n = importNode.apply(document, arguments); if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) { var f = document.createDocumentFragment(); f.appendChild(n); return f; } else { return n; } }; })(); } document.registerElement = register; document.createElement = createElement; document.createElementNS = createElementNS; scope.registry = registry; scope.instanceof = isInstance; scope.reservedTagList = reservedTagList; scope.getRegisteredDefinition = getRegisteredDefinition; document.register = document.registerElement; }); (function(scope) { var useNative = scope.useNative; var initializeModules = scope.initializeModules; var isIE = scope.isIE; if (useNative) { var nop = function() {}; scope.watchShadow = nop; scope.upgrade = nop; scope.upgradeAll = nop; scope.upgradeDocumentTree = nop; scope.upgradeSubtree = nop; scope.takeRecords = nop; scope.instanceof = function(obj, base) { return obj instanceof base; }; } else { initializeModules(); } var upgradeDocumentTree = scope.upgradeDocumentTree; var upgradeDocument = scope.upgradeDocument; if (!window.wrap) { if (window.ShadowDOMPolyfill) { window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded; window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded; } else { window.wrap = window.unwrap = function(node) { return node; }; } } if (window.HTMLImports) { window.HTMLImports.__importsParsingHook = function(elt) { if (elt.import) { upgradeDocument(wrap(elt.import)); } }; } function bootstrap() { upgradeDocumentTree(window.wrap(document)); window.CustomElements.ready = true; var requestAnimationFrame = window.requestAnimationFrame || function(f) { setTimeout(f, 16); }; requestAnimationFrame(function() { setTimeout(function() { window.CustomElements.readyTime = Date.now(); if (window.HTMLImports) { window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime; } document.dispatchEvent(new CustomEvent("WebComponentsReady", { bubbles: true })); }); }); } if (isIE && typeof window.CustomEvent !== "function") { window.CustomEvent = function(inType, params) { params = params || {}; var e = document.createEvent("CustomEvent"); e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail); e.preventDefault = function() { Object.defineProperty(this, "defaultPrevented", { get: function() { return true; } }); }; return e; }; window.CustomEvent.prototype = window.Event.prototype; } if (document.readyState === "complete" || scope.flags.eager) { bootstrap(); } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) { bootstrap(); } else { var loadEvent = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; window.addEventListener(loadEvent, bootstrap); } })(window.CustomElements);
{ "pile_set_name": "Github" }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP___LOCALE #define _LIBCPP___LOCALE #include <__config> #include <string> #include <memory> #include <utility> #include <mutex> #include <cstdint> #include <cctype> #include <locale.h> #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) # include <support/win32/locale_win32.h> #elif defined(_AIX) # include <support/ibm/xlocale.h> #elif defined(__ANDROID__) // Android gained the locale aware functions in L (API level 21) # include <android/api-level.h> # if __ANDROID_API__ <= 20 # include <support/android/locale_bionic.h> # endif #elif defined(__sun__) # include <support/solaris/xlocale.h> #elif defined(_NEWLIB_VERSION) # include <support/newlib/xlocale.h> #elif (defined(__GLIBC__) || defined(__APPLE__) || defined(__FreeBSD__) \ || defined(__EMSCRIPTEN__) || defined(__IBMCPP__)) # include <xlocale.h> #endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__ #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD class _LIBCPP_TYPE_VIS locale; template <class _Facet> _LIBCPP_INLINE_VISIBILITY bool has_facet(const locale&) _NOEXCEPT; template <class _Facet> _LIBCPP_INLINE_VISIBILITY const _Facet& use_facet(const locale&); class _LIBCPP_TYPE_VIS locale { public: // types: class _LIBCPP_TYPE_VIS facet; class _LIBCPP_TYPE_VIS id; typedef int category; static const category // values assigned here are for exposition only none = 0, collate = LC_COLLATE_MASK, ctype = LC_CTYPE_MASK, monetary = LC_MONETARY_MASK, numeric = LC_NUMERIC_MASK, time = LC_TIME_MASK, messages = LC_MESSAGES_MASK, all = collate | ctype | monetary | numeric | time | messages; // construct/copy/destroy: locale() _NOEXCEPT; locale(const locale&) _NOEXCEPT; explicit locale(const char*); explicit locale(const string&); locale(const locale&, const char*, category); locale(const locale&, const string&, category); template <class _Facet> _LIBCPP_INLINE_VISIBILITY locale(const locale&, _Facet*); locale(const locale&, const locale&, category); ~locale(); const locale& operator=(const locale&) _NOEXCEPT; template <class _Facet> locale combine(const locale&) const; // locale operations: string name() const; bool operator==(const locale&) const; bool operator!=(const locale& __y) const {return !(*this == __y);} template <class _CharT, class _Traits, class _Allocator> bool operator()(const basic_string<_CharT, _Traits, _Allocator>&, const basic_string<_CharT, _Traits, _Allocator>&) const; // global locale objects: static locale global(const locale&); static const locale& classic(); private: class __imp; __imp* __locale_; void __install_ctor(const locale&, facet*, long); static locale& __global(); bool has_facet(id&) const; const facet* use_facet(id&) const; template <class _Facet> friend bool has_facet(const locale&) _NOEXCEPT; template <class _Facet> friend const _Facet& use_facet(const locale&); }; class _LIBCPP_TYPE_VIS locale::facet : public __shared_count { protected: _LIBCPP_INLINE_VISIBILITY explicit facet(size_t __refs = 0) : __shared_count(static_cast<long>(__refs)-1) {} virtual ~facet(); // facet(const facet&) = delete; // effectively done in __shared_count // void operator=(const facet&) = delete; private: virtual void __on_zero_shared() _NOEXCEPT; }; class _LIBCPP_TYPE_VIS locale::id { once_flag __flag_; int32_t __id_; static int32_t __next_id; public: _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR id() :__id_(0) {} private: void __init(); void operator=(const id&); // = delete; id(const id&); // = delete; public: // only needed for tests long __get(); friend class locale; friend class locale::__imp; }; template <class _Facet> inline _LIBCPP_INLINE_VISIBILITY locale::locale(const locale& __other, _Facet* __f) { __install_ctor(__other, __f, __f ? __f->id.__get() : 0); } template <class _Facet> locale locale::combine(const locale& __other) const { #ifndef _LIBCPP_NO_EXCEPTIONS if (!_VSTD::has_facet<_Facet>(__other)) throw runtime_error("locale::combine: locale missing facet"); #endif // _LIBCPP_NO_EXCEPTIONS return locale(*this, &const_cast<_Facet&>(_VSTD::use_facet<_Facet>(__other))); } template <class _Facet> inline _LIBCPP_INLINE_VISIBILITY bool has_facet(const locale& __l) _NOEXCEPT { return __l.has_facet(_Facet::id); } template <class _Facet> inline _LIBCPP_INLINE_VISIBILITY const _Facet& use_facet(const locale& __l) { return static_cast<const _Facet&>(*__l.use_facet(_Facet::id)); } // template <class _CharT> class collate; template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY collate : public locale::facet { public: typedef _CharT char_type; typedef basic_string<char_type> string_type; _LIBCPP_INLINE_VISIBILITY explicit collate(size_t __refs = 0) : locale::facet(__refs) {} _LIBCPP_INLINE_VISIBILITY int compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const { return do_compare(__lo1, __hi1, __lo2, __hi2); } _LIBCPP_INLINE_VISIBILITY string_type transform(const char_type* __lo, const char_type* __hi) const { return do_transform(__lo, __hi); } _LIBCPP_INLINE_VISIBILITY long hash(const char_type* __lo, const char_type* __hi) const { return do_hash(__lo, __hi); } static locale::id id; protected: ~collate(); virtual int do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const; virtual string_type do_transform(const char_type* __lo, const char_type* __hi) const {return string_type(__lo, __hi);} virtual long do_hash(const char_type* __lo, const char_type* __hi) const; }; template <class _CharT> locale::id collate<_CharT>::id; template <class _CharT> collate<_CharT>::~collate() { } template <class _CharT> int collate<_CharT>::do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const { for (; __lo2 != __hi2; ++__lo1, ++__lo2) { if (__lo1 == __hi1 || *__lo1 < *__lo2) return -1; if (*__lo2 < *__lo1) return 1; } return __lo1 != __hi1; } template <class _CharT> long collate<_CharT>::do_hash(const char_type* __lo, const char_type* __hi) const { size_t __h = 0; const size_t __sr = __CHAR_BIT__ * sizeof(size_t) - 8; const size_t __mask = size_t(0xF) << (__sr + 4); for(const char_type* __p = __lo; __p != __hi; ++__p) { __h = (__h << 4) + static_cast<size_t>(*__p); size_t __g = __h & __mask; __h ^= __g | (__g >> __sr); } return static_cast<long>(__h); } _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS collate<char>) _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS collate<wchar_t>) // template <class CharT> class collate_byname; template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY collate_byname; template <> class _LIBCPP_TYPE_VIS collate_byname<char> : public collate<char> { locale_t __l; public: typedef char char_type; typedef basic_string<char_type> string_type; explicit collate_byname(const char* __n, size_t __refs = 0); explicit collate_byname(const string& __n, size_t __refs = 0); protected: ~collate_byname(); virtual int do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const; virtual string_type do_transform(const char_type* __lo, const char_type* __hi) const; }; template <> class _LIBCPP_TYPE_VIS collate_byname<wchar_t> : public collate<wchar_t> { locale_t __l; public: typedef wchar_t char_type; typedef basic_string<char_type> string_type; explicit collate_byname(const char* __n, size_t __refs = 0); explicit collate_byname(const string& __n, size_t __refs = 0); protected: ~collate_byname(); virtual int do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const; virtual string_type do_transform(const char_type* __lo, const char_type* __hi) const; }; template <class _CharT, class _Traits, class _Allocator> bool locale::operator()(const basic_string<_CharT, _Traits, _Allocator>& __x, const basic_string<_CharT, _Traits, _Allocator>& __y) const { return _VSTD::use_facet<_VSTD::collate<_CharT> >(*this).compare( __x.data(), __x.data() + __x.size(), __y.data(), __y.data() + __y.size()) < 0; } // template <class charT> class ctype class _LIBCPP_TYPE_VIS ctype_base { public: #ifdef __GLIBC__ typedef unsigned short mask; static const mask space = _ISspace; static const mask print = _ISprint; static const mask cntrl = _IScntrl; static const mask upper = _ISupper; static const mask lower = _ISlower; static const mask alpha = _ISalpha; static const mask digit = _ISdigit; static const mask punct = _ISpunct; static const mask xdigit = _ISxdigit; static const mask blank = _ISblank; #elif defined(_WIN32) typedef unsigned short mask; static const mask space = _SPACE; static const mask print = _BLANK|_PUNCT|_ALPHA|_DIGIT; static const mask cntrl = _CONTROL; static const mask upper = _UPPER; static const mask lower = _LOWER; static const mask alpha = _ALPHA; static const mask digit = _DIGIT; static const mask punct = _PUNCT; static const mask xdigit = _HEX; static const mask blank = _BLANK; #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || defined(__ANDROID__) #ifdef __APPLE__ typedef __uint32_t mask; #elif defined(__FreeBSD__) typedef unsigned long mask; #elif defined(__EMSCRIPTEN__) || defined(__NetBSD__) typedef unsigned short mask; #elif defined(__ANDROID__) typedef unsigned char mask; #endif static const mask space = _CTYPE_S; static const mask print = _CTYPE_R; static const mask cntrl = _CTYPE_C; static const mask upper = _CTYPE_U; static const mask lower = _CTYPE_L; static const mask alpha = _CTYPE_A; static const mask digit = _CTYPE_D; static const mask punct = _CTYPE_P; # if defined(__ANDROID__) static const mask xdigit = _CTYPE_X | _CTYPE_D; # else static const mask xdigit = _CTYPE_X; # endif # if defined(__NetBSD__) static const mask blank = _CTYPE_BL; # else static const mask blank = _CTYPE_B; # endif #elif defined(__sun__) || defined(_AIX) typedef unsigned int mask; static const mask space = _ISSPACE; static const mask print = _ISPRINT; static const mask cntrl = _ISCNTRL; static const mask upper = _ISUPPER; static const mask lower = _ISLOWER; static const mask alpha = _ISALPHA; static const mask digit = _ISDIGIT; static const mask punct = _ISPUNCT; static const mask xdigit = _ISXDIGIT; static const mask blank = _ISBLANK; #else // __GLIBC__ || _WIN32 || __APPLE__ || __FreeBSD__ || __EMSCRIPTEN__ || __sun__ typedef unsigned long mask; static const mask space = 1<<0; static const mask print = 1<<1; static const mask cntrl = 1<<2; static const mask upper = 1<<3; static const mask lower = 1<<4; static const mask alpha = 1<<5; static const mask digit = 1<<6; static const mask punct = 1<<7; static const mask xdigit = 1<<8; static const mask blank = 1<<9; #endif // __GLIBC__ || _WIN32 || __APPLE__ || __FreeBSD__ static const mask alnum = alpha | digit; static const mask graph = alnum | punct; _LIBCPP_ALWAYS_INLINE ctype_base() {} }; template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY ctype; template <> class _LIBCPP_TYPE_VIS ctype<wchar_t> : public locale::facet, public ctype_base { public: typedef wchar_t char_type; _LIBCPP_ALWAYS_INLINE explicit ctype(size_t __refs = 0) : locale::facet(__refs) {} _LIBCPP_ALWAYS_INLINE bool is(mask __m, char_type __c) const { return do_is(__m, __c); } _LIBCPP_ALWAYS_INLINE const char_type* is(const char_type* __low, const char_type* __high, mask* __vec) const { return do_is(__low, __high, __vec); } _LIBCPP_ALWAYS_INLINE const char_type* scan_is(mask __m, const char_type* __low, const char_type* __high) const { return do_scan_is(__m, __low, __high); } _LIBCPP_ALWAYS_INLINE const char_type* scan_not(mask __m, const char_type* __low, const char_type* __high) const { return do_scan_not(__m, __low, __high); } _LIBCPP_ALWAYS_INLINE char_type toupper(char_type __c) const { return do_toupper(__c); } _LIBCPP_ALWAYS_INLINE const char_type* toupper(char_type* __low, const char_type* __high) const { return do_toupper(__low, __high); } _LIBCPP_ALWAYS_INLINE char_type tolower(char_type __c) const { return do_tolower(__c); } _LIBCPP_ALWAYS_INLINE const char_type* tolower(char_type* __low, const char_type* __high) const { return do_tolower(__low, __high); } _LIBCPP_ALWAYS_INLINE char_type widen(char __c) const { return do_widen(__c); } _LIBCPP_ALWAYS_INLINE const char* widen(const char* __low, const char* __high, char_type* __to) const { return do_widen(__low, __high, __to); } _LIBCPP_ALWAYS_INLINE char narrow(char_type __c, char __dfault) const { return do_narrow(__c, __dfault); } _LIBCPP_ALWAYS_INLINE const char_type* narrow(const char_type* __low, const char_type* __high, char __dfault, char* __to) const { return do_narrow(__low, __high, __dfault, __to); } static locale::id id; protected: ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __low, const char_type* __high, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __low, const char_type* __high) const; virtual const char_type* do_scan_not(mask __m, const char_type* __low, const char_type* __high) const; virtual char_type do_toupper(char_type) const; virtual const char_type* do_toupper(char_type* __low, const char_type* __high) const; virtual char_type do_tolower(char_type) const; virtual const char_type* do_tolower(char_type* __low, const char_type* __high) const; virtual char_type do_widen(char) const; virtual const char* do_widen(const char* __low, const char* __high, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __low, const char_type* __high, char __dfault, char* __dest) const; }; template <> class _LIBCPP_TYPE_VIS ctype<char> : public locale::facet, public ctype_base { const mask* __tab_; bool __del_; public: typedef char char_type; explicit ctype(const mask* __tab = 0, bool __del = false, size_t __refs = 0); _LIBCPP_ALWAYS_INLINE bool is(mask __m, char_type __c) const { return isascii(__c) ? (__tab_[static_cast<int>(__c)] & __m) !=0 : false; } _LIBCPP_ALWAYS_INLINE const char_type* is(const char_type* __low, const char_type* __high, mask* __vec) const { for (; __low != __high; ++__low, ++__vec) *__vec = isascii(*__low) ? __tab_[static_cast<int>(*__low)] : 0; return __low; } _LIBCPP_ALWAYS_INLINE const char_type* scan_is (mask __m, const char_type* __low, const char_type* __high) const { for (; __low != __high; ++__low) if (isascii(*__low) && (__tab_[static_cast<int>(*__low)] & __m)) break; return __low; } _LIBCPP_ALWAYS_INLINE const char_type* scan_not(mask __m, const char_type* __low, const char_type* __high) const { for (; __low != __high; ++__low) if (!(isascii(*__low) && (__tab_[static_cast<int>(*__low)] & __m))) break; return __low; } _LIBCPP_ALWAYS_INLINE char_type toupper(char_type __c) const { return do_toupper(__c); } _LIBCPP_ALWAYS_INLINE const char_type* toupper(char_type* __low, const char_type* __high) const { return do_toupper(__low, __high); } _LIBCPP_ALWAYS_INLINE char_type tolower(char_type __c) const { return do_tolower(__c); } _LIBCPP_ALWAYS_INLINE const char_type* tolower(char_type* __low, const char_type* __high) const { return do_tolower(__low, __high); } _LIBCPP_ALWAYS_INLINE char_type widen(char __c) const { return do_widen(__c); } _LIBCPP_ALWAYS_INLINE const char* widen(const char* __low, const char* __high, char_type* __to) const { return do_widen(__low, __high, __to); } _LIBCPP_ALWAYS_INLINE char narrow(char_type __c, char __dfault) const { return do_narrow(__c, __dfault); } _LIBCPP_ALWAYS_INLINE const char* narrow(const char_type* __low, const char_type* __high, char __dfault, char* __to) const { return do_narrow(__low, __high, __dfault, __to); } static locale::id id; #ifdef _CACHED_RUNES static const size_t table_size = _CACHED_RUNES; #else static const size_t table_size = 256; // FIXME: Don't hardcode this. #endif _LIBCPP_ALWAYS_INLINE const mask* table() const _NOEXCEPT {return __tab_;} static const mask* classic_table() _NOEXCEPT; #if defined(__GLIBC__) || defined(__EMSCRIPTEN__) static const int* __classic_upper_table() _NOEXCEPT; static const int* __classic_lower_table() _NOEXCEPT; #endif #if defined(__NetBSD__) static const short* __classic_upper_table() _NOEXCEPT; static const short* __classic_lower_table() _NOEXCEPT; #endif protected: ~ctype(); virtual char_type do_toupper(char_type __c) const; virtual const char_type* do_toupper(char_type* __low, const char_type* __high) const; virtual char_type do_tolower(char_type __c) const; virtual const char_type* do_tolower(char_type* __low, const char_type* __high) const; virtual char_type do_widen(char __c) const; virtual const char* do_widen(const char* __low, const char* __high, char_type* __to) const; virtual char do_narrow(char_type __c, char __dfault) const; virtual const char* do_narrow(const char_type* __low, const char_type* __high, char __dfault, char* __to) const; }; // template <class CharT> class ctype_byname; template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY ctype_byname; template <> class _LIBCPP_TYPE_VIS ctype_byname<char> : public ctype<char> { locale_t __l; public: explicit ctype_byname(const char*, size_t = 0); explicit ctype_byname(const string&, size_t = 0); protected: ~ctype_byname(); virtual char_type do_toupper(char_type) const; virtual const char_type* do_toupper(char_type* __low, const char_type* __high) const; virtual char_type do_tolower(char_type) const; virtual const char_type* do_tolower(char_type* __low, const char_type* __high) const; }; template <> class _LIBCPP_TYPE_VIS ctype_byname<wchar_t> : public ctype<wchar_t> { locale_t __l; public: explicit ctype_byname(const char*, size_t = 0); explicit ctype_byname(const string&, size_t = 0); protected: ~ctype_byname(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __low, const char_type* __high, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __low, const char_type* __high) const; virtual const char_type* do_scan_not(mask __m, const char_type* __low, const char_type* __high) const; virtual char_type do_toupper(char_type) const; virtual const char_type* do_toupper(char_type* __low, const char_type* __high) const; virtual char_type do_tolower(char_type) const; virtual const char_type* do_tolower(char_type* __low, const char_type* __high) const; virtual char_type do_widen(char) const; virtual const char* do_widen(const char* __low, const char* __high, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __low, const char_type* __high, char __dfault, char* __dest) const; }; template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isspace(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::space, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isprint(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::print, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool iscntrl(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::cntrl, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isupper(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::upper, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool islower(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::lower, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isalpha(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::alpha, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isdigit(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::digit, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool ispunct(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::punct, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isxdigit(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::xdigit, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isalnum(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::alnum, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY bool isgraph(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).is(ctype_base::graph, __c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY _CharT toupper(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).toupper(__c); } template <class _CharT> inline _LIBCPP_INLINE_VISIBILITY _CharT tolower(_CharT __c, const locale& __loc) { return use_facet<ctype<_CharT> >(__loc).tolower(__c); } // codecvt_base class _LIBCPP_TYPE_VIS codecvt_base { public: _LIBCPP_ALWAYS_INLINE codecvt_base() {} enum result {ok, partial, error, noconv}; }; // template <class internT, class externT, class stateT> class codecvt; template <class _InternT, class _ExternT, class _StateT> class _LIBCPP_TYPE_VIS_ONLY codecvt; // template <> class codecvt<char, char, mbstate_t> template <> class _LIBCPP_TYPE_VIS codecvt<char, char, mbstate_t> : public locale::facet, public codecvt_base { public: typedef char intern_type; typedef char extern_type; typedef mbstate_t state_type; _LIBCPP_ALWAYS_INLINE explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} _LIBCPP_ALWAYS_INLINE result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const { return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE int encoding() const _NOEXCEPT { return do_encoding(); } _LIBCPP_ALWAYS_INLINE bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } _LIBCPP_ALWAYS_INLINE int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } _LIBCPP_ALWAYS_INLINE int max_length() const _NOEXCEPT { return do_max_length(); } static locale::id id; protected: _LIBCPP_ALWAYS_INLINE explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} ~codecvt(); virtual result do_out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual result do_in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; virtual result do_unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual int do_encoding() const _NOEXCEPT; virtual bool do_always_noconv() const _NOEXCEPT; virtual int do_length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const; virtual int do_max_length() const _NOEXCEPT; }; // template <> class codecvt<wchar_t, char, mbstate_t> template <> class _LIBCPP_TYPE_VIS codecvt<wchar_t, char, mbstate_t> : public locale::facet, public codecvt_base { locale_t __l; public: typedef wchar_t intern_type; typedef char extern_type; typedef mbstate_t state_type; explicit codecvt(size_t __refs = 0); _LIBCPP_ALWAYS_INLINE result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const { return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE int encoding() const _NOEXCEPT { return do_encoding(); } _LIBCPP_ALWAYS_INLINE bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } _LIBCPP_ALWAYS_INLINE int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } _LIBCPP_ALWAYS_INLINE int max_length() const _NOEXCEPT { return do_max_length(); } static locale::id id; protected: explicit codecvt(const char*, size_t __refs = 0); ~codecvt(); virtual result do_out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual result do_in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; virtual result do_unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual int do_encoding() const _NOEXCEPT; virtual bool do_always_noconv() const _NOEXCEPT; virtual int do_length(state_type&, const extern_type* __frm, const extern_type* __end, size_t __mx) const; virtual int do_max_length() const _NOEXCEPT; }; // template <> class codecvt<char16_t, char, mbstate_t> template <> class _LIBCPP_TYPE_VIS codecvt<char16_t, char, mbstate_t> : public locale::facet, public codecvt_base { public: typedef char16_t intern_type; typedef char extern_type; typedef mbstate_t state_type; _LIBCPP_ALWAYS_INLINE explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} _LIBCPP_ALWAYS_INLINE result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const { return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE int encoding() const _NOEXCEPT { return do_encoding(); } _LIBCPP_ALWAYS_INLINE bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } _LIBCPP_ALWAYS_INLINE int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } _LIBCPP_ALWAYS_INLINE int max_length() const _NOEXCEPT { return do_max_length(); } static locale::id id; protected: _LIBCPP_ALWAYS_INLINE explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} ~codecvt(); virtual result do_out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual result do_in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; virtual result do_unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual int do_encoding() const _NOEXCEPT; virtual bool do_always_noconv() const _NOEXCEPT; virtual int do_length(state_type&, const extern_type* __frm, const extern_type* __end, size_t __mx) const; virtual int do_max_length() const _NOEXCEPT; }; // template <> class codecvt<char32_t, char, mbstate_t> template <> class _LIBCPP_TYPE_VIS codecvt<char32_t, char, mbstate_t> : public locale::facet, public codecvt_base { public: typedef char32_t intern_type; typedef char extern_type; typedef mbstate_t state_type; _LIBCPP_ALWAYS_INLINE explicit codecvt(size_t __refs = 0) : locale::facet(__refs) {} _LIBCPP_ALWAYS_INLINE result out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const { return do_unshift(__st, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE result in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const { return do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt); } _LIBCPP_ALWAYS_INLINE int encoding() const _NOEXCEPT { return do_encoding(); } _LIBCPP_ALWAYS_INLINE bool always_noconv() const _NOEXCEPT { return do_always_noconv(); } _LIBCPP_ALWAYS_INLINE int length(state_type& __st, const extern_type* __frm, const extern_type* __end, size_t __mx) const { return do_length(__st, __frm, __end, __mx); } _LIBCPP_ALWAYS_INLINE int max_length() const _NOEXCEPT { return do_max_length(); } static locale::id id; protected: _LIBCPP_ALWAYS_INLINE explicit codecvt(const char*, size_t __refs = 0) : locale::facet(__refs) {} ~codecvt(); virtual result do_out(state_type& __st, const intern_type* __frm, const intern_type* __frm_end, const intern_type*& __frm_nxt, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual result do_in(state_type& __st, const extern_type* __frm, const extern_type* __frm_end, const extern_type*& __frm_nxt, intern_type* __to, intern_type* __to_end, intern_type*& __to_nxt) const; virtual result do_unshift(state_type& __st, extern_type* __to, extern_type* __to_end, extern_type*& __to_nxt) const; virtual int do_encoding() const _NOEXCEPT; virtual bool do_always_noconv() const _NOEXCEPT; virtual int do_length(state_type&, const extern_type* __frm, const extern_type* __end, size_t __mx) const; virtual int do_max_length() const _NOEXCEPT; }; // template <class _InternT, class _ExternT, class _StateT> class codecvt_byname template <class _InternT, class _ExternT, class _StateT> class _LIBCPP_TYPE_VIS_ONLY codecvt_byname : public codecvt<_InternT, _ExternT, _StateT> { public: _LIBCPP_ALWAYS_INLINE explicit codecvt_byname(const char* __nm, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__nm, __refs) {} _LIBCPP_ALWAYS_INLINE explicit codecvt_byname(const string& __nm, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__nm.c_str(), __refs) {} protected: ~codecvt_byname(); }; template <class _InternT, class _ExternT, class _StateT> codecvt_byname<_InternT, _ExternT, _StateT>::~codecvt_byname() { } _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname<char, char, mbstate_t>) _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname<wchar_t, char, mbstate_t>) _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname<char16_t, char, mbstate_t>) _LIBCPP_EXTERN_TEMPLATE2(class _LIBCPP_TYPE_VIS codecvt_byname<char32_t, char, mbstate_t>) _LIBCPP_FUNC_VIS void __throw_runtime_error(const char*); template <size_t _Np> struct __narrow_to_utf8 { template <class _OutputIterator, class _CharT> _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const; }; template <> struct __narrow_to_utf8<8> { template <class _OutputIterator, class _CharT> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { for (; __wb < __we; ++__wb, ++__s) *__s = *__wb; return __s; } }; template <> struct __narrow_to_utf8<16> : public codecvt<char16_t, char, mbstate_t> { _LIBCPP_ALWAYS_INLINE __narrow_to_utf8() : codecvt<char16_t, char, mbstate_t>(1) {} ~__narrow_to_utf8(); template <class _OutputIterator, class _CharT> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { result __r = ok; mbstate_t __mb; while (__wb < __we && __r != error) { const int __sz = 32; char __buf[__sz]; char* __bn; const char16_t* __wn = (const char16_t*)__wb; __r = do_out(__mb, (const char16_t*)__wb, (const char16_t*)__we, __wn, __buf, __buf+__sz, __bn); if (__r == codecvt_base::error || __wn == (const char16_t*)__wb) __throw_runtime_error("locale not supported"); for (const char* __p = __buf; __p < __bn; ++__p, ++__s) *__s = *__p; __wb = (const _CharT*)__wn; } return __s; } }; template <> struct __narrow_to_utf8<32> : public codecvt<char32_t, char, mbstate_t> { _LIBCPP_ALWAYS_INLINE __narrow_to_utf8() : codecvt<char32_t, char, mbstate_t>(1) {} ~__narrow_to_utf8(); template <class _OutputIterator, class _CharT> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const _CharT* __wb, const _CharT* __we) const { result __r = ok; mbstate_t __mb; while (__wb < __we && __r != error) { const int __sz = 32; char __buf[__sz]; char* __bn; const char32_t* __wn = (const char32_t*)__wb; __r = do_out(__mb, (const char32_t*)__wb, (const char32_t*)__we, __wn, __buf, __buf+__sz, __bn); if (__r == codecvt_base::error || __wn == (const char32_t*)__wb) __throw_runtime_error("locale not supported"); for (const char* __p = __buf; __p < __bn; ++__p, ++__s) *__s = *__p; __wb = (const _CharT*)__wn; } return __s; } }; template <size_t _Np> struct __widen_from_utf8 { template <class _OutputIterator> _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const; }; template <> struct __widen_from_utf8<8> { template <class _OutputIterator> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { for (; __nb < __ne; ++__nb, ++__s) *__s = *__nb; return __s; } }; template <> struct __widen_from_utf8<16> : public codecvt<char16_t, char, mbstate_t> { _LIBCPP_ALWAYS_INLINE __widen_from_utf8() : codecvt<char16_t, char, mbstate_t>(1) {} ~__widen_from_utf8(); template <class _OutputIterator> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { result __r = ok; mbstate_t __mb; while (__nb < __ne && __r != error) { const int __sz = 32; char16_t __buf[__sz]; char16_t* __bn; const char* __nn = __nb; __r = do_in(__mb, __nb, __ne - __nb > __sz ? __nb+__sz : __ne, __nn, __buf, __buf+__sz, __bn); if (__r == codecvt_base::error || __nn == __nb) __throw_runtime_error("locale not supported"); for (const char16_t* __p = __buf; __p < __bn; ++__p, ++__s) *__s = (wchar_t)*__p; __nb = __nn; } return __s; } }; template <> struct __widen_from_utf8<32> : public codecvt<char32_t, char, mbstate_t> { _LIBCPP_ALWAYS_INLINE __widen_from_utf8() : codecvt<char32_t, char, mbstate_t>(1) {} ~__widen_from_utf8(); template <class _OutputIterator> _LIBCPP_ALWAYS_INLINE _OutputIterator operator()(_OutputIterator __s, const char* __nb, const char* __ne) const { result __r = ok; mbstate_t __mb; while (__nb < __ne && __r != error) { const int __sz = 32; char32_t __buf[__sz]; char32_t* __bn; const char* __nn = __nb; __r = do_in(__mb, __nb, __ne - __nb > __sz ? __nb+__sz : __ne, __nn, __buf, __buf+__sz, __bn); if (__r == codecvt_base::error || __nn == __nb) __throw_runtime_error("locale not supported"); for (const char32_t* __p = __buf; __p < __bn; ++__p, ++__s) *__s = (wchar_t)*__p; __nb = __nn; } return __s; } }; // template <class charT> class numpunct template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY numpunct; template <> class _LIBCPP_TYPE_VIS numpunct<char> : public locale::facet { public: typedef char char_type; typedef basic_string<char_type> string_type; explicit numpunct(size_t __refs = 0); _LIBCPP_ALWAYS_INLINE char_type decimal_point() const {return do_decimal_point();} _LIBCPP_ALWAYS_INLINE char_type thousands_sep() const {return do_thousands_sep();} _LIBCPP_ALWAYS_INLINE string grouping() const {return do_grouping();} _LIBCPP_ALWAYS_INLINE string_type truename() const {return do_truename();} _LIBCPP_ALWAYS_INLINE string_type falsename() const {return do_falsename();} static locale::id id; protected: ~numpunct(); virtual char_type do_decimal_point() const; virtual char_type do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_truename() const; virtual string_type do_falsename() const; char_type __decimal_point_; char_type __thousands_sep_; string __grouping_; }; template <> class _LIBCPP_TYPE_VIS numpunct<wchar_t> : public locale::facet { public: typedef wchar_t char_type; typedef basic_string<char_type> string_type; explicit numpunct(size_t __refs = 0); _LIBCPP_ALWAYS_INLINE char_type decimal_point() const {return do_decimal_point();} _LIBCPP_ALWAYS_INLINE char_type thousands_sep() const {return do_thousands_sep();} _LIBCPP_ALWAYS_INLINE string grouping() const {return do_grouping();} _LIBCPP_ALWAYS_INLINE string_type truename() const {return do_truename();} _LIBCPP_ALWAYS_INLINE string_type falsename() const {return do_falsename();} static locale::id id; protected: ~numpunct(); virtual char_type do_decimal_point() const; virtual char_type do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_truename() const; virtual string_type do_falsename() const; char_type __decimal_point_; char_type __thousands_sep_; string __grouping_; }; // template <class charT> class numpunct_byname template <class _CharT> class _LIBCPP_TYPE_VIS_ONLY numpunct_byname; template <> class _LIBCPP_TYPE_VIS numpunct_byname<char> : public numpunct<char> { public: typedef char char_type; typedef basic_string<char_type> string_type; explicit numpunct_byname(const char* __nm, size_t __refs = 0); explicit numpunct_byname(const string& __nm, size_t __refs = 0); protected: ~numpunct_byname(); private: void __init(const char*); }; template <> class _LIBCPP_TYPE_VIS numpunct_byname<wchar_t> : public numpunct<wchar_t> { public: typedef wchar_t char_type; typedef basic_string<char_type> string_type; explicit numpunct_byname(const char* __nm, size_t __refs = 0); explicit numpunct_byname(const string& __nm, size_t __refs = 0); protected: ~numpunct_byname(); private: void __init(const char*); }; _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP___LOCALE
{ "pile_set_name": "Github" }
import re from lib import BaseTest class EditMirror1Test(BaseTest): """ edit mirror: enable filter """ fixtureDB = True runCmd = "aptly mirror edit -filter=nginx -filter-with-deps wheezy-main" def check(self): self.check_output() self.check_cmd_output("aptly mirror show wheezy-main", "mirror_show", match_prepare=lambda s: re.sub(r"Last update: [0-9:+A-Za-z -]+\n", "", s)) class EditMirror2Test(BaseTest): """ edit mirror: missing mirror """ runCmd = "aptly mirror edit wheezy-main" expectedCode = 1 class EditMirror3Test(BaseTest): """ edit mirror: no changes """ fixtureDB = True runCmd = "aptly mirror edit wheezy-main" def check(self): self.check_output() self.check_cmd_output("aptly mirror show wheezy-main", "mirror_show", match_prepare=lambda s: re.sub(r"Last update: [0-9:+A-Za-z -]+\n", "", s)) class EditMirror4Test(BaseTest): """ edit mirror: wrong query """ fixtureDB = True runCmd = "aptly mirror edit -filter=| wheezy-main" expectedCode = 1 class EditMirror5Test(BaseTest): """ edit mirror: remove filter """ fixtureCmds = [ "aptly mirror create -ignore-signatures -filter='nginx | Priority (required)' mirror5 http://security.debian.org/ wheezy/updates main", ] runCmd = "aptly mirror edit -filter= mirror5" def check(self): def removeDates(s): return re.sub(r"(Date|Valid-Until): [,0-9:+A-Za-z -]+\n", "", s) self.check_output() self.check_cmd_output("aptly mirror show mirror5", "mirror_show", match_prepare=removeDates)
{ "pile_set_name": "Github" }
StartChar: uni06B8.init_LamBaaMemInit Encoding: 66512 -1 1260 Width: 190 Flags: HW AnchorPoint: "TashkilAbove" 73 801 basechar 0 AnchorPoint: "TashkilBelow" 176 -327 basechar 0 LayerCount: 3 Fore Refer: 207 -1 N 1 0 0 1 154 -20 2 Refer: 80 -1 N 1 0 0 1 0 0 3 EndChar
{ "pile_set_name": "Github" }
#### 简单说说 dexopt 与 dex2oat 的区别 dexopt 是对 dex 文件 进行 verification 和 optimization 的操作,其对 dex 文件的优化结果变成了 odex 文件,这个文件和 dex 文件很像,只是使用了一些优化操作码(譬如优化调用虚拟指令等)。 dex2oat 是对 dex 文件的 AOT 提前编译操作,其需要一个 dex 文件,然后对其进行编译,结果是一个本地可执行的 ELF 文件,可以直接被本地处理器执行。 除此之外 Dalvik 虚拟机中有使用 JIT 编译器,也就是说其也能将程序运行的热点 java 字节码编译成本地 code 执行。所以其与 Art 虚拟机还是有区别的,Art 虚拟机的 dex2oat 是提前编译所有 dex 字节码,而 Dalvik 虚拟机只编译使用启发式检测中最频繁执行的热点字节码。
{ "pile_set_name": "Github" }
storage: import: Usage: _build/macosx64/bin/infinit-storage --import --name STORAGE [OPTIONS...] Import storage information: Import options: -i [ --input ] arg File to read the storage from (default: stdin)
{ "pile_set_name": "Github" }
/* * MIT License * * Copyright (c) 2017-2019 nuls.io * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.nuls.contract.storage.service; import io.nuls.contract.dto.ContractTokenTransferInfoPo; import io.nuls.kernel.model.Result; import java.util.List; /** * @desription: * @author: PierreLuo * @date: 2018/8/28 */ public interface ContractTokenTransferStorageService { Result saveTokenTransferInfo(byte[] key, ContractTokenTransferInfoPo tx); Result deleteTokenTransferInfo(byte[] infoKey); Result<ContractTokenTransferInfoPo> getTokenTransferInfo(byte[] infoKey); List<ContractTokenTransferInfoPo> getTokenTransferInfoListByAddress(byte[] address); List<ContractTokenTransferInfoPo> getTokenTransferInfoListByAddress(byte[] address, byte[] txHash); }
{ "pile_set_name": "Github" }
/* * * Copyright 2017 gRPC authors. * * 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 keepalive defines configurable parameters for point-to-point // healthcheck. package keepalive import ( "time" ) // ClientParameters is used to set keepalive parameters on the client-side. // These configure how the client will actively probe to notice when a // connection is broken and send pings so intermediaries will be aware of the // liveness of the connection. Make sure these parameters are set in // coordination with the keepalive policy on the server, as incompatible // settings can result in closing of connection. type ClientParameters struct { // After a duration of this time if the client doesn't see any activity it // pings the server to see if the transport is still alive. // If set below 10s, a minimum value of 10s will be used instead. Time time.Duration // The current default value is infinity. // After having pinged for keepalive check, the client waits for a duration // of Timeout and if no activity is seen even after that the connection is // closed. Timeout time.Duration // The current default value is 20 seconds. // If true, client sends keepalive pings even with no active RPCs. If false, // when there are no active RPCs, Time and Timeout will be ignored and no // keepalive pings will be sent. PermitWithoutStream bool // false by default. } // ServerParameters is used to set keepalive and max-age parameters on the // server-side. type ServerParameters struct { // MaxConnectionIdle is a duration for the amount of time after which an // idle connection would be closed by sending a GoAway. Idleness duration is // defined since the most recent time the number of outstanding RPCs became // zero or the connection establishment. MaxConnectionIdle time.Duration // The current default value is infinity. // MaxConnectionAge is a duration for the maximum amount of time a // connection may exist before it will be closed by sending a GoAway. A // random jitter of +/-10% will be added to MaxConnectionAge to spread out // connection storms. MaxConnectionAge time.Duration // The current default value is infinity. // MaxConnectionAgeGrace is an additive period after MaxConnectionAge after // which the connection will be forcibly closed. MaxConnectionAgeGrace time.Duration // The current default value is infinity. // After a duration of this time if the server doesn't see any activity it // pings the client to see if the transport is still alive. // If set below 1s, a minimum value of 1s will be used instead. Time time.Duration // The current default value is 2 hours. // After having pinged for keepalive check, the server waits for a duration // of Timeout and if no activity is seen even after that the connection is // closed. Timeout time.Duration // The current default value is 20 seconds. } // EnforcementPolicy is used to set keepalive enforcement policy on the // server-side. Server will close connection with a client that violates this // policy. type EnforcementPolicy struct { // MinTime is the minimum amount of time a client should wait before sending // a keepalive ping. MinTime time.Duration // The current default value is 5 minutes. // If true, server allows keepalive pings even when there are no active // streams(RPCs). If false, and client sends ping when there are no active // streams, server will send GOAWAY and close the connection. PermitWithoutStream bool // false by default. }
{ "pile_set_name": "Github" }
--- !COFF header: Machine: IMAGE_FILE_MACHINE_ARMNT Characteristics: [ ] sections: - Name: .rdata Characteristics: [ IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ ] Alignment: 1 SectionData: '' symbols: - Name: Function Value: 0 SectionNumber: 0 SimpleType: IMAGE_SYM_TYPE_NULL ComplexType: IMAGE_SYM_DTYPE_NULL StorageClass: IMAGE_SYM_CLASS_WEAK_EXTERNAL WeakExternal: TagIndex: 9 Characteristics: IMAGE_WEAK_EXTERN_SEARCH_LIBRARY - Name: .weak.Function.default Value: 0 SectionNumber: -1 SimpleType: IMAGE_SYM_TYPE_NULL ComplexType: IMAGE_SYM_DTYPE_NULL StorageClass: IMAGE_SYM_CLASS_EXTERNAL ...
{ "pile_set_name": "Github" }
perf-y += regs_load.o perf-y += dwarf-unwind.o perf-y += vectors-page.o perf-y += arch-tests.o
{ "pile_set_name": "Github" }
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 2000 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Machine-specific command-line options *) let command_line_options = [ "-fPIC", Arg.Set Clflags.pic_code, " Generate position-independent machine code (default)"; "-fno-PIC", Arg.Clear Clflags.pic_code, " Generate position-dependent machine code" ] (* Specific operations for the AMD64 processor *) open Format type addressing_mode = Ibased of string * int (* symbol + displ *) | Iindexed of int (* reg + displ *) | Iindexed2 of int (* reg + reg + displ *) | Iscaled of int * int (* reg * scale + displ *) | Iindexed2scaled of int * int (* reg + reg * scale + displ *) type specific_operation = Ilea of addressing_mode (* "lea" gives scaled adds *) | Istore_int of nativeint * addressing_mode * bool (* Store an integer constant *) | Ioffset_loc of int * addressing_mode (* Add a constant to a location *) | Ifloatarithmem of float_operation * addressing_mode (* Float arith operation with memory *) | Ibswap of int (* endianness conversion *) | Isqrtf (* Float square root *) | Ifloatsqrtf of addressing_mode (* Float square root from memory *) | Isextend32 (* 32 to 64 bit conversion with sign extension *) | Izextend32 (* 32 to 64 bit conversion with zero extension *) and float_operation = Ifloatadd | Ifloatsub | Ifloatmul | Ifloatdiv let spacetime_node_hole_pointer_is_live_before _specific_op = false (* Sizes, endianness *) let big_endian = false let size_addr = 8 let size_int = 8 let size_float = 8 let allow_unaligned_access = true (* Behavior of division *) let division_crashes_on_overflow = true (* Operations on addressing modes *) let identity_addressing = Iindexed 0 let offset_addressing addr delta = match addr with Ibased(s, n) -> Ibased(s, n + delta) | Iindexed n -> Iindexed(n + delta) | Iindexed2 n -> Iindexed2(n + delta) | Iscaled(scale, n) -> Iscaled(scale, n + delta) | Iindexed2scaled(scale, n) -> Iindexed2scaled(scale, n + delta) let num_args_addressing = function Ibased _ -> 0 | Iindexed _ -> 1 | Iindexed2 _ -> 2 | Iscaled _ -> 1 | Iindexed2scaled _ -> 2 (* Printing operations and addressing modes *) let print_addressing printreg addr ppf arg = match addr with | Ibased(s, 0) -> fprintf ppf "\"%s\"" s | Ibased(s, n) -> fprintf ppf "\"%s\" + %i" s n | Iindexed n -> let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in fprintf ppf "%a%s" printreg arg.(0) idx | Iindexed2 n -> let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in fprintf ppf "%a + %a%s" printreg arg.(0) printreg arg.(1) idx | Iscaled(scale, n) -> let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in fprintf ppf "%a * %i%s" printreg arg.(0) scale idx | Iindexed2scaled(scale, n) -> let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in fprintf ppf "%a + %a * %i%s" printreg arg.(0) printreg arg.(1) scale idx let print_specific_operation printreg op ppf arg = match op with | Ilea addr -> print_addressing printreg addr ppf arg | Istore_int(n, addr, is_assign) -> fprintf ppf "[%a] := %nd %s" (print_addressing printreg addr) arg n (if is_assign then "(assign)" else "(init)") | Ioffset_loc(n, addr) -> fprintf ppf "[%a] +:= %i" (print_addressing printreg addr) arg n | Isqrtf -> fprintf ppf "sqrtf %a" printreg arg.(0) | Ifloatsqrtf addr -> fprintf ppf "sqrtf float64[%a]" (print_addressing printreg addr) [|arg.(0)|] | Ifloatarithmem(op, addr) -> let op_name = function | Ifloatadd -> "+f" | Ifloatsub -> "-f" | Ifloatmul -> "*f" | Ifloatdiv -> "/f" in fprintf ppf "%a %s float64[%a]" printreg arg.(0) (op_name op) (print_addressing printreg addr) (Array.sub arg 1 (Array.length arg - 1)) | Ibswap i -> fprintf ppf "bswap_%i %a" i printreg arg.(0) | Isextend32 -> fprintf ppf "sextend32 %a" printreg arg.(0) | Izextend32 -> fprintf ppf "zextend32 %a" printreg arg.(0) let win64 = match Config.system with | "win64" | "mingw64" | "cygwin" -> true | _ -> false
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <DelphiIDETheme modified="2013-04-24 20:47:48" author="Delphi IDE Theme Editor" versionapp="1.1.18.1"> <AdditionalSearchMatchHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FF9933</BackgroundColorNew> </AdditionalSearchMatchHighlight> <Assembler> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00FF0000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Assembler> <AttributeNames> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$000000FF</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </AttributeNames> <AttributeValues> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00FF0000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </AttributeValues> <BraceHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00CCE0DB</BackgroundColorNew> </BraceHighlight> <Character> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$001515A3</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Character> <CodeFoldingTree> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </CodeFoldingTree> <Comment> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00008000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Comment> <DiffAddition> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00CCFFCC</BackgroundColorNew> </DiffAddition> <DiffDeletion> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </DiffDeletion> <DiffMove> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00AAFFFF</BackgroundColorNew> </DiffMove> <DisabledBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clGray</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </DisabledBreak> <EnabledBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FFC7C7</BackgroundColorNew> </EnabledBreak> <ErrorLine> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clWhite</ForegroundColorNew> <BackgroundColorNew>clRed</BackgroundColorNew> </ErrorLine> <ExecutionPoint> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$009999CC</BackgroundColorNew> </ExecutionPoint> <Float> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Float> <FoldedCode> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00CC9999</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </FoldedCode> <Hex> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Hex> <HotLink> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00FF0000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </HotLink> <Identifier> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Identifier> <IllegalChar> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$000000FF</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </IllegalChar> <InvalidBreak> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clWhite</ForegroundColorNew> <BackgroundColorNew>clGreen</BackgroundColorNew> </InvalidBreak> <LineHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FF9933</BackgroundColorNew> </LineHighlight> <LineNumber> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </LineNumber> <MarkedBlock> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FF9933</BackgroundColorNew> </MarkedBlock> <ModifiedLine> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clLime</ForegroundColorNew> <BackgroundColorNew>clYellow</BackgroundColorNew> </ModifiedLine> <Number> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Number> <Octal> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Octal> <PlainText> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </PlainText> <Preprocessor> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00FF0000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Preprocessor> <ReservedWord> <Bold>True</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00882B77</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </ReservedWord> <RightMargin> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00F0F0F0</BackgroundColorNew> </RightMargin> <Scripts> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>True</DefaultBackground> <ForegroundColorNew>clPurple</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </Scripts> <SearchMatch> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FF9933</BackgroundColorNew> </SearchMatch> <String> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$001515A3</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </String> <Symbol> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Symbol> <SyncEditBackground> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>True</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlack</ForegroundColorNew> <BackgroundColorNew>$00FAFFE6</BackgroundColorNew> </SyncEditBackground> <SyncEditHighlight> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>clBlue</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </SyncEditHighlight> <Tags> <Bold>True</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>True</DefaultBackground> <ForegroundColorNew>clNavy</ForegroundColorNew> <BackgroundColorNew>clWhite</BackgroundColorNew> </Tags> <Whitespace> <Bold>False</Bold> <Italic>False</Italic> <Underline>False</Underline> <DefaultForeground>False</DefaultForeground> <DefaultBackground>False</DefaultBackground> <ForegroundColorNew>$00000000</ForegroundColorNew> <BackgroundColorNew>$00FFFFFF</BackgroundColorNew> </Whitespace> </DelphiIDETheme>
{ "pile_set_name": "Github" }
{ "frameGrid" : { "size" : [24, 11], "dimensions" : [8, 2], "names" : [ [ "idle.1", "idle.2", "idle.3", "idle.4", "idle.5", "idle.6", "idle.7", "idle.8" ], [ "walk.1", "walk.2", "walk.3", "walk.4", "walk.5", "walk.6", "walk.7", "walk.8" ] ] } }
{ "pile_set_name": "Github" }
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. as.list.xts <- function(x, ...) { if( NCOL(x) == 1 ) return(structure(list(x),.Names=colnames(x))) cindex <- cnames <- colnames(x) if(is.null(cnames)) { cindex <- 1:NCOL(x) cnames <- paste("x",cindex,sep=".") } names(cindex) <- cnames lapply(cindex, function(f) x[,f], ...) }
{ "pile_set_name": "Github" }
horizon.instances = { user_decided_length: false, getConsoleLog: function(via_user_submit) { var form_element = $("#tail_length"), data; if (!via_user_submit) { via_user_submit = false; } if(this.user_decided_length) { data = $(form_element).serialize(); } else { data = "length=35"; } $.ajax({ url: $(form_element).attr('action'), data: data, method: 'get', success: function(response_body) { $('pre.logs').text(response_body); }, error: function(response) { if(via_user_submit) { horizon.clearErrorMessages(); horizon.alert('error', gettext('There was a problem communicating with the server, please try again.')); } } }); }, disable_launch_button: function() { var launch_button = "#instances__action_launch"; $(launch_button).click(function(e) { if ($(launch_button).hasClass("disabled")) { e.preventDefault(); e.stopPropagation(); } }); } }; horizon.addInitFunction(function () { $(document).on('submit', '#tail_length', function (evt) { horizon.instances.user_decided_length = true; horizon.instances.getConsoleLog(true); evt.preventDefault(); }); // Disable the launch button if required horizon.instances.disable_launch_button(); /* Launch instance workflow */ // Handle field toggles for the Launch Instance source type field function update_launch_source_displayed_fields (field) { var $this = $(field), base_type = $this.val(); $this.find("option").each(function () { if (this.value != base_type) { $("#id_" + this.value).closest(".control-group").hide(); } else { $("#id_" + this.value).closest(".control-group").show(); } }); } $(document).on('change', '.workflow #id_source_type', function (evt) { update_launch_source_displayed_fields(this); }); $('.workflow #id_source_type').change(); horizon.modals.addModalInitFunction(function (modal) { $(modal).find("#id_source_type").change(); }); // Handle field toggles for the Launch Instance volume type field function update_launch_volume_displayed_fields (field) { var $this = $(field), volume_opt = $this.val(), $extra_fields = $("#id_delete_on_terminate, #id_device_name"); $this.find("option").each(function () { if (this.value != volume_opt) { $("#id_" + this.value).closest(".control-group").hide(); } else { $("#id_" + this.value).closest(".control-group").show(); } }); if (volume_opt === "volume_id" || volume_opt === "volume_snapshot_id") { $extra_fields.closest(".control-group").show(); } else { $extra_fields.closest(".control-group").hide(); } } $(document).on('change', '.workflow #id_volume_type', function (evt) { update_launch_volume_displayed_fields(this); }); $('.workflow #id_volume_type').change(); horizon.modals.addModalInitFunction(function (modal) { $(modal).find("#id_volume_type").change(); }); });
{ "pile_set_name": "Github" }
<?php namespace OFFLINE\Mall\Tests\Models; use DB; use October\Rain\Exception\ValidationException; use OFFLINE\Mall\Classes\Exceptions\OutOfStockException; use OFFLINE\Mall\Models\Cart; use OFFLINE\Mall\Models\Customer; use OFFLINE\Mall\Models\CustomField; use OFFLINE\Mall\Models\CustomFieldOption; use OFFLINE\Mall\Models\CustomFieldValue; use OFFLINE\Mall\Models\Discount; use OFFLINE\Mall\Models\Price; use OFFLINE\Mall\Models\Product; use OFFLINE\Mall\Models\ShippingMethod; use OFFLINE\Mall\Models\Variant; use OFFLINE\Mall\Tests\PluginTestCase; class CartTest extends PluginTestCase { public function test_it_stacks_products() { $product = Product::first(); $product->stackable = true; $product->save(); $cart = new Cart(); $cart->addProduct($product); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $cart->addProduct($product); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(2, $cart->products->first()->quantity); } public function test_it_stacks_variants() { $product = Product::first(); $product->stackable = true; $product->save(); $variant = new Variant(); $variant->name = 'Variant'; $variant->product_id = $product->id; $variant->stock = 20; $variant->save(); $cart = new Cart(); $cart->addProduct($product, 1, $variant); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $cart->addProduct($product, 1, $variant); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(2, $cart->products->first()->quantity); } public function test_it_doesnt_stack_unstackable_variants() { $product = Product::first(); $product->stackable = false; $product->save(); $variant = new Variant(); $variant->name = 'Variant'; $variant->product_id = $product->id; $variant->stock = 20; $variant->save(); $cart = new Cart(); $cart->addProduct($product, 1, $variant); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $cart->addProduct($product, 1, $variant); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); } public function test_it_stacks_custom_field_variants() { $product = Product::first(); $product->stackable = true; $product->save(); $sizeA = new CustomFieldOption(); $sizeA->name = 'Size A'; $sizeA->sort_order = 1; $sizeA->save(); $sizeA->prices()->save(new Price([ 'currency_id' => 1, 'price' => 100, ])); $field = new CustomField(); $field->name = 'Size'; $field->type = 'dropdown'; $field->save(); $field->custom_field_options()->save($sizeA); $product->custom_fields()->attach($field); $customFieldValue = new CustomFieldValue(); $customFieldValue->custom_field_id = $field->id; $customFieldValue->custom_field_option_id = $sizeA->id; $customFieldValue->save(); $cart = new Cart(); $cart->addProduct($product, 1, null, collect([$customFieldValue])); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValue->id, $cart->products->first()->fresh()->custom_field_values[0]->id); $cart->addProduct($product, 1, null, collect([$customFieldValue])); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(2, $cart->products->first()->quantity); $this->assertEquals($customFieldValue->id, $cart->products->first()->fresh()->custom_field_values[0]->id); } public function test_it_doesnt_stack_products() { $product = Product::first(); $product->stackable = false; $product->save(); $cart = new Cart(); $cart->addProduct($product); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $cart->addProduct($product); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); } public function test_it_doesnt_stack_product_custom_field_variants() { $product = Product::first(); $product->stackable = false; $product->save(); $sizeA = new CustomFieldOption(); $sizeA->name = 'Size A'; $sizeA->sort_order = 1; $sizeA->save(); $sizeA->prices()->save(new Price([ 'currency_id' => 1, 'price' => 100, ])); $field = new CustomField(); $field->name = 'Size'; $field->type = 'dropdown'; $field->save(); $field->custom_field_options()->save($sizeA); $product->custom_fields()->attach($field); $customFieldValue = new CustomFieldValue(); $customFieldValue->custom_field_id = $field->id; $customFieldValue->custom_field_option_id = $sizeA->id; $customFieldValue->save(); $cart = new Cart(); $cart->addProduct($product, 1, null, collect([$customFieldValue])); $cart->products->first()->refresh('custom_field_values'); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValue->id, $cart->products->first()->fresh()->custom_field_values[0]->id); $cart->addProduct($product, 1, null, collect([$customFieldValue])); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValue->id, $cart->products[1]->fresh()->custom_field_values[0]->id); } public function test_it_doesnt_stack_different_custom_fields_product_variants() { $product = Product::first(); $product->stackable = true; $product->save(); $sizeA = new CustomFieldOption(); $sizeA->name = 'Size A'; $sizeA->sort_order = 1; $sizeB = new CustomFieldOption(); $sizeB->name = 'Size B'; $sizeB->sort_order = 2; $field = new CustomField(); $field->name = 'Size'; $field->type = 'dropdown'; $field->save(); $field->custom_field_options()->save($sizeA); $field->custom_field_options()->save($sizeB); $product->custom_fields()->attach($field); $customFieldValueA = new CustomFieldValue(); $customFieldValueA->custom_field_id = $field->id; $customFieldValueA->custom_field_option_id = $sizeA->id; $customFieldValueB = new CustomFieldValue(); $customFieldValueB->custom_field_id = $field->id; $customFieldValueB->custom_field_option_id = $sizeB->id; $cart = new Cart(); $cart->addProduct($product, 1, null, collect([$customFieldValueA])); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValueA->id, $cart->products->first()->fresh()->custom_field_values[0]->id); $cart->addProduct($product, 1, null, collect([$customFieldValueB])); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValueA->id, $cart->products[0]->fresh()->custom_field_values[0]->id); $this->assertEquals($customFieldValueB->id, $cart->products[1]->fresh()->custom_field_values[0]->id); } public function test_it_doesnt_stack_different_custom_field_product_variants_with_text_values() { $product = Product::first(); $product->stackable = true; $product->save(); $field = new CustomField(); $field->name = 'Size'; $field->type = 'text'; $field->save(); $product->custom_fields()->attach($field); $customFieldValueA = new CustomFieldValue(); $customFieldValueA->custom_field_id = $field->id; $customFieldValueA->value = 'Test'; $customFieldValueB = new CustomFieldValue(); $customFieldValueB->custom_field_id = $field->id; $customFieldValueA->value = 'Test'; $cart = new Cart(); $cart->addProduct($product, 1, null, collect([$customFieldValueA])); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValueA->id, $cart->products->first()->fresh()->custom_field_values[0]->id); $cart->addProduct($product, 1, null, collect([$customFieldValueB])); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->quantity); $this->assertEquals($customFieldValueA->id, $cart->products[0]->fresh()->custom_field_values[0]->id); $this->assertEquals($customFieldValueB->id, $cart->products[1]->fresh()->custom_field_values[0]->id); } public function test_it_uses_default_quantity() { $product = Product::first(); $product->quantity_default = 4; $product->save(); $cart = new Cart(); $cart->addProduct($product); $this->assertEquals(4, $cart->products->first()->quantity); } public function test_it_enforces_min_quantity() { $product = Product::first(); $product->quantity_min = 4; $product->save(); $cart = new Cart(); $cart->addProduct($product, 2); $this->assertEquals(4, $cart->products->first()->quantity); } public function test_it_enforces_max_quantity() { $product = Product::first(); $product->quantity_max = 4; $product->save(); $cart = new Cart(); $cart->addProduct($product, 12); $this->assertEquals(4, $cart->products->first()->quantity); } public function test_it_detects_product_out_of_stock_quantity() { $this->expectException(OutOfStockException::class); $product = Product::first(); $product->stock = 4; $product->save(); $cart = new Cart(); $cart->addProduct($product, 5); $this->assertEquals(0, $cart->products->count()); } public function test_it_detects_variant_out_of_stock_quantity() { $this->expectException(OutOfStockException::class); $product = Product::first(); $product->save(); $variant = new Variant(); $variant->name = 'Variant'; $variant->product_id = $product->id; $variant->stock = 10; $variant->save(); $cart = new Cart(); $cart->addProduct($product, 11, $variant); $this->assertEquals(0, $cart->products->count()); } public function test_it_allows_variant_out_of_stock_purchase() { $product = Product::first(); $product->save(); $variant = new Variant(); $variant->name = 'Variant'; $variant->product_id = $product->id; $variant->allow_out_of_stock_purchases = true; $variant->stock = 10; $variant->save(); $cart = new Cart(); $cart->addProduct($product, 11, $variant); $this->assertEquals(1, $cart->products->count()); } public function test_it_allows_product_out_of_stock_purchase() { $product = Product::first(); $product->allow_out_of_stock_purchases = true; $product->stock = 10; $product->save(); $cart = new Cart(); $cart->addProduct($product, 11); $this->assertEquals(1, $cart->products->count()); } public function test_it_enforces_max_quantity_on_stacked_products() { $product = Product::first(); $product->stackable = true; $product->quantity_max = 4; $product->save(); $cart = new Cart(); $cart->addProduct($product, 2); $this->assertEquals(2, $cart->products->first()->quantity); $cart->addProduct($product, 3); $this->assertEquals(4, $cart->products->first()->quantity); } public function test_it_increases_the_quantity_for_stacked_products() { $product = Product::first(); $product->stackable = true; $product->save(); $cart = new Cart(); $cart->addProduct($product, 2); $this->assertEquals(2, $cart->products->first()->quantity); $cart->addProduct($product, 3); $this->assertEquals(5, $cart->products->first()->quantity); } public function test_the_same_discount_cannot_be_applied_twice() { $this->expectException(ValidationException::class); $product = Product::first(); $product->save(); $cart = new Cart(); $cart->addProduct($product); $discount = new Discount(); $discount->code = 'Test'; $discount->name = 'Test discount'; $discount->type = 'rate'; $discount->rate = 25; $discount->save(); $cart->applyDiscount($discount); $cart->applyDiscount($discount); $this->assertEquals(1, $cart->discounts->count()); } public function test_only_one_shipping_discount_is_applied() { $this->expectException(ValidationException::class); $product = Product::first(); $product->save(); $cart = new Cart(); $cart->addProduct($product); $discountA = new Discount(); $discountA->code = 'Test'; $discountA->name = 'Test discount'; $discountA->type = 'shipping'; $discountA->shipping_description = 'Test shipping'; $discountA->save(); $discountA->shipping_prices()->save(new Price([ 'currency_id' => 1, 'price' => 25, 'field' => 'shipping_price', ])); $discountB = $discountA->replicate(); $discountB->save(); $cart->applyDiscount($discountA); $cart->applyDiscount($discountB); $this->assertEquals(1, $cart->discounts->count()); } public function test_shipping_method_gets_reset_if_it_becomes_unavailable() { DB::table('offline_mall_shipping_methods')->truncate(); $product = Product::first(); $product->stock = 100; $product->save(); $product->price = [ 'CHF' => 100, ]; $product = Product::first(); $availableMethod = $this->getShippingMethod(); $availableMethod->save(); $availableMethod->available_above_totals()->save(new Price([ 'currency_id' => 1, 'price' => 100, 'field' => 'available_above_totals', ])); $unavailableMethod = $this->getShippingMethod(); $unavailableMethod->save(); $unavailableMethod->available_above_totals()->save(new Price([ 'currency_id' => 1, 'price' => 200, 'field' => 'available_above_totals', ])); $cart = new Cart(); $cart->addProduct($product, 2); $cart->setShippingMethod($unavailableMethod); $available = ShippingMethod::getAvailableByCart($cart); $this->assertCount(2, $available); $this->assertEquals($unavailableMethod->id, $cart->shipping_method_id); // Remove one item so that the selected shipping method becomes unavailable $cart->setQuantity($cart->products->first()->id, 1); $available = ShippingMethod::getAvailableByCart($cart); $this->assertCount(1, $available); $this->assertEquals($availableMethod->id, $cart->shipping_method_id); } public function test_shipping_method_gets_nulled_of_none_is_available() { DB::table('offline_mall_shipping_methods')->truncate(); $product = Product::first(); $product->price = ['CHF' => 100, 'EUR' => 150]; $product = Product::first(); $availableMethod = $this->getShippingMethod(); $availableMethod->save(); $availableMethod->available_below_totals()->save(new Price([ 'currency_id' => 1, 'price' => 200, 'field' => 'available_below_totals', ])); $cart = new Cart(); $cart->addProduct($product, 1); $cart->setShippingMethod($availableMethod); $this->assertEquals($availableMethod->id, $cart->shipping_method_id); // The selected shipping method becomes unavailable $cart->addProduct($product, 1); $available = ShippingMethod::getAvailableByCart($cart); $this->assertCount(0, $available); $this->assertNull($cart->shipping_method_id); } public function test_transferred_carts_get_merged() { $customer = Customer::first(); $prod1 = Product::find(1); $prod2 = Product::find(2); // Create an existing Cart for a customer. $cart = new Cart(); $cart->customer_id = $customer->id; $cart->save(); $cart->addProduct($prod1); $this->assertEquals(1, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->id); // Create a new Cart and transfer it to the customer. The Carts // have to be merged. $cart = new Cart(); $cart->save(); $cart->addProduct($prod2); $cart->transferToCustomer($customer); $cart = $cart->fresh(); $this->assertEquals(2, $cart->products->count()); $this->assertEquals(1, $cart->products->first()->id); $this->assertEquals(2, $cart->products->last()->id); } /** * @return ShippingMethod */ protected function getShippingMethod(): ShippingMethod { $availableMethod = new ShippingMethod(); $availableMethod->name = 'Available'; $availableMethod->sort_order = 1; $availableMethod->save(); $availableMethod->prices()->save(new Price([ 'currency_id' => 1, 'price' => 100, ])); return $availableMethod; } }
{ "pile_set_name": "Github" }
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * acl.h * * Copyright (C) 2004, 2008 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef OCFS2_ACL_H #define OCFS2_ACL_H #include <linux/posix_acl_xattr.h> struct ocfs2_acl_entry { __le16 e_tag; __le16 e_perm; __le32 e_id; }; struct posix_acl *ocfs2_iop_get_acl(struct inode *inode, int type); int ocfs2_iop_set_acl(struct inode *inode, struct posix_acl *acl, int type); int ocfs2_set_acl(handle_t *handle, struct inode *inode, struct buffer_head *di_bh, int type, struct posix_acl *acl, struct ocfs2_alloc_context *meta_ac, struct ocfs2_alloc_context *data_ac); extern int ocfs2_acl_chmod(struct inode *, struct buffer_head *); extern int ocfs2_init_acl(handle_t *, struct inode *, struct inode *, struct buffer_head *, struct buffer_head *, struct ocfs2_alloc_context *, struct ocfs2_alloc_context *); #endif /* OCFS2_ACL_H */
{ "pile_set_name": "Github" }
# # This is not a complete Makefile of itself. # Instead, it is designed to be easily embeddable # into other systems of Makefiles. # CONVERT_SRCS = \ srcpos.c \ util.c CONVERT_GEN_SRCS = convert-dtsv0-lexer.lex.c CONVERT_OBJS = $(CONVERT_SRCS:%.c=%.o) $(CONVERT_GEN_SRCS:%.c=%.o)
{ "pile_set_name": "Github" }
code = File.read($*[0]) stack = [] pos = 0 parse = ->(re) do m = code.match(re, pos) pos = m.end(0) - 1 m[1] end while code[pos] case code[pos] when /\d/ then s = parse[/(\d+)/]; stack << s.to_i when /[a-z]/ then stack << code[pos].to_sym when ?+ then a, b = stack.pop, stack.pop; stack << b + a when ?- then a, b = stack.pop, stack.pop; stack << b - a when ?* then a, b = stack.pop, stack.pop; stack << b * a when ?/ then a, b = stack.pop, stack.pop; stack << b / a when ?& then a, b = stack.pop, stack.pop; stack << b & a when ?| then a, b = stack.pop, stack.pop; stack << b | a when ?_ then stack << -stack.pop when ?~ then stack << ~stack.pop when ?= then a, b = stack.pop, stack.pop; stack << (b == a ? -1 : 0) when ?> then a, b = stack.pop, stack.pop; stack << (b > a ? -1 : 0) when ?% then stack.pop when ?$ then stack << stack.last when ?\\ then a, b = stack.pop, stack.pop; stack << a << b when ?@ then a, b, c = stack.pop, stack.pop, stack.pop; stack << b << a << c when ?O then a = stack.pop; stack << stack[-1 - a] when ?: then a, b = stack.pop, stack.pop; vars[a] = b when ?; then a = stack.pop; stack << vars[a] when ?. then print "%d" % stack.pop when ?, then print stack.pop.chr when ?^ then stack << $stdin.getc when ?B then $stdin.flush; $stdout.flush when ?" then s = parse[/"(.*?)"/]; print s when ?{ then s = parse[/\}/] when ?' then stack << code[pos += 1].ord when ?` then raise when ?[ stack << [:func, pos] m = code.match(/(?<b>\[(\g<b>|\{.*?\}|\".*?\"|[^\{\}\"\[\]])*\])/) pos = m.end(0) - 1 when ?] case npos = ret.pop when :det if stack.pop == 0 pos = ret.pop ret.pop; ret.pop else ret << :body pos = ret[-3] end when :body stack << :det pos = ret[-4] else pos = npos end when ?! then ret << pos; pos = stack.pop[1] when ?? tpos = stack.pop[1]; b = stack.pop; (ret << pos; pos = tpos) if b when ?# body = stack.pop[1] det = stack.pop[1] ret << det << body << pos << :det pos = det when /\A\s\z/ else raise "unknown symbol: %p" % code[pos] end pos += 1 end
{ "pile_set_name": "Github" }
describe 'The mock server should be able to search mock details' do before :each do data = { has_before_script: true, before_script_name: 'before_script_name.rb', has_after_script: true, after_script_name: 'after_script_name.rb', mock_cookie: 'cookie_name 987654321' } TestHelper.insert_mock_row_into_db(data) visit('/mock/search') fill_in('search_mock_request_url', with: 'a/test/url') click_button('Search') click_link('1', href: '/mock/update/1') click_button('Show Advanced Options') end it 'Should be able to retrieve details of an existing mock' do expect(find('#mock_name').value).to eq('TEST MOCK 1') expect(find('#mock_http_status').value).to eq('200') expect(find('#chk_mock_state').value).to eq('1') expect(find('#mock_request_url').value).to eq('a/test/url') expect(page).to have_select('sl_mock_http_verb', selected: 'GET') expect(page).to have_select('sl_mock_environment', selected: 'production') expect(page).to have_select('id_mock_content_type', selected: 'text/plain') expect(find('#mock_data_response_headers').value).to eq('x:==:y') expect(find('#chk_has_before_script').value).to eq('1') expect(find('#chk_has_after_script').value).to eq('1') expect(find('#before_script_name').value).to eq('before_script_name.rb') expect(find('#after_script_name').value).to eq('after_script_name.rb') expect(find('#mock_cookie').value).to eq('cookie_name 987654321') end it 'Should be able to update an attribute of the mock data' do fill_in('mock_http_status', with: 503) select 'POST', :from => 'sl_mock_http_verb' click_button('Create/Update Mock Data') expect(page).to have_content('Mock Data - UPDATED') click_link('Search', href: '/mock/search') fill_in('search_mock_request_url', with: 'a/test/url') click_button('Search') expect(page).to have_content('503') expect(page).to have_content('POST') end end
{ "pile_set_name": "Github" }
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_java_awt_peer_gtk_GtkCursor__ #define __gnu_java_awt_peer_gtk_GtkCursor__ #pragma interface #include <java/awt/Cursor.h> extern "Java" { namespace gnu { namespace java { namespace awt { namespace peer { namespace gtk { class GtkCursor; class GtkImage; } } } } } namespace java { namespace awt { class Image; class Point; } } } class gnu::java::awt::peer::gtk::GtkCursor : public ::java::awt::Cursor { public: // actually package-private GtkCursor(::java::awt::Image *, ::java::awt::Point *, ::java::lang::String *); virtual ::gnu::java::awt::peer::gtk::GtkImage * getGtkImage(); virtual ::java::awt::Point * getHotspot(); private: ::gnu::java::awt::peer::gtk::GtkImage * __attribute__((aligned(__alignof__( ::java::awt::Cursor)))) image; ::java::awt::Point * hotspot; public: static ::java::lang::Class class$; }; #endif // __gnu_java_awt_peer_gtk_GtkCursor__
{ "pile_set_name": "Github" }
# model settings model = dict( type='FasterRCNN', pretrained='open-mmlab://resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='GARPNHead', in_channels=256, feat_channels=256, octave_base_scale=8, scales_per_octave=3, octave_ratios=[0.5, 1.0, 2.0], anchor_strides=[4, 8, 16, 32, 64], anchor_base_sizes=None, anchoring_means=[.0, .0, .0, .0], anchoring_stds=[0.07, 0.07, 0.14, 0.14], target_means=(.0, .0, .0, .0), target_stds=[0.07, 0.07, 0.11, 0.11], loc_filter_thr=0.01, loss_loc=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='SharedFCBBoxHead', num_fcs=2, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=81, target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1], reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))) # model training and testing settings train_cfg = dict( rpn=dict( ga_assigner=dict( type='ApproxMaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), ga_sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, center_ratio=0.2, ignore_ratio=0.5, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_num=300, nms_thr=0.7, min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), pos_weight=-1, debug=False)) test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_num=300, nms_thr=0.7, min_bbox_size=0), rcnn=dict( score_thr=1e-3, nms=dict(type='nms', iou_thr=0.5), max_per_img=100)) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) data = dict( imgs_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0.5, with_mask=False, with_crowd=True, with_label=True), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=True, with_label=True), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_label=False, test_mode=True)) # optimizer optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]) checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable # runtime settings total_epochs = 12 dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = './work_dirs/ga_faster_rcnn_r50_caffe_fpn_1x' load_from = None resume_from = None workflow = [('train', 1)]
{ "pile_set_name": "Github" }
{ "file_format_version" : "1.0.0", "layer" : { "name": "VK_LAYER_LUNARG_test", "type": "GLOBAL", "library_path": ".\\libVkLayer_test.dll", "api_version": "1.1.74", "implementation_version": "1", "description": "LunarG Test Layer", "enable_environment": { "ENABLE_LAYER_TEST_1": "enable" }, "disable_environment": { "DISABLE_LAYER_TEST_1": "" } } }
{ "pile_set_name": "Github" }
/* * Generic HDLC support routines for Linux * Point-to-point protocol support * * Copyright (C) 1999 - 2008 Krzysztof Halasa <khc@pm.waw.pl> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. */ #include <linux/errno.h> #include <linux/hdlc.h> #include <linux/if_arp.h> #include <linux/inetdevice.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/pkt_sched.h> #include <linux/poll.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <linux/spinlock.h> #define DEBUG_CP 0 /* also bytes# to dump */ #define DEBUG_STATE 0 #define DEBUG_HARD_HEADER 0 #define HDLC_ADDR_ALLSTATIONS 0xFF #define HDLC_CTRL_UI 0x03 #define PID_LCP 0xC021 #define PID_IP 0x0021 #define PID_IPCP 0x8021 #define PID_IPV6 0x0057 #define PID_IPV6CP 0x8057 enum {IDX_LCP = 0, IDX_IPCP, IDX_IPV6CP, IDX_COUNT}; enum {CP_CONF_REQ = 1, CP_CONF_ACK, CP_CONF_NAK, CP_CONF_REJ, CP_TERM_REQ, CP_TERM_ACK, CP_CODE_REJ, LCP_PROTO_REJ, LCP_ECHO_REQ, LCP_ECHO_REPLY, LCP_DISC_REQ, CP_CODES}; #if DEBUG_CP static const char *const code_names[CP_CODES] = { "0", "ConfReq", "ConfAck", "ConfNak", "ConfRej", "TermReq", "TermAck", "CodeRej", "ProtoRej", "EchoReq", "EchoReply", "Discard" }; static char debug_buffer[64 + 3 * DEBUG_CP]; #endif enum {LCP_OPTION_MRU = 1, LCP_OPTION_ACCM, LCP_OPTION_MAGIC = 5}; struct hdlc_header { u8 address; u8 control; __be16 protocol; }; struct cp_header { u8 code; u8 id; __be16 len; }; struct proto { struct net_device *dev; struct timer_list timer; unsigned long timeout; u16 pid; /* protocol ID */ u8 state; u8 cr_id; /* ID of last Configuration-Request */ u8 restart_counter; }; struct ppp { struct proto protos[IDX_COUNT]; spinlock_t lock; unsigned long last_pong; unsigned int req_timeout, cr_retries, term_retries; unsigned int keepalive_interval, keepalive_timeout; u8 seq; /* local sequence number for requests */ u8 echo_id; /* ID of last Echo-Request (LCP) */ }; enum {CLOSED = 0, STOPPED, STOPPING, REQ_SENT, ACK_RECV, ACK_SENT, OPENED, STATES, STATE_MASK = 0xF}; enum {START = 0, STOP, TO_GOOD, TO_BAD, RCR_GOOD, RCR_BAD, RCA, RCN, RTR, RTA, RUC, RXJ_GOOD, RXJ_BAD, EVENTS}; enum {INV = 0x10, IRC = 0x20, ZRC = 0x40, SCR = 0x80, SCA = 0x100, SCN = 0x200, STR = 0x400, STA = 0x800, SCJ = 0x1000}; #if DEBUG_STATE static const char *const state_names[STATES] = { "Closed", "Stopped", "Stopping", "ReqSent", "AckRecv", "AckSent", "Opened" }; static const char *const event_names[EVENTS] = { "Start", "Stop", "TO+", "TO-", "RCR+", "RCR-", "RCA", "RCN", "RTR", "RTA", "RUC", "RXJ+", "RXJ-" }; #endif static struct sk_buff_head tx_queue; /* used when holding the spin lock */ static int ppp_ioctl(struct net_device *dev, struct ifreq *ifr); static inline struct ppp* get_ppp(struct net_device *dev) { return (struct ppp *)dev_to_hdlc(dev)->state; } static inline struct proto* get_proto(struct net_device *dev, u16 pid) { struct ppp *ppp = get_ppp(dev); switch (pid) { case PID_LCP: return &ppp->protos[IDX_LCP]; case PID_IPCP: return &ppp->protos[IDX_IPCP]; case PID_IPV6CP: return &ppp->protos[IDX_IPV6CP]; default: return NULL; } } static inline const char* proto_name(u16 pid) { switch (pid) { case PID_LCP: return "LCP"; case PID_IPCP: return "IPCP"; case PID_IPV6CP: return "IPV6CP"; default: return NULL; } } static __be16 ppp_type_trans(struct sk_buff *skb, struct net_device *dev) { struct hdlc_header *data = (struct hdlc_header*)skb->data; if (skb->len < sizeof(struct hdlc_header)) return htons(ETH_P_HDLC); if (data->address != HDLC_ADDR_ALLSTATIONS || data->control != HDLC_CTRL_UI) return htons(ETH_P_HDLC); switch (data->protocol) { case cpu_to_be16(PID_IP): skb_pull(skb, sizeof(struct hdlc_header)); return htons(ETH_P_IP); case cpu_to_be16(PID_IPV6): skb_pull(skb, sizeof(struct hdlc_header)); return htons(ETH_P_IPV6); default: return htons(ETH_P_HDLC); } } static int ppp_hard_header(struct sk_buff *skb, struct net_device *dev, u16 type, const void *daddr, const void *saddr, unsigned int len) { struct hdlc_header *data; #if DEBUG_HARD_HEADER printk(KERN_DEBUG "%s: ppp_hard_header() called\n", dev->name); #endif skb_push(skb, sizeof(struct hdlc_header)); data = (struct hdlc_header*)skb->data; data->address = HDLC_ADDR_ALLSTATIONS; data->control = HDLC_CTRL_UI; switch (type) { case ETH_P_IP: data->protocol = htons(PID_IP); break; case ETH_P_IPV6: data->protocol = htons(PID_IPV6); break; case PID_LCP: case PID_IPCP: case PID_IPV6CP: data->protocol = htons(type); break; default: /* unknown protocol */ data->protocol = 0; } return sizeof(struct hdlc_header); } static void ppp_tx_flush(void) { struct sk_buff *skb; while ((skb = skb_dequeue(&tx_queue)) != NULL) dev_queue_xmit(skb); } static void ppp_tx_cp(struct net_device *dev, u16 pid, u8 code, u8 id, unsigned int len, const void *data) { struct sk_buff *skb; struct cp_header *cp; unsigned int magic_len = 0; static u32 magic; #if DEBUG_CP int i; char *ptr; #endif if (pid == PID_LCP && (code == LCP_ECHO_REQ || code == LCP_ECHO_REPLY)) magic_len = sizeof(magic); skb = dev_alloc_skb(sizeof(struct hdlc_header) + sizeof(struct cp_header) + magic_len + len); if (!skb) { netdev_warn(dev, "out of memory in ppp_tx_cp()\n"); return; } skb_reserve(skb, sizeof(struct hdlc_header)); cp = (struct cp_header *)skb_put(skb, sizeof(struct cp_header)); cp->code = code; cp->id = id; cp->len = htons(sizeof(struct cp_header) + magic_len + len); if (magic_len) memcpy(skb_put(skb, magic_len), &magic, magic_len); if (len) memcpy(skb_put(skb, len), data, len); #if DEBUG_CP BUG_ON(code >= CP_CODES); ptr = debug_buffer; *ptr = '\x0'; for (i = 0; i < min_t(unsigned int, magic_len + len, DEBUG_CP); i++) { sprintf(ptr, " %02X", skb->data[sizeof(struct cp_header) + i]); ptr += strlen(ptr); } printk(KERN_DEBUG "%s: TX %s [%s id 0x%X]%s\n", dev->name, proto_name(pid), code_names[code], id, debug_buffer); #endif ppp_hard_header(skb, dev, pid, NULL, NULL, 0); skb->priority = TC_PRIO_CONTROL; skb->dev = dev; skb_reset_network_header(skb); skb_queue_tail(&tx_queue, skb); } /* State transition table (compare STD-51) Events Actions TO+ = Timeout with counter > 0 irc = Initialize-Restart-Count TO- = Timeout with counter expired zrc = Zero-Restart-Count RCR+ = Receive-Configure-Request (Good) scr = Send-Configure-Request RCR- = Receive-Configure-Request (Bad) RCA = Receive-Configure-Ack sca = Send-Configure-Ack RCN = Receive-Configure-Nak/Rej scn = Send-Configure-Nak/Rej RTR = Receive-Terminate-Request str = Send-Terminate-Request RTA = Receive-Terminate-Ack sta = Send-Terminate-Ack RUC = Receive-Unknown-Code scj = Send-Code-Reject RXJ+ = Receive-Code-Reject (permitted) or Receive-Protocol-Reject RXJ- = Receive-Code-Reject (catastrophic) or Receive-Protocol-Reject */ static int cp_table[EVENTS][STATES] = { /* CLOSED STOPPED STOPPING REQ_SENT ACK_RECV ACK_SENT OPENED 0 1 2 3 4 5 6 */ {IRC|SCR|3, INV , INV , INV , INV , INV , INV }, /* START */ { INV , 0 , 0 , 0 , 0 , 0 , 0 }, /* STOP */ { INV , INV ,STR|2, SCR|3 ,SCR|3, SCR|5 , INV }, /* TO+ */ { INV , INV , 1 , 1 , 1 , 1 , INV }, /* TO- */ { STA|0 ,IRC|SCR|SCA|5, 2 , SCA|5 ,SCA|6, SCA|5 ,SCR|SCA|5}, /* RCR+ */ { STA|0 ,IRC|SCR|SCN|3, 2 , SCN|3 ,SCN|4, SCN|3 ,SCR|SCN|3}, /* RCR- */ { STA|0 , STA|1 , 2 , IRC|4 ,SCR|3, 6 , SCR|3 }, /* RCA */ { STA|0 , STA|1 , 2 ,IRC|SCR|3,SCR|3,IRC|SCR|5, SCR|3 }, /* RCN */ { STA|0 , STA|1 ,STA|2, STA|3 ,STA|3, STA|3 ,ZRC|STA|2}, /* RTR */ { 0 , 1 , 1 , 3 , 3 , 5 , SCR|3 }, /* RTA */ { SCJ|0 , SCJ|1 ,SCJ|2, SCJ|3 ,SCJ|4, SCJ|5 , SCJ|6 }, /* RUC */ { 0 , 1 , 2 , 3 , 3 , 5 , 6 }, /* RXJ+ */ { 0 , 1 , 1 , 1 , 1 , 1 ,IRC|STR|2}, /* RXJ- */ }; /* SCA: RCR+ must supply id, len and data SCN: RCR- must supply code, id, len and data STA: RTR must supply id SCJ: RUC must supply CP packet len and data */ static void ppp_cp_event(struct net_device *dev, u16 pid, u16 event, u8 code, u8 id, unsigned int len, const void *data) { int old_state, action; struct ppp *ppp = get_ppp(dev); struct proto *proto = get_proto(dev, pid); old_state = proto->state; BUG_ON(old_state >= STATES); BUG_ON(event >= EVENTS); #if DEBUG_STATE printk(KERN_DEBUG "%s: %s ppp_cp_event(%s) %s ...\n", dev->name, proto_name(pid), event_names[event], state_names[proto->state]); #endif action = cp_table[event][old_state]; proto->state = action & STATE_MASK; if (action & (SCR | STR)) /* set Configure-Req/Terminate-Req timer */ mod_timer(&proto->timer, proto->timeout = jiffies + ppp->req_timeout * HZ); if (action & ZRC) proto->restart_counter = 0; if (action & IRC) proto->restart_counter = (proto->state == STOPPING) ? ppp->term_retries : ppp->cr_retries; if (action & SCR) /* send Configure-Request */ ppp_tx_cp(dev, pid, CP_CONF_REQ, proto->cr_id = ++ppp->seq, 0, NULL); if (action & SCA) /* send Configure-Ack */ ppp_tx_cp(dev, pid, CP_CONF_ACK, id, len, data); if (action & SCN) /* send Configure-Nak/Reject */ ppp_tx_cp(dev, pid, code, id, len, data); if (action & STR) /* send Terminate-Request */ ppp_tx_cp(dev, pid, CP_TERM_REQ, ++ppp->seq, 0, NULL); if (action & STA) /* send Terminate-Ack */ ppp_tx_cp(dev, pid, CP_TERM_ACK, id, 0, NULL); if (action & SCJ) /* send Code-Reject */ ppp_tx_cp(dev, pid, CP_CODE_REJ, ++ppp->seq, len, data); if (old_state != OPENED && proto->state == OPENED) { netdev_info(dev, "%s up\n", proto_name(pid)); if (pid == PID_LCP) { netif_dormant_off(dev); ppp_cp_event(dev, PID_IPCP, START, 0, 0, 0, NULL); ppp_cp_event(dev, PID_IPV6CP, START, 0, 0, 0, NULL); ppp->last_pong = jiffies; mod_timer(&proto->timer, proto->timeout = jiffies + ppp->keepalive_interval * HZ); } } if (old_state == OPENED && proto->state != OPENED) { netdev_info(dev, "%s down\n", proto_name(pid)); if (pid == PID_LCP) { netif_dormant_on(dev); ppp_cp_event(dev, PID_IPCP, STOP, 0, 0, 0, NULL); ppp_cp_event(dev, PID_IPV6CP, STOP, 0, 0, 0, NULL); } } if (old_state != CLOSED && proto->state == CLOSED) del_timer(&proto->timer); #if DEBUG_STATE printk(KERN_DEBUG "%s: %s ppp_cp_event(%s) ... %s\n", dev->name, proto_name(pid), event_names[event], state_names[proto->state]); #endif } static void ppp_cp_parse_cr(struct net_device *dev, u16 pid, u8 id, unsigned int req_len, const u8 *data) { static u8 const valid_accm[6] = { LCP_OPTION_ACCM, 6, 0, 0, 0, 0 }; const u8 *opt; u8 *out; unsigned int len = req_len, nak_len = 0, rej_len = 0; if (!(out = kmalloc(len, GFP_ATOMIC))) { dev->stats.rx_dropped++; return; /* out of memory, ignore CR packet */ } for (opt = data; len; len -= opt[1], opt += opt[1]) { if (len < 2 || len < opt[1]) { dev->stats.rx_errors++; kfree(out); return; /* bad packet, drop silently */ } if (pid == PID_LCP) switch (opt[0]) { case LCP_OPTION_MRU: continue; /* MRU always OK and > 1500 bytes? */ case LCP_OPTION_ACCM: /* async control character map */ if (!memcmp(opt, valid_accm, sizeof(valid_accm))) continue; if (!rej_len) { /* NAK it */ memcpy(out + nak_len, valid_accm, sizeof(valid_accm)); nak_len += sizeof(valid_accm); continue; } break; case LCP_OPTION_MAGIC: if (opt[1] != 6 || (!opt[2] && !opt[3] && !opt[4] && !opt[5])) break; /* reject invalid magic number */ continue; } /* reject this option */ memcpy(out + rej_len, opt, opt[1]); rej_len += opt[1]; } if (rej_len) ppp_cp_event(dev, pid, RCR_BAD, CP_CONF_REJ, id, rej_len, out); else if (nak_len) ppp_cp_event(dev, pid, RCR_BAD, CP_CONF_NAK, id, nak_len, out); else ppp_cp_event(dev, pid, RCR_GOOD, CP_CONF_ACK, id, req_len, data); kfree(out); } static int ppp_rx(struct sk_buff *skb) { struct hdlc_header *hdr = (struct hdlc_header*)skb->data; struct net_device *dev = skb->dev; struct ppp *ppp = get_ppp(dev); struct proto *proto; struct cp_header *cp; unsigned long flags; unsigned int len; u16 pid; #if DEBUG_CP int i; char *ptr; #endif spin_lock_irqsave(&ppp->lock, flags); /* Check HDLC header */ if (skb->len < sizeof(struct hdlc_header)) goto rx_error; cp = (struct cp_header*)skb_pull(skb, sizeof(struct hdlc_header)); if (hdr->address != HDLC_ADDR_ALLSTATIONS || hdr->control != HDLC_CTRL_UI) goto rx_error; pid = ntohs(hdr->protocol); proto = get_proto(dev, pid); if (!proto) { if (ppp->protos[IDX_LCP].state == OPENED) ppp_tx_cp(dev, PID_LCP, LCP_PROTO_REJ, ++ppp->seq, skb->len + 2, &hdr->protocol); goto rx_error; } len = ntohs(cp->len); if (len < sizeof(struct cp_header) /* no complete CP header? */ || skb->len < len /* truncated packet? */) goto rx_error; skb_pull(skb, sizeof(struct cp_header)); len -= sizeof(struct cp_header); /* HDLC and CP headers stripped from skb */ #if DEBUG_CP if (cp->code < CP_CODES) sprintf(debug_buffer, "[%s id 0x%X]", code_names[cp->code], cp->id); else sprintf(debug_buffer, "[code %u id 0x%X]", cp->code, cp->id); ptr = debug_buffer + strlen(debug_buffer); for (i = 0; i < min_t(unsigned int, len, DEBUG_CP); i++) { sprintf(ptr, " %02X", skb->data[i]); ptr += strlen(ptr); } printk(KERN_DEBUG "%s: RX %s %s\n", dev->name, proto_name(pid), debug_buffer); #endif /* LCP only */ if (pid == PID_LCP) switch (cp->code) { case LCP_PROTO_REJ: pid = ntohs(*(__be16*)skb->data); if (pid == PID_LCP || pid == PID_IPCP || pid == PID_IPV6CP) ppp_cp_event(dev, pid, RXJ_BAD, 0, 0, 0, NULL); goto out; case LCP_ECHO_REQ: /* send Echo-Reply */ if (len >= 4 && proto->state == OPENED) ppp_tx_cp(dev, PID_LCP, LCP_ECHO_REPLY, cp->id, len - 4, skb->data + 4); goto out; case LCP_ECHO_REPLY: if (cp->id == ppp->echo_id) ppp->last_pong = jiffies; goto out; case LCP_DISC_REQ: /* discard */ goto out; } /* LCP, IPCP and IPV6CP */ switch (cp->code) { case CP_CONF_REQ: ppp_cp_parse_cr(dev, pid, cp->id, len, skb->data); break; case CP_CONF_ACK: if (cp->id == proto->cr_id) ppp_cp_event(dev, pid, RCA, 0, 0, 0, NULL); break; case CP_CONF_REJ: case CP_CONF_NAK: if (cp->id == proto->cr_id) ppp_cp_event(dev, pid, RCN, 0, 0, 0, NULL); break; case CP_TERM_REQ: ppp_cp_event(dev, pid, RTR, 0, cp->id, 0, NULL); break; case CP_TERM_ACK: ppp_cp_event(dev, pid, RTA, 0, 0, 0, NULL); break; case CP_CODE_REJ: ppp_cp_event(dev, pid, RXJ_BAD, 0, 0, 0, NULL); break; default: len += sizeof(struct cp_header); if (len > dev->mtu) len = dev->mtu; ppp_cp_event(dev, pid, RUC, 0, 0, len, cp); break; } goto out; rx_error: dev->stats.rx_errors++; out: spin_unlock_irqrestore(&ppp->lock, flags); dev_kfree_skb_any(skb); ppp_tx_flush(); return NET_RX_DROP; } static void ppp_timer(unsigned long arg) { struct proto *proto = (struct proto *)arg; struct ppp *ppp = get_ppp(proto->dev); unsigned long flags; spin_lock_irqsave(&ppp->lock, flags); switch (proto->state) { case STOPPING: case REQ_SENT: case ACK_RECV: case ACK_SENT: if (proto->restart_counter) { ppp_cp_event(proto->dev, proto->pid, TO_GOOD, 0, 0, 0, NULL); proto->restart_counter--; } else ppp_cp_event(proto->dev, proto->pid, TO_BAD, 0, 0, 0, NULL); break; case OPENED: if (proto->pid != PID_LCP) break; if (time_after(jiffies, ppp->last_pong + ppp->keepalive_timeout * HZ)) { netdev_info(proto->dev, "Link down\n"); ppp_cp_event(proto->dev, PID_LCP, STOP, 0, 0, 0, NULL); ppp_cp_event(proto->dev, PID_LCP, START, 0, 0, 0, NULL); } else { /* send keep-alive packet */ ppp->echo_id = ++ppp->seq; ppp_tx_cp(proto->dev, PID_LCP, LCP_ECHO_REQ, ppp->echo_id, 0, NULL); proto->timer.expires = jiffies + ppp->keepalive_interval * HZ; add_timer(&proto->timer); } break; } spin_unlock_irqrestore(&ppp->lock, flags); ppp_tx_flush(); } static void ppp_start(struct net_device *dev) { struct ppp *ppp = get_ppp(dev); int i; for (i = 0; i < IDX_COUNT; i++) { struct proto *proto = &ppp->protos[i]; proto->dev = dev; init_timer(&proto->timer); proto->timer.function = ppp_timer; proto->timer.data = (unsigned long)proto; proto->state = CLOSED; } ppp->protos[IDX_LCP].pid = PID_LCP; ppp->protos[IDX_IPCP].pid = PID_IPCP; ppp->protos[IDX_IPV6CP].pid = PID_IPV6CP; ppp_cp_event(dev, PID_LCP, START, 0, 0, 0, NULL); } static void ppp_stop(struct net_device *dev) { ppp_cp_event(dev, PID_LCP, STOP, 0, 0, 0, NULL); } static void ppp_close(struct net_device *dev) { ppp_tx_flush(); } static struct hdlc_proto proto = { .start = ppp_start, .stop = ppp_stop, .close = ppp_close, .type_trans = ppp_type_trans, .ioctl = ppp_ioctl, .netif_rx = ppp_rx, .module = THIS_MODULE, }; static const struct header_ops ppp_header_ops = { .create = ppp_hard_header, }; static int ppp_ioctl(struct net_device *dev, struct ifreq *ifr) { hdlc_device *hdlc = dev_to_hdlc(dev); struct ppp *ppp; int result; switch (ifr->ifr_settings.type) { case IF_GET_PROTO: if (dev_to_hdlc(dev)->proto != &proto) return -EINVAL; ifr->ifr_settings.type = IF_PROTO_PPP; return 0; /* return protocol only, no settable parameters */ case IF_PROTO_PPP: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (dev->flags & IFF_UP) return -EBUSY; /* no settable parameters */ result = hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT); if (result) return result; result = attach_hdlc_protocol(dev, &proto, sizeof(struct ppp)); if (result) return result; ppp = get_ppp(dev); spin_lock_init(&ppp->lock); ppp->req_timeout = 2; ppp->cr_retries = 10; ppp->term_retries = 2; ppp->keepalive_interval = 10; ppp->keepalive_timeout = 60; dev->hard_header_len = sizeof(struct hdlc_header); dev->header_ops = &ppp_header_ops; dev->type = ARPHRD_PPP; netif_dormant_on(dev); return 0; } return -EINVAL; } static int __init mod_init(void) { skb_queue_head_init(&tx_queue); register_hdlc_protocol(&proto); return 0; } static void __exit mod_exit(void) { unregister_hdlc_protocol(&proto); } module_init(mod_init); module_exit(mod_exit); MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>"); MODULE_DESCRIPTION("PPP protocol support for generic HDLC"); MODULE_LICENSE("GPL v2");
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sparql", function(config) { var indentUnit = config.indentUnit; var curPunc; function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", "iri", "uri", "bnode", "count", "sum", "min", "max", "avg", "sample", "group_concat", "rand", "abs", "ceil", "floor", "round", "concat", "substr", "strlen", "replace", "ucase", "lcase", "encode_for_uri", "contains", "strstarts", "strends", "strbefore", "strafter", "year", "month", "day", "hours", "minutes", "seconds", "timezone", "tz", "now", "uuid", "struuid", "md5", "sha1", "sha256", "sha384", "sha512", "coalesce", "if", "strlang", "strdt", "isnumeric", "regex", "exists", "isblank", "isliteral", "a", "bind"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc", "as", "having", "undef", "values", "group", "minus", "in", "not", "service", "silent", "using", "insert", "delete", "union", "true", "false", "with", "data", "copy", "to", "move", "add", "create", "drop", "clear", "load"]); var operatorChars = /[*+\-<>=&|\^\/!\?]/; function tokenBase(stream, state) { var ch = stream.next(); curPunc = null; if (ch == "$" || ch == "?") { if(ch == "?" && stream.match(/\s/, false)){ return "operator"; } stream.match(/^[\w\d]*/); return "variable-2"; } else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) { stream.match(/^[^\s\u00a0>]*>?/); return "atom"; } else if (ch == "\"" || ch == "'") { state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if (/[{}\(\),\.;\[\]]/.test(ch)) { curPunc = ch; return "bracket"; } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (operatorChars.test(ch)) { stream.eatWhile(operatorChars); return "operator"; } else if (ch == ":") { stream.eatWhile(/[\w\d\._\-]/); return "atom"; } else if (ch == "@") { stream.eatWhile(/[a-z\d\-]/i); return "meta"; } else { stream.eatWhile(/[_\w\d]/); if (stream.eat(":")) { stream.eatWhile(/[\w\d_\-]/); return "atom"; } var word = stream.current(); if (ops.test(word)) return "builtin"; else if (keywords.test(word)) return "keyword"; else return "variable"; } } function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return "string"; }; } function pushContext(state, type, col) { state.context = {prev: state.context, indent: state.indent, col: col, type: type}; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null, indent: 0, col: 0}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; state.indent = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") { state.context.align = true; } if (curPunc == "(") pushContext(state, ")", stream.column()); else if (curPunc == "[") pushContext(state, "]", stream.column()); else if (curPunc == "{") pushContext(state, "}", stream.column()); else if (/[\]\}\)]/.test(curPunc)) { while (state.context && state.context.type == "pattern") popContext(state); if (state.context && curPunc == state.context.type) { popContext(state); if (curPunc == "}" && state.context && state.context.type == "pattern") popContext(state); } } else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state); else if (/atom|string|variable/.test(style) && state.context) { if (/[\}\]]/.test(state.context.type)) pushContext(state, "pattern", stream.column()); else if (state.context.type == "pattern" && !state.context.align) { state.context.align = true; state.context.col = stream.column(); } } return style; }, indent: function(state, textAfter) { var firstChar = textAfter && textAfter.charAt(0); var context = state.context; if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == context.type; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col + (closing ? 0 : 1); else return context.indent + (closing ? 0 : indentUnit); }, lineComment: "#" }; }); CodeMirror.defineMIME("application/sparql-query", "sparql"); });
{ "pile_set_name": "Github" }
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash, Debug)] pub enum Authentication { WaitingForOK(bool), WaitingForAgreeUnixFD, Error, Begin(bool), } impl Authentication { pub fn new(do_unix_fd: bool) -> (Self, String) { let uid = crate::sys::getuid(); let uid = uid.to_string(); let mut s = String::from("\0AUTH EXTERNAL "); for c in uid.as_bytes() { s.push_str(&format!("{:2x}", c)); } s.push_str("\r\n"); (Authentication::WaitingForOK(do_unix_fd), s) } pub fn handle(&mut self, data: &[u8]) -> Result<&'static str, Box<dyn std::error::Error>> { let old_state = *self; *self = Authentication::Error; let s = std::str::from_utf8(data)?; if !s.ends_with("\r\n") { Err("D-Bus authentication error (no newline)")? }; let s = s.trim(); match old_state { Authentication::Error | Authentication::Begin(_) => Err("D-Bus invalid authentication state")?, Authentication::WaitingForOK(b) => if s.starts_with("OK ") || s == "OK" { if b { *self = Authentication::WaitingForAgreeUnixFD; Ok("NEGOTIATE_UNIX_FD\r\n") } else { *self = Authentication::Begin(false); Ok("BEGIN\r\n") } } else { Err(format!("D-Bus authentication error ({})", s))? }, Authentication::WaitingForAgreeUnixFD => if s == "AGREE_UNIX_FD" { *self = Authentication::Begin(true); Ok("BEGIN\r\n") } else if s.starts_with("ERROR ") || s == "ERROR" { *self = Authentication::Begin(false); Ok("BEGIN\r\n") } else { Err(format!("D-Bus invalid response ({})", s))? }, } } pub fn blocking<R: std::io::BufRead, W: std::io::Write>(r: &mut R, w: &mut W, do_unix_fd: bool) -> Result<bool, Box<dyn std::error::Error>> { let (mut a, s) = Authentication::new(do_unix_fd); w.write_all(s.as_bytes())?; let mut b = vec![]; r.read_until(b'\n', &mut b)?; let s = a.handle(&b)?; w.write_all(s.as_bytes())?; if a == Authentication::WaitingForAgreeUnixFD { let mut b = vec![]; r.read_until(b'\n', &mut b)?; let s = a.handle(&b)?; w.write_all(s.as_bytes())?; } if let Authentication::Begin(ufd) = a { Ok(ufd) } else { unreachable!() } } } #[test] fn session_auth() { let addr = crate::address::read_session_address().unwrap(); // dbus-deamon (not the systemd variant) has abstract sockets, which rust does not // support. https://github.com/rust-lang/rust/issues/42048 if !addr.starts_with("unix:path=") { return; } let path = std::path::Path::new(&addr["unix:path=".len()..]); let stream = std::os::unix::net::UnixStream::connect(&path).unwrap(); let mut reader = std::io::BufReader::new(&stream); assert!(Authentication::blocking(&mut reader, &mut &stream, true).unwrap()); }
{ "pile_set_name": "Github" }
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * or via info@adempiere.net or http://www.adempiere.net/license.html * *****************************************************************************/ package org.spin.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.model.*; import org.compiere.util.KeyNamePair; /** Generated Interface for FM_ProductApplicability * @author Adempiere (generated) * @version Release 3.9.2 */ public interface I_FM_ProductApplicability { /** TableName=FM_ProductApplicability */ public static final String Table_Name = "FM_ProductApplicability"; /** AD_Table_ID=54373 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 3 - Client - Org */ BigDecimal accessLevel = BigDecimal.valueOf(3); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name C_BP_Group_ID */ public static final String COLUMNNAME_C_BP_Group_ID = "C_BP_Group_ID"; /** Set Business Partner Group. * Business Partner Group */ public void setC_BP_Group_ID (int C_BP_Group_ID); /** Get Business Partner Group. * Business Partner Group */ public int getC_BP_Group_ID(); public org.compiere.model.I_C_BP_Group getC_BP_Group() throws RuntimeException; /** Column name C_BPartner_ID */ public static final String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID"; /** Set Business Partner . * Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID); /** Get Business Partner . * Identifies a Business Partner */ public int getC_BPartner_ID(); public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException; /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name FM_ProductApplicability_ID */ public static final String COLUMNNAME_FM_ProductApplicability_ID = "FM_ProductApplicability_ID"; /** Set Financial Product Applicability */ public void setFM_ProductApplicability_ID (int FM_ProductApplicability_ID); /** Get Financial Product Applicability */ public int getFM_ProductApplicability_ID(); /** Column name FM_Product_ID */ public static final String COLUMNNAME_FM_Product_ID = "FM_Product_ID"; /** Set Financial Product */ public void setFM_Product_ID (int FM_Product_ID); /** Get Financial Product */ public int getFM_Product_ID(); public org.spin.model.I_FM_Product getFM_Product() throws RuntimeException; /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name UUID */ public static final String COLUMNNAME_UUID = "UUID"; /** Set Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public void setUUID (String UUID); /** Get Immutable Universally Unique Identifier. * Immutable Universally Unique Identifier */ public String getUUID(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name ValidFrom */ public static final String COLUMNNAME_ValidFrom = "ValidFrom"; /** Set Valid from. * Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom); /** Get Valid from. * Valid from including this date (first day) */ public Timestamp getValidFrom(); /** Column name ValidTo */ public static final String COLUMNNAME_ValidTo = "ValidTo"; /** Set Valid to. * Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo); /** Get Valid to. * Valid to including this date (last day) */ public Timestamp getValidTo(); }
{ "pile_set_name": "Github" }
class PropertyTabChangedEventHandler(MulticastDelegate,ICloneable,ISerializable): """ Represents the method that will handle the System.Windows.Forms.PropertyGrid.PropertyTabChanged event of a System.Windows.Forms.PropertyGrid. PropertyTabChangedEventHandler(object: object,method: IntPtr) """ def BeginInvoke(self,s,e,callback,object): """ BeginInvoke(self: PropertyTabChangedEventHandler,s: object,e: PropertyTabChangedEventArgs,callback: AsyncCallback,object: object) -> IAsyncResult """ pass def CombineImpl(self,*args): """ CombineImpl(self: MulticastDelegate,follow: Delegate) -> Delegate Combines this System.Delegate with the specified System.Delegate to form a new delegate. follow: The delegate to combine with this delegate. Returns: A delegate that is the new root of the System.MulticastDelegate invocation list. """ pass def DynamicInvokeImpl(self,*args): """ DynamicInvokeImpl(self: Delegate,args: Array[object]) -> object Dynamically invokes (late-bound) the method represented by the current delegate. args: An array of objects that are the arguments to pass to the method represented by the current delegate.-or- null,if the method represented by the current delegate does not require arguments. Returns: The object returned by the method represented by the delegate. """ pass def EndInvoke(self,result): """ EndInvoke(self: PropertyTabChangedEventHandler,result: IAsyncResult) """ pass def GetMethodImpl(self,*args): """ GetMethodImpl(self: MulticastDelegate) -> MethodInfo Returns a static method represented by the current System.MulticastDelegate. Returns: A static method represented by the current System.MulticastDelegate. """ pass def Invoke(self,s,e): """ Invoke(self: PropertyTabChangedEventHandler,s: object,e: PropertyTabChangedEventArgs) """ pass def RemoveImpl(self,*args): """ RemoveImpl(self: MulticastDelegate,value: Delegate) -> Delegate Removes an element from the invocation list of this System.MulticastDelegate that is equal to the specified delegate. value: The delegate to search for in the invocation list. Returns: If value is found in the invocation list for this instance,then a new System.Delegate without value in its invocation list; otherwise,this instance with its original invocation list. """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,object,method): """ __new__(cls: type,object: object,method: IntPtr) """ pass def __reduce_ex__(self,*args): pass
{ "pile_set_name": "Github" }
/*! * Font Awesome Free 5.9.0 by @fontawesome - https://fontawesome.com * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) */ .fa, .fas, .far, .fal, .fab { -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; display: inline-block; font-style: normal; font-variant: normal; text-rendering: auto; line-height: 1; } .fa-lg { font-size: 1.33333em; line-height: 0.75em; vertical-align: -.0667em; } .fa-xs { font-size: .75em; } .fa-sm { font-size: .875em; } .fa-1x { font-size: 1em; } .fa-2x { font-size: 2em; } .fa-3x { font-size: 3em; } .fa-4x { font-size: 4em; } .fa-5x { font-size: 5em; } .fa-6x { font-size: 6em; } .fa-7x { font-size: 7em; } .fa-8x { font-size: 8em; } .fa-9x { font-size: 9em; } .fa-10x { font-size: 10em; } .fa-fw { text-align: center; width: 1.25em; } .fa-ul { list-style-type: none; margin-left: 2.5em; padding-left: 0; } .fa-ul > li { position: relative; } .fa-li { left: -2em; position: absolute; text-align: center; width: 2em; line-height: inherit; } .fa-border { border: solid 0.08em #eee; border-radius: .1em; padding: .2em .25em .15em; } .fa-pull-left { float: left; } .fa-pull-right { float: right; } .fa.fa-pull-left, .fas.fa-pull-left, .far.fa-pull-left, .fal.fa-pull-left, .fab.fa-pull-left { margin-right: .3em; } .fa.fa-pull-right, .fas.fa-pull-right, .far.fa-pull-right, .fal.fa-pull-right, .fab.fa-pull-right { margin-left: .3em; } .fa-spin { -webkit-animation: fa-spin 2s infinite linear; animation: fa-spin 2s infinite linear; } .fa-pulse { -webkit-animation: fa-spin 1s infinite steps(8); animation: fa-spin 1s infinite steps(8); } @-webkit-keyframes fa-spin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes fa-spin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } .fa-rotate-90 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; -webkit-transform: rotate(90deg); transform: rotate(90deg); } .fa-rotate-180 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)"; -webkit-transform: rotate(180deg); transform: rotate(180deg); } .fa-rotate-270 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)"; -webkit-transform: rotate(270deg); transform: rotate(270deg); } .fa-flip-horizontal { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)"; -webkit-transform: scale(-1, 1); transform: scale(-1, 1); } .fa-flip-vertical { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"; -webkit-transform: scale(1, -1); transform: scale(1, -1); } .fa-flip-both, .fa-flip-horizontal.fa-flip-vertical { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"; -webkit-transform: scale(-1, -1); transform: scale(-1, -1); } :root .fa-rotate-90, :root .fa-rotate-180, :root .fa-rotate-270, :root .fa-flip-horizontal, :root .fa-flip-vertical, :root .fa-flip-both { -webkit-filter: none; filter: none; } .fa-stack { display: inline-block; height: 2em; line-height: 2em; position: relative; vertical-align: middle; width: 2.5em; } .fa-stack-1x, .fa-stack-2x { left: 0; position: absolute; text-align: center; width: 100%; } .fa-stack-1x { line-height: inherit; } .fa-stack-2x { font-size: 2em; } .fa-inverse { color: #fff; } /* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent icons */ .fa-500px:before { content: "\f26e"; } .fa-accessible-icon:before { content: "\f368"; } .fa-accusoft:before { content: "\f369"; } .fa-acquisitions-incorporated:before { content: "\f6af"; } .fa-ad:before { content: "\f641"; } .fa-address-book:before { content: "\f2b9"; } .fa-address-card:before { content: "\f2bb"; } .fa-adjust:before { content: "\f042"; } .fa-adn:before { content: "\f170"; } .fa-adobe:before { content: "\f778"; } .fa-adversal:before { content: "\f36a"; } .fa-affiliatetheme:before { content: "\f36b"; } .fa-air-freshener:before { content: "\f5d0"; } .fa-airbnb:before { content: "\f834"; } .fa-algolia:before { content: "\f36c"; } .fa-align-center:before { content: "\f037"; } .fa-align-justify:before { content: "\f039"; } .fa-align-left:before { content: "\f036"; } .fa-align-right:before { content: "\f038"; } .fa-alipay:before { content: "\f642"; } .fa-allergies:before { content: "\f461"; } .fa-amazon:before { content: "\f270"; } .fa-amazon-pay:before { content: "\f42c"; } .fa-ambulance:before { content: "\f0f9"; } .fa-american-sign-language-interpreting:before { content: "\f2a3"; } .fa-amilia:before { content: "\f36d"; } .fa-anchor:before { content: "\f13d"; } .fa-android:before { content: "\f17b"; } .fa-angellist:before { content: "\f209"; } .fa-angle-double-down:before { content: "\f103"; } .fa-angle-double-left:before { content: "\f100"; } .fa-angle-double-right:before { content: "\f101"; } .fa-angle-double-up:before { content: "\f102"; } .fa-angle-down:before { content: "\f107"; } .fa-angle-left:before { content: "\f104"; } .fa-angle-right:before { content: "\f105"; } .fa-angle-up:before { content: "\f106"; } .fa-angry:before { content: "\f556"; } .fa-angrycreative:before { content: "\f36e"; } .fa-angular:before { content: "\f420"; } .fa-ankh:before { content: "\f644"; } .fa-app-store:before { content: "\f36f"; } .fa-app-store-ios:before { content: "\f370"; } .fa-apper:before { content: "\f371"; } .fa-apple:before { content: "\f179"; } .fa-apple-alt:before { content: "\f5d1"; } .fa-apple-pay:before { content: "\f415"; } .fa-archive:before { content: "\f187"; } .fa-archway:before { content: "\f557"; } .fa-arrow-alt-circle-down:before { content: "\f358"; } .fa-arrow-alt-circle-left:before { content: "\f359"; } .fa-arrow-alt-circle-right:before { content: "\f35a"; } .fa-arrow-alt-circle-up:before { content: "\f35b"; } .fa-arrow-circle-down:before { content: "\f0ab"; } .fa-arrow-circle-left:before { content: "\f0a8"; } .fa-arrow-circle-right:before { content: "\f0a9"; } .fa-arrow-circle-up:before { content: "\f0aa"; } .fa-arrow-down:before { content: "\f063"; } .fa-arrow-left:before { content: "\f060"; } .fa-arrow-right:before { content: "\f061"; } .fa-arrow-up:before { content: "\f062"; } .fa-arrows-alt:before { content: "\f0b2"; } .fa-arrows-alt-h:before { content: "\f337"; } .fa-arrows-alt-v:before { content: "\f338"; } .fa-artstation:before { content: "\f77a"; } .fa-assistive-listening-systems:before { content: "\f2a2"; } .fa-asterisk:before { content: "\f069"; } .fa-asymmetrik:before { content: "\f372"; } .fa-at:before { content: "\f1fa"; } .fa-atlas:before { content: "\f558"; } .fa-atlassian:before { content: "\f77b"; } .fa-atom:before { content: "\f5d2"; } .fa-audible:before { content: "\f373"; } .fa-audio-description:before { content: "\f29e"; } .fa-autoprefixer:before { content: "\f41c"; } .fa-avianex:before { content: "\f374"; } .fa-aviato:before { content: "\f421"; } .fa-award:before { content: "\f559"; } .fa-aws:before { content: "\f375"; } .fa-baby:before { content: "\f77c"; } .fa-baby-carriage:before { content: "\f77d"; } .fa-backspace:before { content: "\f55a"; } .fa-backward:before { content: "\f04a"; } .fa-bacon:before { content: "\f7e5"; } .fa-balance-scale:before { content: "\f24e"; } .fa-balance-scale-left:before { content: "\f515"; } .fa-balance-scale-right:before { content: "\f516"; } .fa-ban:before { content: "\f05e"; } .fa-band-aid:before { content: "\f462"; } .fa-bandcamp:before { content: "\f2d5"; } .fa-barcode:before { content: "\f02a"; } .fa-bars:before { content: "\f0c9"; } .fa-baseball-ball:before { content: "\f433"; } .fa-basketball-ball:before { content: "\f434"; } .fa-bath:before { content: "\f2cd"; } .fa-battery-empty:before { content: "\f244"; } .fa-battery-full:before { content: "\f240"; } .fa-battery-half:before { content: "\f242"; } .fa-battery-quarter:before { content: "\f243"; } .fa-battery-three-quarters:before { content: "\f241"; } .fa-battle-net:before { content: "\f835"; } .fa-bed:before { content: "\f236"; } .fa-beer:before { content: "\f0fc"; } .fa-behance:before { content: "\f1b4"; } .fa-behance-square:before { content: "\f1b5"; } .fa-bell:before { content: "\f0f3"; } .fa-bell-slash:before { content: "\f1f6"; } .fa-bezier-curve:before { content: "\f55b"; } .fa-bible:before { content: "\f647"; } .fa-bicycle:before { content: "\f206"; } .fa-biking:before { content: "\f84a"; } .fa-bimobject:before { content: "\f378"; } .fa-binoculars:before { content: "\f1e5"; } .fa-biohazard:before { content: "\f780"; } .fa-birthday-cake:before { content: "\f1fd"; } .fa-bitbucket:before { content: "\f171"; } .fa-bitcoin:before { content: "\f379"; } .fa-bity:before { content: "\f37a"; } .fa-black-tie:before { content: "\f27e"; } .fa-blackberry:before { content: "\f37b"; } .fa-blender:before { content: "\f517"; } .fa-blender-phone:before { content: "\f6b6"; } .fa-blind:before { content: "\f29d"; } .fa-blog:before { content: "\f781"; } .fa-blogger:before { content: "\f37c"; } .fa-blogger-b:before { content: "\f37d"; } .fa-bluetooth:before { content: "\f293"; } .fa-bluetooth-b:before { content: "\f294"; } .fa-bold:before { content: "\f032"; } .fa-bolt:before { content: "\f0e7"; } .fa-bomb:before { content: "\f1e2"; } .fa-bone:before { content: "\f5d7"; } .fa-bong:before { content: "\f55c"; } .fa-book:before { content: "\f02d"; } .fa-book-dead:before { content: "\f6b7"; } .fa-book-medical:before { content: "\f7e6"; } .fa-book-open:before { content: "\f518"; } .fa-book-reader:before { content: "\f5da"; } .fa-bookmark:before { content: "\f02e"; } .fa-bootstrap:before { content: "\f836"; } .fa-border-all:before { content: "\f84c"; } .fa-border-none:before { content: "\f850"; } .fa-border-style:before { content: "\f853"; } .fa-bowling-ball:before { content: "\f436"; } .fa-box:before { content: "\f466"; } .fa-box-open:before { content: "\f49e"; } .fa-boxes:before { content: "\f468"; } .fa-braille:before { content: "\f2a1"; } .fa-brain:before { content: "\f5dc"; } .fa-bread-slice:before { content: "\f7ec"; } .fa-briefcase:before { content: "\f0b1"; } .fa-briefcase-medical:before { content: "\f469"; } .fa-broadcast-tower:before { content: "\f519"; } .fa-broom:before { content: "\f51a"; } .fa-brush:before { content: "\f55d"; } .fa-btc:before { content: "\f15a"; } .fa-buffer:before { content: "\f837"; } .fa-bug:before { content: "\f188"; } .fa-building:before { content: "\f1ad"; } .fa-bullhorn:before { content: "\f0a1"; } .fa-bullseye:before { content: "\f140"; } .fa-burn:before { content: "\f46a"; } .fa-buromobelexperte:before { content: "\f37f"; } .fa-bus:before { content: "\f207"; } .fa-bus-alt:before { content: "\f55e"; } .fa-business-time:before { content: "\f64a"; } .fa-buysellads:before { content: "\f20d"; } .fa-calculator:before { content: "\f1ec"; } .fa-calendar:before { content: "\f133"; } .fa-calendar-alt:before { content: "\f073"; } .fa-calendar-check:before { content: "\f274"; } .fa-calendar-day:before { content: "\f783"; } .fa-calendar-minus:before { content: "\f272"; } .fa-calendar-plus:before { content: "\f271"; } .fa-calendar-times:before { content: "\f273"; } .fa-calendar-week:before { content: "\f784"; } .fa-camera:before { content: "\f030"; } .fa-camera-retro:before { content: "\f083"; } .fa-campground:before { content: "\f6bb"; } .fa-canadian-maple-leaf:before { content: "\f785"; } .fa-candy-cane:before { content: "\f786"; } .fa-cannabis:before { content: "\f55f"; } .fa-capsules:before { content: "\f46b"; } .fa-car:before { content: "\f1b9"; } .fa-car-alt:before { content: "\f5de"; } .fa-car-battery:before { content: "\f5df"; } .fa-car-crash:before { content: "\f5e1"; } .fa-car-side:before { content: "\f5e4"; } .fa-caret-down:before { content: "\f0d7"; } .fa-caret-left:before { content: "\f0d9"; } .fa-caret-right:before { content: "\f0da"; } .fa-caret-square-down:before { content: "\f150"; } .fa-caret-square-left:before { content: "\f191"; } .fa-caret-square-right:before { content: "\f152"; } .fa-caret-square-up:before { content: "\f151"; } .fa-caret-up:before { content: "\f0d8"; } .fa-carrot:before { content: "\f787"; } .fa-cart-arrow-down:before { content: "\f218"; } .fa-cart-plus:before { content: "\f217"; } .fa-cash-register:before { content: "\f788"; } .fa-cat:before { content: "\f6be"; } .fa-cc-amazon-pay:before { content: "\f42d"; } .fa-cc-amex:before { content: "\f1f3"; } .fa-cc-apple-pay:before { content: "\f416"; } .fa-cc-diners-club:before { content: "\f24c"; } .fa-cc-discover:before { content: "\f1f2"; } .fa-cc-jcb:before { content: "\f24b"; } .fa-cc-mastercard:before { content: "\f1f1"; } .fa-cc-paypal:before { content: "\f1f4"; } .fa-cc-stripe:before { content: "\f1f5"; } .fa-cc-visa:before { content: "\f1f0"; } .fa-centercode:before { content: "\f380"; } .fa-centos:before { content: "\f789"; } .fa-certificate:before { content: "\f0a3"; } .fa-chair:before { content: "\f6c0"; } .fa-chalkboard:before { content: "\f51b"; } .fa-chalkboard-teacher:before { content: "\f51c"; } .fa-charging-station:before { content: "\f5e7"; } .fa-chart-area:before { content: "\f1fe"; } .fa-chart-bar:before { content: "\f080"; } .fa-chart-line:before { content: "\f201"; } .fa-chart-pie:before { content: "\f200"; } .fa-check:before { content: "\f00c"; } .fa-check-circle:before { content: "\f058"; } .fa-check-double:before { content: "\f560"; } .fa-check-square:before { content: "\f14a"; } .fa-cheese:before { content: "\f7ef"; } .fa-chess:before { content: "\f439"; } .fa-chess-bishop:before { content: "\f43a"; } .fa-chess-board:before { content: "\f43c"; } .fa-chess-king:before { content: "\f43f"; } .fa-chess-knight:before { content: "\f441"; } .fa-chess-pawn:before { content: "\f443"; } .fa-chess-queen:before { content: "\f445"; } .fa-chess-rook:before { content: "\f447"; } .fa-chevron-circle-down:before { content: "\f13a"; } .fa-chevron-circle-left:before { content: "\f137"; } .fa-chevron-circle-right:before { content: "\f138"; } .fa-chevron-circle-up:before { content: "\f139"; } .fa-chevron-down:before { content: "\f078"; } .fa-chevron-left:before { content: "\f053"; } .fa-chevron-right:before { content: "\f054"; } .fa-chevron-up:before { content: "\f077"; } .fa-child:before { content: "\f1ae"; } .fa-chrome:before { content: "\f268"; } .fa-chromecast:before { content: "\f838"; } .fa-church:before { content: "\f51d"; } .fa-circle:before { content: "\f111"; } .fa-circle-notch:before { content: "\f1ce"; } .fa-city:before { content: "\f64f"; } .fa-clinic-medical:before { content: "\f7f2"; } .fa-clipboard:before { content: "\f328"; } .fa-clipboard-check:before { content: "\f46c"; } .fa-clipboard-list:before { content: "\f46d"; } .fa-clock:before { content: "\f017"; } .fa-clone:before { content: "\f24d"; } .fa-closed-captioning:before { content: "\f20a"; } .fa-cloud:before { content: "\f0c2"; } .fa-cloud-download-alt:before { content: "\f381"; } .fa-cloud-meatball:before { content: "\f73b"; } .fa-cloud-moon:before { content: "\f6c3"; } .fa-cloud-moon-rain:before { content: "\f73c"; } .fa-cloud-rain:before { content: "\f73d"; } .fa-cloud-showers-heavy:before { content: "\f740"; } .fa-cloud-sun:before { content: "\f6c4"; } .fa-cloud-sun-rain:before { content: "\f743"; } .fa-cloud-upload-alt:before { content: "\f382"; } .fa-cloudscale:before { content: "\f383"; } .fa-cloudsmith:before { content: "\f384"; } .fa-cloudversify:before { content: "\f385"; } .fa-cocktail:before { content: "\f561"; } .fa-code:before { content: "\f121"; } .fa-code-branch:before { content: "\f126"; } .fa-codepen:before { content: "\f1cb"; } .fa-codiepie:before { content: "\f284"; } .fa-coffee:before { content: "\f0f4"; } .fa-cog:before { content: "\f013"; } .fa-cogs:before { content: "\f085"; } .fa-coins:before { content: "\f51e"; } .fa-columns:before { content: "\f0db"; } .fa-comment:before { content: "\f075"; } .fa-comment-alt:before { content: "\f27a"; } .fa-comment-dollar:before { content: "\f651"; } .fa-comment-dots:before { content: "\f4ad"; } .fa-comment-medical:before { content: "\f7f5"; } .fa-comment-slash:before { content: "\f4b3"; } .fa-comments:before { content: "\f086"; } .fa-comments-dollar:before { content: "\f653"; } .fa-compact-disc:before { content: "\f51f"; } .fa-compass:before { content: "\f14e"; } .fa-compress:before { content: "\f066"; } .fa-compress-arrows-alt:before { content: "\f78c"; } .fa-concierge-bell:before { content: "\f562"; } .fa-confluence:before { content: "\f78d"; } .fa-connectdevelop:before { content: "\f20e"; } .fa-contao:before { content: "\f26d"; } .fa-cookie:before { content: "\f563"; } .fa-cookie-bite:before { content: "\f564"; } .fa-copy:before { content: "\f0c5"; } .fa-copyright:before { content: "\f1f9"; } .fa-couch:before { content: "\f4b8"; } .fa-cpanel:before { content: "\f388"; } .fa-creative-commons:before { content: "\f25e"; } .fa-creative-commons-by:before { content: "\f4e7"; } .fa-creative-commons-nc:before { content: "\f4e8"; } .fa-creative-commons-nc-eu:before { content: "\f4e9"; } .fa-creative-commons-nc-jp:before { content: "\f4ea"; } .fa-creative-commons-nd:before { content: "\f4eb"; } .fa-creative-commons-pd:before { content: "\f4ec"; } .fa-creative-commons-pd-alt:before { content: "\f4ed"; } .fa-creative-commons-remix:before { content: "\f4ee"; } .fa-creative-commons-sa:before { content: "\f4ef"; } .fa-creative-commons-sampling:before { content: "\f4f0"; } .fa-creative-commons-sampling-plus:before { content: "\f4f1"; } .fa-creative-commons-share:before { content: "\f4f2"; } .fa-creative-commons-zero:before { content: "\f4f3"; } .fa-credit-card:before { content: "\f09d"; } .fa-critical-role:before { content: "\f6c9"; } .fa-crop:before { content: "\f125"; } .fa-crop-alt:before { content: "\f565"; } .fa-cross:before { content: "\f654"; } .fa-crosshairs:before { content: "\f05b"; } .fa-crow:before { content: "\f520"; } .fa-crown:before { content: "\f521"; } .fa-crutch:before { content: "\f7f7"; } .fa-css3:before { content: "\f13c"; } .fa-css3-alt:before { content: "\f38b"; } .fa-cube:before { content: "\f1b2"; } .fa-cubes:before { content: "\f1b3"; } .fa-cut:before { content: "\f0c4"; } .fa-cuttlefish:before { content: "\f38c"; } .fa-d-and-d:before { content: "\f38d"; } .fa-d-and-d-beyond:before { content: "\f6ca"; } .fa-dashcube:before { content: "\f210"; } .fa-database:before { content: "\f1c0"; } .fa-deaf:before { content: "\f2a4"; } .fa-delicious:before { content: "\f1a5"; } .fa-democrat:before { content: "\f747"; } .fa-deploydog:before { content: "\f38e"; } .fa-deskpro:before { content: "\f38f"; } .fa-desktop:before { content: "\f108"; } .fa-dev:before { content: "\f6cc"; } .fa-deviantart:before { content: "\f1bd"; } .fa-dharmachakra:before { content: "\f655"; } .fa-dhl:before { content: "\f790"; } .fa-diagnoses:before { content: "\f470"; } .fa-diaspora:before { content: "\f791"; } .fa-dice:before { content: "\f522"; } .fa-dice-d20:before { content: "\f6cf"; } .fa-dice-d6:before { content: "\f6d1"; } .fa-dice-five:before { content: "\f523"; } .fa-dice-four:before { content: "\f524"; } .fa-dice-one:before { content: "\f525"; } .fa-dice-six:before { content: "\f526"; } .fa-dice-three:before { content: "\f527"; } .fa-dice-two:before { content: "\f528"; } .fa-digg:before { content: "\f1a6"; } .fa-digital-ocean:before { content: "\f391"; } .fa-digital-tachograph:before { content: "\f566"; } .fa-directions:before { content: "\f5eb"; } .fa-discord:before { content: "\f392"; } .fa-discourse:before { content: "\f393"; } .fa-divide:before { content: "\f529"; } .fa-dizzy:before { content: "\f567"; } .fa-dna:before { content: "\f471"; } .fa-dochub:before { content: "\f394"; } .fa-docker:before { content: "\f395"; } .fa-dog:before { content: "\f6d3"; } .fa-dollar-sign:before { content: "\f155"; } .fa-dolly:before { content: "\f472"; } .fa-dolly-flatbed:before { content: "\f474"; } .fa-donate:before { content: "\f4b9"; } .fa-door-closed:before { content: "\f52a"; } .fa-door-open:before { content: "\f52b"; } .fa-dot-circle:before { content: "\f192"; } .fa-dove:before { content: "\f4ba"; } .fa-download:before { content: "\f019"; } .fa-draft2digital:before { content: "\f396"; } .fa-drafting-compass:before { content: "\f568"; } .fa-dragon:before { content: "\f6d5"; } .fa-draw-polygon:before { content: "\f5ee"; } .fa-dribbble:before { content: "\f17d"; } .fa-dribbble-square:before { content: "\f397"; } .fa-dropbox:before { content: "\f16b"; } .fa-drum:before { content: "\f569"; } .fa-drum-steelpan:before { content: "\f56a"; } .fa-drumstick-bite:before { content: "\f6d7"; } .fa-drupal:before { content: "\f1a9"; } .fa-dumbbell:before { content: "\f44b"; } .fa-dumpster:before { content: "\f793"; } .fa-dumpster-fire:before { content: "\f794"; } .fa-dungeon:before { content: "\f6d9"; } .fa-dyalog:before { content: "\f399"; } .fa-earlybirds:before { content: "\f39a"; } .fa-ebay:before { content: "\f4f4"; } .fa-edge:before { content: "\f282"; } .fa-edit:before { content: "\f044"; } .fa-egg:before { content: "\f7fb"; } .fa-eject:before { content: "\f052"; } .fa-elementor:before { content: "\f430"; } .fa-ellipsis-h:before { content: "\f141"; } .fa-ellipsis-v:before { content: "\f142"; } .fa-ello:before { content: "\f5f1"; } .fa-ember:before { content: "\f423"; } .fa-empire:before { content: "\f1d1"; } .fa-envelope:before { content: "\f0e0"; } .fa-envelope-open:before { content: "\f2b6"; } .fa-envelope-open-text:before { content: "\f658"; } .fa-envelope-square:before { content: "\f199"; } .fa-envira:before { content: "\f299"; } .fa-equals:before { content: "\f52c"; } .fa-eraser:before { content: "\f12d"; } .fa-erlang:before { content: "\f39d"; } .fa-ethereum:before { content: "\f42e"; } .fa-ethernet:before { content: "\f796"; } .fa-etsy:before { content: "\f2d7"; } .fa-euro-sign:before { content: "\f153"; } .fa-evernote:before { content: "\f839"; } .fa-exchange-alt:before { content: "\f362"; } .fa-exclamation:before { content: "\f12a"; } .fa-exclamation-circle:before { content: "\f06a"; } .fa-exclamation-triangle:before { content: "\f071"; } .fa-expand:before { content: "\f065"; } .fa-expand-arrows-alt:before { content: "\f31e"; } .fa-expeditedssl:before { content: "\f23e"; } .fa-external-link-alt:before { content: "\f35d"; } .fa-external-link-square-alt:before { content: "\f360"; } .fa-eye:before { content: "\f06e"; } .fa-eye-dropper:before { content: "\f1fb"; } .fa-eye-slash:before { content: "\f070"; } .fa-facebook:before { content: "\f09a"; } .fa-facebook-f:before { content: "\f39e"; } .fa-facebook-messenger:before { content: "\f39f"; } .fa-facebook-square:before { content: "\f082"; } .fa-fan:before { content: "\f863"; } .fa-fantasy-flight-games:before { content: "\f6dc"; } .fa-fast-backward:before { content: "\f049"; } .fa-fast-forward:before { content: "\f050"; } .fa-fax:before { content: "\f1ac"; } .fa-feather:before { content: "\f52d"; } .fa-feather-alt:before { content: "\f56b"; } .fa-fedex:before { content: "\f797"; } .fa-fedora:before { content: "\f798"; } .fa-female:before { content: "\f182"; } .fa-fighter-jet:before { content: "\f0fb"; } .fa-figma:before { content: "\f799"; } .fa-file:before { content: "\f15b"; } .fa-file-alt:before { content: "\f15c"; } .fa-file-archive:before { content: "\f1c6"; } .fa-file-audio:before { content: "\f1c7"; } .fa-file-code:before { content: "\f1c9"; } .fa-file-contract:before { content: "\f56c"; } .fa-file-csv:before { content: "\f6dd"; } .fa-file-download:before { content: "\f56d"; } .fa-file-excel:before { content: "\f1c3"; } .fa-file-export:before { content: "\f56e"; } .fa-file-image:before { content: "\f1c5"; } .fa-file-import:before { content: "\f56f"; } .fa-file-invoice:before { content: "\f570"; } .fa-file-invoice-dollar:before { content: "\f571"; } .fa-file-medical:before { content: "\f477"; } .fa-file-medical-alt:before { content: "\f478"; } .fa-file-pdf:before { content: "\f1c1"; } .fa-file-powerpoint:before { content: "\f1c4"; } .fa-file-prescription:before { content: "\f572"; } .fa-file-signature:before { content: "\f573"; } .fa-file-upload:before { content: "\f574"; } .fa-file-video:before { content: "\f1c8"; } .fa-file-word:before { content: "\f1c2"; } .fa-fill:before { content: "\f575"; } .fa-fill-drip:before { content: "\f576"; } .fa-film:before { content: "\f008"; } .fa-filter:before { content: "\f0b0"; } .fa-fingerprint:before { content: "\f577"; } .fa-fire:before { content: "\f06d"; } .fa-fire-alt:before { content: "\f7e4"; } .fa-fire-extinguisher:before { content: "\f134"; } .fa-firefox:before { content: "\f269"; } .fa-first-aid:before { content: "\f479"; } .fa-first-order:before { content: "\f2b0"; } .fa-first-order-alt:before { content: "\f50a"; } .fa-firstdraft:before { content: "\f3a1"; } .fa-fish:before { content: "\f578"; } .fa-fist-raised:before { content: "\f6de"; } .fa-flag:before { content: "\f024"; } .fa-flag-checkered:before { content: "\f11e"; } .fa-flag-usa:before { content: "\f74d"; } .fa-flask:before { content: "\f0c3"; } .fa-flickr:before { content: "\f16e"; } .fa-flipboard:before { content: "\f44d"; } .fa-flushed:before { content: "\f579"; } .fa-fly:before { content: "\f417"; } .fa-folder:before { content: "\f07b"; } .fa-folder-minus:before { content: "\f65d"; } .fa-folder-open:before { content: "\f07c"; } .fa-folder-plus:before { content: "\f65e"; } .fa-font:before { content: "\f031"; } .fa-font-awesome:before { content: "\f2b4"; } .fa-font-awesome-alt:before { content: "\f35c"; } .fa-font-awesome-flag:before { content: "\f425"; } .fa-font-awesome-logo-full:before { content: "\f4e6"; } .fa-fonticons:before { content: "\f280"; } .fa-fonticons-fi:before { content: "\f3a2"; } .fa-football-ball:before { content: "\f44e"; } .fa-fort-awesome:before { content: "\f286"; } .fa-fort-awesome-alt:before { content: "\f3a3"; } .fa-forumbee:before { content: "\f211"; } .fa-forward:before { content: "\f04e"; } .fa-foursquare:before { content: "\f180"; } .fa-free-code-camp:before { content: "\f2c5"; } .fa-freebsd:before { content: "\f3a4"; } .fa-frog:before { content: "\f52e"; } .fa-frown:before { content: "\f119"; } .fa-frown-open:before { content: "\f57a"; } .fa-fulcrum:before { content: "\f50b"; } .fa-funnel-dollar:before { content: "\f662"; } .fa-futbol:before { content: "\f1e3"; } .fa-galactic-republic:before { content: "\f50c"; } .fa-galactic-senate:before { content: "\f50d"; } .fa-gamepad:before { content: "\f11b"; } .fa-gas-pump:before { content: "\f52f"; } .fa-gavel:before { content: "\f0e3"; } .fa-gem:before { content: "\f3a5"; } .fa-genderless:before { content: "\f22d"; } .fa-get-pocket:before { content: "\f265"; } .fa-gg:before { content: "\f260"; } .fa-gg-circle:before { content: "\f261"; } .fa-ghost:before { content: "\f6e2"; } .fa-gift:before { content: "\f06b"; } .fa-gifts:before { content: "\f79c"; } .fa-git:before { content: "\f1d3"; } .fa-git-alt:before { content: "\f841"; } .fa-git-square:before { content: "\f1d2"; } .fa-github:before { content: "\f09b"; } .fa-github-alt:before { content: "\f113"; } .fa-github-square:before { content: "\f092"; } .fa-gitkraken:before { content: "\f3a6"; } .fa-gitlab:before { content: "\f296"; } .fa-gitter:before { content: "\f426"; } .fa-glass-cheers:before { content: "\f79f"; } .fa-glass-martini:before { content: "\f000"; } .fa-glass-martini-alt:before { content: "\f57b"; } .fa-glass-whiskey:before { content: "\f7a0"; } .fa-glasses:before { content: "\f530"; } .fa-glide:before { content: "\f2a5"; } .fa-glide-g:before { content: "\f2a6"; } .fa-globe:before { content: "\f0ac"; } .fa-globe-africa:before { content: "\f57c"; } .fa-globe-americas:before { content: "\f57d"; } .fa-globe-asia:before { content: "\f57e"; } .fa-globe-europe:before { content: "\f7a2"; } .fa-gofore:before { content: "\f3a7"; } .fa-golf-ball:before { content: "\f450"; } .fa-goodreads:before { content: "\f3a8"; } .fa-goodreads-g:before { content: "\f3a9"; } .fa-google:before { content: "\f1a0"; } .fa-google-drive:before { content: "\f3aa"; } .fa-google-play:before { content: "\f3ab"; } .fa-google-plus:before { content: "\f2b3"; } .fa-google-plus-g:before { content: "\f0d5"; } .fa-google-plus-square:before { content: "\f0d4"; } .fa-google-wallet:before { content: "\f1ee"; } .fa-gopuram:before { content: "\f664"; } .fa-graduation-cap:before { content: "\f19d"; } .fa-gratipay:before { content: "\f184"; } .fa-grav:before { content: "\f2d6"; } .fa-greater-than:before { content: "\f531"; } .fa-greater-than-equal:before { content: "\f532"; } .fa-grimace:before { content: "\f57f"; } .fa-grin:before { content: "\f580"; } .fa-grin-alt:before { content: "\f581"; } .fa-grin-beam:before { content: "\f582"; } .fa-grin-beam-sweat:before { content: "\f583"; } .fa-grin-hearts:before { content: "\f584"; } .fa-grin-squint:before { content: "\f585"; } .fa-grin-squint-tears:before { content: "\f586"; } .fa-grin-stars:before { content: "\f587"; } .fa-grin-tears:before { content: "\f588"; } .fa-grin-tongue:before { content: "\f589"; } .fa-grin-tongue-squint:before { content: "\f58a"; } .fa-grin-tongue-wink:before { content: "\f58b"; } .fa-grin-wink:before { content: "\f58c"; } .fa-grip-horizontal:before { content: "\f58d"; } .fa-grip-lines:before { content: "\f7a4"; } .fa-grip-lines-vertical:before { content: "\f7a5"; } .fa-grip-vertical:before { content: "\f58e"; } .fa-gripfire:before { content: "\f3ac"; } .fa-grunt:before { content: "\f3ad"; } .fa-guitar:before { content: "\f7a6"; } .fa-gulp:before { content: "\f3ae"; } .fa-h-square:before { content: "\f0fd"; } .fa-hacker-news:before { content: "\f1d4"; } .fa-hacker-news-square:before { content: "\f3af"; } .fa-hackerrank:before { content: "\f5f7"; } .fa-hamburger:before { content: "\f805"; } .fa-hammer:before { content: "\f6e3"; } .fa-hamsa:before { content: "\f665"; } .fa-hand-holding:before { content: "\f4bd"; } .fa-hand-holding-heart:before { content: "\f4be"; } .fa-hand-holding-usd:before { content: "\f4c0"; } .fa-hand-lizard:before { content: "\f258"; } .fa-hand-middle-finger:before { content: "\f806"; } .fa-hand-paper:before { content: "\f256"; } .fa-hand-peace:before { content: "\f25b"; } .fa-hand-point-down:before { content: "\f0a7"; } .fa-hand-point-left:before { content: "\f0a5"; } .fa-hand-point-right:before { content: "\f0a4"; } .fa-hand-point-up:before { content: "\f0a6"; } .fa-hand-pointer:before { content: "\f25a"; } .fa-hand-rock:before { content: "\f255"; } .fa-hand-scissors:before { content: "\f257"; } .fa-hand-spock:before { content: "\f259"; } .fa-hands:before { content: "\f4c2"; } .fa-hands-helping:before { content: "\f4c4"; } .fa-handshake:before { content: "\f2b5"; } .fa-hanukiah:before { content: "\f6e6"; } .fa-hard-hat:before { content: "\f807"; } .fa-hashtag:before { content: "\f292"; } .fa-hat-wizard:before { content: "\f6e8"; } .fa-haykal:before { content: "\f666"; } .fa-hdd:before { content: "\f0a0"; } .fa-heading:before { content: "\f1dc"; } .fa-headphones:before { content: "\f025"; } .fa-headphones-alt:before { content: "\f58f"; } .fa-headset:before { content: "\f590"; } .fa-heart:before { content: "\f004"; } .fa-heart-broken:before { content: "\f7a9"; } .fa-heartbeat:before { content: "\f21e"; } .fa-helicopter:before { content: "\f533"; } .fa-highlighter:before { content: "\f591"; } .fa-hiking:before { content: "\f6ec"; } .fa-hippo:before { content: "\f6ed"; } .fa-hips:before { content: "\f452"; } .fa-hire-a-helper:before { content: "\f3b0"; } .fa-history:before { content: "\f1da"; } .fa-hockey-puck:before { content: "\f453"; } .fa-holly-berry:before { content: "\f7aa"; } .fa-home:before { content: "\f015"; } .fa-hooli:before { content: "\f427"; } .fa-hornbill:before { content: "\f592"; } .fa-horse:before { content: "\f6f0"; } .fa-horse-head:before { content: "\f7ab"; } .fa-hospital:before { content: "\f0f8"; } .fa-hospital-alt:before { content: "\f47d"; } .fa-hospital-symbol:before { content: "\f47e"; } .fa-hot-tub:before { content: "\f593"; } .fa-hotdog:before { content: "\f80f"; } .fa-hotel:before { content: "\f594"; } .fa-hotjar:before { content: "\f3b1"; } .fa-hourglass:before { content: "\f254"; } .fa-hourglass-end:before { content: "\f253"; } .fa-hourglass-half:before { content: "\f252"; } .fa-hourglass-start:before { content: "\f251"; } .fa-house-damage:before { content: "\f6f1"; } .fa-houzz:before { content: "\f27c"; } .fa-hryvnia:before { content: "\f6f2"; } .fa-html5:before { content: "\f13b"; } .fa-hubspot:before { content: "\f3b2"; } .fa-i-cursor:before { content: "\f246"; } .fa-ice-cream:before { content: "\f810"; } .fa-icicles:before { content: "\f7ad"; } .fa-icons:before { content: "\f86d"; } .fa-id-badge:before { content: "\f2c1"; } .fa-id-card:before { content: "\f2c2"; } .fa-id-card-alt:before { content: "\f47f"; } .fa-igloo:before { content: "\f7ae"; } .fa-image:before { content: "\f03e"; } .fa-images:before { content: "\f302"; } .fa-imdb:before { content: "\f2d8"; } .fa-inbox:before { content: "\f01c"; } .fa-indent:before { content: "\f03c"; } .fa-industry:before { content: "\f275"; } .fa-infinity:before { content: "\f534"; } .fa-info:before { content: "\f129"; } .fa-info-circle:before { content: "\f05a"; } .fa-instagram:before { content: "\f16d"; } .fa-intercom:before { content: "\f7af"; } .fa-internet-explorer:before { content: "\f26b"; } .fa-invision:before { content: "\f7b0"; } .fa-ioxhost:before { content: "\f208"; } .fa-italic:before { content: "\f033"; } .fa-itch-io:before { content: "\f83a"; } .fa-itunes:before { content: "\f3b4"; } .fa-itunes-note:before { content: "\f3b5"; } .fa-java:before { content: "\f4e4"; } .fa-jedi:before { content: "\f669"; } .fa-jedi-order:before { content: "\f50e"; } .fa-jenkins:before { content: "\f3b6"; } .fa-jira:before { content: "\f7b1"; } .fa-joget:before { content: "\f3b7"; } .fa-joint:before { content: "\f595"; } .fa-joomla:before { content: "\f1aa"; } .fa-journal-whills:before { content: "\f66a"; } .fa-js:before { content: "\f3b8"; } .fa-js-square:before { content: "\f3b9"; } .fa-jsfiddle:before { content: "\f1cc"; } .fa-kaaba:before { content: "\f66b"; } .fa-kaggle:before { content: "\f5fa"; } .fa-key:before { content: "\f084"; } .fa-keybase:before { content: "\f4f5"; } .fa-keyboard:before { content: "\f11c"; } .fa-keycdn:before { content: "\f3ba"; } .fa-khanda:before { content: "\f66d"; } .fa-kickstarter:before { content: "\f3bb"; } .fa-kickstarter-k:before { content: "\f3bc"; } .fa-kiss:before { content: "\f596"; } .fa-kiss-beam:before { content: "\f597"; } .fa-kiss-wink-heart:before { content: "\f598"; } .fa-kiwi-bird:before { content: "\f535"; } .fa-korvue:before { content: "\f42f"; } .fa-landmark:before { content: "\f66f"; } .fa-language:before { content: "\f1ab"; } .fa-laptop:before { content: "\f109"; } .fa-laptop-code:before { content: "\f5fc"; } .fa-laptop-medical:before { content: "\f812"; } .fa-laravel:before { content: "\f3bd"; } .fa-lastfm:before { content: "\f202"; } .fa-lastfm-square:before { content: "\f203"; } .fa-laugh:before { content: "\f599"; } .fa-laugh-beam:before { content: "\f59a"; } .fa-laugh-squint:before { content: "\f59b"; } .fa-laugh-wink:before { content: "\f59c"; } .fa-layer-group:before { content: "\f5fd"; } .fa-leaf:before { content: "\f06c"; } .fa-leanpub:before { content: "\f212"; } .fa-lemon:before { content: "\f094"; } .fa-less:before { content: "\f41d"; } .fa-less-than:before { content: "\f536"; } .fa-less-than-equal:before { content: "\f537"; } .fa-level-down-alt:before { content: "\f3be"; } .fa-level-up-alt:before { content: "\f3bf"; } .fa-life-ring:before { content: "\f1cd"; } .fa-lightbulb:before { content: "\f0eb"; } .fa-line:before { content: "\f3c0"; } .fa-link:before { content: "\f0c1"; } .fa-linkedin:before { content: "\f08c"; } .fa-linkedin-in:before { content: "\f0e1"; } .fa-linode:before { content: "\f2b8"; } .fa-linux:before { content: "\f17c"; } .fa-lira-sign:before { content: "\f195"; } .fa-list:before { content: "\f03a"; } .fa-list-alt:before { content: "\f022"; } .fa-list-ol:before { content: "\f0cb"; } .fa-list-ul:before { content: "\f0ca"; } .fa-location-arrow:before { content: "\f124"; } .fa-lock:before { content: "\f023"; } .fa-lock-open:before { content: "\f3c1"; } .fa-long-arrow-alt-down:before { content: "\f309"; } .fa-long-arrow-alt-left:before { content: "\f30a"; } .fa-long-arrow-alt-right:before { content: "\f30b"; } .fa-long-arrow-alt-up:before { content: "\f30c"; } .fa-low-vision:before { content: "\f2a8"; } .fa-luggage-cart:before { content: "\f59d"; } .fa-lyft:before { content: "\f3c3"; } .fa-magento:before { content: "\f3c4"; } .fa-magic:before { content: "\f0d0"; } .fa-magnet:before { content: "\f076"; } .fa-mail-bulk:before { content: "\f674"; } .fa-mailchimp:before { content: "\f59e"; } .fa-male:before { content: "\f183"; } .fa-mandalorian:before { content: "\f50f"; } .fa-map:before { content: "\f279"; } .fa-map-marked:before { content: "\f59f"; } .fa-map-marked-alt:before { content: "\f5a0"; } .fa-map-marker:before { content: "\f041"; } .fa-map-marker-alt:before { content: "\f3c5"; } .fa-map-pin:before { content: "\f276"; } .fa-map-signs:before { content: "\f277"; } .fa-markdown:before { content: "\f60f"; } .fa-marker:before { content: "\f5a1"; } .fa-mars:before { content: "\f222"; } .fa-mars-double:before { content: "\f227"; } .fa-mars-stroke:before { content: "\f229"; } .fa-mars-stroke-h:before { content: "\f22b"; } .fa-mars-stroke-v:before { content: "\f22a"; } .fa-mask:before { content: "\f6fa"; } .fa-mastodon:before { content: "\f4f6"; } .fa-maxcdn:before { content: "\f136"; } .fa-medal:before { content: "\f5a2"; } .fa-medapps:before { content: "\f3c6"; } .fa-medium:before { content: "\f23a"; } .fa-medium-m:before { content: "\f3c7"; } .fa-medkit:before { content: "\f0fa"; } .fa-medrt:before { content: "\f3c8"; } .fa-meetup:before { content: "\f2e0"; } .fa-megaport:before { content: "\f5a3"; } .fa-meh:before { content: "\f11a"; } .fa-meh-blank:before { content: "\f5a4"; } .fa-meh-rolling-eyes:before { content: "\f5a5"; } .fa-memory:before { content: "\f538"; } .fa-mendeley:before { content: "\f7b3"; } .fa-menorah:before { content: "\f676"; } .fa-mercury:before { content: "\f223"; } .fa-meteor:before { content: "\f753"; } .fa-microchip:before { content: "\f2db"; } .fa-microphone:before { content: "\f130"; } .fa-microphone-alt:before { content: "\f3c9"; } .fa-microphone-alt-slash:before { content: "\f539"; } .fa-microphone-slash:before { content: "\f131"; } .fa-microscope:before { content: "\f610"; } .fa-microsoft:before { content: "\f3ca"; } .fa-minus:before { content: "\f068"; } .fa-minus-circle:before { content: "\f056"; } .fa-minus-square:before { content: "\f146"; } .fa-mitten:before { content: "\f7b5"; } .fa-mix:before { content: "\f3cb"; } .fa-mixcloud:before { content: "\f289"; } .fa-mizuni:before { content: "\f3cc"; } .fa-mobile:before { content: "\f10b"; } .fa-mobile-alt:before { content: "\f3cd"; } .fa-modx:before { content: "\f285"; } .fa-monero:before { content: "\f3d0"; } .fa-money-bill:before { content: "\f0d6"; } .fa-money-bill-alt:before { content: "\f3d1"; } .fa-money-bill-wave:before { content: "\f53a"; } .fa-money-bill-wave-alt:before { content: "\f53b"; } .fa-money-check:before { content: "\f53c"; } .fa-money-check-alt:before { content: "\f53d"; } .fa-monument:before { content: "\f5a6"; } .fa-moon:before { content: "\f186"; } .fa-mortar-pestle:before { content: "\f5a7"; } .fa-mosque:before { content: "\f678"; } .fa-motorcycle:before { content: "\f21c"; } .fa-mountain:before { content: "\f6fc"; } .fa-mouse-pointer:before { content: "\f245"; } .fa-mug-hot:before { content: "\f7b6"; } .fa-music:before { content: "\f001"; } .fa-napster:before { content: "\f3d2"; } .fa-neos:before { content: "\f612"; } .fa-network-wired:before { content: "\f6ff"; } .fa-neuter:before { content: "\f22c"; } .fa-newspaper:before { content: "\f1ea"; } .fa-nimblr:before { content: "\f5a8"; } .fa-node:before { content: "\f419"; } .fa-node-js:before { content: "\f3d3"; } .fa-not-equal:before { content: "\f53e"; } .fa-notes-medical:before { content: "\f481"; } .fa-npm:before { content: "\f3d4"; } .fa-ns8:before { content: "\f3d5"; } .fa-nutritionix:before { content: "\f3d6"; } .fa-object-group:before { content: "\f247"; } .fa-object-ungroup:before { content: "\f248"; } .fa-odnoklassniki:before { content: "\f263"; } .fa-odnoklassniki-square:before { content: "\f264"; } .fa-oil-can:before { content: "\f613"; } .fa-old-republic:before { content: "\f510"; } .fa-om:before { content: "\f679"; } .fa-opencart:before { content: "\f23d"; } .fa-openid:before { content: "\f19b"; } .fa-opera:before { content: "\f26a"; } .fa-optin-monster:before { content: "\f23c"; } .fa-osi:before { content: "\f41a"; } .fa-otter:before { content: "\f700"; } .fa-outdent:before { content: "\f03b"; } .fa-page4:before { content: "\f3d7"; } .fa-pagelines:before { content: "\f18c"; } .fa-pager:before { content: "\f815"; } .fa-paint-brush:before { content: "\f1fc"; } .fa-paint-roller:before { content: "\f5aa"; } .fa-palette:before { content: "\f53f"; } .fa-palfed:before { content: "\f3d8"; } .fa-pallet:before { content: "\f482"; } .fa-paper-plane:before { content: "\f1d8"; } .fa-paperclip:before { content: "\f0c6"; } .fa-parachute-box:before { content: "\f4cd"; } .fa-paragraph:before { content: "\f1dd"; } .fa-parking:before { content: "\f540"; } .fa-passport:before { content: "\f5ab"; } .fa-pastafarianism:before { content: "\f67b"; } .fa-paste:before { content: "\f0ea"; } .fa-patreon:before { content: "\f3d9"; } .fa-pause:before { content: "\f04c"; } .fa-pause-circle:before { content: "\f28b"; } .fa-paw:before { content: "\f1b0"; } .fa-paypal:before { content: "\f1ed"; } .fa-peace:before { content: "\f67c"; } .fa-pen:before { content: "\f304"; } .fa-pen-alt:before { content: "\f305"; } .fa-pen-fancy:before { content: "\f5ac"; } .fa-pen-nib:before { content: "\f5ad"; } .fa-pen-square:before { content: "\f14b"; } .fa-pencil-alt:before { content: "\f303"; } .fa-pencil-ruler:before { content: "\f5ae"; } .fa-penny-arcade:before { content: "\f704"; } .fa-people-carry:before { content: "\f4ce"; } .fa-pepper-hot:before { content: "\f816"; } .fa-percent:before { content: "\f295"; } .fa-percentage:before { content: "\f541"; } .fa-periscope:before { content: "\f3da"; } .fa-person-booth:before { content: "\f756"; } .fa-phabricator:before { content: "\f3db"; } .fa-phoenix-framework:before { content: "\f3dc"; } .fa-phoenix-squadron:before { content: "\f511"; } .fa-phone:before { content: "\f095"; } .fa-phone-alt:before { content: "\f879"; } .fa-phone-slash:before { content: "\f3dd"; } .fa-phone-square:before { content: "\f098"; } .fa-phone-square-alt:before { content: "\f87b"; } .fa-phone-volume:before { content: "\f2a0"; } .fa-photo-video:before { content: "\f87c"; } .fa-php:before { content: "\f457"; } .fa-pied-piper:before { content: "\f2ae"; } .fa-pied-piper-alt:before { content: "\f1a8"; } .fa-pied-piper-hat:before { content: "\f4e5"; } .fa-pied-piper-pp:before { content: "\f1a7"; } .fa-piggy-bank:before { content: "\f4d3"; } .fa-pills:before { content: "\f484"; } .fa-pinterest:before { content: "\f0d2"; } .fa-pinterest-p:before { content: "\f231"; } .fa-pinterest-square:before { content: "\f0d3"; } .fa-pizza-slice:before { content: "\f818"; } .fa-place-of-worship:before { content: "\f67f"; } .fa-plane:before { content: "\f072"; } .fa-plane-arrival:before { content: "\f5af"; } .fa-plane-departure:before { content: "\f5b0"; } .fa-play:before { content: "\f04b"; } .fa-play-circle:before { content: "\f144"; } .fa-playstation:before { content: "\f3df"; } .fa-plug:before { content: "\f1e6"; } .fa-plus:before { content: "\f067"; } .fa-plus-circle:before { content: "\f055"; } .fa-plus-square:before { content: "\f0fe"; } .fa-podcast:before { content: "\f2ce"; } .fa-poll:before { content: "\f681"; } .fa-poll-h:before { content: "\f682"; } .fa-poo:before { content: "\f2fe"; } .fa-poo-storm:before { content: "\f75a"; } .fa-poop:before { content: "\f619"; } .fa-portrait:before { content: "\f3e0"; } .fa-pound-sign:before { content: "\f154"; } .fa-power-off:before { content: "\f011"; } .fa-pray:before { content: "\f683"; } .fa-praying-hands:before { content: "\f684"; } .fa-prescription:before { content: "\f5b1"; } .fa-prescription-bottle:before { content: "\f485"; } .fa-prescription-bottle-alt:before { content: "\f486"; } .fa-print:before { content: "\f02f"; } .fa-procedures:before { content: "\f487"; } .fa-product-hunt:before { content: "\f288"; } .fa-project-diagram:before { content: "\f542"; } .fa-pushed:before { content: "\f3e1"; } .fa-puzzle-piece:before { content: "\f12e"; } .fa-python:before { content: "\f3e2"; } .fa-qq:before { content: "\f1d6"; } .fa-qrcode:before { content: "\f029"; } .fa-question:before { content: "\f128"; } .fa-question-circle:before { content: "\f059"; } .fa-quidditch:before { content: "\f458"; } .fa-quinscape:before { content: "\f459"; } .fa-quora:before { content: "\f2c4"; } .fa-quote-left:before { content: "\f10d"; } .fa-quote-right:before { content: "\f10e"; } .fa-quran:before { content: "\f687"; } .fa-r-project:before { content: "\f4f7"; } .fa-radiation:before { content: "\f7b9"; } .fa-radiation-alt:before { content: "\f7ba"; } .fa-rainbow:before { content: "\f75b"; } .fa-random:before { content: "\f074"; } .fa-raspberry-pi:before { content: "\f7bb"; } .fa-ravelry:before { content: "\f2d9"; } .fa-react:before { content: "\f41b"; } .fa-reacteurope:before { content: "\f75d"; } .fa-readme:before { content: "\f4d5"; } .fa-rebel:before { content: "\f1d0"; } .fa-receipt:before { content: "\f543"; } .fa-recycle:before { content: "\f1b8"; } .fa-red-river:before { content: "\f3e3"; } .fa-reddit:before { content: "\f1a1"; } .fa-reddit-alien:before { content: "\f281"; } .fa-reddit-square:before { content: "\f1a2"; } .fa-redhat:before { content: "\f7bc"; } .fa-redo:before { content: "\f01e"; } .fa-redo-alt:before { content: "\f2f9"; } .fa-registered:before { content: "\f25d"; } .fa-remove-format:before { content: "\f87d"; } .fa-renren:before { content: "\f18b"; } .fa-reply:before { content: "\f3e5"; } .fa-reply-all:before { content: "\f122"; } .fa-replyd:before { content: "\f3e6"; } .fa-republican:before { content: "\f75e"; } .fa-researchgate:before { content: "\f4f8"; } .fa-resolving:before { content: "\f3e7"; } .fa-restroom:before { content: "\f7bd"; } .fa-retweet:before { content: "\f079"; } .fa-rev:before { content: "\f5b2"; } .fa-ribbon:before { content: "\f4d6"; } .fa-ring:before { content: "\f70b"; } .fa-road:before { content: "\f018"; } .fa-robot:before { content: "\f544"; } .fa-rocket:before { content: "\f135"; } .fa-rocketchat:before { content: "\f3e8"; } .fa-rockrms:before { content: "\f3e9"; } .fa-route:before { content: "\f4d7"; } .fa-rss:before { content: "\f09e"; } .fa-rss-square:before { content: "\f143"; } .fa-ruble-sign:before { content: "\f158"; } .fa-ruler:before { content: "\f545"; } .fa-ruler-combined:before { content: "\f546"; } .fa-ruler-horizontal:before { content: "\f547"; } .fa-ruler-vertical:before { content: "\f548"; } .fa-running:before { content: "\f70c"; } .fa-rupee-sign:before { content: "\f156"; } .fa-sad-cry:before { content: "\f5b3"; } .fa-sad-tear:before { content: "\f5b4"; } .fa-safari:before { content: "\f267"; } .fa-salesforce:before { content: "\f83b"; } .fa-sass:before { content: "\f41e"; } .fa-satellite:before { content: "\f7bf"; } .fa-satellite-dish:before { content: "\f7c0"; } .fa-save:before { content: "\f0c7"; } .fa-schlix:before { content: "\f3ea"; } .fa-school:before { content: "\f549"; } .fa-screwdriver:before { content: "\f54a"; } .fa-scribd:before { content: "\f28a"; } .fa-scroll:before { content: "\f70e"; } .fa-sd-card:before { content: "\f7c2"; } .fa-search:before { content: "\f002"; } .fa-search-dollar:before { content: "\f688"; } .fa-search-location:before { content: "\f689"; } .fa-search-minus:before { content: "\f010"; } .fa-search-plus:before { content: "\f00e"; } .fa-searchengin:before { content: "\f3eb"; } .fa-seedling:before { content: "\f4d8"; } .fa-sellcast:before { content: "\f2da"; } .fa-sellsy:before { content: "\f213"; } .fa-server:before { content: "\f233"; } .fa-servicestack:before { content: "\f3ec"; } .fa-shapes:before { content: "\f61f"; } .fa-share:before { content: "\f064"; } .fa-share-alt:before { content: "\f1e0"; } .fa-share-alt-square:before { content: "\f1e1"; } .fa-share-square:before { content: "\f14d"; } .fa-shekel-sign:before { content: "\f20b"; } .fa-shield-alt:before { content: "\f3ed"; } .fa-ship:before { content: "\f21a"; } .fa-shipping-fast:before { content: "\f48b"; } .fa-shirtsinbulk:before { content: "\f214"; } .fa-shoe-prints:before { content: "\f54b"; } .fa-shopping-bag:before { content: "\f290"; } .fa-shopping-basket:before { content: "\f291"; } .fa-shopping-cart:before { content: "\f07a"; } .fa-shopware:before { content: "\f5b5"; } .fa-shower:before { content: "\f2cc"; } .fa-shuttle-van:before { content: "\f5b6"; } .fa-sign:before { content: "\f4d9"; } .fa-sign-in-alt:before { content: "\f2f6"; } .fa-sign-language:before { content: "\f2a7"; } .fa-sign-out-alt:before { content: "\f2f5"; } .fa-signal:before { content: "\f012"; } .fa-signature:before { content: "\f5b7"; } .fa-sim-card:before { content: "\f7c4"; } .fa-simplybuilt:before { content: "\f215"; } .fa-sistrix:before { content: "\f3ee"; } .fa-sitemap:before { content: "\f0e8"; } .fa-sith:before { content: "\f512"; } .fa-skating:before { content: "\f7c5"; } .fa-sketch:before { content: "\f7c6"; } .fa-skiing:before { content: "\f7c9"; } .fa-skiing-nordic:before { content: "\f7ca"; } .fa-skull:before { content: "\f54c"; } .fa-skull-crossbones:before { content: "\f714"; } .fa-skyatlas:before { content: "\f216"; } .fa-skype:before { content: "\f17e"; } .fa-slack:before { content: "\f198"; } .fa-slack-hash:before { content: "\f3ef"; } .fa-slash:before { content: "\f715"; } .fa-sleigh:before { content: "\f7cc"; } .fa-sliders-h:before { content: "\f1de"; } .fa-slideshare:before { content: "\f1e7"; } .fa-smile:before { content: "\f118"; } .fa-smile-beam:before { content: "\f5b8"; } .fa-smile-wink:before { content: "\f4da"; } .fa-smog:before { content: "\f75f"; } .fa-smoking:before { content: "\f48d"; } .fa-smoking-ban:before { content: "\f54d"; } .fa-sms:before { content: "\f7cd"; } .fa-snapchat:before { content: "\f2ab"; } .fa-snapchat-ghost:before { content: "\f2ac"; } .fa-snapchat-square:before { content: "\f2ad"; } .fa-snowboarding:before { content: "\f7ce"; } .fa-snowflake:before { content: "\f2dc"; } .fa-snowman:before { content: "\f7d0"; } .fa-snowplow:before { content: "\f7d2"; } .fa-socks:before { content: "\f696"; } .fa-solar-panel:before { content: "\f5ba"; } .fa-sort:before { content: "\f0dc"; } .fa-sort-alpha-down:before { content: "\f15d"; } .fa-sort-alpha-down-alt:before { content: "\f881"; } .fa-sort-alpha-up:before { content: "\f15e"; } .fa-sort-alpha-up-alt:before { content: "\f882"; } .fa-sort-amount-down:before { content: "\f160"; } .fa-sort-amount-down-alt:before { content: "\f884"; } .fa-sort-amount-up:before { content: "\f161"; } .fa-sort-amount-up-alt:before { content: "\f885"; } .fa-sort-down:before { content: "\f0dd"; } .fa-sort-numeric-down:before { content: "\f162"; } .fa-sort-numeric-down-alt:before { content: "\f886"; } .fa-sort-numeric-up:before { content: "\f163"; } .fa-sort-numeric-up-alt:before { content: "\f887"; } .fa-sort-up:before { content: "\f0de"; } .fa-soundcloud:before { content: "\f1be"; } .fa-sourcetree:before { content: "\f7d3"; } .fa-spa:before { content: "\f5bb"; } .fa-space-shuttle:before { content: "\f197"; } .fa-speakap:before { content: "\f3f3"; } .fa-speaker-deck:before { content: "\f83c"; } .fa-spell-check:before { content: "\f891"; } .fa-spider:before { content: "\f717"; } .fa-spinner:before { content: "\f110"; } .fa-splotch:before { content: "\f5bc"; } .fa-spotify:before { content: "\f1bc"; } .fa-spray-can:before { content: "\f5bd"; } .fa-square:before { content: "\f0c8"; } .fa-square-full:before { content: "\f45c"; } .fa-square-root-alt:before { content: "\f698"; } .fa-squarespace:before { content: "\f5be"; } .fa-stack-exchange:before { content: "\f18d"; } .fa-stack-overflow:before { content: "\f16c"; } .fa-stackpath:before { content: "\f842"; } .fa-stamp:before { content: "\f5bf"; } .fa-star:before { content: "\f005"; } .fa-star-and-crescent:before { content: "\f699"; } .fa-star-half:before { content: "\f089"; } .fa-star-half-alt:before { content: "\f5c0"; } .fa-star-of-david:before { content: "\f69a"; } .fa-star-of-life:before { content: "\f621"; } .fa-staylinked:before { content: "\f3f5"; } .fa-steam:before { content: "\f1b6"; } .fa-steam-square:before { content: "\f1b7"; } .fa-steam-symbol:before { content: "\f3f6"; } .fa-step-backward:before { content: "\f048"; } .fa-step-forward:before { content: "\f051"; } .fa-stethoscope:before { content: "\f0f1"; } .fa-sticker-mule:before { content: "\f3f7"; } .fa-sticky-note:before { content: "\f249"; } .fa-stop:before { content: "\f04d"; } .fa-stop-circle:before { content: "\f28d"; } .fa-stopwatch:before { content: "\f2f2"; } .fa-store:before { content: "\f54e"; } .fa-store-alt:before { content: "\f54f"; } .fa-strava:before { content: "\f428"; } .fa-stream:before { content: "\f550"; } .fa-street-view:before { content: "\f21d"; } .fa-strikethrough:before { content: "\f0cc"; } .fa-stripe:before { content: "\f429"; } .fa-stripe-s:before { content: "\f42a"; } .fa-stroopwafel:before { content: "\f551"; } .fa-studiovinari:before { content: "\f3f8"; } .fa-stumbleupon:before { content: "\f1a4"; } .fa-stumbleupon-circle:before { content: "\f1a3"; } .fa-subscript:before { content: "\f12c"; } .fa-subway:before { content: "\f239"; } .fa-suitcase:before { content: "\f0f2"; } .fa-suitcase-rolling:before { content: "\f5c1"; } .fa-sun:before { content: "\f185"; } .fa-superpowers:before { content: "\f2dd"; } .fa-superscript:before { content: "\f12b"; } .fa-supple:before { content: "\f3f9"; } .fa-surprise:before { content: "\f5c2"; } .fa-suse:before { content: "\f7d6"; } .fa-swatchbook:before { content: "\f5c3"; } .fa-swimmer:before { content: "\f5c4"; } .fa-swimming-pool:before { content: "\f5c5"; } .fa-symfony:before { content: "\f83d"; } .fa-synagogue:before { content: "\f69b"; } .fa-sync:before { content: "\f021"; } .fa-sync-alt:before { content: "\f2f1"; } .fa-syringe:before { content: "\f48e"; } .fa-table:before { content: "\f0ce"; } .fa-table-tennis:before { content: "\f45d"; } .fa-tablet:before { content: "\f10a"; } .fa-tablet-alt:before { content: "\f3fa"; } .fa-tablets:before { content: "\f490"; } .fa-tachometer-alt:before { content: "\f3fd"; } .fa-tag:before { content: "\f02b"; } .fa-tags:before { content: "\f02c"; } .fa-tape:before { content: "\f4db"; } .fa-tasks:before { content: "\f0ae"; } .fa-taxi:before { content: "\f1ba"; } .fa-teamspeak:before { content: "\f4f9"; } .fa-teeth:before { content: "\f62e"; } .fa-teeth-open:before { content: "\f62f"; } .fa-telegram:before { content: "\f2c6"; } .fa-telegram-plane:before { content: "\f3fe"; } .fa-temperature-high:before { content: "\f769"; } .fa-temperature-low:before { content: "\f76b"; } .fa-tencent-weibo:before { content: "\f1d5"; } .fa-tenge:before { content: "\f7d7"; } .fa-terminal:before { content: "\f120"; } .fa-text-height:before { content: "\f034"; } .fa-text-width:before { content: "\f035"; } .fa-th:before { content: "\f00a"; } .fa-th-large:before { content: "\f009"; } .fa-th-list:before { content: "\f00b"; } .fa-the-red-yeti:before { content: "\f69d"; } .fa-theater-masks:before { content: "\f630"; } .fa-themeco:before { content: "\f5c6"; } .fa-themeisle:before { content: "\f2b2"; } .fa-thermometer:before { content: "\f491"; } .fa-thermometer-empty:before { content: "\f2cb"; } .fa-thermometer-full:before { content: "\f2c7"; } .fa-thermometer-half:before { content: "\f2c9"; } .fa-thermometer-quarter:before { content: "\f2ca"; } .fa-thermometer-three-quarters:before { content: "\f2c8"; } .fa-think-peaks:before { content: "\f731"; } .fa-thumbs-down:before { content: "\f165"; } .fa-thumbs-up:before { content: "\f164"; } .fa-thumbtack:before { content: "\f08d"; } .fa-ticket-alt:before { content: "\f3ff"; } .fa-times:before { content: "\f00d"; } .fa-times-circle:before { content: "\f057"; } .fa-tint:before { content: "\f043"; } .fa-tint-slash:before { content: "\f5c7"; } .fa-tired:before { content: "\f5c8"; } .fa-toggle-off:before { content: "\f204"; } .fa-toggle-on:before { content: "\f205"; } .fa-toilet:before { content: "\f7d8"; } .fa-toilet-paper:before { content: "\f71e"; } .fa-toolbox:before { content: "\f552"; } .fa-tools:before { content: "\f7d9"; } .fa-tooth:before { content: "\f5c9"; } .fa-torah:before { content: "\f6a0"; } .fa-torii-gate:before { content: "\f6a1"; } .fa-tractor:before { content: "\f722"; } .fa-trade-federation:before { content: "\f513"; } .fa-trademark:before { content: "\f25c"; } .fa-traffic-light:before { content: "\f637"; } .fa-train:before { content: "\f238"; } .fa-tram:before { content: "\f7da"; } .fa-transgender:before { content: "\f224"; } .fa-transgender-alt:before { content: "\f225"; } .fa-trash:before { content: "\f1f8"; } .fa-trash-alt:before { content: "\f2ed"; } .fa-trash-restore:before { content: "\f829"; } .fa-trash-restore-alt:before { content: "\f82a"; } .fa-tree:before { content: "\f1bb"; } .fa-trello:before { content: "\f181"; } .fa-tripadvisor:before { content: "\f262"; } .fa-trophy:before { content: "\f091"; } .fa-truck:before { content: "\f0d1"; } .fa-truck-loading:before { content: "\f4de"; } .fa-truck-monster:before { content: "\f63b"; } .fa-truck-moving:before { content: "\f4df"; } .fa-truck-pickup:before { content: "\f63c"; } .fa-tshirt:before { content: "\f553"; } .fa-tty:before { content: "\f1e4"; } .fa-tumblr:before { content: "\f173"; } .fa-tumblr-square:before { content: "\f174"; } .fa-tv:before { content: "\f26c"; } .fa-twitch:before { content: "\f1e8"; } .fa-twitter:before { content: "\f099"; } .fa-twitter-square:before { content: "\f081"; } .fa-typo3:before { content: "\f42b"; } .fa-uber:before { content: "\f402"; } .fa-ubuntu:before { content: "\f7df"; } .fa-uikit:before { content: "\f403"; } .fa-umbrella:before { content: "\f0e9"; } .fa-umbrella-beach:before { content: "\f5ca"; } .fa-underline:before { content: "\f0cd"; } .fa-undo:before { content: "\f0e2"; } .fa-undo-alt:before { content: "\f2ea"; } .fa-uniregistry:before { content: "\f404"; } .fa-universal-access:before { content: "\f29a"; } .fa-university:before { content: "\f19c"; } .fa-unlink:before { content: "\f127"; } .fa-unlock:before { content: "\f09c"; } .fa-unlock-alt:before { content: "\f13e"; } .fa-untappd:before { content: "\f405"; } .fa-upload:before { content: "\f093"; } .fa-ups:before { content: "\f7e0"; } .fa-usb:before { content: "\f287"; } .fa-user:before { content: "\f007"; } .fa-user-alt:before { content: "\f406"; } .fa-user-alt-slash:before { content: "\f4fa"; } .fa-user-astronaut:before { content: "\f4fb"; } .fa-user-check:before { content: "\f4fc"; } .fa-user-circle:before { content: "\f2bd"; } .fa-user-clock:before { content: "\f4fd"; } .fa-user-cog:before { content: "\f4fe"; } .fa-user-edit:before { content: "\f4ff"; } .fa-user-friends:before { content: "\f500"; } .fa-user-graduate:before { content: "\f501"; } .fa-user-injured:before { content: "\f728"; } .fa-user-lock:before { content: "\f502"; } .fa-user-md:before { content: "\f0f0"; } .fa-user-minus:before { content: "\f503"; } .fa-user-ninja:before { content: "\f504"; } .fa-user-nurse:before { content: "\f82f"; } .fa-user-plus:before { content: "\f234"; } .fa-user-secret:before { content: "\f21b"; } .fa-user-shield:before { content: "\f505"; } .fa-user-slash:before { content: "\f506"; } .fa-user-tag:before { content: "\f507"; } .fa-user-tie:before { content: "\f508"; } .fa-user-times:before { content: "\f235"; } .fa-users:before { content: "\f0c0"; } .fa-users-cog:before { content: "\f509"; } .fa-usps:before { content: "\f7e1"; } .fa-ussunnah:before { content: "\f407"; } .fa-utensil-spoon:before { content: "\f2e5"; } .fa-utensils:before { content: "\f2e7"; } .fa-vaadin:before { content: "\f408"; } .fa-vector-square:before { content: "\f5cb"; } .fa-venus:before { content: "\f221"; } .fa-venus-double:before { content: "\f226"; } .fa-venus-mars:before { content: "\f228"; } .fa-viacoin:before { content: "\f237"; } .fa-viadeo:before { content: "\f2a9"; } .fa-viadeo-square:before { content: "\f2aa"; } .fa-vial:before { content: "\f492"; } .fa-vials:before { content: "\f493"; } .fa-viber:before { content: "\f409"; } .fa-video:before { content: "\f03d"; } .fa-video-slash:before { content: "\f4e2"; } .fa-vihara:before { content: "\f6a7"; } .fa-vimeo:before { content: "\f40a"; } .fa-vimeo-square:before { content: "\f194"; } .fa-vimeo-v:before { content: "\f27d"; } .fa-vine:before { content: "\f1ca"; } .fa-vk:before { content: "\f189"; } .fa-vnv:before { content: "\f40b"; } .fa-voicemail:before { content: "\f897"; } .fa-volleyball-ball:before { content: "\f45f"; } .fa-volume-down:before { content: "\f027"; } .fa-volume-mute:before { content: "\f6a9"; } .fa-volume-off:before { content: "\f026"; } .fa-volume-up:before { content: "\f028"; } .fa-vote-yea:before { content: "\f772"; } .fa-vr-cardboard:before { content: "\f729"; } .fa-vuejs:before { content: "\f41f"; } .fa-walking:before { content: "\f554"; } .fa-wallet:before { content: "\f555"; } .fa-warehouse:before { content: "\f494"; } .fa-water:before { content: "\f773"; } .fa-wave-square:before { content: "\f83e"; } .fa-waze:before { content: "\f83f"; } .fa-weebly:before { content: "\f5cc"; } .fa-weibo:before { content: "\f18a"; } .fa-weight:before { content: "\f496"; } .fa-weight-hanging:before { content: "\f5cd"; } .fa-weixin:before { content: "\f1d7"; } .fa-whatsapp:before { content: "\f232"; } .fa-whatsapp-square:before { content: "\f40c"; } .fa-wheelchair:before { content: "\f193"; } .fa-whmcs:before { content: "\f40d"; } .fa-wifi:before { content: "\f1eb"; } .fa-wikipedia-w:before { content: "\f266"; } .fa-wind:before { content: "\f72e"; } .fa-window-close:before { content: "\f410"; } .fa-window-maximize:before { content: "\f2d0"; } .fa-window-minimize:before { content: "\f2d1"; } .fa-window-restore:before { content: "\f2d2"; } .fa-windows:before { content: "\f17a"; } .fa-wine-bottle:before { content: "\f72f"; } .fa-wine-glass:before { content: "\f4e3"; } .fa-wine-glass-alt:before { content: "\f5ce"; } .fa-wix:before { content: "\f5cf"; } .fa-wizards-of-the-coast:before { content: "\f730"; } .fa-wolf-pack-battalion:before { content: "\f514"; } .fa-won-sign:before { content: "\f159"; } .fa-wordpress:before { content: "\f19a"; } .fa-wordpress-simple:before { content: "\f411"; } .fa-wpbeginner:before { content: "\f297"; } .fa-wpexplorer:before { content: "\f2de"; } .fa-wpforms:before { content: "\f298"; } .fa-wpressr:before { content: "\f3e4"; } .fa-wrench:before { content: "\f0ad"; } .fa-x-ray:before { content: "\f497"; } .fa-xbox:before { content: "\f412"; } .fa-xing:before { content: "\f168"; } .fa-xing-square:before { content: "\f169"; } .fa-y-combinator:before { content: "\f23b"; } .fa-yahoo:before { content: "\f19e"; } .fa-yammer:before { content: "\f840"; } .fa-yandex:before { content: "\f413"; } .fa-yandex-international:before { content: "\f414"; } .fa-yarn:before { content: "\f7e3"; } .fa-yelp:before { content: "\f1e9"; } .fa-yen-sign:before { content: "\f157"; } .fa-yin-yang:before { content: "\f6ad"; } .fa-yoast:before { content: "\f2b1"; } .fa-youtube:before { content: "\f167"; } .fa-youtube-square:before { content: "\f431"; } .fa-zhihu:before { content: "\f63f"; } .sr-only { border: 0; clip: rect(0, 0, 0, 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .sr-only-focusable:active, .sr-only-focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } @font-face { font-family: 'Font Awesome 5 Brands'; font-style: normal; font-weight: normal; font-display: auto; src: url("../fonts/fontawesome/brands.woff") format("woff"); } .fab { font-family: 'Font Awesome 5 Brands'; } @font-face { font-family: 'Font Awesome 5 Free'; font-style: normal; font-weight: 400; font-display: auto; src: url("../fonts/fontawesome/regular.woff") format("woff"); } .far { font-family: 'Font Awesome 5 Free'; font-weight: 400; } @font-face { font-family: 'Font Awesome 5 Free'; font-style: normal; font-weight: 900; font-display: auto; src: url("../fonts/fontawesome/solid.woff") format("woff"); } .fa, .fas { font-family: 'Font Awesome 5 Free'; font-weight: 900; }
{ "pile_set_name": "Github" }
<?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-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.kie.server</groupId> <artifactId>kie-server-services-task-assigning</artifactId> <version>7.44.0-SNAPSHOT</version> </parent> <artifactId>kie-server-services-task-assigning-runtime</artifactId> <name>KIE :: Execution Server :: Services :: Task Assigning :: Runtime</name> <description>KIE Execution Server Services Task Assigning Runtime</description> <dependencies> <dependency> <groupId>org.kie.soup</groupId> <artifactId>kie-soup-dataset-api</artifactId> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-api</artifactId> </dependency> <dependency> <groupId>org.jbpm</groupId> <artifactId>jbpm-kie-services</artifactId> <exclusions> <exclusion> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.kie.server</groupId> <artifactId>kie-server-services-common</artifactId> <exclusions> <exclusion> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.kie.server</groupId> <artifactId>kie-server-services-jbpm</artifactId> </dependency> <dependency> <groupId>org.kie.server</groupId> <artifactId>kie-server-api</artifactId> <exclusions> <exclusion> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <!-- test dependencies --> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "pile_set_name": "Github" }
/* * Copyright 2012 The Netty Project * * The Netty Project 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. */ /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. 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. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ package org.jboss.netty.util.internal.jzlib; final class StaticTree { static final short[] static_ltree = { 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8 }; static final short[] static_dtree = { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 }; static final StaticTree static_l_desc = new StaticTree(static_ltree, Tree.extra_lbits, JZlib.LITERALS + 1, JZlib.L_CODES, JZlib.MAX_BITS); static final StaticTree static_d_desc = new StaticTree(static_dtree, Tree.extra_dbits, 0, JZlib.D_CODES, JZlib.MAX_BITS); static final StaticTree static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, JZlib.BL_CODES, JZlib.MAX_BL_BITS); final short[] static_tree; // static tree or null final int[] extra_bits; // extra bits for each code or null final int extra_base; // base index for extra_bits final int elems; // max number of elements in the tree final int max_length; // max bit length for the codes StaticTree(short[] static_tree, int[] extra_bits, int extra_base, int elems, int max_length) { this.static_tree = static_tree; this.extra_bits = extra_bits; this.extra_base = extra_base; this.elems = elems; this.max_length = max_length; } }
{ "pile_set_name": "Github" }
// Copyright 2004-present Facebook. All Rights Reserved. #include "NativeToJsBridge.h" #include <folly/json.h> #include <folly/Memory.h> #include <folly/MoveWrapper.h> #include "Instance.h" #include "JSBigString.h" #include "SystraceSection.h" #include "MethodCall.h" #include "MessageQueueThread.h" #include "RAMBundleRegistry.h" #ifdef WITH_FBSYSTRACE #include <fbsystrace.h> using fbsystrace::FbSystraceAsyncFlow; #endif namespace facebook { namespace react { // This class manages calls from JS to native code. class JsToNativeBridge : public react::ExecutorDelegate { public: JsToNativeBridge(std::shared_ptr<ModuleRegistry> registry, std::shared_ptr<InstanceCallback> callback) : m_registry(registry) , m_callback(callback) {} std::shared_ptr<ModuleRegistry> getModuleRegistry() override { return m_registry; } void callNativeModules( JSExecutor& executor, folly::dynamic&& calls, bool isEndOfBatch) override { CHECK(m_registry || calls.empty()) << "native module calls cannot be completed with no native modules"; m_batchHadNativeModuleCalls = m_batchHadNativeModuleCalls || !calls.empty(); // An exception anywhere in here stops processing of the batch. This // was the behavior of the Android bridge, and since exception handling // terminates the whole bridge, there's not much point in continuing. for (auto& call : parseMethodCalls(std::move(calls))) { m_registry->callNativeMethod(call.moduleId, call.methodId, std::move(call.arguments), call.callId); } if (isEndOfBatch) { // onBatchComplete will be called on the native (module) queue, but // decrementPendingJSCalls will be called sync. Be aware that the bridge may still // be processing native calls when the birdge idle signaler fires. if (m_batchHadNativeModuleCalls) { m_callback->onBatchComplete(); m_batchHadNativeModuleCalls = false; } m_callback->decrementPendingJSCalls(); } } MethodCallResult callSerializableNativeHook( JSExecutor& executor, unsigned int moduleId, unsigned int methodId, folly::dynamic&& args) override { return m_registry->callSerializableNativeHook(moduleId, methodId, std::move(args)); } private: // These methods are always invoked from an Executor. The NativeToJsBridge // keeps a reference to the executor, and when destroy() is called, the // executor is destroyed synchronously on its queue. std::shared_ptr<ModuleRegistry> m_registry; std::shared_ptr<InstanceCallback> m_callback; bool m_batchHadNativeModuleCalls = false; }; NativeToJsBridge::NativeToJsBridge( JSExecutorFactory* jsExecutorFactory, std::shared_ptr<ModuleRegistry> registry, std::shared_ptr<MessageQueueThread> jsQueue, std::shared_ptr<InstanceCallback> callback) : m_destroyed(std::make_shared<bool>(false)) , m_delegate(std::make_shared<JsToNativeBridge>(registry, callback)) , m_executor(jsExecutorFactory->createJSExecutor(m_delegate, jsQueue)) , m_executorMessageQueueThread(std::move(jsQueue)) {} // This must be called on the same thread on which the constructor was called. NativeToJsBridge::~NativeToJsBridge() { CHECK(*m_destroyed) << "NativeToJsBridge::destroy() must be called before deallocating the NativeToJsBridge!"; } void NativeToJsBridge::loadApplication( std::unique_ptr<RAMBundleRegistry> bundleRegistry, std::unique_ptr<const JSBigString> startupScript, std::string startupScriptSourceURL) { runOnExecutorQueue( [bundleRegistryWrap=folly::makeMoveWrapper(std::move(bundleRegistry)), startupScript=folly::makeMoveWrapper(std::move(startupScript)), startupScriptSourceURL=std::move(startupScriptSourceURL)] (JSExecutor* executor) mutable { auto bundleRegistry = bundleRegistryWrap.move(); if (bundleRegistry) { executor->setBundleRegistry(std::move(bundleRegistry)); } executor->loadApplicationScript(std::move(*startupScript), std::move(startupScriptSourceURL)); }); } void NativeToJsBridge::loadApplicationSync( std::unique_ptr<RAMBundleRegistry> bundleRegistry, std::unique_ptr<const JSBigString> startupScript, std::string startupScriptSourceURL) { if (bundleRegistry) { m_executor->setBundleRegistry(std::move(bundleRegistry)); } m_executor->loadApplicationScript(std::move(startupScript), std::move(startupScriptSourceURL)); } void NativeToJsBridge::callFunction( std::string&& module, std::string&& method, folly::dynamic&& arguments) { int systraceCookie = -1; #ifdef WITH_FBSYSTRACE systraceCookie = m_systraceCookie++; FbSystraceAsyncFlow::begin( TRACE_TAG_REACT_CXX_BRIDGE, "JSCall", systraceCookie); #endif runOnExecutorQueue([module = std::move(module), method = std::move(method), arguments = std::move(arguments), systraceCookie] (JSExecutor* executor) { #ifdef WITH_FBSYSTRACE FbSystraceAsyncFlow::end( TRACE_TAG_REACT_CXX_BRIDGE, "JSCall", systraceCookie); SystraceSection s("NativeToJsBridge::callFunction", "module", module, "method", method); #endif // This is safe because we are running on the executor's thread: it won't // destruct until after it's been unregistered (which we check above) and // that will happen on this thread executor->callFunction(module, method, arguments); }); } void NativeToJsBridge::invokeCallback(double callbackId, folly::dynamic&& arguments) { int systraceCookie = -1; #ifdef WITH_FBSYSTRACE systraceCookie = m_systraceCookie++; FbSystraceAsyncFlow::begin( TRACE_TAG_REACT_CXX_BRIDGE, "<callback>", systraceCookie); #endif runOnExecutorQueue([callbackId, arguments = std::move(arguments), systraceCookie] (JSExecutor* executor) { #ifdef WITH_FBSYSTRACE FbSystraceAsyncFlow::end( TRACE_TAG_REACT_CXX_BRIDGE, "<callback>", systraceCookie); SystraceSection s("NativeToJsBridge::invokeCallback"); #endif executor->invokeCallback(callbackId, arguments); }); } void NativeToJsBridge::registerBundle(uint32_t bundleId, const std::string& bundlePath) { runOnExecutorQueue([bundleId, bundlePath] (JSExecutor* executor) { executor->registerBundle(bundleId, bundlePath); }); } void NativeToJsBridge::setGlobalVariable(std::string propName, std::unique_ptr<const JSBigString> jsonValue) { runOnExecutorQueue([propName=std::move(propName), jsonValue=folly::makeMoveWrapper(std::move(jsonValue))] (JSExecutor* executor) mutable { executor->setGlobalVariable(propName, jsonValue.move()); }); } void* NativeToJsBridge::getJavaScriptContext() { // TODO(cjhopman): this seems unsafe unless we require that it is only called on the main js queue. return m_executor->getJavaScriptContext(); } bool NativeToJsBridge::isInspectable() { return m_executor->isInspectable(); } #ifdef WITH_JSC_MEMORY_PRESSURE void NativeToJsBridge::handleMemoryPressure(int pressureLevel) { runOnExecutorQueue([=] (JSExecutor* executor) { executor->handleMemoryPressure(pressureLevel); }); } #endif void NativeToJsBridge::destroy() { // All calls made through runOnExecutorQueue have an early exit if // m_destroyed is true. Setting this before the runOnQueueSync will cause // pending work to be cancelled and we won't have to wait for it. *m_destroyed = true; m_executorMessageQueueThread->runOnQueueSync([this] { m_executor->destroy(); m_executorMessageQueueThread->quitSynchronous(); m_executor = nullptr; }); } void NativeToJsBridge::runOnExecutorQueue(std::function<void(JSExecutor*)> task) { if (*m_destroyed) { return; } std::shared_ptr<bool> isDestroyed = m_destroyed; m_executorMessageQueueThread->runOnQueue([this, isDestroyed, task=std::move(task)] { if (*isDestroyed) { return; } // The executor is guaranteed to be valid for the duration of the task because: // 1. the executor is only destroyed after it is unregistered // 2. the executor is unregistered on this queue // 3. we just confirmed that the executor hasn't been unregistered above task(m_executor.get()); }); } } }
{ "pile_set_name": "Github" }
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // ************************************************************************* // // avtViscousStressExpression.C // // ************************************************************************* // #include <avtViscousStressExpression.h> #include <math.h> #include <vtkCell.h> #include <vtkCellData.h> #include <vtkDataArray.h> #include <vtkDataSet.h> #include <vtkIdList.h> #include <vtkPointData.h> #include <ExpressionException.h> // **************************************************************************** // Method: avtViscousStressExpression constructor // // Programmer: Cyrus Harrison // Creation: June 5, 2007 // // **************************************************************************** avtViscousStressExpression::avtViscousStressExpression() { ; } // **************************************************************************** // Method: avtViscousStressExpression destructor // // Programmer: Cyrus Harrison // Creation: June 5, 2007 // // **************************************************************************** avtViscousStressExpression::~avtViscousStressExpression() { ; } // **************************************************************************** // Method: avtViscousStressExpression::DeriveVariable // // Purpose: // Constructs a viscous stress tensor given a velocity vector // // Programmer: Cyrus Harrison // Creation: June 5, 2007 // // Modifications: // Cyrus Harrison, Mon Jun 18 13:41:51 PDT 2007 // Added explicit check for rectilinear or structured grid. // // **************************************************************************** vtkDataArray * avtViscousStressExpression::DeriveVariable(vtkDataSet *in_ds, int currentDomainsIndex) { // get dim and rz_mesh int topo_dim = -1; bool rz_mesh = false; if ( *(GetInput()) != NULL ) { avtDataAttributes &atts = GetInput()->GetInfo().GetAttributes(); topo_dim = atts.GetTopologicalDimension(); if(topo_dim == 2) { if (GetInput()->GetInfo().GetAttributes().GetMeshCoordType()== AVT_XY) rz_mesh = false; } else rz_mesh = true; if(topo_dim != 2) { EXCEPTION2(ExpressionException, outputVariableName, "The viscous stress expression " "currently only supports 2D datasets."); } } // make sure input dataset is a rectilinear or structured grid int dtype = in_ds->GetDataObjectType(); if( ( dtype != VTK_STRUCTURED_GRID) && ( dtype != VTK_RECTILINEAR_GRID )) { EXCEPTION2(ExpressionException, outputVariableName, "Viscous Stress Expression requires a rectilinear or structured mesh"); } // velocity is nodal value vtkDataArray *vel = in_ds->GetPointData()->GetArray(activeVariable); if( vel == NULL || vel->GetNumberOfComponents() != 3 ) { EXCEPTION2(ExpressionException, outputVariableName, "The viscous stress expression " "was not passed a valid velocity vector."); } // get number of cells vtkIdType ncells = in_ds->GetNumberOfCells(); // create the result dataset vtkDataArray *res_tensor = vel->NewInstance(); res_tensor->SetNumberOfComponents(9); res_tensor->SetNumberOfTuples(ncells); // tensor values double res_vals[9]; // calculate tensor for each cell for( vtkIdType i = 0; i < ncells; i++) { if(topo_dim == 2) {CalculateVStress2D(in_ds,vel,i,rz_mesh,res_vals);} res_tensor->SetTuple(i, res_vals); } return res_tensor; } // **************************************************************************** // Method: avtViscousStressExpression::CalculateVStress2D // // Purpose: // Calculate 2D Viscous Stress Tensor for a Cell // // Programmer: Cyrus Harrison // Creation: June 10 13:35:13 PDT 2007 // // Modifications: // Cyrus Harrison, Mon Jun 18 13:41:51 PDT 2007 // Added explicit check for quad cells // // Cyrus Harrison, Thu Oct 11 09:21:36 PDT 2007 // Changed 'i' to 'idx' in ds->GetCellType calls. // // **************************************************************************** void avtViscousStressExpression::CalculateVStress2D(vtkDataSet *ds, vtkDataArray *ve, int idx, bool rz_mesh, double *vstress) { // point locs and velocities double px[4], py[4], vx[4], vy[4]; // gradient terms double dx[2], dy[2], du[2], dv[2]; double div = 0.0; // gradients double dvx[2], dvy[2]; // extra divergence term if rz_mesh double cyl_term = 0.0; // helper to make sure we do not divide by zero double tiny = 1e-3; double *pt_val = NULL; double *ve_val = NULL; // make sure the cell is a quad (assumed for proper vel gradients) if ( ( ds->GetCellType(idx) != VTK_QUAD ) && ( ds->GetCellType(idx) != VTK_PIXEL ) ) { // if cell is not a quad, ignore memset(vstress,0,sizeof(double)*9); return; } // extract the location and velocity vtkCell *cell = ds->GetCell(idx); vtkIdList *cids = cell->GetPointIds(); vtkIdType ids[4]; // get ids that match the gradient template ids[3] = cids->GetId(0); ids[0] = cids->GetId(1); ids[1] = cids->GetId(2); ids[2] = cids->GetId(3); vtkIdType id = 0; for( vtkIdType i = 0; i< 4; i++) { id = ids[i]; pt_val = ds->GetPoint(id); ve_val = ve->GetTuple(id); px[i] = pt_val[0]; py[i] = pt_val[1]; vx[i] = ve_val[0]; vy[i] = ve_val[1]; } // calculate the gradient dx[0] = .5 * (px[0] + px[1] - px[2] - px[3]); dx[1] = .5 * (px[1] + px[2] - px[3] - px[0]); dy[0] = .5 * (py[0] + py[1] - py[2] - py[3]); dy[1] = .5 * (py[1] + py[2] - py[3] - py[0]); du[0] = .5 * (vx[0] + vx[1] - vx[2] - vx[3]); du[1] = .5 * (vx[1] + vx[2] - vx[3] - vx[0]); dv[0] = .5 * (vy[0] + vy[1] - vy[2] - vy[3]); dv[1] = .5 * (vy[1] + vy[2] - vy[3] - vy[0]); div = 1.0 / (dx[0] *dy[1] - dx[1] *dy[0] + tiny); dvx[0] = div * (du[0]*dy[1] - du[1] * dy[0]); dvx[1] = div * (du[1]*dx[0] - du[0] * dx[1]); dvy[0] = div * (dv[0]*dy[1] - dv[1] * dy[0]); dvy[1] = div * (dv[1]*dx[0] - dv[0] * dx[1]); // create the tensor // if rz mesh include extra divergence term if( rz_mesh ) { cyl_term = (vy[0] + vy[1] + vy[2] + vy[3]) / (py[0] + py[1] + py[2] + py[3] + tiny); } // diag terms vstress[0] = 1/3.0 * (2.0 * dvx[0] - dvy[1]- cyl_term); vstress[4] = 1/3.0 * (2.0 * dvy[1] - dvx[0]- cyl_term); vstress[8] = 0.0; // other terms vstress[1] = 0.5 * (dvy[0] + dvx[1]); vstress[2] = 0.0; vstress[5] = 0.0; // use symm to fill out remaining terms vstress[3] = vstress[1]; vstress[6] = vstress[2]; vstress[7] = vstress[5]; }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.multiuser.resource.api.workspace; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.eclipse.che.multiuser.resource.api.workspace.TestObjects.createConfig; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.model.workspace.WorkspaceConfig; import org.eclipse.che.api.core.model.workspace.config.Environment; import org.eclipse.che.multiuser.resource.api.exception.NoEnoughResourcesException; import org.eclipse.che.multiuser.resource.api.type.RamResourceType; import org.eclipse.che.multiuser.resource.api.type.RuntimeResourceType; import org.eclipse.che.multiuser.resource.api.type.WorkspaceResourceType; import org.eclipse.che.multiuser.resource.api.usage.ResourceManager; import org.eclipse.che.multiuser.resource.api.usage.tracker.EnvironmentRamCalculator; import org.eclipse.che.multiuser.resource.spi.impl.ResourceImpl; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests for {@link LimitsCheckingWorkspaceManager}. * * @author Yevhenii Voevodin * @author Alexander Garagatyi * @author Igor Vinokur * @author Sergii Leshchenko */ @Listeners(MockitoTestNGListener.class) public class LimitsCheckingWorkspaceManagerTest { public static final String NAMESPACE = "namespace"; public static final String ACCOUNT_ID = "accountId"; @Mock private EnvironmentRamCalculator environmentRamCalculator; @Mock private ResourceManager resourceManager; @Test public void shouldUseRamOfSpecifiedEnvironmentOnCheckingAvailabilityOfRamResource() throws Exception { // given LimitsCheckingWorkspaceManager manager = managerBuilder() .setResourceManager(resourceManager) .setEnvironmentRamCalculator(environmentRamCalculator) .build(); when(environmentRamCalculator.calculate(any(Environment.class))).thenReturn(3000L); WorkspaceConfig config = createConfig("3gb"); String envToStart = config.getDefaultEnv(); // when manager.checkRamResourcesAvailability(ACCOUNT_ID, NAMESPACE, config, envToStart); // then verify(environmentRamCalculator).calculate(config.getEnvironments().get(envToStart)); verify(resourceManager) .checkResourcesAvailability( ACCOUNT_ID, singletonList(new ResourceImpl(RamResourceType.ID, 3000, RamResourceType.UNIT))); } @Test public void shouldUseRamOfDefaultEnvironmentOnCheckingAvailabilityOfRamResourceWhen() throws Exception { // given LimitsCheckingWorkspaceManager manager = managerBuilder() .setResourceManager(resourceManager) .setEnvironmentRamCalculator(environmentRamCalculator) .build(); when(environmentRamCalculator.calculate(any(Environment.class))).thenReturn(3000L); WorkspaceConfig config = createConfig("3gb"); // when manager.checkRamResourcesAvailability(ACCOUNT_ID, NAMESPACE, config, null); // then verify(environmentRamCalculator) .calculate(config.getEnvironments().get(config.getDefaultEnv())); verify(resourceManager) .checkResourcesAvailability( ACCOUNT_ID, singletonList(new ResourceImpl(RamResourceType.ID, 3000, RamResourceType.UNIT))); } @Test( expectedExceptions = LimitExceededException.class, expectedExceptionsMessageRegExp = "Workspace namespace/workspace.. needs 3000MB to start\\. " + "Your account has 200MB available and 100MB in use\\. " + "The workspace can't be start. Stop other workspaces or grant more resources\\.") public void shouldThrowLimitExceedExceptionIfAccountDoesNotHaveEnoughAvailableRamResource() throws Exception { doThrow( new NoEnoughResourcesException( singletonList(new ResourceImpl(RamResourceType.ID, 200L, RamResourceType.UNIT)), singletonList(new ResourceImpl(RamResourceType.ID, 3000L, RamResourceType.UNIT)), emptyList())) .when(resourceManager) .checkResourcesAvailability(any(), any()); doReturn(singletonList(new ResourceImpl(RamResourceType.ID, 100L, RamResourceType.UNIT))) .when(resourceManager) .getUsedResources(any()); // given LimitsCheckingWorkspaceManager manager = managerBuilder() .setResourceManager(resourceManager) .setEnvironmentRamCalculator(environmentRamCalculator) .build(); when(environmentRamCalculator.calculate(any(Environment.class))).thenReturn(3000L); WorkspaceConfig config = createConfig("3gb"); // when manager.checkRamResourcesAvailability(ACCOUNT_ID, NAMESPACE, config, null); } @Test public void shouldNotThrowLimitExceedExceptionIfAccountHasEnoughAvailableWorkspaceResource() throws Exception { // given LimitsCheckingWorkspaceManager manager = managerBuilder().setResourceManager(resourceManager).build(); // when manager.checkWorkspaceResourceAvailability(ACCOUNT_ID); // then verify(resourceManager) .checkResourcesAvailability( ACCOUNT_ID, singletonList( new ResourceImpl(WorkspaceResourceType.ID, 1, WorkspaceResourceType.UNIT))); } @Test( expectedExceptions = LimitExceededException.class, expectedExceptionsMessageRegExp = "You are not allowed to create more workspaces\\.") public void shouldThrowLimitExceedExceptionIfAccountDoesNotHaveEnoughAvailableWorkspaceResource() throws Exception { // given doThrow(new NoEnoughResourcesException(emptyList(), emptyList(), emptyList())) .when(resourceManager) .checkResourcesAvailability(any(), any()); doReturn( singletonList( new ResourceImpl(WorkspaceResourceType.ID, 5, WorkspaceResourceType.UNIT))) .when(resourceManager) .getTotalResources(anyString()); LimitsCheckingWorkspaceManager manager = managerBuilder().setResourceManager(resourceManager).build(); // when manager.checkWorkspaceResourceAvailability(ACCOUNT_ID); } @Test public void shouldNotThrowLimitExceedExceptionIfAccountHasEnoughAvailableRuntimeResource() throws Exception { // given LimitsCheckingWorkspaceManager manager = managerBuilder().setResourceManager(resourceManager).build(); // when manager.checkRuntimeResourceAvailability(ACCOUNT_ID); // then verify(resourceManager) .checkResourcesAvailability( ACCOUNT_ID, singletonList(new ResourceImpl(RuntimeResourceType.ID, 1, RuntimeResourceType.UNIT))); } @Test( expectedExceptions = LimitExceededException.class, expectedExceptionsMessageRegExp = "You are not allowed to start more workspaces\\.") public void shouldThrowLimitExceedExceptionIfAccountDoesNotHaveEnoughAvailableRuntimeResource() throws Exception { // given doThrow(new NoEnoughResourcesException(emptyList(), emptyList(), emptyList())) .when(resourceManager) .checkResourcesAvailability(any(), any()); doReturn(singletonList(new ResourceImpl(RuntimeResourceType.ID, 5, RuntimeResourceType.UNIT))) .when(resourceManager) .getTotalResources(anyString()); LimitsCheckingWorkspaceManager manager = managerBuilder().setResourceManager(resourceManager).build(); // when manager.checkRuntimeResourceAvailability(ACCOUNT_ID); } @Test( expectedExceptions = LimitExceededException.class, expectedExceptionsMessageRegExp = "You are only allowed to use 2048 mb. RAM per workspace.") public void shouldNotBeAbleToCreateWorkspaceWhichExceedsRamLimit() throws Exception { when(environmentRamCalculator.calculate(any(Environment.class))).thenReturn(3072L); final WorkspaceConfig config = createConfig("3gb"); final LimitsCheckingWorkspaceManager manager = managerBuilder() .setMaxRamPerEnv("2gb") .setEnvironmentRamCalculator(environmentRamCalculator) .build(); manager.checkMaxEnvironmentRam(config); } @Test public void shouldNotCheckWorkspaceRamLimitIfItIsSetToMinusOne() throws Exception { final WorkspaceConfig config = createConfig("3gb"); final LimitsCheckingWorkspaceManager manager = managerBuilder() .setMaxRamPerEnv("-1") .setEnvironmentRamCalculator(environmentRamCalculator) .build(); manager.checkMaxEnvironmentRam(config); verify(environmentRamCalculator, never()).calculate(any(Environment.class)); } private static ManagerBuilder managerBuilder() throws ServerException { return new ManagerBuilder(); } private static class ManagerBuilder { private String maxRamPerEnv; private EnvironmentRamCalculator environmentRamCalculator; private ResourceManager resourceManager; ManagerBuilder() throws ServerException { maxRamPerEnv = "1gb"; } public LimitsCheckingWorkspaceManager build() { return spy( new LimitsCheckingWorkspaceManager( null, null, null, null, null, null, maxRamPerEnv, environmentRamCalculator, resourceManager, null, null)); } ManagerBuilder setMaxRamPerEnv(String maxRamPerEnv) { this.maxRamPerEnv = maxRamPerEnv; return this; } ManagerBuilder setEnvironmentRamCalculator(EnvironmentRamCalculator environmentRamCalculator) { this.environmentRamCalculator = environmentRamCalculator; return this; } ManagerBuilder setResourceManager(ResourceManager resourceManager) { this.resourceManager = resourceManager; return this; } } }
{ "pile_set_name": "Github" }
# Clean Go Code ## Preface: Why Write Clean Code? This document is a reference for the Go community that aims to help developers write cleaner code. Whether you're working on a personal project or as part of a larger team, writing clean code is an important skill to have. Establishing good paradigms and consistent, accessible standards for writing clean code can help prevent developers from wasting many meaningless hours on trying to understand their own (or others') work. > <em>We don’t read code, we <b>decode</b> it &ndash; Peter Seibel</em> As developers, we're sometimes tempted to write code in a way that's convenient for the time being without regard for best practices; this makes code reviews and testing more difficult. In a sense, we're <em>encoding</em>&mdash;and, in doing so, making it more difficult for others to decode our work. But we want our code to be usable, readable, and maintainable. And that requires coding the <em>right</em> way, not the easy way. This document begins with a simple and short introduction to the fundamentals of writing clean code. Later, we'll discuss concrete refactoring examples specific to Go. ##### A short word on `gofmt` I'd like to take a few sentences to clarify my stance on `gofmt` because there are plenty of things I disagree with when it comes to this tool. I prefer snake case over camel case, and I quite like my constant variables to be uppercase. And, naturally, I also have many opinions on bracket placement. *That being said*, `gofmt` does allow us to have a common standard for writing Go code, and that's a great thing. As a developer myself, I can certainly appreciate that Go programmers may feel somewhat restricted by `gofmt`, especially if they disagree with some of its rules. But in my opinion, homogeneous code is more important than having complete expressive freedom. ## Table of Contents * [Introduction to Clean Code](#Introduction-to-Clean-Code) * [Test-Driven Development](#Test-Driven-Development) * [Naming Conventions](#Naming-Conventions) * * [Comments](#Comments) * [Function Naming](#Function-Naming) * [Variable Naming](#Variable-Naming) * [Cleaning Functions](#Cleaning-Functions) * [Function Length](#Function-Length) * [Function Signatures](#Function-Signatures) * [Variable Scope](#Variable-Scope) * [Variable Declaration](#Variable-Declaration) * [Clean Go](#Clean-Go) * [Return Values](#Return-Values) * [Returning Defined Errors](#Returning-Defined-Errors) * [Returning Dynamic Errors](#Returning-Dynamic-Errors) * [Pointers in Go](#Pointers-in-Go) * [Closures Are Function Pointers](#Closures-are-Function-Pointers) * [Interfaces in Go](#Interfaces-in-Go) * [The Empty `interface{}`](#The-Empty-Interface) * [Summary](#Summary) ## Introduction to Clean Code Clean code is the pragmatic concept of promoting readable and maintainable software. Clean code establishes trust in the codebase and helps minimize the chances of careless bugs being introduced. It also helps developers maintain their agility, which typically plummets as the codebase expands due to the increased risk of introducing bugs. ### Test-Driven Development Test-driven development is the practice of testing your code frequently throughout short development cycles or sprints. It ultimately contributes to code cleanliness by inviting developers to question the functionality and purpose of their code. To make testing easier, developers are encouraged to write short functions that only do one thing. For example, it's arguably much easier to test (and understand) a function that's only 4 lines long than one that's 40. Test-driven development consists of the following cycle: 1. Write (or execute) a test 2. If the test fails, make it pass 3. Refactor your code accordingly 4. Repeat Testing and refactoring are intertwined in this process. As you refactor your code to make it more understandable or maintainable, you need to test your changes thoroughly to ensure that you haven't altered the behavior of your functions. This can be incredibly useful as the codebase grows. ### Naming Conventions #### Comments I'd like to first address the topic of commenting code, which is an essential practice but tends to be misapplied. Unnecessary comments can indicate problems with the underlying code, such as the use of poor naming conventions. However, whether or not a particular comment is "necessary" is somewhat subjective and depends on how legibly the code was written. For example, the logic of well-written code may still be so complex that it requires a comment to clarify what is going on. In that case, one might argue that the comment is <em>helpful</em> and therefore necessary. In Go, according to `gofmt`, <em>all</em> public variables and functions should be annotated. I think this is absolutely fine, as it gives us consistent rules for documenting our code. However, I always want to distinguish between comments that enable auto-generated documentation and <em>all other</em> comments. Annotation comments, for documentation, should be written like documentation&mdash;they should be at a high level of abstraction and concern the logical implementation of the code as little as possible. I say this because there are other ways to explain code and ensure that it's being written comprehensibly and expressively. If the code is neither of those, some people find it acceptable to introduce a comment explaining the convoluted logic. Unfortunately, that doesn't really help. For one, most people simply won't read comments, as they tend to be very intrusive to the experience of reviewing code. Additionally, as you can imagine, a developer won't be too happy if they're forced to review unclear code that's been slathered with comments. The less that people have to read to understand what your code is doing, the better off they'll be. Let's take a step back and look at some concrete examples. Here's how you <em>shouldn't</em> comment your code: ```go // iterate over the range 0 to 9 // and invoke the doSomething function // for each iteration for i := 0; i < 10; i++ { doSomething(i) } ``` This is what I like to call a <strong>tutorial comment</strong>; it's fairly common in tutorials, which often explain the low-level functionality of a language (or programming in general). While these comments may be helpful for beginners, they're absolutely useless in production code. Hopefully, we aren't collaborating with programmers who don't understand something as simple as a looping construct by the time they've begun working on a development team. As programmers, we shouldn't have to read the comment to understand what's going on&mdash;we know that we're iterating over the range 0 to 9 because we can simply read the code. Hence the proverb: > <em>Document why, not how. &ndash; Venkat Subramaniam</em> Following this logic, we can now change our comment to explain <em>why</em> we are iterating from the range 0 to 9: ```go // instatiate 10 threads to handle upcoming work load for i := 0; i < 10; i++ { doSomething(i) } ``` Now we understand <em>why</em> we have a loop and can tell <em>what</em> we're doing by simply reading the code... Sort of. This still isn't what I'd consider clean code. The comment is worrying because it probably should not be necessary to express such an explanation in prose, assuming the code is well written (which it isn't). Technically, we're still saying what we're doing, not why we're doing it. We can easily express this "what" directly in our code by using more meaningful names: ```go for workerID := 0; workerID < 10; workerID++ { instantiateThread(workerID) } ``` With just a few changes to our variable and function names, we've managed to explain what we're doing directly in our code. This is much clearer for the reader because they won't have to read the comment and then map the prose to the code. Instead, they can simply read the code to understand what it's doing. Of course, this was a relatively trivial example. Writing clear and expressive code is unfortunately not always so easy; it can become increasingly difficult as the codebase itself grows in complexity. The more you practice writing comments in this mindset and avoid explaining what you're doing, the cleaner your code will become. #### Function Naming Let's now move on to function naming conventions. The general rule here is really simple: the more specific the function, the more general its name. In other words, we want to start with a very broad and short function name, such as `Run` or `Parse`, that describes the general functionality. Let's imagine that we are creating a configuration parser. Following this naming convention, our top level of abstraction might look something like the following: ```go func main() { configpath := flag.String("config-path", "", "configuration file path") flag.Parse() config, err := configuration.Parse(*configpath) ... } ``` We'll focus on the naming of the `Parse` function. Despite this function's very short and general name, it's actually quite clear what it attempts to achieve. When we go one layer deeper, our function naming will become slightly more specific: ```go func Parse(filepath string) (Config, error) { switch fileExtension(filepath) { case "json": return parseJSON(filepath) case "yaml": return parseYAML(filepath) case "toml": return parseTOML(filepath) default: return Config{}, ErrUnknownFileExtension } } ``` Here, we've clearly distinguished the nested function calls from their parent without being overly specific. This allows each nested function call to make sense on its own as well as within the context of the parent. On the other hand, if we had named the `parseJSON` function `json` instead, it couldn't possibly stand on its own. The functionality would become lost in the name, and we would no longer be able to tell whether this function is parsing, creating, or marshalling JSON. Notice that `fileExtension` is actually a little more specific. However, this is because its functionality is in fact quite specific in nature: ```go func fileExtension(filepath string) string { segments := strings.Split(filepath, ".") return segments[len(segments)-1] } ``` This kind of logical progression in our function names&mdash;from a high level of abstraction to a lower, more specific one&mdash;makes the code easier to follow and read. Consider the alternative: If our highest level of abstraction is too specific, then we'll end up with a name that attempts to cover all bases, like `DetermineFileExtensionAndParseConfigurationFile`. This is horrendously difficult to read; we are trying to be too specific too soon and end up confusing the reader, despite trying to be clear! #### Variable Naming Rather interestingly, the opposite is true for variables. Unlike functions, our variables should be named from more to less specific the deeper we go into nested scopes. > <em>You shouldn’t name your variables after their types for the same reason you wouldn’t name your pets 'dog' or 'cat'. &ndash; Dave Cheney</em> Why should our variable names become less specific as we travel deeper into a function's scope? Simply put, as a variable's scope becomes smaller, it becomes increasingly clear for the reader what that variable represents, thereby eliminating the need for specific naming. In the example of the previous function `fileExtension`, we could even shorten the name of the variable `segments` to `s` if we wanted to. The context of the variable is so clear that it's unnecessary to explain it any further with longer variable names. Another good example of this is in nested for loops: ```go func PrintBrandsInList(brands []BeerBrand) { for _, b := range brands { fmt.Println(b) } } ``` In the above example, the scope of the variable `b` is so small that we don't need to spend any additional brain power on remembering what exactly it represents. However, because the scope of `brands` is slightly larger, it helps for it to be more specific. When expanding the variable scope in the function below, this distinction becomes even more apparent: ```go func BeerBrandListToBeerList(beerBrands []BeerBrand) []Beer { var beerList []Beer for _, brand := range beerBrands { for _, beer := range brand { beerList = append(beerList, beer) } } return beerList } ``` Great! This function is easy to read. Now, let's apply the opposite (i.e., wrong) logic when naming our variables: ```go func BeerBrandListToBeerList(b []BeerBrand) []Beer { var bl []Beer for _, beerBrand := range b { for _, beerBrandBeerName := range beerBrand { bl = append(bl, beerBrandBeerName) } } return bl } ``` Even though it's possible to figure out what this function is doing, the excessive brevity of the variable names makes it difficult to follow the logic as we travel deeper. This could very well spiral into full-blown confusion because we're mixing short and long variable names inconsistently. ### Cleaning Functions Now that we know some best practices for naming our variables and functions, as well as clarifying our code with comments, let's dive into some specifics of how we can refactor functions to make them cleaner. #### Function Length > <em>How small should a function be? Smaller than that! &ndash; Robert C. Martin</em> When writing clean code, our primary goal is to make our code easily digestible. The most effective way to do this is to make our functions as short as possible. It's important to understand that we don't necessarily do this to avoid code duplication. The more important reason is to improve <em>code comprehension</em>. It can help to look at a function's description at a very high level to understand this better: ``` fn GetItem: - parse json input for order id - get user from context - check user has appropriate role - get order from database ``` By writing short functions (which are typically 5&ndash;8 lines in Go), we can create code that reads almost as naturally as our description above: ```go var ( NullItem = Item{} ErrInsufficientPrivileges = errors.New("user does not have sufficient privileges") ) func GetItem(ctx context.Context, json []bytes) (Item, error) { order, err := NewItemFromJSON(json) if err != nil { return NullItem, err } if !GetUserFromContext(ctx).IsAdmin() { return NullItem, ErrInsufficientPrivileges } return db.GetItem(order.ItemID) } ``` Using smaller functions also eliminates another horrible habit of writing code: indentation hell. <strong>Indentation hell</strong> typically occurs when a chain of `if` statements are carelessly nested in a function. This makes it <em>very</em> difficult for human beings to parse the code and should be eliminated whenever spotted. Indentation hell is particularly common when working with `interface{}` and using type casting: ```go func GetItem(extension string) (Item, error) { if refIface, ok := db.ReferenceCache.Get(extension); ok { if ref, ok := refIface.(string); ok { if itemIface, ok := db.ItemCache.Get(ref); ok { if item, ok := itemIface.(Item); ok { if item.Active { return Item, nil } else { return EmptyItem, errors.New("no active item found in cache") } } else { return EmptyItem, errors.New("could not cast cache interface to Item") } } else { return EmptyItem, errors.New("extension was not found in cache reference") } } else { return EmptyItem, errors.New("could not cast cache reference interface to Item") } } return EmptyItem, errors.New("reference not found in cache") } ``` First, indentation hell makes it difficult for other developers to understand the flow of your code. Second, if the logic in our `if` statements expands, it'll become exponentially more difficult to figure out which statement returns what (and to ensure that all paths return some value). Yet another problem is that this deep nesting of conditional statements forces the reader to frequently scroll and keep track of many logical states in their head. It also makes it more difficult to test the code and catch bugs because there are so many different nested possibilities that you have to account for. Indentation hell can result in reader fatigue if a developer has to constantly parse unwieldy code like the sample above. Naturally, this is something we want to avoid at all costs. So, how do we clean this function? Fortunately, it's actually quite simple. On our first iteration, we will try to ensure that we are returning an error as soon as possible. Instead of nesting the `if` and `else` statements, we want to "push our code to the left," so to speak. Take a look: ```go func GetItem(extension string) (Item, error) { refIface, ok := db.ReferenceCache.Get(extension) if !ok { return EmptyItem, errors.New("reference not found in cache") } ref, ok := refIface.(string) if !ok { // return cast error on reference } itemIface, ok := db.ItemCache.Get(ref) if !ok { // return no item found in cache by reference } item, ok := itemIface.(Item) if !ok { // return cast error on item interface } if !item.Active { // return no item active } return Item, nil } ``` Once we're done with our first attempt at refactoring the function, we can proceed to split up the function into smaller functions. Here's a good rule of thumb: If the `value, err :=` pattern is repeated more than once in a function, this is an indication that we can split the logic of our code into smaller pieces: ```go func GetItem(extension string) (Item, error) { ref, ok := getReference(extension) if !ok { return EmptyItem, ErrReferenceNotFound } return getItemByReference(ref) } func getReference(extension string) (string, bool) { refIface, ok := db.ReferenceCache.Get(extension) if !ok { return EmptyItem, false } return refIface.(string) } func getItemByReference(reference string) (Item, error) { item, ok := getItemFromCache(reference) if !item.Active || !ok { return EmptyItem, ErrItemNotFound } return Item, nil } func getItemFromCache(reference string) (Item, bool) { if itemIface, ok := db.ItemCache.Get(ref); ok { return EmptyItem, false } return itemIface.(Item), true } ``` As mentioned previously, indentation hell can make it difficult to test our code. When we split up our `GetItem` function into several helpers, we make it easier to track down bugs when testing our code. Unlike the original version, which consisted of several `if` statements in the same scope, the refactored version of `GetItem` has just two branching paths that we must consider. The helper functions are also short and digestible, making them easier to read. > Note: For production code, one should elaborate on the code even further by returning errors instead of `bool` values. This makes it much easier to understand where the error is originating from. However, as these are just example functions, returning `bool` values will suffice for now. Examples of returning errors more explicitly will be explained in more detail later. Notice that cleaning the `GetItem` function resulted in more lines of code overall. However, the code itself is now much easier to read. It's layered in an onion-style fashion, where we can ignore "layers" that we aren't interested in and simply peel back the ones that we do want to examine. This makes it easier to understand low-level functionality because we only have to read maybe 3&ndash;5 lines at a time. This example illustrates that we cannot measure the cleanliness of our code by the number of lines it uses. The first version of the code was certainly much shorter. However, it was <em>artificially</em> short and very difficult to read. In most cases, cleaning code will initially expand the existing codebase in terms of the number of lines. But this is highly preferable to the alternative of having messy, convoluted logic. If you're ever in doubt about this, just consider how you feel about the following function, which does exactly the same thing as our code but only uses two lines: ```go func GetItemIfActive(extension string) (Item, error) { if refIface,ok := db.ReferenceCache.Get(extension); ok {if ref,ok := refIface.(string); ok { if itemIface,ok := db.ItemCache.Get(ref); ok { if item,ok := itemIface.(Item); ok { if item.Active { return Item,nil }}}}} return EmptyItem, errors.New("reference not found in cache") } ``` #### Function Signatures Creating a good function naming structure makes it easier to read and understand the intent of the code. As we saw above, making our functions shorter helps us understand the function's logic. The last part of cleaning our functions involves understanding the context of the function input. With this comes another easy-to-follow rule: <strong>Function signatures should only contain one or two input parameters</strong>. In certain exceptional cases, three can be acceptable, but this is where we should start considering a refactor. Much like the rule that our functions should only be 5&ndash;8 lines long, this can seem quite extreme at first. However, I feel that this rule is much easier to justify. Take the following function from [RabbitMQ's introduction tutorial to its Go library](https://www.rabbitmq.com/tutorials/tutorial-one-go.html): ```go q, err := ch.QueueDeclare( "hello", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) ``` The function `QueueDeclare` takes six input parameters, which is quite a lot. With some effort, it's possible to understand what this code does thanks to the comments. However, the comments are actually part of the problem&mdash;as mentioned earlier, they should be substituted with descriptive code whenever possible. After all, there's nothing preventing us from invoking the `QueueDeclare` function <em>without</em> comments: ```go q, err := ch.QueueDeclare("hello", false, false, false, false, nil) ``` Now, without looking at the commented version, try to remember what the fourth and fifth `false` arguments represent. It's impossible, right? You will inevitably forget at some point. This can lead to costly mistakes and bugs that are difficult to correct. The mistakes might even occur through incorrect comments&mdash;imagine labeling the wrong input parameter. Correcting this mistake will be unbearably difficult to correct, especially when familiarity with the code has deteriorated over time or was low to begin with. Therefore, it is recommended to replace these input parameters with an 'Options' `struct` instead: ```go type QueueOptions struct { Name string Durable bool DeleteOnExit bool Exclusive bool NoWait bool Arguments []interface{} } q, err := ch.QueueDeclare(QueueOptions{ Name: "hello", Durable: false, DeleteOnExit: false, Exclusive: false, NoWait: false, Arguments: nil, }) ``` This solves two problems: misusing comments, and accidentally labeling the variables incorrectly. Of course, we can still confuse properties with the wrong value, but in these cases, it will be much easier to determine where our mistake lies within the code. The ordering of the properties also doesn't matter anymore, so incorrectly ordering the input values is no longer a concern. The last added bonus of this technique is that we can use our `QueueOptions` struct to infer the default values of our function's input parameters. When structures in Go are declared, all properties are initialised to their default value. This means that our `QueueDeclare` option can actually be invoked in the following way: ```go q, err := ch.QueueDeclare(QueueOptions{ Name: "hello", }) ``` The rest of the values are initialised to their default value of `false` (except for `Arguments`, which as an interface has a default value of `nil`). Not only are we much safer with this approach, but we are also much clearer with our intentions. In this case, we could actually write less code. This is an all-around win for everyone on the project. One final note on this: It's not always possible to change a function's signature. In this case, for example, we don't actually have control over our `QueueDeclare` function signature because it's from the RabbitMQ library. It's not our code, so we can't change it. However, we can wrap these functions to suit our purposes: ```go type RMQChannel struct { channel *amqp.Channel } func (rmqch *RMQChannel) QueueDeclare(opts QueueOptions) (Queue, error) { return rmqch.channel.QueueDeclare( opts.Name, opts.Durable, opts.DeleteOnExit, opts.Exclusive, opts.NoWait, opts.Arguments, ) } ``` Basically, we create a new structure named `RMQChannel` that contains the `amqp.Channel` type, which has the `QueueDeclare` method. We then create our own version of this method, which essentially just calls the old version of the RabbitMQ library function. Our new method has all the advantages described before, and we achieved this without actually having to change any of the code in the RabbitMQ library. We'll use this idea of wrapping functions to introduce more clean and safe code later when discussing `interface{}`. ### Variable Scope Now, let's take a step back and revisit the idea of writing smaller functions. This has another nice side effect that we didn't cover in the previous chapter: Writing smaller functions can typically eliminate reliance on mutable variables that leak into the global scope. Global variables are problematic and don't belong in clean code; they make it very difficult for programmers to understand the current state of a variable. If a variable is global and mutable, then by definition, its value can be changed by any part of the codebase. At no point can you guarantee that this variable is going to be a specific value... And that's a headache for everyone. This is yet another example of a trivial problem that's exacerbated when the codebase expands. Let's look at a short example of how non-global variables with a large scope can cause problems. These variables also introduce the issue of <strong>variable shadowing</strong>, as demonstrated in the code taken from an article titled [Golang scope issue](https://idiallo.com/blog/golang-scopes): ```go func doComplex() (string, error) { return "Success", nil } func main() { var val string num := 32 switch num { case 16: // do nothing case 32: val, err := doComplex() if err != nil { panic(err) } if val == "" { // do something else } case 64: // do nothing } fmt.Println(val) } ``` What's the problem with this code? From a quick skim, it seems the `var val string` value should be printed out as `Success` by the end of the `main` function. Unfortunately, this is not the case. The reason for this lies in the following line: ```go val, err := doComplex() ``` This declares a new variable `val` in the switch's `case 32` scope and has nothing to do with the variable declared in the first line of `main`. Of course, it can be argued that Go syntax is a little tricky, which I don't necessarily disagree with, but there is a much worse issue at hand. The declaration of `var val string` as a mutable, largely scoped variable is completely unnecessary. If we do a <strong>very</strong> simple refactor, we will no longer have this issue: ```go func getStringResult(num int) (string, error) { switch num { case 16: // do nothing case 32: return doComplex() case 64: // do nothing } return "" } func main() { val, err := getStringResult(32) if err != nil { panic(err) } if val == "" { // do something else } fmt.Println(val) } ``` After our refactor, `val` is no longer modified, and the scope has been reduced. Again, keep in mind that these functions are very simple. Once this kind of code style becomes a part of larger, more complex systems, it can be impossible to figure out why errors are occurring. We don't want this to happen&mdash;not only because we generally dislike software errors but also because it's disrespectful to our colleagues, and ourselves; we are potentially wasting each other's time having to debug this type of code. Developers need to take responsibility for their own code rather than blaming these issues on the variable declaration syntax of a particular language like Go. On a side note, if the `// do something else` part is another attempt to mutate the `val` variable, we should extract that logic out as its own self-contained function, as well as the previous part of it. This way, instead of expanding the mutable scope of our variables, we can just return a new value: ```go func getVal(num int) (string, error) { val, err := getStringResult(32) if err != nil { return "", err } if val == "" { return NewValue() // pretend function } } func main() { val, err := getVal(32) if err != nil { panic(err) } fmt.Println(val) } ``` ### Variable Declaration Other than avoiding issues with variable scope and mutability, we can also improve readability by declaring variables as close to their usage as possible. In C programming, it's common to see the following approach to declaring variables: ```go func main() { var err error var items []Item var sender, receiver chan Item items = store.GetItems() sender = make(chan Item) receiver = make(chan Item) for _, item := range items { ... } } ``` This suffers from the same symptom as described in our discussion of variable scope. Even though these variables might not actually be reassigned at any point, this kind of coding style keeps the readers on their toes, in all the wrong ways. Much like computer memory, our brain's short-term memory has a limited capacity. Having to keep track of which variables are mutable and whether or not a particular fragment of code will mutate them makes it more difficult to understand what the code is doing. Figuring out the eventually returned value can be a nightmare. Therefore, to makes this easier for our readers (and our future selves), it's recommended that you declare variables as close to their usage as possible: ```go func main() { var sender chan Item sender = make(chan Item) go func() { for { select { case item := <-sender: // do something } } }() } ``` However, we can do even better by invoking the function directly after its declaration. This makes it much clearer that the function logic is associated with the declared variable: ```go func main() { sender := func() chan Item { channel := make(chan Item) go func() { for { select { ... } } }() return channel } } ``` And coming full circle, we can move the anonymous function to make it a named function instead: ```go func main() { sender := NewSenderChannel() } func NewSenderChannel() chan Item { channel := make(chan Item) go func() { for { select { ... } } }() return channel } ``` It is still clear that we are declaring a variable, and the logic associated with the returned channel is simple, unlike in the first example. This makes it easier to traverse the code and understand the role of each variable. Of course, this doesn't actually prevent us from mutating our `sender` variable. There is nothing that we can do about this, as there is no way of declaring a `const struct` or `static` variables in Go. This means that we'll have to restrain ourselves from modifying this variable at a later point in the code. > NOTE: The keyword `const` does exist but is limited in use to primitive types only. One way of getting around this can at least limit the mutability of a variable to the package level. The trick involves creating a structure with the variable as a private property. This private property is thenceforth only accessible through other methods provided by this wrapping structure. Expanding on our channel example, this would look something like the following: ```go type Sender struct { sender chan Item } func NewSender() *Sender { return &Sender{ sender: NewSenderChannel(), } } func (s *Sender) Send(item Item) { s.sender <- item } ``` We have now ensured that the `sender` property of our `Sender` struct is never mutated&mdash;at least not from outside of the package. As of writing this document, this is the only way of creating publicly immutable non-primitive variables. It's a little verbose, but it's truly worth the effort to ensure that we don't end up with strange bugs resulting from accidental variable modification. ```go func main() { sender := NewSender() sender.Send(&Item{}) } ``` Looking at the example above, it's clear how this also simplifies the usage of our package. This way of hiding the implementation is beneficial not only for the maintainers of the package but also for the users. Now, when initialising and using the `Sender` structure, there is no concern over its implementation. This opens up for a much looser architecture. Because our users aren't concerned with the implementation, we are free to change it at any point, since we have reduced the point of contact that users have with the package. If we no longer wish to use a channel implementation in our package, we can easily change this without breaking the usage of the `Send` method (as long as we adhere to its current function signature). > NOTE: There is a fantastic explanation of how to handle the abstraction in client libraries, taken from the talk [AWS re:Invent 2017: Embracing Change without Breaking the World (DEV319)](https://www.youtube.com/watch?v=kJq81Y7OEx4). ## Clean Go This section focuses less on the generic aspects of writing clean Go code and more on the specifics, with an emphasis on the underlying clean code principles. ### Return Values #### Returning Defined Errors We'll start things off nice and easy by describing a cleaner way to return errors. As we discussed earlier, our main goal with writing clean code is to ensure readability, testability, and maintainability of the codebase. The technique for returning errors that we'll discuss here will achieve all three of those goals with very little effort. Let's consider the normal way to return a custom error. This is a hypothetical example taken from a thread-safe map implementation that we've named `Store`: ```go package smelly func (store *Store) GetItem(id string) (Item, error) { store.mtx.Lock() defer store.mtx.Unlock() item, ok := store.items[id] if !ok { return Item{}, errors.New("item could not be found in the store") } return item, nil } ``` There is nothing inherently smelly about this function when we consider it in isolation. We look into the `items` map of our `Store` struct to see if we already have an item with the given `id`. If we do, we return it; otherwise, we return an error. Pretty standard. So, what is the issue with returning custom errors as string values? Well, let's look at what happens when we use this function inside another package: ```go func GetItemHandler(w http.ReponseWriter, r http.Request) { item, err := smelly.GetItem("123") if err != nil { if err.Error() == "item could not be found in the store" { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, errr.Error(), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } ``` This is actually not too bad. However, there is one glaring problem: An error in Go is simply an `interface` that implements a function (`Error()`) returning a string; thus, we are now hardcoding the expected error code into our codebase, which isn't ideal. This hardcoded string is known as a <strong>magic string</strong>. And its main problem is flexibility: If at some point we decide to change the string value used to represent an error, our code will break (softly) unless we update it in possibly many different places. Our code is tightly coupled&mdash;it relies on that specific magic string and the assumption that it will never change as the codebase grows. An even worse situation would arise if a client were to use our package in their own code. Imagine that we decided to update our package and changed the string that represents an error&mdash;the client's software would now suddenly break. This is quite obviously something that we want to avoid. Fortunately, the fix is very simple: ```go package clean var ( NullItem = Item{} ErrItemNotFound = errors.New("item could not be found in the store") ) func (store *Store) GetItem(id string) (Item, error) { store.mtx.Lock() defer store.mtx.Unlock() item, ok := store.items[id] if !ok { return NullItem, ErrItemNotFound } return item, nil } ``` By simply representing the error as a variable (`ErrItemNotFound`), we've ensured that anyone using this package can check against the variable rather than the actual string that it returns: ```go func GetItemHandler(w http.ReponseWriter, r http.Request) { item, err := clean.GetItem("123") if err != nil { if err == clean.ErrItemNotFound { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } ``` This feels much nicer and is also much safer. Some would even say that it's easier to read as well. In the case of a more verbose error message, it certainly would be preferable for a developer to simply read `ErrItemNotFound` rather than a novel on why a certain error has been returned. This approach is not limited to errors and can be used for other returned values. As an example, we are also returning a `NullItem` instead of `Item{}` as we did before. There are many different scenarios in which it might be preferable to return a defined object, rather than initialising it on return. Returning default `NullItem` values like we did in the previous examples can also be safer in certain cases. As an example, a user of our package could forget to check for errors and end up initialising a variable that points to an empty struct containing a default value of `nil` as one or more property values. When attempting to access this `nil` value later in the code, the client software would panic. However, when we return our custom default value instead, we can ensure that all values that would otherwise default to `nil` are initialised. Thus, we'd ensure that we do not cause panics in our users' software. This also benefits us. Consider this: If we wanted to achieve the same safety without returning a default value, we would have to change our code everywhere we return this type of empty value. However, with our default value approach, we now only have to change our code in a single place: ```go var NullItem = Item{ itemMap: map[string]Item{}, } ``` > NOTE: In many scenarios, invoking a panic will actually be preferable to indicate that there is an error check missing. > NOTE: Every interface property in Go has a default value of `nil`. This means that this is useful for any struct that has an interface property. This is also true for structs that contain channels, maps, and slices, which could potentially also have a `nil` value. #### Returning Dynamic Errors There are certainly some scenarios where returning an error variable might not actually be viable. In cases where the information in customised errors is dynamic, if we want to describe error events more specifically, we can no longer define and return our static errors. Here's an example: ```go func (store *Store) GetItem(id string) (Item, error) { store.mtx.Lock() defer store.mtx.Unlock() item, ok := store.items[id] if !ok { return NullItem, fmt.Errorf("Could not find item with ID: %s", id) } return item, nil } ``` So, what to do? There is no well-defined or standard method for handling and returning these kinds of dynamic errors. My personal preference is to return a new interface, with a bit of added functionality: ```go type ErrorDetails interface { Error() string Type() string } type errDetails struct { errtype error details interface{} } func NewErrorDetails(err error, details ...interface{}) ErrorDetails { return &errDetails{ errtype: err, details: details, } } func (err *errDetails) Error() string { return fmt.Sprintf("%v: %v", err.errtype, err.details) } func (err *errDetails) Type() error { return err.errtype } ``` This new data structure still works as our standard error. We can still compare it to `nil` since it's an interface implementation, and we can still call `.Error()` on it, so it won't break any existing implementations. However, the advantage is that we can now check our error type as we could previously, despite our error now containing the <em>dynamic</em> details: ```go func (store *Store) GetItem(id string) (Item, error) { store.mtx.Lock() defer store.mtx.Unlock() item, ok := store.items[id] if !ok { return NullItem, NewErrorDetails( ErrItemNotFound, fmt.Sprintf("could not find item with id: %s", id)) } return item, nil } ``` And our HTTP handler function can then be refactored to check for a specific error again: ```go func GetItemHandler(w http.ReponseWriter, r http.Request) { item, err := clean.GetItem("123") if err != nil { if err.Type() == clean.ErrItemNotFound { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } ``` ### Nil Values A controversial aspect of Go is the addition of `nil`. This value corresponds to the value `NULL` in C and is essentially an uninitialised pointer. We've already seen some of the problems that `nil` can cause, but to sum up: Things break when you try to access methods or properties of a `nil` value. Thus, it's recommended to avoid returning a `nil` value when possible. This way, the users of our code are less likely to accidentally access `nil` values. There are other scenarios in which it is common to find `nil` values that can cause some unnecessary pain. An example of this is incorrectly initialising a `struct` (as in the example below), which can lead to it containing `nil` properties. If accessed, those `nil`s will cause a panic. ```go type App struct { Cache *KVCache } type KVCache struct { mtx sync.RWMutex store map[string]string } func (cache *KVCache) Add(key, value string) { cache.mtx.Lock() defer cache.mtx.Unlock() cache.store[key] = value } ``` This code is absolutely fine. However, the danger is that our `App` can be initialised incorrectly, without initialising the `Cache` property within. Should the following code be invoked, our application will panic: ```go app := App{} app.Cache.Add("panic", "now") ``` The `Cache` property has never been initialised and is therefore a `nil` pointer. Thus, invoking the `Add` method like we did here will cause a panic, with the following message: > panic: runtime error: invalid memory address or nil pointer dereference Instead, we can turn the `Cache` property of our `App` structure into a private property and create a getter-like method to access it. This gives us more control over what we are returning; specifically, it ensures that we aren't returning a `nil` value: ```go type App struct { cache *KVCache } func (app *App) Cache() *KVCache { if app.cache == nil { app.cache = NewKVCache() } return app.cache } ``` The code that previously panicked will now be refactored to the following: ```go app := App{} app.Cache().Add("panic", "now") ``` This ensures that users of our package don't have to worry about the implementation and whether they're using our package in an unsafe manner. All they need to worry about is writing their own clean code. > NOTE: There are other methods of achieving a similarly safe outcome. However, I believe this is the most straightforward approach. ### Pointers in Go Pointers in Go are a rather extensive topic. They're a very big part of working with the language&mdash;so much so that it is essentially impossible to write Go without some knowledge of pointers and their workings in the language. Therefore, it is important to understand how to use pointers without adding unnecessary complexity (and thereby keeping your codebase clean). Note that we will not review the details of how pointers are implemented in Go. Instead, we will focus on the quirks of Go pointers and how we can handle them. Pointers add complexity to code. If we aren't cautious, incorrectly using pointers can introduce nasty side effects or bugs that are particularly difficult to debug. By sticking to the basic principles of writing clean code that we covered in the first part of this document, we can at least reduce the chances of introducing unnecessary complexity to our code. #### Pointer Mutability We've already looked at the problem of mutability in the context of globally or largely scoped variables. However, mutability is not necessarily always a bad thing, and I am by no means an advocate for writing 100% pure functional programs. Mutability is a powerful tool, but we should really only ever use it when it's necessary. Let's have a look at a code example illustrating why: ```go func (store *UserStore) Insert(user *User) error { if store.userExists(user.ID) { return ErrItemAlreaydExists } store.users[user.ID] = user return nil } func (store *UserStore) userExists(id int64) bool { _, ok := store.users[id] return ok } ``` At first glance, this doesn't seem too bad. In fact, it might even seem like a rather simple insert function for a common list structure. We accept a pointer as input, and if no other users with this `id` exist, then we insert the provided user pointer into our list. Then, we use this functionality in our public API for creating new users: ```go func CreateUser(w http.ResponseWriter, r *http.Request) { user, err := parseUserFromRequest(r) if err != nil { http.Error(w, err, http.StatusBadRequest) return } if err := insertUser(w, user); err != nil { http.Error(w, err, http.StatusInternalServerError) return } } func insertUser(w http.ResponseWriter, user User) error { if err := store.Insert(user); err != nil { return err } user.Password = "" return json.NewEncoder(w).Encode(user) } ``` Once again, at first glance, everything looks fine. We parse the user from the received request and insert the user struct into our store. Once we have successfully inserted our user into the store, we then set the password to be an empty string before returning the user as a JSON object to our client. This is all quite common practice, typically when returning a user object whose password has been hashed, since we don't want to return the hashed password. However, imagine that we are using an in-memory store based on a `map`. This code will produce some unexpected results. If we check our user store, we'll see that the change we made to the users password in the HTTP handler function also affected the object in our store. This is because the pointer address returned by `parseUserFromRequest` is what we populated our store with, rather than an actual value. Therefore, when making changes to the dereferenced password value, we end up changing the value of the object we are pointing to in our store. This is a great example of why both mutability and variable scope can cause some serious issues and bugs when used incorrectly. When passing pointers as an input parameter of a function, we are expanding the scope of the variable whose data is being pointed to. Even more worrying is the fact that we are expanding the scope to an undefined level. We are *almost* expanding the scope of the variable to the global level. As demonstrated by the above example, this can lead to disastrous bugs that are particularly difficult to find and eradicate. Fortunately, the fix for this is rather simple: ```go func (store *UserStore) Insert(user User) error { if store.userExists(user.ID) { return ErrItemAlreaydExists } store.users[user.ID] = &user return nil } ``` Instead of passing a pointer to a `User` struct, we are now passing in a copy of a `User`. We are still storing a pointer to our store; however, instead of storing the pointer from outside of the function, we are storing the pointer to the copied value, whose scope is inside the function. This fixes the immediate problem but might still cause issues further down the line if we aren't careful. Consider this code: ```go func (store *UserStore) Get(id int64) (*User, error) { user, ok := store.users[id] if !ok { return EmptyUser, ErrUserNotFound } return store.users[id], nil } ``` Again, this is a very standard implementation of a getter function for our store. However, it's still bad code because we are once again expanding the scope of our pointer, which may end up causing unexpected side effects. When returning the actual pointer value, which we are storing in our user store, we are essentially giving other parts of our application the ability to change our store values. This is bound to cause confusion. Our store should be the only entity allowed to make changes to its values. The easiest fix for this is to return a value of `User` rather than returning a pointer. > NOTE: Consider the case where our application uses multiple threads. In this scenario, passing pointers to the same memory location can also potentially result in a race condition. In other words, we aren't only potentially corrupting our data&mdash;we could also cause a panic from a data race. Please keep in mind that there is intrinsically nothing wrong with returning pointers. However, the expanded scope of variables (and the number of owners pointing to those variables) is the most important consideration when working with pointers. This is what categorises our previous example as a smelly operation. This is also why common Go constructors are absolutely fine: ```go func AddName(user *User, name string) { user.Name = name } ``` This is *okay* because the variable scope, which is defined by whoever invokes the function, remains the same after the function returns. Combined with the fact that the function invoker remains the sole owner of the variable, this means that the pointer cannot be manipulated in an unexpected manner. ### Closures Are Function Pointers Before we get into the next topic of using interfaces in Go, I would like to introduce a common alternative. It's what C programmers know as "function pointers" and what most other programming languages call <strong>closures</strong>. A closure is simply an input parameter like any other, except it represents (points to) a function that can be invoked. In JavaScript, it's quite common to use closures as callbacks, which are just functions that are invoked after some asynchronous operation has finished. In Go, we don't really have this notion. We can, however, use closures to partially overcome a different hurdle: The lack of generics. Consider the following function signature: ```go func something(closure func(float64) float64) float64 { ... } ``` Here, `something` takes another function (a closure) as input and returns a `float64`. The input function takes a `float64` as input and also returns a `float64`. This pattern can be particularly useful for creating a loosely coupled architecture, making it easier to to add functionality without affecting other parts of the code. Suppose we have a struct containing data that we want to manipulate in some form. Through this structure's `Do()` method, we can perform operations on that data. If we know the operation ahead of time, we can obviously handle that logic directly in our `Do()` method: ```go func (datastore *Datastore) Do(operation Operation, data []byte) error { switch(operation) { case COMPARE: return datastore.compare(data) case CONCAT: return datastore.add(data) default: return ErrUnknownOperation } } ``` But as you can imagine, this function is quite rigid&mdash;it performs a predetermined operation on the data contained in the `Datastore` struct. If at some point we would like to introduce more operations, we'd end up bloating our `Do` method with quite a lot of irrelevant logic that would be hard to maintain. The function would have to always care about what operation it's performing and to cycle through a number of nested options for each operation. It might also be an issue for developers wanting to use our `Datastore` object who don't have access to edit our package code, since there is no way of extending structure methods in Go as there is in most OOP languages. So instead, let's try a different approach using closures: ```go func (datastore *Datastore) Do(operation func(data []byte, data []byte) ([]byte, error), data []byte) error { result, err := operation(datastore.data, data) if err != nil { return err } datastore.data = result return nil } func concat(a []byte, b []byte) ([]byte, error) { ... } func main() { ... datastore.Do(concat, data) ... } ``` You'll notice immediately that the function signature for `Do` ends up being quite messy. We also have another issue: The closure isn't particularly generic. What happens if we find out that we actually want the `concat` to be able to take more than just two byte arrays as input? Or if we want to add some completely new functionality that may also need more or fewer input values than `(data []byte, data []byte)`? One way to solve this issue is to change our `concat` function. In the example below, I have changed it to only take a single byte array as an input argument, but it could just as well have been the opposite case: ```go func concat(data []byte) func(data []byte) ([]byte, error) { return func(concatting []byte) ([]byte, error) { return append(data, concatting), nil } } func (datastore *Datastore) Do(operation func(data []byte) ([]byte, error)) error { result, err := operation(datastore.data) if err != nil { return err } datastore.data = result return nil } func main() { ... datastore.Do(compare(data)) ... } ``` Notice how we've effectively moved some of the clutter out of the `Do` method signature and into the `concat` method signature. Here, the `concat` function returns yet another function. Within the returned function, we store the input values originally passed in to our `concat` function. The returned function can therefore now take a single input parameter; within our function logic, we will append it to our original input value. As a newly introduced concept, this may seem quite strange. However, it's good to get used to having this as an option; it can help loosen up logic coupling and get rid of bloated functions. In the next section, we'll get into interfaces. Before we do so, let's take a short moment to discuss the difference between interfaces and closures. First, it's worth noting that interfaces and closures definitely solve some common problems. However, the way that interfaces are implemented in Go can sometimes make it tricky to decide whether to use interfaces or closures for a particular problem. Usually, whether an interface or a closure is used isn't really of importance; the right choice is whichever one solves the problem at hand. Typically, closures will be simpler to implement if the operation is simple by nature. However, as soon as the logic contained within a closure becomes complex, one should strongly consider using an interface instead. Dave Cheney has an excellent write-up on this topic, as well as a talk: * https://dave.cheney.net/2016/11/13/do-not-fear-first-class-functions * https://www.youtube.com/watch?v=5buaPyJ0XeQ&t=9s Jon Bodner also has a related talk: * https://www.youtube.com/watch?v=5IKcPMJXkKs ### Interfaces in Go In general, Go's approach to handling `interface`s is quite different from those of other languages. Interfaces aren't explicitly implemented like they would be in Java or C#; rather, they are implicitly created if they fulfill the contract of the interface. As an example, this means that any `struct` that has an `Error()` method implements (or "fulfills") the `Error` interface and can be returned as an `error`. This manner of implementing interfaces is extremely easy and makes Go feel more fast paced and dynamic. However, there are certainly disadvantages with this approach. As the interface implementation is no longer explicit, it can be difficult to see which interfaces are implemented by a struct. Therefore, it's common to define interfaces with as few methods as possible; this makes it easier to understand whether a particular struct fulfills the contract of the interface. An alternative is to create constructors that return an interface rather than the concrete type: ```go type Writer interface { Write(p []byte) (n int, err error) } type NullWriter struct {} func (writer *NullWriter) Write(data []byte) (n int, err error) { // do nothing return len(data), nil } func NewNullWriter() io.Writer { return &NullWriter{} } ``` The above function ensures that the `NullWriter` struct implements the `Writer` interface. If we were to delete the `Write` method from `NullWriter`, we would get a compilation error. This is a good way of ensuring that our code behaves as expected and that we can rely on the compiler as a safety net in case we try to write invalid code. In certain cases, it might not be desirable to write a constructor, or perhaps we would like for our constructor to return the concrete type, rather than the interface. As an example, the `NullWriter` struct has no properties to populate on initialisation, so writing a constructor is a little redundant. Therefore, we can use the less verbose method of checking interface compatibility: ```go type Writer interface { Write(p []byte) (n int, err error) } type NullWriter struct {} var _ io.Writer = &NullWriter{} ``` In the above code, we are initialising a variable with the Go `blank identifier`, with the type assignment of `io.Writer`. This results in our variable being checked to fulfill the `io.Writer` interface contract, before being discarded. This method of checking interface fulfillment also makes it possible to check that several interface contracts are fulfilled: ```go type NullReaderWriter struct{} var _ io.Writer = &NullWriter{} var _ io.Reader = &NullWriter{} ``` From the above code, it's very easy to understand which interfaces must be fulfilled; this ensures that the compiler will help us out during compile time. Therefore, this is generally the preferred solution for checking interface contract fulfillment. There's yet another method of trying to be more explicit about which interfaces a given struct implements. However, this third method actually achieves the opposite of what we want. It involves using embedded interfaces as a struct property. > <em>Wait what? &ndash; Presumably most people</em> Let's rewind a bit before we dive deep into the forbidden forest of smelly Go. In Go, we can use embedded structs as a type of inheritance in our struct definitions. This is really nice, as we can decouple our code by defining reusable structs. ```go type Metadata struct { CreatedBy types.User } type Document struct { *Metadata Title string Body string } type AudioFile struct { *Metadata Title string Body string } ``` Above, we are defining a `Metadata` object that will provide us with property fields that we are likely to use on many different struct types. The neat thing about using the embedded struct, rather than explicitly defining the properties directly in our struct, is that it has decoupled the `Metadata` fields. Should we choose to update our `Metadata` object, we can change it in just a single place. As we've seen several times so far, we want to ensure that a change in one place in our code doesn't break other parts. Keeping these properties centralised makes it clear that structures with an embedded `Metadata` have the same properties&mdash;much like how structures that fulfill interfaces have the same methods. Now, let's look at an example of how we can use a constructor to further prevent breaking our code when making changes to our `Metadata` struct: ```go func NewMetadata(user types.User) Metadata { return &Metadata{ CreatedBy: user, } } func NewDocument(title string, body string) Document { return Document{ Metadata: NewMetadata(), Title: title, Body: body, } } ``` Suppose that at a later point in time, we decide that we'd also like a `CreatedAt` field on our `Metadata` object. We can now easily achieve this by simply updating our `NewMetadata` constructor: ```go func NewMetadata(user types.User) Metadata { return &Metadata{ CreatedBy: user, CreatedAt: time.Now(), } } ``` Now, both our `Document` and `AudioFile` structures are updated to also populate these fields on construction. This is the core principle behind decoupling and an excellent example of ensuring maintainability of code. We can also add new methods without breaking our existing code: ```go type Metadata struct { CreatedBy types.User CreatedAt time.Time UpdatedBy types.User UpdatedAt time.Time } func (metadata *Metadata) AddUpdateInfo(user types.User) { metadata.UpdatedBy = user metadata.UpdatedAt = time.Now() } ``` Again, without breaking the rest of our codebase, we've managed to introduce new functionality. This kind of programming makes implementing new features very quick and painless, which is exactly what we are trying to achieve by writing clean code. Let's return to the topic of interface contract fulfillment using embedded interfaces. Consider the following code as an example: ```go type NullWriter struct { Writer } func NewNullWriter() io.Writer { return &NullWriter{} } ``` The above code compiles. Technically, we are implementing the interface of `Writer` in our `NullWriter`, as `NullWriter` will inherit all the functions that are associated with this interface. Some see this as a clear way of showing that our `NullWriter` is implementing the `Writer` interface. However, we must be careful when using this technique. ```go func main() { w := NewNullWriter() w.Write([]byte{1, 2, 3}) } ``` As mentioned before, the above code will compile. The `NewNullWriter` returns a `Writer`, and everything is hunky-dory according to the compiler because `NullWriter` fulfills the contract of `io.Writer`, via the embedded interface. However, running the code above will result in the following: > panic: runtime error: invalid memory address or nil pointer dereference What happened? An interface method in Go is essentially a function pointer. In this case, since we are pointing to the function of an interface, rather than an actual method implementation, we are trying to invoke a function that's actually a `nil` pointer. To prevent this from happening, we would have to provide the `NulllWriter` with a struct that fulfills the interface contract, with actual implemented methods. ```go func main() { w := NullWriter{ Writer: &bytes.Buffer{}, } w.Write([]byte{1, 2, 3}) } ``` > NOTE: In the above example, `Writer` is referring to the embedded `io.Writer` interface. It is also possible to invoke the `Write` method by accessing this property with `w.Writer.Write()`. We are no longer triggering a panic and can now use the `NullWriter` as a `Writer`. This initialisation process is not much different from having properties that are initialised as `nil`, as discussed previously. Therefore, logically, we should try to handle them in a similar way. However, this is where embedded interfaces become a little difficult to work with. In a previous section, it was explained that the best way to handle potential `nil` values is to make the property in question private and create a public *getter* method. This way, we could ensure that our property is, in fact, not `nil`. Unfortunately, this is simply not possible with embedded interfaces, as they are by nature always public. Another concern raised by using embedded interfaces is the potential confusion caused by partially overwritten interface methods: ```go type MyReadCloser struct { io.ReadCloser } func (closer *ReadCloser) Read(data []byte) { ... } func main() { closer := MyReadCloser{} closer.Read([]byte{1, 2, 3}) // works fine closer.Close() // causes panic closer.ReadCloser.Closer() // no panic } ``` Even though this might look like we're overriding methods, which is common in languages such as C# and Java, we actually aren't. Go doesn't support inheritance (and thus has no notion of a superclass). We can imitate the behaviour, but it is not a built-in part of the language. By using methods such as interface embedding without caution, we can create confusing and potentially buggy code, just to save a few more lines. > NOTE: Some argue that using embedded interfaces is a good way of creating a mock structure for testing a subset of interface methods. Essentially, by using an embedded interface, you won't have to implement all of the methods of the interface; rather, you can choose to implement only the few methods that you'd like to test. Within the context of testing/mocking, I can see this argument, but I am still not a fan of this approach. Let's quickly get back to clean code and proper usage of interfaces. It's time to discuss using interfaces as function parameters and return values. The most common proverb for interface usage with functions in Go is the following: > <em>Be conservative in what you do; be liberal in what you accept from others &ndash; Jon Postel</em> > FUN FACT: This proverb actually has nothing to do with Go. It's taken from an early specification of the TCP networking protocol. In other words, you should write functions that accept an interface and return a concrete type. This is generally good practice and is especially useful when doing tests with mocking. As an example, we can create a function that takes a writer interface as its input and invokes the `Write` method of that interface: ```go type Pipe struct { writer io.Writer buffer bytes.Buffer } func NewPipe(w io.Writer) *Pipe { return &Pipe{ writer: w, } } func (pipe *Pipe) Save() error { if _, err := pipe.writer.Write(pipe.FlushBuffer()); err != nil { return err } return nil } ``` Let's assume that we are writing to a file when our application is running, but we don't want to write to a new file for all tests that invoke this function. We can implement a new mock type that will basically do nothing. Essentially, this is just basic dependency injection and mocking, but the point is that it is extremely easy to achieve in Go: ```go type NullWriter struct {} func (w *NullWriter) Write(data []byte) (int, error) { return len(data), nil } func TestFn(t *testing.T) { ... pipe := NewPipe(NullWriter{}) ... } ``` > NOTE: There is actually already a null writer implementation built into the `ioutil` package named `Discard`. When constructing our `Pipe` struct with `NullWriter` (rather than a different writer), when invoking our `Save` function, nothing will happen. The only thing we had to do was add four lines of code. This is why it is encouraged to make interfaces as small as possible in idiomatic Go&mdash;it makes it especially easy to implement patterns like the one we just saw. However, this implementation of interfaces also comes with a <em>huge</em> downside. ### The Empty `interface{}` Unlike other languages, Go does not have an implementation for generics. There have been many proposals for one, but all have been turned down by the Go language team. Unfortunately, without generics, developers must try to find creative alternatives, which very often involves using the empty `interface{}`. This section describes why these often <em>too</em> creative implementations should be considered bad practice and unclean code. There will also be examples of appropriate usage of the empty `interface{}` and how to avoid some pitfalls of writing code with it. As mentioned in a previous section, Go determines whether a concrete type implements a particular interface by checking whether the type implements the <em>methods</em> of that interface. So what happens if our interface declares no methods, as is the case with the empty interface? ```go type EmptyInterface interface {} ``` The above is equivalent to the built-in type `interface{}`. A natural consequence of this is that we can write generic functions that accept any type as arguments. This is extremely useful for certain kinds of functions, such as print helpers. Interestingly, this is actually what makes it possible to pass in any type to the `Println` function from the `fmt` package: ```go func Println(v ...interface{}) { ... } ``` In this case, `Println` isn't just accepting a single `interface{}`; rather, the function accepts a <em>slice</em> of types that implement the empty `interface{}`. As there are no methods associated with the empty `interface{}`, <em>all</em> types are accepted, even making it possible to feed `Println` with a slice of different types. This is a very common pattern when handling string conversion (both from and to a string). Good examples of this come from the `json` standard library package: ```go func InsertItemHandler(w http.ResponseWriter, r *http.Request) { var item Item if err := json.NewDecoder(r.Body).Decode(&item); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := db.InsertItem(item); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatsOK) } ``` All the less elegant code is contained within the `Decode` function. Thus, developers using this functionality won't have to worry about type reflection or type casting; we just have to worry about providing a pointer to a concrete type. This is good because the `Decode()` function is technically returning a concrete type. We are passing in our `Item` value, which will be populated from the body of the HTTP request. This means we won't have to deal with the potential risks of handling the `interface{}` value ourselves. However, even when using the empty `interface{}` with good programming practices, we still have some issues. If we pass in a JSON string that has nothing to do with our `Item` type but is still valid JSON, we won't receive an error&mdash;our `item` variable will just be left with the default values. So, while we don't have to worry about reflection and casting errors, we will still have to make sure that the message sent from our client is a valid `Item` type. Unfortunately, as of writing this document, there is no simple or good way to implement these types of generic decoders without using the empty `interface{}` type. The problem with using `interface{}` in this manner is that we are leaning towards using Go, a statically typed language, as a dynamically typed language. This becomes even clearer when looking at poor implementations of the `interface{}` type. The most common example of this comes from developers trying to implement a generic store or list of some sort. Let's look at an example of trying to implement a generic HashMap package that can store any type using `interface{}`. ```go type HashMap struct { store map[string]interface{} } func (hashmap *HashMap) Insert(key string, value interface{}) { hashmap.store[key] = value } func (hashmap *HashMap) Get(key string) (interface{}, error) { value, ok := hashmap.store[key] if !ok { return nil, ErrKeyNotFoundInHashMap } return value } ``` > NOTE: I have omitted thread safety from this example to keep it simple. Please keep in mind that the implementation pattern shown above is actually used in quite a lot of Go packages. It is even used in the standard library `sync` package for the `sync.Map` type. So what's the problem with this implementation? Well, let's have a look at an example of using the package: ```go func SomeFunction(id string) (Item, error) { itemIface, err := hashmap.Get(id) if err != nil { return EmptyItem, err } item, ok := itemIface.(Item) if !ok { return EmptyItem, ErrCastingItem } return item, nil } ``` At first glance, this looks fine. However, we'll start getting into trouble if we add <em>different</em> types to our store, something that's currently allowed. There is nothing preventing us from adding something other than the `Item` type. So what happens when someone starts adding other types into our HashMap, like a pointer `*Item` instead of an `Item`? Our function now might return an error. Worst of all, this might not even be caught by our tests. Depending on the complexity of the system, this could introduce some bugs that are particularly difficult to debug. This type of code should never reach production. Remember: Go does not (yet) support generics. That's just a fact that developers must accept for the time being. If we want to use generics, then we should use a different language that does support generics rather than relying on dangerous hacks. So, how do we prevent this code from reaching production? The simplest solution is to just write the functions with concrete types instead of using `interface{}` values. Of course, this is not always the best approach, as there might be some functionality within the package that is not trivial to implement ourselves. Therefore, a better approach may be to create wrappers that expose the functionality we need but still ensure type safety: ```go type ItemCache struct { kv tinykv.KV } func (cache *ItemCache) Get(id string) (Item, error) { value, ok := cache.kv.Get(id) if !ok { return EmptyItem, ErrItemNotFound } return interfaceToItem(value) } func interfaceToItem(v interface{}) (Item, error) { item, ok := v.(Item) if !ok { return EmptyItem, ErrCouldNotCastItem } return item, nil } func (cache *ItemCache) Put(id string, item Item) error { return cache.kv.Put(id, item) } ``` > NOTE: Implementations of other functionalities of the `tinykv.KV` cache have been omitted for the sake of brevity. The wrapper above now ensures that we are using the actual types and that we are no longer passing in `interface{}` types. It is therefore no longer possible to accidentally populate our store with a wrong value type, and we have restricted our casting of types as much as possible. This is a very straightforward way of solving our issue, even if somewhat manually. ## Summary First of all, thank you for making it all the way through this article! I hope it has provided some insight into clean code and how it helps ensure maintainability, readability, and stability in any codebase. Let's briefly sum up all the topics we've covered: - <strong>Functions</strong>&mdash;A function's name should reflect its scope; the smaller the scope of a function, the more specific its name. Ensure that all functions serve a single purpose in as few lines as possible. A good rule of thumb is to limit your functions to 5&ndash;8 lines and to only accept 2&ndash;3 arguments. - <strong>Variables</strong>&mdash;Unlike functions, variables should assume more generic names as their scope becomes smaller. It's also recommended that you limit the scope of a variable as much as possible to prevent unintentional modification. On a similar note, you should keep the modification of variables to a minimum; this becomes an especially important consideration as the scope of a variable grows. - <strong>Return Values</strong>&mdash;Concrete types should be returned whenever possible. Make it as difficult as possible for users of your package to make mistakes and as easy as possible for them to understand the values returned by your functions. - <strong>Pointers</strong>&mdash;Use pointers with caution, and limit their scope and mutability to an absolute minimum. Remember: Garbage collection only assists with memory management; it does not assist with all of the other complexities associated with pointers. - <strong>Interfaces</strong>&mdash;Use interfaces as much as possible to loosen the coupling of your code. Hide any code using the empty `interface{}` as much as possible from end users to prevent it from being exposed. As a final note, it's worth mentioning that the notion of clean code is particularly subjective, and that likely won't ever change. However, much like my statement concerning `gofmt`, I think it's more important to find a common standard than something that everyone agrees with; the latter is extremely difficult to achieve. It's also important to understand that fanaticism is never the goal with clean code. A codebase will most likely never be fully 'clean,' in the same way that your office desk probably isn't either. There's certainly room for you to step outside the rules and boundaries covered in this article. However, remember that the most important reason for writing clean code is to help yourself and other developers. We support engineers by ensuring stability in the software we produce and by making it easier to debug faulty code. We help our fellow developers by ensuring that our code is readable and easily digestible. We help <em>everyone</em> involved in the project by establishing a flexible codebase that allows us to quickly introduce new features without breaking our current platform. We move quickly by going slowly, and everyone is satisfied. I hope you will join this discussion to help the Go community define (and refine) the concept of clean code. Let's establish a common ground so that we can improve software&mdash;not only for ourselves but for the sake of everyone.
{ "pile_set_name": "Github" }
#!/bin/sh . "${APPVEYOR_BUILD_FOLDER}/ci/appveyor/defs.sh" . "${APPVEYOR_BUILD_FOLDER}/ci/appveyor/package_versions.sh" print_headline "Installing dependencies" pacman --noconfirm -S mingw-w64-x86_64-freetype mingw-w64-x86_64-openjpeg2 mingw-w64-x86_64-lcms2 mingw-w64-x86_64-libpng mingw-w64-x86_64-libtiff mingw-w64-x86_64-curl mingw-w64-x86_64-lua print_headline "Installing poppler-data" print_info "Downloading poppler-data" mkdir -p /c/projects/poppler-data cd /c/projects/poppler-data curl -sSL -O "${popplerdata_URL}" # FIXME: Check checksum print_info "Extracting poppler-data" 7z x "${popplerdata_ARCHIVE}" -so | 7z x -si -ttar print_info "Renaming ${popplerdata_DIRNAME} > poppler-data" mv "${popplerdata_DIRNAME}" poppler-data print_headline "Installing poppler" print_info "Downloading poppler" mkdir -p /c/projects/poppler cd /c/projects/poppler curl -sSL -O "${poppler_URL}" # FIXME: Check checksum print_info "Extracting poppler" 7z x "${poppler_ARCHIVE}" -so | 7z x -si -ttar cd "${poppler_DIRNAME}" print_info "Patching poppler" for PATCH in $(find "${APPVEYOR_BUILD_FOLDER}/ci/travis-ci/mxe/" -iname 'poppler-*.patch'); do echo "Applying ${PATCH}" patch -p1 < "${PATCH}" done print_info "Building poppler" mkdir build && cd build && cmake -G"MSYS Makefiles" -DCMAKE_BUILD_TYPE="Release" -DBUILD_QT5_TESTS=OFF -DENABLE_CPP=OFF -DENABLE_UTILS=OFF -DENABLE_UNSTABLE_API_ABI_HEADERS=ON -DCMAKE_INSTALL_PREFIX="/mingw64" .. && make -j && make install print_headline "Installing hunspell" print_info "Downloading hunspell" mkdir -p /c/projects/hunspell cd /c/projects/hunspell curl -sSL -O "${hunspell_URL}" # FIXME: Check checksum print_info "Extracting hunspell" 7z x "${hunspell_ARCHIVE}" -so | 7z x -si -ttar print_info "Building hunspell" cd "${hunspell_DIRNAME}" autoreconf -i && ./configure && make -j && make install
{ "pile_set_name": "Github" }
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture * * (c) 2006 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #pragma once #include "config.h" #include <sofa/core/behavior/OdeSolver.h> namespace sofa { namespace component { namespace odesolver { /** The simplest time integration. Two variants are available, depending on the value of field "symplectic". If true (the default), the symplectic variant of Euler's method is applied: If false, the basic Euler's method is applied (less robust) */ class SOFA_EXPLICIT_ODE_SOLVER_API EulerExplicitSolver : public sofa::core::behavior::OdeSolver { public: SOFA_CLASS(EulerExplicitSolver, sofa::core::behavior::OdeSolver); protected: EulerExplicitSolver(); public: void solve(const core::ExecParams* params, SReal dt, sofa::core::MultiVecCoordId xResult, sofa::core::MultiVecDerivId vResult) override; Data<bool> d_symplectic; ///< If true, the velocities are updated before the positions and the method is symplectic (more robust). If false, the positions are updated before the velocities (standard Euler, less robust). Data<bool> d_optimizedForDiagonalMatrix; ///< If M matrix is sparse (MeshMatrixMass), must be set to false (function addMDx() will compute the mass). Else, if true, solution to the system Ax=b can be directly found by computing x = f/m. The function accFromF() in the mass API will be used. Data<bool> d_threadSafeVisitor; /// Given an input derivative order (0 for position, 1 for velocity, 2 for acceleration), /// how much will it affect the output derivative of the given order. double getIntegrationFactor(int inputDerivative, int outputDerivative) const override ; /// Given a solution of the linear system, /// how much will it affect the output derivative of the given order. /// double getSolutionIntegrationFactor(int outputDerivative) const override ; void init() override ; protected: /// the solution vector is stored for warm-start core::behavior::MultiVecDeriv x; }; } // namespace odesolver } // namespace component } // namespace sofa
{ "pile_set_name": "Github" }
--- ms.openlocfilehash: a4476fbff572c004632153e5a98812c241efca57 ms.sourcegitcommit: 0926684d8d34f4c6b5acce58d2193db093cb9cf2 ms.translationtype: HT ms.contentlocale: es-ES ms.lasthandoff: 05/20/2020 ms.locfileid: "83721526" --- ### <a name="openssl-versions-on-macos"></a>Versiones de OpenSSL en macOS Ahora, los runtime de .NET Core 3.0 y versiones posteriores en macOS prefieren las versiones de OpenSSL 1.1.x a las versiones de OpenSSL 1.0.x en los tipos <xref:System.Security.Cryptography.AesCcm>, <xref:System.Security.Cryptography.AesGcm>, <xref:System.Security.Cryptography.DSAOpenSsl>, <xref:System.Security.Cryptography.ECDiffieHellmanOpenSsl>, <xref:System.Security.Cryptography.ECDsaOpenSsl>, <xref:System.Security.Cryptography.RSAOpenSsl> y <xref:System.Security.Cryptography.SafeEvpPKeyHandle>. Ahora, el runtime de .NET Core 2.1 es compatible con las versiones de OpenSSL 1.1.x, pero siguen siendo preferibles las versiones de OpenSSL 1.0.x. #### <a name="change-description"></a>Descripción del cambio Antes, el runtime de .NET Core usaba versiones de OpenSSL 1.0.x en macOS para en los tipos que interactúan con OpenSSL. La versión más reciente de OpenSSL 1.0.x, OpenSSL 1.0.2, ya no se admite. Para mantener los tipos que usan OpenSSL en versiones compatibles de OpenSSL, los runtime de .NET Core 3.0 y versiones posteriores usan ahora las versiones más recientes de OpenSSL en macOS. Con este cambio, el comportamiento de los runtime de .NET Core en macOS es el siguiente: - Los runtime de .NET Core 3.0 y versiones posteriores usan OpenSSL 1.1.x (si está disponible) y revierten a OpenSSL 1.0.x solo si no hay disponible ninguna versión 1.1.x. En el caso de los autores de llamada que usen los tipos de interoperabilidad de OpenSSL con P/Invoke personalizados, siga las instrucciones de los comentarios sobre <xref:System.Security.Cryptography.SafeEvpPKeyHandle.OpenSslVersion?displayProperty=nameWithType>. La aplicación se puede bloquear si no se comprueba el valor de <xref:System.Security.Cryptography.SafeEvpPKeyHandle.OpenSslVersion>. - Los runtime de .NET Core 2.1 usan OpenSSL 1.0.x (si está disponible) y revierten a OpenSSL 1.1.x si no hay disponible ninguna versión 1.0.x. El runtime 2.1 prefiere la versión anterior de OpenSSL porque la propiedad <xref:System.Security.Cryptography.SafeEvpPKeyHandle.OpenSslVersion?displayProperty=nameWithType> no existe en .NET Core 2.1, por lo que la versión de OpenSSL no se puede determinar de forma confiable en tiempo de ejecución. #### <a name="version-introduced"></a>Versión introducida - .NET Core 2.1.16 - .NET Core 3.0.3 - .NET Core 3.1.2 #### <a name="recommended-action"></a>Acción recomendada - Desinstale la versión 1.0.2 de OpenSSL si ya no la necesita. - Instale OpenSSL 1.1.x si usa los tipos <xref:System.Security.Cryptography.AesCcm>, <xref:System.Security.Cryptography.AesGcm>, <xref:System.Security.Cryptography.DSAOpenSsl>, <xref:System.Security.Cryptography.ECDiffieHellmanOpenSsl>, <xref:System.Security.Cryptography.ECDsaOpenSsl>, <xref:System.Security.Cryptography.RSAOpenSsl> o <xref:System.Security.Cryptography.SafeEvpPKeyHandle>. - Si usa los tipos de interoperabilidad de OpenSSL con P/Invoke personalizados, siga las instrucciones de los comentarios sobre <xref:System.Security.Cryptography.SafeEvpPKeyHandle.OpenSslVersion?displayProperty=nameWithType>. #### <a name="category"></a>Categoría Bibliotecas de Core .NET #### <a name="affected-apis"></a>API afectadas - <xref:System.Security.Cryptography.AesCcm?displayProperty=fullName> - <xref:System.Security.Cryptography.AesGcm?displayProperty=fullName> - <xref:System.Security.Cryptography.DSAOpenSsl?displayProperty=fullName> - <xref:System.Security.Cryptography.ECDiffieHellmanOpenSsl?displayProperty=fullName> - <xref:System.Security.Cryptography.ECDsaOpenSsl?displayProperty=fullName> - <xref:System.Security.Cryptography.RSAOpenSsl?displayProperty=fullName> - <xref:System.Security.Cryptography.SafeEvpPKeyHandle?displayProperty=fullName> <!-- #### Affected APIs - `T:System.Security.Cryptography.AesCcm`` - `T:System.Security.Cryptography.AesGcm` - `T:System.Security.Cryptography.DSAOpenSsl` - `T:System.Security.Cryptography.ECDiffieHellmanOpenSsl` - `T:System.Security.Cryptography.ECDsaOpenSsl` - `T:System.Security.Cryptography.RSAOpenSsl` - `T:System.Security.Cryptography.SafeEvpPKeyHandle` -->
{ "pile_set_name": "Github" }
/**@brief 仿照linux kfifo写的ring buffer *@atuher Anker date:2013-12-18 * ring_buffer.h * */ #ifndef KFIFO_HEADER_H #define KFIFO_HEADER_H #include <inttypes.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <assert.h> //判断x是否是2的次方 #define is_power_of_2(x) ((x) != 0 && (((x) & ((x) - 1)) == 0)) //取a和b中最小值 #define min(a, b) (((a) < (b)) ? (a) : (b)) struct ring_buffer { void *buffer; //缓冲区 uint32_t size; //大小 uint32_t in; //入口位置 uint32_t out; //出口位置 pthread_mutex_t *f_lock; //互斥锁 }; //初始化缓冲区 struct ring_buffer* ring_buffer_init(void *buffer, uint32_t size, pthread_mutex_t *f_lock) { assert(buffer); struct ring_buffer *ring_buf = NULL; if (!is_power_of_2(size)) { fprintf(stderr,"size must be power of 2.\n"); return ring_buf; } ring_buf = (struct ring_buffer *)malloc(sizeof(struct ring_buffer)); if (!ring_buf) { fprintf(stderr,"Failed to malloc memory,errno:%u,reason:%s", errno, strerror(errno)); return ring_buf; } memset(ring_buf, 0, sizeof(struct ring_buffer)); ring_buf->buffer = buffer; ring_buf->size = size; ring_buf->in = 0; ring_buf->out = 0; ring_buf->f_lock = f_lock; return ring_buf; } //释放缓冲区 void ring_buffer_free(struct ring_buffer *ring_buf) { if (ring_buf) { if (ring_buf->buffer) { free(ring_buf->buffer); ring_buf->buffer = NULL; } free(ring_buf); ring_buf = NULL; } } //缓冲区的长度 uint32_t __ring_buffer_len(const struct ring_buffer *ring_buf) { return (ring_buf->in - ring_buf->out); } //从缓冲区中取数据 uint32_t __ring_buffer_get(struct ring_buffer *ring_buf, void * buffer, uint32_t size) { assert(ring_buf || buffer); uint32_t len = 0; size = min(size, ring_buf->in - ring_buf->out); /* first get the data from fifo->out until the end of the buffer */ len = min(size, ring_buf->size - (ring_buf->out & (ring_buf->size - 1))); memcpy(buffer, ring_buf->buffer + (ring_buf->out & (ring_buf->size - 1)), len); /* then get the rest (if any) from the beginning of the buffer */ memcpy(buffer + len, ring_buf->buffer, size - len); ring_buf->out += size; return size; } //向缓冲区中存放数据 uint32_t __ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size) { assert(ring_buf || buffer); uint32_t len = 0; size = min(size, ring_buf->size - ring_buf->in + ring_buf->out); /* first put the data starting from fifo->in to buffer end */ len = min(size, ring_buf->size - (ring_buf->in & (ring_buf->size - 1))); memcpy(ring_buf->buffer + (ring_buf->in & (ring_buf->size - 1)), buffer, len); /* then put the rest (if any) at the beginning of the buffer */ memcpy(ring_buf->buffer, buffer + len, size - len); ring_buf->in += size; return size; } uint32_t ring_buffer_len(const struct ring_buffer *ring_buf) { uint32_t len = 0; pthread_mutex_lock(ring_buf->f_lock); len = __ring_buffer_len(ring_buf); pthread_mutex_unlock(ring_buf->f_lock); return len; } uint32_t ring_buffer_get(struct ring_buffer *ring_buf, void *buffer, uint32_t size) { uint32_t ret; pthread_mutex_lock(ring_buf->f_lock); ret = __ring_buffer_get(ring_buf, buffer, size); //buffer中没有数据 if (ring_buf->in == ring_buf->out) ring_buf->in = ring_buf->out = 0; pthread_mutex_unlock(ring_buf->f_lock); return ret; } uint32_t ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size) { uint32_t ret; pthread_mutex_lock(ring_buf->f_lock); ret = __ring_buffer_put(ring_buf, buffer, size); pthread_mutex_unlock(ring_buf->f_lock); return ret; } #endif
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" initialViewController="B8D-0N-5wS"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14460.31"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Application--> <scene sceneID="JPo-4y-FX3"> <objects> <application id="hnw-xV-0zn" sceneMemberID="viewController"> <menu key="mainMenu" title="Main Menu" systemMenu="main" id="AYu-sK-qS6"> <items> <menuItem title="SKTiled" id="1Xt-HY-uBw"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="SKTiled" systemMenu="apple" identifier="derpy" id="uQy-DD-JDr"> <items> <menuItem title="About SKTiled Demo" id="5kV-Vb-QxS"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/> <menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/> <menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/> <menuItem title="Services" id="NMo-om-nkz"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/> </menuItem> <menuItem isSeparatorItem="YES" id="qu8-Tk-8zd"/> <menuItem title="Hide SKTiled Demo" keyEquivalent="h" id="Olw-nP-bQN"> <connections> <action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/> </connections> </menuItem> <menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO"> <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/> <connections> <action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/> </connections> </menuItem> <menuItem title="Show All" id="Kd2-mp-pUS"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/> <menuItem title="Quit SKTiled Demo" keyEquivalent="q" id="4sb-4s-VLi"> <connections> <action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/> </connections> </menuItem> </items> </menu> </menuItem> <menuItem title="File" id="dMs-cI-mzQ"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="File" id="bib-Uj-vzu"> <items> <menuItem title="Load tile map..." keyEquivalent="o" id="IAo-SY-fd9"> <connections> <action selector="loadTilemapAction:" target="Voe-Tx-rLC" id="Bm9-MU-z0p"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="ydn-Ww-N0c"/> <menuItem title="Recent files..." id="PxH-bD-OZi"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Recent files..." id="8G9-Wf-vRY"/> </menuItem> <menuItem isSeparatorItem="YES" id="iXz-gw-ITL"/> <menuItem title="Reload tile map" keyEquivalent="r" id="f06-eB-0wr"> <connections> <action selector="reloadTilemapAction:" target="Voe-Tx-rLC" id="Uxe-wl-Cmz"/> </connections> </menuItem> </items> </menu> </menuItem> <menuItem title="Demo" id="uVs-e1-HbL"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Demo" id="7f1-H8-tvV"> <items> <menuItem title="Isolate Tiles:" identifier="menu-identifier" id="wI7-rC-RX7"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Time Display:" id="HRD-GT-00b"/> <accessibility description="access-description" identifier="123"/> </menuItem> <menuItem isSeparatorItem="YES" id="vLE-jt-JQA"/> <menuItem title="Current Maps..." id="OCC-zQ-5nF"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="showCurrentMapsAction:" target="Voe-Tx-rLC" id="Aba-AJ-F6X"/> </connections> </menuItem> <menuItem title="Show All Assets..." id="ANV-Se-DZa"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="showAllAssetsAction:" target="Voe-Tx-rLC" id="HBJ-4C-J1p"/> </connections> </menuItem> <menuItem title="Show External Assets..." id="Ywb-f1-YfU"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="getExternallyLoadedAssetsAction:" target="Voe-Tx-rLC" id="F2c-PT-vSQ"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="9YA-hV-8Rw"/> <menuItem title="Demo Preferences..." id="a6d-zy-UTc"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="showDemoPreferencesAction:" target="Voe-Tx-rLC" id="aia-1w-Zwh"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="ks9-Lh-oUG"/> <menuItem title="Time Display:" id="EBE-ZU-Vi0" userLabel="Time Display:"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Time Display:" id="e9x-wD-4ub"/> </menuItem> <menuItem title="Logging Level:" id="2jg-PU-w23" userLabel="Logging Level Menu"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Logging Level:" id="6yZ-kP-7C4"/> </menuItem> </items> </menu> </menuItem> <menuItem title="Map" id="Ybf-hB-7LM" userLabel="Map"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Map" id="Zq2-nK-8O0"> <items> <menuItem title="Tilemap Statistics..." id="OXT-yC-4Eg"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="mapStatisticsPressed:" target="Voe-Tx-rLC" id="Jpq-Ut-F27"/> </connections> </menuItem> <menuItem title="Render Quality..." id="vcc-iK-5KE"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="mapRenderQualityPressed:" target="Voe-Tx-rLC" id="hBU-XH-3Jf"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="y0t-cE-erH"/> <menuItem title="Update Mode:" id="01r-QV-0xf"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Update Mode:" id="BHT-Ar-GlC"/> </menuItem> <menuItem title="Render Effects..." id="wkw-1O-o10"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="toggleRenderTilemapEffects:" target="Voe-Tx-rLC" id="FQB-Rx-bNb"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="qs1-uO-RgJ"/> <menuItem title="Debug Draw:" id="g9m-EM-X6F"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Debug Draw:" id="v1O-eo-EAD"/> </menuItem> <menuItem isSeparatorItem="YES" id="8Q1-bU-kd4"/> <menuItem title="Visibility:" id="ofi-Kh-OpM"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" id="ojP-Qo-swd"/> </menuItem> <menuItem title="Isolate:" id="cCe-8N-Uhp"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" id="Miq-qF-Qjd"/> </menuItem> </items> </menu> </menuItem> <menuItem title="Camera" id="3by-9S-Udp"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Camera" id="I0g-27-7sL"> <items> <menuItem title="Camera Statistics..." id="e0H-t9-Xrc"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraStatistics:" target="Voe-Tx-rLC" id="T4f-nD-Xpc"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="ecI-qg-OSO"/> <menuItem title="Camera callbacks..." id="o3p-eM-sA8"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraCallbacksAction:" target="Voe-Tx-rLC" id="Xml-lj-cFQ"/> </connections> </menuItem> <menuItem title="Visible Node callbacks..." id="t9z-XR-lm8" userLabel="Camera Node Callbacks Contained Menu Item"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraVisibleNodesCallbacksAction:" target="Voe-Tx-rLC" id="Ska-B5-lZq"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="ceh-Zb-Rb0"/> <menuItem title="Fit to view..." id="h0m-Sd-EwV"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraFitToViewAction:" target="Voe-Tx-rLC" id="xvZ-Y5-gdR"/> </connections> </menuItem> <menuItem title="Use zoom constraints" id="1eq-9H-4kc"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraIgnoreZoomConstraintsAction:" target="Voe-Tx-rLC" id="WAn-L6-EDI"/> </connections> </menuItem> <menuItem title="Use previous camera" id="0Do-gU-SoY"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="cameraUsePreviousCameraAction:" target="Voe-Tx-rLC" id="Y1T-fx-B0m"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="SaJ-4g-Zre"/> <menuItem title="Zoom clamping:" id="NmO-k3-pZV" userLabel="Zoom clamping:"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" id="PjI-dV-OUe"/> </menuItem> </items> </menu> </menuItem> <menuItem title="Debug" id="mK5-ya-h2q"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Debug" id="5q1-w7-WWB"> <items> <menuItem title="SKTiled Globals..." id="m01-be-fPS" userLabel="Globals..."> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="showGlobalsAction:" target="Voe-Tx-rLC" id="REC-vc-0qo"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="PaH-my-jqn"/> <menuItem title="Render Statistics" id="8DF-Mo-t1x"> <modifierMask key="keyEquivalentModifierMask"/> <connections> <action selector="renderStatisticsVisibilityAction:" target="Voe-Tx-rLC" id="Mzc-xl-pjC"/> </connections> </menuItem> <menuItem isSeparatorItem="YES" id="ah8-dN-ZnU"/> <menuItem title="Mouse Filters:" id="ATK-4p-nLS"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Mouse Filters:" id="oq8-Jb-xFt"/> </menuItem> <menuItem isSeparatorItem="YES" id="q5c-TB-yFM"/> <menuItem title="Tile Color:" id="hnS-2z-nKA"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Tile Color:" id="hWE-5E-kN1"/> </menuItem> <menuItem title="Object Color:" id="69E-5M-crK"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Object Color:" id="prY-eX-DfI"/> </menuItem> </items> </menu> </menuItem> <menuItem title="Help" id="wpr-3q-Mcd"> <modifierMask key="keyEquivalentModifierMask"/> <menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ"> <items> <menuItem title="SKTiled Demo Help" keyEquivalent="?" id="FKE-Sm-Kum"> <connections> <action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/> </connections> </menuItem> </items> </menu> </menuItem> </items> </menu> <connections> <outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/> </connections> </application> <customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="SKTiled_Demo" customModuleProvider="target"> <connections> <outlet property="cameraCallbacksContainedMenuItem" destination="t9z-XR-lm8" id="uJe-1n-kkJ"/> <outlet property="cameraCallbacksMenuItem" destination="o3p-eM-sA8" id="4a6-Pk-NSP"/> <outlet property="cameraIgnoreMaxZoomMenuItem" destination="1eq-9H-4kc" id="a3X-Cr-9N1"/> <outlet property="cameraUserPreviousMenuItem" destination="0Do-gU-SoY" id="ZYA-eO-egL"/> <outlet property="cameraZoomClampingMenuItem" destination="NmO-k3-pZV" id="MSe-rw-GiS"/> <outlet property="isolateTilesMenuItem" destination="wI7-rC-RX7" id="JIC-LU-OsQ"/> <outlet property="layerIsolationMenu" destination="cCe-8N-Uhp" id="RIH-hV-AvD"/> <outlet property="layerVisibilityMenu" destination="ofi-Kh-OpM" id="EXP-Xd-vY6"/> <outlet property="loggingLevelMenuItem" destination="2jg-PU-w23" id="PCS-Fy-fCC"/> <outlet property="mapDebugDrawMenu" destination="g9m-EM-X6F" id="olI-40-ckw"/> <outlet property="mapMenuItem" destination="Ybf-hB-7LM" id="7pI-qT-NHE"/> <outlet property="mouseFiltersMenuItem" destination="ATK-4p-nLS" id="Suf-LS-YT5"/> <outlet property="objectColorsMenuItem" destination="69E-5M-crK" id="wOQ-bR-nt9"/> <outlet property="recentFilesMenu" destination="PxH-bD-OZi" id="bB9-r3-H32"/> <outlet property="recentFilesSubmenu" destination="8G9-Wf-vRY" id="AL4-Rt-RYW"/> <outlet property="renderEffectsMenuItem" destination="wkw-1O-o10" id="UbN-iN-brG"/> <outlet property="renderStatisticsMenuItem" destination="8DF-Mo-t1x" id="pAi-xd-fpR"/> <outlet property="tileColorsMenuItem" destination="hnS-2z-nKA" id="Seb-hg-B27"/> <outlet property="timeDisplayMenuItem" destination="EBE-ZU-Vi0" id="U0H-Rq-jsO"/> <outlet property="updateModeMenuItem" destination="01r-QV-0xf" id="NJ6-M8-3Di"/> </connections> </customObject> <customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> <userDefaultsController representsSharedInstance="YES" id="aIM-ST-Kfn"/> </objects> <point key="canvasLocation" x="-753" y="-523"/> </scene> <!--Window Controller--> <scene sceneID="R2V-B0-nI4"> <objects> <windowController id="B8D-0N-5wS" customClass="GameWindowController" customModule="SKTiled_Demo" customModuleProvider="target" sceneMemberID="viewController"> <window key="window" title="SKTiled" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" restorable="NO" releasedWhenClosed="NO" animationBehavior="default" id="IQv-IB-iLA"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="196" y="240" width="1280" height="720"/> <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1027"/> <connections> <outlet property="delegate" destination="B8D-0N-5wS" id="YaQ-v4-LMo"/> </connections> </window> <connections> <segue destination="XfG-lQ-9wD" kind="relationship" relationship="window.shadowedContentViewController" id="cq2-FE-JQM"/> </connections> </windowController> <customObject id="Oky-zY-oP4" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-717" y="154"/> </scene> <!--Game View Controller--> <scene sceneID="hIz-AP-VOD"> <objects> <viewController id="XfG-lQ-9wD" customClass="GameViewController" customModule="SKTiled_Demo" customModuleProvider="target" sceneMemberID="viewController"> <view key="view" wantsLayer="YES" id="m2S-Jp-Qdl" customClass="SKView"> <rect key="frame" x="0.0" y="0.0" width="1280" height="720"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <stackView distribution="fill" orientation="vertical" alignment="centerX" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Bgh-ex-Ztr" userLabel="Output-Top"> <rect key="frame" x="616" y="644" width="49" height="64"/> <subviews> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Rpo-Bf-MrJ" userLabel="Camera Info Label"> <rect key="frame" x="-2" y="48" width="53" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Camera" id="96K-OU-ekP"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="qaU-aN-dXC" userLabel="Paused Label"> <rect key="frame" x="-1" y="24" width="51" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Paused" id="8mb-3y-U6G"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="laT-E3-Leu" userLabel="Isolate Label"> <rect key="frame" x="1" y="0.0" width="47" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Isolate" id="sVx-4m-rwW"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> <stackView distribution="fill" orientation="vertical" alignment="centerX" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="bpV-ih-FVj" userLabel="Output-Bottom"> <rect key="frame" x="606" y="52" width="69" height="88"/> <subviews> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="P0U-y9-0fU" userLabel="Map Info Label"> <rect key="frame" x="16" y="72" width="37" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Map:" id="exA-0S-gy3"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="oa4-I2-u1i" userLabel="Tile Info Label"> <rect key="frame" x="18" y="48" width="33" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Tile:" id="sRi-Cf-RZd"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="3AA-Cl-qmn" userLabel="Properties Info Label"> <rect key="frame" x="-2" y="24" width="73" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Properties:" id="cFa-yZ-KBh"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="npC-Jr-qjF" userLabel="Debug Info Label"> <rect key="frame" x="11" y="0.0" width="46" height="16"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Debug" id="faQ-9y-P5R" userLabel="Debug Info Label"> <font key="font" metaFont="systemMedium" size="12"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" name="controlShadowColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> </subviews> <constraints> <constraint firstItem="P0U-y9-0fU" firstAttribute="centerX" secondItem="oa4-I2-u1i" secondAttribute="centerX" id="5xk-Ca-8uv"/> <constraint firstItem="oa4-I2-u1i" firstAttribute="centerX" secondItem="3AA-Cl-qmn" secondAttribute="centerX" id="lLH-WE-P90"/> </constraints> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> <stackView alphaValue="0.84999999999999998" distribution="fillEqually" orientation="horizontal" alignment="top" spacing="12" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="LqZ-dY-ggy" userLabel="Controls"> <rect key="frame" x="381" y="18" width="518" height="22"/> <subviews> <button verticalHuggingPriority="750" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="IwQ-St-3Wv" userLabel="Fit Button"> <rect key="frame" x="0.0" y="-1" width="94" height="23"/> <buttonCell key="cell" type="roundTextured" title="fit view" bezelStyle="texturedRounded" alignment="center" state="on" borderStyle="border" inset="2" id="rDK-p5-LCC"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <color key="contentTintColor" name="labelColor" catalog="System" colorSpace="catalog"/> <connections> <action selector="fitButtonPressed:" target="XfG-lQ-9wD" id="pwv-aH-Jh5"/> </connections> </button> <button verticalHuggingPriority="750" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="nuZ-Nw-3Kh" userLabel="Grid Button"> <rect key="frame" x="106" y="-1" width="94" height="23"/> <buttonCell key="cell" type="roundTextured" title="show grid" bezelStyle="texturedRounded" alignment="center" state="on" borderStyle="border" inset="2" id="0tE-qU-scK"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <color key="contentTintColor" name="labelColor" catalog="System" colorSpace="catalog"/> <connections> <action selector="gridButtonPressed:" target="XfG-lQ-9wD" id="oeM-7A-j3e"/> </connections> </button> <button verticalHuggingPriority="750" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="npW-cn-J3N" userLabel="Graph Button"> <rect key="frame" x="212" y="-1" width="94" height="23"/> <buttonCell key="cell" type="roundTextured" title="show graph" bezelStyle="texturedRounded" alignment="center" state="on" borderStyle="border" inset="2" id="bG8-NK-J7V"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <color key="contentTintColor" name="labelColor" catalog="System" colorSpace="catalog"/> <connections> <action selector="graphButtonPressed:" target="XfG-lQ-9wD" id="gzn-BO-9bN"/> </connections> </button> <button verticalHuggingPriority="750" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="rbx-7u-m9u" userLabel="Objects Button"> <rect key="frame" x="318" y="-1" width="94" height="23"/> <buttonCell key="cell" type="roundTextured" title="show objects" bezelStyle="texturedRounded" alignment="center" state="on" borderStyle="border" inset="2" id="6Iv-9I-VvD"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <color key="contentTintColor" name="labelColor" catalog="System" colorSpace="catalog"/> <connections> <action selector="objectsButtonPressed:" target="XfG-lQ-9wD" id="nco-tV-9UG"/> </connections> </button> <button verticalHuggingPriority="750" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="H0N-Ds-9yi" userLabel="Next Button"> <rect key="frame" x="424" y="-1" width="94" height="23"/> <buttonCell key="cell" type="roundTextured" title="next" bezelStyle="texturedRounded" alignment="center" state="on" borderStyle="border" inset="2" id="DO4-5u-aVv"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> </buttonCell> <color key="contentTintColor" name="labelColor" catalog="System" colorSpace="catalog"/> <connections> <action selector="nextButtonPressed:" target="XfG-lQ-9wD" id="lza-4Y-UOI"/> </connections> </button> </subviews> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> <stackView distribution="fill" orientation="vertical" alignment="leading" spacing="0.0" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="AWK-NZ-EcJ" userLabel="Stats Stack View"> <rect key="frame" x="4" y="4" width="109" height="135"/> <subviews> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="uha-XC-cXI" userLabel="Stats Header Label"> <rect key="frame" x="-2" y="120" width="98" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Render Stats:" id="BeR-AF-VlP" userLabel="Render Stats"> <font key="font" size="12" name="Courier-Bold"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="W4s-ny-MAx" userLabel="Stats Render Mode Label"> <rect key="frame" x="-2" y="105" width="113" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Render Mode: --" id="Q4G-QC-XPw" userLabel="Render Mode"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="cCh-yV-hn8" userLabel="Stats CPU Label"> <rect key="frame" x="-2" y="90" width="98" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" allowsUndo="NO" sendsActionOnEndEditing="YES" alignment="left" title="CPU Usage: --" id="Ne8-aA-QtM" userLabel="CPU Usage"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="TDW-3b-x8p" userLabel="Stats Visible Label"> <rect key="frame" x="-2" y="75" width="84" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Visible: --" id="sHQ-sa-FHX" userLabel="Visible"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Bvo-K8-F5b" userLabel="Stats Actions Label"> <rect key="frame" x="-2" y="60" width="77" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Actions: 0" id="VXu-6T-95h" userLabel="Actions"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Dw1-tm-WO4" userLabel="Stats Objects Label"> <rect key="frame" x="-2" y="45" width="77" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Objects: 0" id="e7Z-GQ-e93" userLabel="Objects"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="5BW-OW-rgF" userLabel="Stats Updated Label"> <rect key="frame" x="-2" y="30" width="77" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Updated: 0" id="8Wi-4w-sRq" userLabel="Updated:"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="1Vj-2A-SbA" userLabel="Stats Effects Label"> <rect key="frame" x="-2" y="15" width="91" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Effects: off" id="5rU-3N-MpZ" userLabel="Effects:"> <font key="font" size="12" name="Courier"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="pli-ih-OsQ" userLabel="Stats Render Label"> <rect key="frame" x="-2" y="0.0" width="105" height="15"/> <textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Render time: 0" id="t5Y-cU-9KB" userLabel="Effects"> <font key="font" size="12" name="Courier-Bold"/> <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="0.1176470588" green="0.1176470588" blue="0.1176470588" alpha="0.29999999999999999" colorSpace="custom" customColorSpace="sRGB"/> </textFieldCell> </textField> </subviews> <visibilityPriorities> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> <integer value="1000"/> </visibilityPriorities> <customSpacing> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> <real value="3.4028234663852886e+38"/> </customSpacing> </stackView> </subviews> <constraints> <constraint firstAttribute="bottom" secondItem="LqZ-dY-ggy" secondAttribute="bottom" constant="18" id="FpW-ev-RXT"/> <constraint firstItem="LqZ-dY-ggy" firstAttribute="centerX" secondItem="m2S-Jp-Qdl" secondAttribute="centerX" id="Gkp-Gf-1lM"/> <constraint firstAttribute="bottom" secondItem="AWK-NZ-EcJ" secondAttribute="bottom" constant="4" id="HxY-az-QGj"/> <constraint firstItem="LqZ-dY-ggy" firstAttribute="centerX" secondItem="m2S-Jp-Qdl" secondAttribute="centerX" id="MWP-Tu-zuC"/> <constraint firstItem="bpV-ih-FVj" firstAttribute="centerX" secondItem="m2S-Jp-Qdl" secondAttribute="centerX" id="SuM-qs-Xo7"/> <constraint firstItem="LqZ-dY-ggy" firstAttribute="top" secondItem="bpV-ih-FVj" secondAttribute="bottom" constant="12" id="bjC-aK-4cF"/> <constraint firstItem="AWK-NZ-EcJ" firstAttribute="leading" secondItem="m2S-Jp-Qdl" secondAttribute="leading" constant="4" id="q5W-ts-DgK"/> <constraint firstItem="Bgh-ex-Ztr" firstAttribute="top" secondItem="m2S-Jp-Qdl" secondAttribute="top" constant="12" id="qEn-DF-P5C"/> <constraint firstItem="Bgh-ex-Ztr" firstAttribute="centerX" secondItem="m2S-Jp-Qdl" secondAttribute="centerX" id="yBA-Pi-6Vs"/> </constraints> </view> <connections> <outlet property="cameraInfoLabel" destination="Rpo-Bf-MrJ" id="RyX-41-fZZ"/> <outlet property="debugInfoLabel" destination="npC-Jr-qjF" id="s9h-0V-GwJ"/> <outlet property="demoFileAttributes" destination="roh-5A-x7m" id="IIt-Ds-dF2"/> <outlet property="fitButton" destination="IwQ-St-3Wv" id="cst-mf-zi5"/> <outlet property="graphButton" destination="npW-cn-J3N" id="bDT-MQ-AjA"/> <outlet property="gridButton" destination="nuZ-Nw-3Kh" id="YwV-TN-gdQ"/> <outlet property="isolatedInfoLabel" destination="laT-E3-Leu" id="n55-Wt-6Fk"/> <outlet property="mapInfoLabel" destination="P0U-y9-0fU" id="T6u-RD-e0v"/> <outlet property="nextButton" destination="H0N-Ds-9yi" id="Dbn-Fv-lOd"/> <outlet property="objectsButton" destination="rbx-7u-m9u" id="cqO-dj-HqS"/> <outlet property="pauseInfoLabel" destination="qaU-aN-dXC" id="OHo-cQ-UJv"/> <outlet property="propertiesInfoLabel" destination="3AA-Cl-qmn" id="Kqk-Q6-bCh"/> <outlet property="statsActionsLabel" destination="Bvo-K8-F5b" id="fd0-Ww-1cb"/> <outlet property="statsCPULabel" destination="cCh-yV-hn8" id="ebq-Fx-TCh"/> <outlet property="statsEffectsLabel" destination="1Vj-2A-SbA" id="NmK-2V-SRw"/> <outlet property="statsHeaderLabel" destination="uha-XC-cXI" id="YQA-zB-3et"/> <outlet property="statsObjectsLabel" destination="Dw1-tm-WO4" id="czg-lh-wu9"/> <outlet property="statsRenderLabel" destination="pli-ih-OsQ" id="mdg-yk-89V"/> <outlet property="statsRenderModeLabel" destination="W4s-ny-MAx" id="d8z-hX-s1m"/> <outlet property="statsStackView" destination="AWK-NZ-EcJ" id="B18-dN-npO"/> <outlet property="statsUpdatedLabel" destination="5BW-OW-rgF" id="qhi-Do-MGi"/> <outlet property="statsVisibleLabel" destination="TDW-3b-x8p" id="3sd-Kh-jsi"/> <outlet property="tileInfoLabel" destination="oa4-I2-u1i" id="4iy-KG-um6"/> </connections> </viewController> <customObject id="rPt-NT-nkU" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> <arrayController id="roh-5A-x7m"/> </objects> <point key="canvasLocation" x="-718" y="1148"/> </scene> </scenes> </document>
{ "pile_set_name": "Github" }
/* Project : Wolf Engine. Copyright(c) Pooya Eimandar (http://PooyaEimandar.com) . All rights reserved. Source : Please direct any bug to https://github.com/PooyaEimandar/Wolf.Engine/issues Website : http://WolfSource.io Name : main.cpp Description : This sample shows how to interact lua as script engine of Wolf Engine Comment : Read more information about this sample on http://wolfsource.io/gpunotes/wolfengine/ */ #include "pch.h" //namespaces using namespace wolf; using namespace wolf::system; //Entry point of program WOLF_MAIN() { w_logger_config _log_config; _log_config.app_name = L"07_xml"; _log_config.log_path = wolf::system::io::get_current_directoryW(); #ifdef __WIN32 _log_config.log_to_std_out = false; #else _log_config.log_to_std_out = true; #endif logger.initialize(_log_config); logger.write(L"Wolf initialized"); //create root node w_xml_data _root; _root.node = L"peoples"; //create first node w_xml_data _node_0; //assign attributes to first node w_xml_data::w_xml_data_attribute _attr; _attr.name = L"name"; _attr.value = L"pooya"; _node_0.attributes.push_back(_attr); _attr.name = L"age"; _attr.value = L"31"; _node_0.attributes.push_back(_attr); //add to the root node _node_0.node = L"people"; _root.children.push_back(_node_0); //create second node w_xml_data _node_1; _attr.name = L"name"; _attr.value = L"rayan"; _node_1.attributes.push_back(_attr); _attr.name = L"age"; _attr.value = L"0"; _node_1.attributes.push_back(_attr); _node_1.node = L"people"; _root.children.push_back(_node_1); bool _save_as_utf8 = false; #if defined(__WIN32) || defined(__UWP) _save_as_utf8 = true; const wchar_t* _path = L"test.xml"; #else const char* _path = "test.xml"; #endif if(w_xml::save(_path, _save_as_utf8, _root, L"<!-- Sample XML -->") == W_PASSED) { //Successfully saved, now load it again std::ifstream _file("test.xml"); std::stringstream _string_stream; _string_stream << _file.rdbuf(); _file.close(); std::string _content(_string_stream.str()); using namespace rapidxml; xml_document<> _doc; try { _doc.parse<0>(&_content[0]); auto _node = _doc.first_node(); if (_node) { logger.write(_node->name()); for (auto _child = _node->first_node(); _child != nullptr; _child = _child->next_sibling()) { logger.write(_child->name()); } } _doc.clear(); } catch (...) { logger.error(L"Could not parse xml file"); } } else { logger.write(L"failed to save xml"); } logger.release(); return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
// Horizontal dividers // // Dividers (basically an hr) within dropdowns and nav lists @mixin nav-divider($color: $nav-divider-color, $margin-y: $nav-divider-margin-y, $ignore-warning: false) { height: 0; margin: $margin-y 0; overflow: hidden; border-top: 1px solid $color; @include deprecate("The `nav-divider()` mixin", "v4.4.0", "v5", $ignore-warning); }
{ "pile_set_name": "Github" }
# Acknowledgements This application makes use of the following third party libraries: ## MPSkewed Copyright (c) Alex Manzella. All rights reserved. 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. Neither the name of Alex Manzella nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Generated by CocoaPods - http://cocoapods.org
{ "pile_set_name": "Github" }
/** * Asynchronously loads the component for TargetsPage */ import Loadable from 'react-loadable'; import PageLoadingIndicator from 'components/PageLoadingIndicator'; export default Loadable({ loader: () => import('./index'), loading: PageLoadingIndicator, });
{ "pile_set_name": "Github" }
{ "id": "iron-hanger-stand", "name": "Iron Hanger Stand", "games": { "nh": { "customizable": true, "sellPrice": { "currency": "bells", "value": 2250 }, "buyPrices": [ { "currency": "bells", "value": 9000 } ], "recipe": { "iron-nugget": 3 } } }, "category": "Furniture" }
{ "pile_set_name": "Github" }
// +build !windows package ole func (v *IInspectable) GetIids() ([]*GUID, error) { return []*GUID{}, NewError(E_NOTIMPL) } func (v *IInspectable) GetRuntimeClassName() (string, error) { return "", NewError(E_NOTIMPL) } func (v *IInspectable) GetTrustLevel() (uint32, error) { return uint32(0), NewError(E_NOTIMPL) }
{ "pile_set_name": "Github" }
# Example Ruby Sinatra App # This code uses [Sinatra](http://www.sinatrarb.com) to display a very simple web page within the Locker UI. Mostly, this is a demonstration of how to put the ruby process lifetime at the mercy of the lockerd service loader, and how to launch sinatra based on the launch requirements of lockerd. There is a slight change to sinatra neccessary to have it return the data neededon successful launch; because of this the project currently uses [Bundler](http://gembundler.com/) to point at [Sinatra HEAD](https://github.com/sinatra/sinatra) on [GitHub](https://github.com). Sinatra 1.3.0 should include the neccessary changes. If you are unfamiliar with Bundler, simply: $ gem install bundler $ cd <path/to/HelloRuby> $ bundle install
{ "pile_set_name": "Github" }
# Makefile for libpng # Microsoft Visual C++ with Intel C/C++ Compiler 4.0 and later # Copyright (C) 2006, 2014 Glenn Randers-Pehrson # Copyright (C) 2000, Pawel Mrochen, based on makefile.msc which is # copyright 1995 Guy Eric Schalnat, Group 42, Inc. # # This code is released under the libpng license. # For conditions of distribution and use, see the disclaimer # and license in png.h # # To use, do "nmake /f scripts\makefile.intel" # # ------------------- Intel C/C++ Compiler 4.0 and later ------------------- # Where the zlib library and include files are located ZLIBLIB=..\zlib ZLIBINC=..\zlib # Target CPU CPU=6 # Pentium II #CPU=5 # Pentium # Calling convention CALLING=r # __fastcall #CALLING=z # __stdcall #CALLING=d # __cdecl # Uncomment next to put error messages in a file #ERRFILE=>>pngerrs # -------------------------------------------------------------------------- CC=icl -c CPPFLAGS=-I$(ZLIBINC) CFLAGS=-O2 -G$(CPU)$(CALLING) -Qip -Qunroll4 -nologo LD=link LDFLAGS=/SUBSYSTEM:CONSOLE /NOLOGO CP=cp # Pre-built configuration # See scripts\pnglibconf.mak for more options PNGLIBCONF_H_PREBUILT = scripts\pnglibconf.h.prebuilt O=.obj OBJS=png$(O) pngset$(O) pngget$(O) pngrutil$(O) pngtrans$(O) pngwutil$(O) \ pngmem$(O) pngpread$(O) pngread$(O) pngerror$(O) pngwrite$(O) \ pngrtran$(O) pngwtran$(O) pngrio$(O) pngwio$(O) all: test pnglibconf.h: $(PNGLIBCONF_H_PREBUILT) $(CP) $(PNGLIBCONF_H_PREBUILT) $@ png$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngset$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngget$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngread$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngpread$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngrtran$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngrutil$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngerror$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngmem$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngrio$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngwio$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngtrans$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngwrite$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngwtran$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) pngwutil$(O): png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) libpng.lib: $(OBJS) if exist libpng.lib del libpng.lib lib /NOLOGO /OUT:libpng.lib $(OBJS) pngtest.exe: pngtest.obj libpng.lib $(LD) $(LDFLAGS) /OUT:pngtest.exe pngtest.obj libpng.lib $(ZLIBLIB)\zlib.lib pngtest$(O): png.h pngconf.h pnglibconf.h $(CC) $(CPPFLAGS) $(CFLAGS) $*.c $(ERRFILE) test: pngtest.exe pngtest.exe # End of makefile for libpng
{ "pile_set_name": "Github" }
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "list -a", "program": "${workspaceFolder}/src/index.js", "args": ["list", "-a"], "env": { "DEBUG": "pgsh:*" } }, { "type": "node", "request": "launch", "name": "create hyphen-ated", "program": "${workspaceFolder}/src/index.js", "args": ["create", "hyphen-ated"], "env": { "DEBUG": "pgsh:*" } } ] }
{ "pile_set_name": "Github" }
/* Copyright: All contributers to the Umple Project This file is made available subject to the open source license found at: http://umple.org/license */ namespace cruise.umple.compiler; class RTCppGenerator { public void generate() { try { final StringBuilder code = new StringBuilder(); new UmpleCppPoliciesProcessor() { @Override public void handleGeneratedContents(List<ContentsDescriptor> contentsDescriptor) { try { for(ContentsDescriptor descriptor:contentsDescriptor){ generateContents(model, code, descriptor.getFileName(), descriptor.getContents(), descriptor.getPath()); } } catch (IOException e) { throw new UmpleCompilerException("There was a problem with generating classes. " + e, e); } } }.generateRootElement(model); model.setCode(code.toString()); } catch (Exception e) { throw new UmpleCompilerException("There was a problem with generating classes. " + e, e); } } protected void generateContents(UmpleModel model ,StringBuilder model_code, String filename, String content, String owingFolder) throws IOException { String path = model.getUmpleFile().getPath() + "/"; owingFolder= owingFolder.replace(".", "::").replace("::", "/"); String qualifiedPath = path+ owingFolder; File folder = new File(qualifiedPath); if (!folder.exists()) { folder.mkdirs(); } File folderFile = new File(qualifiedPath+ "/"+ filename); if (!folderFile.exists()) { folderFile.createNewFile(); } model.getGeneratedCode().put(filename,content); model_code.append(content); model_code.append("\n\n"); BufferedWriter output = new BufferedWriter(new FileWriter(folderFile)); output.write(content); output.close(); } }
{ "pile_set_name": "Github" }
<!doctype html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.8/d3.min.js" type="text/JavaScript"></script> <style> .link { stroke: #93C464; } marker { fill: #93C464; } </style> </head> <body> <div id="controls"> </div> <div id="viz"> <svg style="width:600px;height:600px;" ></svg> </div> <script> var roleScale = d3.scaleOrdinal() .domain(["contractor", "employee", "manager"]) .range(["#75739F", "#41A368", "#FE9922"]); var PromiseWrapper = d => new Promise(resolve => d3.csv(d, p => resolve(p))); Promise .all([ PromiseWrapper("../data/nodelist.csv"), PromiseWrapper("../data/edgelist.csv") ]) .then(resolve => { createForceLayout(resolve[0], resolve[1]); }); function createForceLayout(nodes,edges) { var marker = d3.select("svg").append('defs') .append('marker') .attr("id", "Triangle") .attr("refX", 12) .attr("refY", 6) .attr("markerUnits", 'userSpaceOnUse') .attr("markerWidth", 12) .attr("markerHeight", 18) .attr("orient", 'auto') .append('path') .attr("d", 'M 0 0 12 6 0 12 3 6'); var nodeHash = {}; nodes.forEach(node => { nodeHash[node.id] = node; }); edges.forEach(edge => { edge.weight = parseInt(edge.weight); edge.source = nodeHash[edge.source]; edge.target = nodeHash[edge.target]; }); nodes.forEach(d => { d.degreeCentrality = edges.filter( p => p.source === d || p.target === d).length }); console.log(nodes); var linkForce = d3.forceLink().strength(d => d.weight * .1); var simulation = d3.forceSimulation() .force("charge", d3.forceManyBody().strength(-500)) .force("x", d3.forceX(250)) .force("y", d3.forceY(250)) .force("link", linkForce) .nodes(nodes) .on("tick", forceTick); simulation.force("link").links(edges); d3.select("svg").selectAll("line.link") .data(edges, d => `${d.source.id}-${d.target.id}`) .enter() .append("line") .attr("class", "link") .style("opacity", .5) .style("stroke-width", d => d.weight); d3.selectAll("line").attr("marker-end", "url(#Triangle)"); var nodeEnter = d3.select("svg").selectAll("g.node") .data(nodes, d => d.id) .enter() .append("g") .attr("class", "node"); nodeEnter.append("circle") .attr("r", d => d.degreeCentrality * 2) .style("fill", d => roleScale(d.role)); nodeEnter.append("text") .style("text-anchor", "middle") .attr("y", 15) .text(d => d.id); d3.select("svg") .on("click", manuallyPositionNodes); function manuallyPositionNodes() { var xExtent = d3.extent(simulation.nodes(), d => parseInt(d.degreeCentrality)); var yExtent = d3.extent(simulation.nodes(), d => parseInt(d.salary)); var xScale = d3.scaleLinear().domain(xExtent).range([50,450]); var yScale = d3.scaleLinear().domain(yExtent).range([450,50]); simulation.stop(); d3.selectAll("g.node") .transition() .duration(1000) .attr("transform", d => `translate(${xScale(d.degreeCentrality)} , ${yScale(d.salary) })`); d3.selectAll("line.link") .transition() .duration(1000) .attr("x1", d => xScale(d.source.degreeCentrality)) .attr("y1", d => yScale(d.source.salary)) .attr("x2", d => xScale(d.target.degreeCentrality)) .attr("y2", d => yScale(d.target.salary)); var xAxis = d3.axisBottom().scale(xScale).tickSize(4); var yAxis = d3.axisRight().scale(yScale).tickSize(4); d3.select("svg").append("g").attr("transform", "translate(0,460)").call(xAxis); d3.select("svg").append("g").attr("transform", "translate(460,0)").call(yAxis); d3.selectAll("g.node").each(d => { d.x = xScale(d.degreeCentrality); d.vx = 0; d.y = yScale(d.salary); d.vy = 0; }); } function forceTick() { d3.selectAll("line.link") .attr("x1", d => d.source.x) .attr("x2", d => d.target.x) .attr("y1", d => d.source.y) .attr("y2", d => d.target.y); d3.selectAll("g.node") .attr("transform", d => `translate(${d.x},${d.y})`); } } </script> </body> </html>
{ "pile_set_name": "Github" }
/* Copyright (c) 2013 Gildas Lormeau. All rights reserved. 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. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc. * JZlib is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ (function(global) { "use strict"; // Global var MAX_BITS = 15; var D_CODES = 30; var BL_CODES = 19; var LENGTH_CODES = 29; var LITERALS = 256; var L_CODES = (LITERALS + 1 + LENGTH_CODES); var HEAP_SIZE = (2 * L_CODES + 1); var END_BLOCK = 256; // Bit length codes must not exceed MAX_BL_BITS bits var MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count) var REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) var REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) var REPZ_11_138 = 18; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. var Buf_size = 8 * 2; // JZlib version : "1.0.2" var Z_DEFAULT_COMPRESSION = -1; // compression strategy var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_DEFAULT_STRATEGY = 0; var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_BUF_ERROR = -5; // Tree // see definition of array dist_code below var _dist_code = [ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 ]; function Tree() { var that = this; // dyn_tree; // the dynamic tree // max_code; // largest code with non zero frequency // stat_desc; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit // length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. function gen_bitlen(s) { var tree = that.dyn_tree; var stree = that.stat_desc.static_tree; var extra = that.stat_desc.extra_bits; var base = that.stat_desc.extra_base; var max_length = that.stat_desc.max_length; var h; // heap index var n, m; // iterate over the tree elements var bits; // bit length var xbits; // extra bits var f; // frequency var overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = bits; // We overwrite tree[n*2+1] which is no longer needed if (n > that.max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n - base]; f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree) s.static_len += f * (stree[n * 2 + 1] + xbits); } if (overflow === 0) return; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] === 0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] += 2; // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > that.max_code) continue; if (tree[m * 2 + 1] != bits) { s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; tree[m * 2 + 1] = bits; } n--; } } } // Reverse the first len bits of a code, using straightforward code (a // faster // method would use a table) // IN assertion: 1 <= len <= 15 function bi_reverse(code, // the value to invert len // its bit length ) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. function gen_codes(tree, // the tree to decorate max_code, // largest code with non zero frequency bl_count // number of codes at each bit length ) { var next_code = []; // next code value for each // bit length var code = 0; // running code value var bits; // bit index var n; // code index var len; // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); // Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { len = tree[n * 2 + 1]; if (len === 0) continue; // Now reverse the bits tree[n * 2] = bi_reverse(next_code[len]++, len); } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. that.build_tree = function(s) { var tree = that.dyn_tree; var stree = that.stat_desc.static_tree; var elems = that.stat_desc.elems; var n, m; // iterate over heap elements var max_code = -1; // largest code with non zero frequency var node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } that.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = Math.floor(s.heap_len / 2); n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = (tree[n * 2] + tree[m * 2]); s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1; tree[n * 2 + 1] = tree[m * 2 + 1] = node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, that.max_code, s.bl_count); }; } Tree._length_code = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 ]; Tree.base_length = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 ]; Tree.base_dist = [ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 ]; // Mapping from a distance to a distance code. dist is the distance - 1 and // must not have side effects. _dist_code[256] and _dist_code[257] are never // used. Tree.d_code = function(dist) { return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]); }; // extra bits for each length code Tree.extra_lbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ]; // extra bits for each distance code Tree.extra_dbits = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ]; // extra bits for each bit length code Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ]; Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; // StaticTree function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) { var that = this; that.static_tree = static_tree; that.extra_bits = extra_bits; that.extra_base = extra_base; that.elems = elems; that.max_length = max_length; } StaticTree.static_ltree = [ 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8 ]; StaticTree.static_dtree = [ 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ]; StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS); StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); // Deflate var MAX_MEM_LEVEL = 9; var DEF_MEM_LEVEL = 8; function Config(good_length, max_lazy, nice_length, max_chain, func) { var that = this; that.good_length = good_length; that.max_lazy = max_lazy; that.nice_length = nice_length; that.max_chain = max_chain; that.func = func; } var STORED = 0; var FAST = 1; var SLOW = 2; var config_table = [ new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST), new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW), new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ]; var z_errmsg = [ "need dictionary", // Z_NEED_DICT // 2 "stream end", // Z_STREAM_END 1 "", // Z_OK 0 "", // Z_ERRNO (-1) "stream error", // Z_STREAM_ERROR (-2) "data error", // Z_DATA_ERROR (-3) "", // Z_MEM_ERROR (-4) "buffer error", // Z_BUF_ERROR (-5) "",// Z_VERSION_ERROR (-6) "" ]; // block not completed, need more input or more output var NeedMore = 0; // block flush performed var BlockDone = 1; // finish started, need only more output at next deflate var FinishStarted = 2; // finish done, accept no more input or output var FinishDone = 3; // preset dictionary flag in zlib header var PRESET_DICT = 0x20; var INIT_STATE = 42; var BUSY_STATE = 113; var FINISH_STATE = 666; // The deflate compression method var Z_DEFLATED = 8; var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); function smaller(tree, n, m, depth) { var tn2 = tree[n * 2]; var tm2 = tree[m * 2]; return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m])); } function Deflate() { var that = this; var strm; // pointer back to this zlib stream var status; // as the name implies // pending_buf; // output still pending var pending_buf_size; // size of pending_buf // pending_out; // next pending byte to output to the stream // pending; // nb of bytes in the pending buffer var method; // STORED (for zip only) or DEFLATED var last_flush; // value of flush param for previous deflate call var w_size; // LZ77 window size (32K by default) var w_bits; // log2(w_size) (8..16) var w_mask; // w_size - 1 var window; // Sliding window. Input bytes are read into the second half of the window, // and move to the first half later to keep a dictionary of at least wSize // bytes. With this organization, matches are limited to a distance of // wSize-MAX_MATCH bytes, but this ensures that IO is always // performed with a length multiple of the block size. Also, it limits // the window size to 64K, which is quite useful on MSDOS. // To do: use the user input buffer as sliding window. var window_size; // Actual size of window: 2*wSize, except when the user input buffer // is directly used as sliding window. var prev; // Link to older string with same hash index. To limit the size of this // array to 64K, this link is maintained only for the last 32K strings. // An index in this array is thus a window index modulo 32K. var head; // Heads of the hash chains or NIL. var ins_h; // hash index of string to be inserted var hash_size; // number of elements in hash table var hash_bits; // log2(hash_size) var hash_mask; // hash_size-1 // Number of bits by which ins_h must be shifted at each input // step. It must be such that after MIN_MATCH steps, the oldest // byte no longer takes part in the hash key, that is: // hash_shift * MIN_MATCH >= hash_bits var hash_shift; // Window position at the beginning of the current output block. Gets // negative when the window is moved backwards. var block_start; var match_length; // length of best match var prev_match; // previous match var match_available; // set if previous match exists var strstart; // start of string to insert var match_start; // start of matching string var lookahead; // number of valid bytes ahead in window // Length of the best match at previous step. Matches not greater than this // are discarded. This is used in the lazy match evaluation. var prev_length; // To speed up deflation, hash chains are never searched beyond this // length. A higher limit improves compression ratio but degrades the speed. var max_chain_length; // Attempt to find a better match only when the current match is strictly // smaller than this value. This mechanism is used only for compression // levels >= 4. var max_lazy_match; // Insert new strings in the hash table only if the match length is not // greater than this length. This saves time but degrades compression. // max_insert_length is used only for compression levels <= 3. var level; // compression level (1..9) var strategy; // favor or force Huffman coding // Use a faster search when the previous match is longer than this var good_match; // Stop searching when current match exceeds this var nice_match; var dyn_ltree; // literal and length tree var dyn_dtree; // distance tree var bl_tree; // Huffman tree for bit lengths var l_desc = new Tree(); // desc for literal tree var d_desc = new Tree(); // desc for distance tree var bl_desc = new Tree(); // desc for bit length tree // that.heap_len; // number of elements in the heap // that.heap_max; // element of largest frequency // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. // The same heap array is used to build all trees. // Depth of each subtree used as tie breaker for trees of equal frequency that.depth = []; var l_buf; // index for literals or lengths */ // Size of match buffer for literals/lengths. There are 4 reasons for // limiting lit_bufsize to 64K: // - frequencies can be kept in 16 bit counters // - if compression is not successful for the first block, all input // data is still in the window so we can still emit a stored block even // when input comes from standard input. (This can also be done for // all blocks if lit_bufsize is not greater than 32K.) // - if compression is not successful for a file smaller than 64K, we can // even emit a stored file instead of a stored block (saving 5 bytes). // This is applicable only for zip (not gzip or zlib). // - creating new Huffman trees less frequently may not provide fast // adaptation to changes in the input data statistics. (Take for // example a binary file with poorly compressible code followed by // a highly compressible string table.) Smaller buffer sizes give // fast adaptation but have of course the overhead of transmitting // trees more frequently. // - I can't count above 4 var lit_bufsize; var last_lit; // running index in l_buf // Buffer for distances. To simplify the code, d_buf and l_buf have // the same number of elements. To use different lengths, an extra flag // array would be necessary. var d_buf; // index of pendig_buf // that.opt_len; // bit length of current block with optimal trees // that.static_len; // bit length of current block with static trees var matches; // number of string matches in current block var last_eob_len; // bit length of EOB code for last block // Output buffer. bits are inserted starting at the bottom (least // significant bits). var bi_buf; // Number of valid bits in bi_buf. All bits above the last valid bit // are always zero. var bi_valid; // number of codes at each bit length for an optimal tree that.bl_count = []; // heap used to build the Huffman trees that.heap = []; dyn_ltree = []; dyn_dtree = []; bl_tree = []; function lm_init() { var i; window_size = 2 * w_size; head[hash_size - 1] = 0; for (i = 0; i < hash_size - 1; i++) { head[i] = 0; } // Set the default configuration parameters: max_lazy_match = config_table[level].max_lazy; good_match = config_table[level].good_length; nice_match = config_table[level].nice_length; max_chain_length = config_table[level].max_chain; strstart = 0; block_start = 0; lookahead = 0; match_length = prev_length = MIN_MATCH - 1; match_available = 0; ins_h = 0; } function init_block() { var i; // Initialize the trees. for (i = 0; i < L_CODES; i++) dyn_ltree[i * 2] = 0; for (i = 0; i < D_CODES; i++) dyn_dtree[i * 2] = 0; for (i = 0; i < BL_CODES; i++) bl_tree[i * 2] = 0; dyn_ltree[END_BLOCK * 2] = 1; that.opt_len = that.static_len = 0; last_lit = matches = 0; } // Initialize the tree data structures for a new zlib stream. function tr_init() { l_desc.dyn_tree = dyn_ltree; l_desc.stat_desc = StaticTree.static_l_desc; d_desc.dyn_tree = dyn_dtree; d_desc.stat_desc = StaticTree.static_d_desc; bl_desc.dyn_tree = bl_tree; bl_desc.stat_desc = StaticTree.static_bl_desc; bi_buf = 0; bi_valid = 0; last_eob_len = 8; // enough lookahead for inflate // Initialize the first block of the first file: init_block(); } // Restore the heap property by moving down the tree starting at node k, // exchanging a node with the smallest of its two sons if necessary, // stopping // when the heap property is re-established (each father smaller than its // two sons). that.pqdownheap = function(tree, // the tree to restore k // node to move down ) { var heap = that.heap; var v = heap[k]; var j = k << 1; // left son of k while (j <= that.heap_len) { // Set j to the smallest of the two sons: if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) { j++; } // Exit if v is smaller than both sons if (smaller(tree, v, heap[j], that.depth)) break; // Exchange v with the smallest son heap[k] = heap[j]; k = j; // And continue down the tree, setting j to the left son of k j <<= 1; } heap[k] = v; }; // Scan a literal or distance tree to determine the frequencies of the codes // in the bit length tree. function scan_tree(tree,// the tree to be scanned max_code // and its largest code of non zero frequency ) { var n; // iterates over all tree elements var prevlen = -1; // last emitted length var curlen; // length of current code var nextlen = tree[0 * 2 + 1]; // length of next code var count = 0; // repeat count of the current code var max_count = 7; // max repeat count var min_count = 4; // min repeat count if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1] = 0xffff; // guard for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { bl_tree[curlen * 2] += count; } else if (curlen !== 0) { if (curlen != prevlen) bl_tree[curlen * 2]++; bl_tree[REP_3_6 * 2]++; } else if (count <= 10) { bl_tree[REPZ_3_10 * 2]++; } else { bl_tree[REPZ_11_138 * 2]++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } // Construct the Huffman tree for the bit lengths and return the index in // bl_order of the last bit length code to send. function build_bl_tree() { var max_blindex; // index of last bit length code of non zero freq // Determine the bit length frequencies for literal and distance trees scan_tree(dyn_ltree, l_desc.max_code); scan_tree(dyn_dtree, d_desc.max_code); // Build the bit length tree: bl_desc.build_tree(that); // opt_len now includes the length of the tree representations, except // the lengths of the bit lengths codes and the 5+5+4 bits for the // counts. // Determine the number of bit length codes to send. The pkzip format // requires that at least 4 bit length codes be sent. (appnote.txt says // 3 but the actual value used is 4.) for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0) break; } // Update opt_len to include the bit length tree and counts that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; return max_blindex; } // Output a byte on the stream. // IN assertion: there is enough room in pending_buf. function put_byte(p) { that.pending_buf[that.pending++] = p; } function put_short(w) { put_byte(w & 0xff); put_byte((w >>> 8) & 0xff); } function putShortMSB(b) { put_byte((b >> 8) & 0xff); put_byte((b & 0xff) & 0xff); } function send_bits(value, length) { var val, len = length; if (bi_valid > Buf_size - len) { val = value; // bi_buf |= (val << bi_valid); bi_buf |= ((val << bi_valid) & 0xffff); put_short(bi_buf); bi_buf = val >>> (Buf_size - bi_valid); bi_valid += len - Buf_size; } else { // bi_buf |= (value) << bi_valid; bi_buf |= (((value) << bi_valid) & 0xffff); bi_valid += len; } } function send_code(c, tree) { var c2 = c * 2; send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff); } // Send a literal or distance tree in compressed form, using the codes in // bl_tree. function send_tree(tree,// the tree to be sent max_code // and its largest code of non zero frequency ) { var n; // iterates over all tree elements var prevlen = -1; // last emitted length var curlen; // length of current code var nextlen = tree[0 * 2 + 1]; // length of next code var count = 0; // repeat count of the current code var max_count = 7; // max repeat count var min_count = 4; // min repeat count if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(curlen, bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen != prevlen) { send_code(curlen, bl_tree); count--; } send_code(REP_3_6, bl_tree); send_bits(count - 3, 2); } else if (count <= 10) { send_code(REPZ_3_10, bl_tree); send_bits(count - 3, 3); } else { send_code(REPZ_11_138, bl_tree); send_bits(count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } // Send the header for a block using dynamic Huffman trees: the counts, the // lengths of the bit length codes, the literal tree and the distance tree. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. function send_all_trees(lcodes, dcodes, blcodes) { var rank; // index in bl_order send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt send_bits(dcodes - 1, 5); send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt for (rank = 0; rank < blcodes; rank++) { send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3); } send_tree(dyn_ltree, lcodes - 1); // literal tree send_tree(dyn_dtree, dcodes - 1); // distance tree } // Flush the bit buffer, keeping at most 7 bits in it. function bi_flush() { if (bi_valid == 16) { put_short(bi_buf); bi_buf = 0; bi_valid = 0; } else if (bi_valid >= 8) { put_byte(bi_buf & 0xff); bi_buf >>>= 8; bi_valid -= 8; } } // Send one empty static block to give enough lookahead for inflate. // This takes 10 bits, of which 7 may remain in the bit buffer. // The current inflate code requires 9 bits of lookahead. If the // last two codes for the previous block (real code plus EOB) were coded // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode // the last real code. In this case we send two empty static blocks instead // of one. (There are no problems if the previous block is stored or fixed.) // To simplify the code, we assume the worst case of last real code encoded // on one bit only. function _tr_align() { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.static_ltree); bi_flush(); // Of the 10 bits for the empty block, we have already sent // (10 - bi_valid) bits. The lookahead for the last real code (before // the EOB of the previous block) was thus at least one plus the length // of the EOB plus what we have just sent of the empty static block. if (1 + last_eob_len + 10 - bi_valid < 9) { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.static_ltree); bi_flush(); } last_eob_len = 7; } // Save the match info and tally the frequency counts. Return true if // the current block must be flushed. function _tr_tally(dist, // distance of matched string lc // match length-MIN_MATCH or unmatched char (if dist==0) ) { var out_length, in_length, dcode; that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff; that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff; that.pending_buf[l_buf + last_lit] = lc & 0xff; last_lit++; if (dist === 0) { // lc is the unmatched char dyn_ltree[lc * 2]++; } else { matches++; // Here, lc is the match length - MIN_MATCH dist--; // dist = match distance - 1 dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++; dyn_dtree[Tree.d_code(dist) * 2]++; } if ((last_lit & 0x1fff) === 0 && level > 2) { // Compute an upper bound for the compressed length out_length = last_lit * 8; in_length = strstart - block_start; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]); } out_length >>>= 3; if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2)) return true; } return (last_lit == lit_bufsize - 1); // We avoid equality with lit_bufsize because of wraparound at 64K // on 16 bit machines and because stored blocks are restricted to // 64K-1 bytes. } // Send the block data compressed using the given Huffman trees function compress_block(ltree, dtree) { var dist; // distance of matched string var lc; // match length or unmatched char (if dist === 0) var lx = 0; // running index in l_buf var code; // the code to send var extra; // number of extra bits to send if (last_lit !== 0) { do { dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff); lc = (that.pending_buf[l_buf + lx]) & 0xff; lx++; if (dist === 0) { send_code(lc, ltree); // send a literal byte } else { // Here, lc is the match length - MIN_MATCH code = Tree._length_code[lc]; send_code(code + LITERALS + 1, ltree); // send the length // code extra = Tree.extra_lbits[code]; if (extra !== 0) { lc -= Tree.base_length[code]; send_bits(lc, extra); // send the extra length bits } dist--; // dist is now the match distance - 1 code = Tree.d_code(dist); send_code(code, dtree); // send the distance code extra = Tree.extra_dbits[code]; if (extra !== 0) { dist -= Tree.base_dist[code]; send_bits(dist, extra); // send the extra distance bits } } // literal or match pair ? // Check that the overlay between pending_buf and d_buf+l_buf is // ok: } while (lx < last_lit); } send_code(END_BLOCK, ltree); last_eob_len = ltree[END_BLOCK * 2 + 1]; } // Flush the bit buffer and align the output on a byte boundary function bi_windup() { if (bi_valid > 8) { put_short(bi_buf); } else if (bi_valid > 0) { put_byte(bi_buf & 0xff); } bi_buf = 0; bi_valid = 0; } // Copy a stored block, storing first the length and its // one's complement if requested. function copy_block(buf, // the input data len, // its length header // true if block header must be written ) { bi_windup(); // align on byte boundary last_eob_len = 8; // enough lookahead for inflate if (header) { put_short(len); put_short(~len); } that.pending_buf.set(window.subarray(buf, buf + len), that.pending); that.pending += len; } // Send a stored block function _tr_stored_block(buf, // input block stored_len, // length of input block eof // true if this is the last block for a file ) { send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type copy_block(buf, stored_len, true); // with header } // Determine the best encoding for the current block: dynamic trees, static // trees or store, and output the encoded block to the zip file. function _tr_flush_block(buf, // input block, or NULL if too old stored_len, // length of input block eof // true if this is the last block for a file ) { var opt_lenb, static_lenb;// opt_len and static_len in bytes var max_blindex = 0; // index of last bit length code of non zero freq // Build the Huffman trees unless a stored block is forced if (level > 0) { // Construct the literal and distance trees l_desc.build_tree(that); d_desc.build_tree(that); // At this point, opt_len and static_len are the total bit lengths // of // the compressed block data, excluding the tree representations. // Build the bit length tree for the above two trees, and get the // index // in bl_order of the last bit length code to send. max_blindex = build_bl_tree(); // Determine the best encoding. Compute first the block length in // bytes opt_lenb = (that.opt_len + 3 + 7) >>> 3; static_lenb = (that.static_len + 3 + 7) >>> 3; if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { opt_lenb = static_lenb = stored_len + 5; // force a stored block } if ((stored_len + 4 <= opt_lenb) && buf != -1) { // 4: two words for the lengths // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. // Otherwise we can't have processed more than WSIZE input bytes // since // the last block flush, because compression would have been // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to // transform a block into a stored block. _tr_stored_block(buf, stored_len, eof); } else if (static_lenb == opt_lenb) { send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3); compress_block(StaticTree.static_ltree, StaticTree.static_dtree); } else { send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3); send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1); compress_block(dyn_ltree, dyn_dtree); } // The above check is made mod 2^32, for files larger than 512 MB // and uLong implemented on 32 bits. init_block(); if (eof) { bi_windup(); } } function flush_block_only(eof) { _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof); block_start = strstart; strm.flush_pending(); } // Fill the window when the lookahead becomes insufficient. // Updates strstart and lookahead. // // IN assertion: lookahead < MIN_LOOKAHEAD // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD // At least one byte has been read, or avail_in === 0; reads are // performed for at least two bytes (required for the zip translate_eol // option -- not supported here). function fill_window() { var n, m; var p; var more; // Amount of free space at the end of the window. do { more = (window_size - lookahead - strstart); // Deal with !@#$% 64K limit: if (more === 0 && strstart === 0 && lookahead === 0) { more = w_size; } else if (more == -1) { // Very unlikely, but possible on 16 bit machine if strstart == // 0 // and lookahead == 1 (input done one byte at time) more--; // If the window is almost full and there is insufficient // lookahead, // move the upper half to the lower one to make room in the // upper half. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) { window.set(window.subarray(w_size, w_size + w_size), 0); match_start -= w_size; strstart -= w_size; // we now have strstart >= MAX_DIST block_start -= w_size; // Slide the hash table (could be avoided with 32 bit values // at the expense of memory usage). We slide even when level == // 0 // to keep the hash table consistent if we switch back to level // > 0 // later. (Using level 0 permanently is not an optimal usage of // zlib, so we don't care about this pathological case.) n = hash_size; p = n; do { m = (head[--p] & 0xffff); head[p] = (m >= w_size ? m - w_size : 0); } while (--n !== 0); n = w_size; p = n; do { m = (prev[--p] & 0xffff); prev[p] = (m >= w_size ? m - w_size : 0); // If n is not on any hash chain, prev[n] is garbage but // its value will never be used. } while (--n !== 0); more += w_size; } if (strm.avail_in === 0) return; // If there was no sliding: // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && // more == window_size - lookahead - strstart // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) // => more >= window_size - 2*WSIZE + 2 // In the BIG_MEM or MMAP case (not yet supported), // window_size == input_size + MIN_LOOKAHEAD && // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. // Otherwise, window_size == 2*WSIZE so more >= 2. // If there was sliding, more >= WSIZE. So in all cases, more >= 2. n = strm.read_buf(window, strstart + lookahead, more); lookahead += n; // Initialize the hash value now that we have some input: if (lookahead >= MIN_MATCH) { ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; } // If the whole input has less than MIN_MATCH bytes, ins_h is // garbage, // but this is not important since only literal bytes will be // emitted. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0); } // Copy without compression as much as possible from the input stream, // return // the current block state. // This function does not insert new strings in the dictionary since // uncompressible data is probably not useful. This function is used // only for the level=0 compression option. // NOTE: this function should be optimized to avoid extra copying from // window to pending_buf. function deflate_stored(flush) { // Stored blocks are limited to 0xffff bytes, pending_buf is limited // to pending_buf_size, and each stored block has a 5 byte header: var max_block_size = 0xffff; var max_start; if (max_block_size > pending_buf_size - 5) { max_block_size = pending_buf_size - 5; } // Copy as much as possible from input to output: while (true) { // Fill the window as much as possible: if (lookahead <= 1) { fill_window(); if (lookahead === 0 && flush == Z_NO_FLUSH) return NeedMore; if (lookahead === 0) break; // flush the current block } strstart += lookahead; lookahead = 0; // Emit a stored block if pending_buf will be full: max_start = block_start + max_block_size; if (strstart === 0 || strstart >= max_start) { // strstart === 0 is possible when wraparound on 16-bit machine lookahead = (strstart - max_start); strstart = max_start; flush_block_only(false); if (strm.avail_out === 0) return NeedMore; } // Flush if we may have to slide, otherwise block_start may become // negative and the data will be gone: if (strstart - block_start >= w_size - MIN_LOOKAHEAD) { flush_block_only(false); if (strm.avail_out === 0) return NeedMore; } } flush_block_only(flush == Z_FINISH); if (strm.avail_out === 0) return (flush == Z_FINISH) ? FinishStarted : NeedMore; return flush == Z_FINISH ? FinishDone : BlockDone; } function longest_match(cur_match) { var chain_length = max_chain_length; // max hash chain length var scan = strstart; // current string var match; // matched string var len; // length of current match var best_len = prev_length; // best match length so far var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0; var _nice_match = nice_match; // Stop when cur_match becomes <= limit. To simplify the code, // we prevent matches with the string of window index 0. var wmask = w_mask; var strend = strstart + MAX_MATCH; var scan_end1 = window[scan + best_len - 1]; var scan_end = window[scan + best_len]; // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of // 16. // It is easy to get rid of this optimization if necessary. // Do not waste too much time if we already have a good match: if (prev_length >= good_match) { chain_length >>= 2; } // Do not look for matches beyond the end of the input. This is // necessary // to make deflate deterministic. if (_nice_match > lookahead) _nice_match = lookahead; do { match = cur_match; // Skip to next match if the match length cannot increase // or if the match length is less than 2: if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1]) continue; // The check at best_len-1 can be removed because it will be made // again later. (This heuristic is not always a win.) // It is not necessary to compare scan[2] and match[2] since they // are always equal when the other bytes match, given that // the hash keys are equal and that HASH_BITS >= 8. scan += 2; match++; // We check for insufficient lookahead only every 8th comparison; // the 256th check will be made at strstart+258. do { } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { match_start = cur_match; best_len = len; if (len >= _nice_match) break; scan_end1 = window[scan + best_len - 1]; scan_end = window[scan + best_len]; } } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0); if (best_len <= lookahead) return best_len; return lookahead; } // Compress as much as possible from the input stream, return the current // block state. // This function does not perform lazy evaluation of matches and inserts // new strings in the dictionary only for unmatched strings or for short // matches. It is used only for the fast compression options. function deflate_fast(flush) { // short hash_head = 0; // head of the hash chain var hash_head = 0; // head of the hash chain var bflush; // set if current block must be flushed while (true) { // Make sure that we always have enough lookahead, except // at the end of the input file. We need MAX_MATCH bytes // for the next match, plus MIN_MATCH bytes to insert the // string following the next match. if (lookahead < MIN_LOOKAHEAD) { fill_window(); if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return NeedMore; } if (lookahead === 0) break; // flush the current block } // Insert the string window[strstart .. strstart+2] in the // dictionary, and set hash_head to the head of the hash chain: if (lookahead >= MIN_MATCH) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = strstart; } // Find the longest match, discarding those <= prev_length. // At this point we have always match_length < MIN_MATCH if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { // To simplify the code, we prevent matches with the string // of window index 0 (in particular we have to avoid a match // of the string with itself at the start of the input file). if (strategy != Z_HUFFMAN_ONLY) { match_length = longest_match(hash_head); } // longest_match() sets match_start } if (match_length >= MIN_MATCH) { // check_match(strstart, match_start, match_length); bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH); lookahead -= match_length; // Insert new strings in the hash table only if the match length // is not too large. This saves time but degrades compression. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) { match_length--; // string at strstart already in hash table do { strstart++; ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = strstart; // strstart never exceeds WSIZE-MAX_MATCH, so there are // always MIN_MATCH bytes ahead. } while (--match_length !== 0); strstart++; } else { strstart += match_length; match_length = 0; ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; // If lookahead < MIN_MATCH, ins_h is garbage, but it does // not // matter since it will be recomputed at next deflate call. } } else { // No match, output a literal byte bflush = _tr_tally(0, window[strstart] & 0xff); lookahead--; strstart++; } if (bflush) { flush_block_only(false); if (strm.avail_out === 0) return NeedMore; } } flush_block_only(flush == Z_FINISH); if (strm.avail_out === 0) { if (flush == Z_FINISH) return FinishStarted; else return NeedMore; } return flush == Z_FINISH ? FinishDone : BlockDone; } // Same as above, but achieves better compression. We use a lazy // evaluation for matches: a match is finally adopted only if there is // no better match at the next window position. function deflate_slow(flush) { // short hash_head = 0; // head of hash chain var hash_head = 0; // head of hash chain var bflush; // set if current block must be flushed var max_insert; // Process the input block. while (true) { // Make sure that we always have enough lookahead, except // at the end of the input file. We need MAX_MATCH bytes // for the next match, plus MIN_MATCH bytes to insert the // string following the next match. if (lookahead < MIN_LOOKAHEAD) { fill_window(); if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return NeedMore; } if (lookahead === 0) break; // flush the current block } // Insert the string window[strstart .. strstart+2] in the // dictionary, and set hash_head to the head of the hash chain: if (lookahead >= MIN_MATCH) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = strstart; } // Find the longest match, discarding those <= prev_length. prev_length = match_length; prev_match = match_start; match_length = MIN_MATCH - 1; if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { // To simplify the code, we prevent matches with the string // of window index 0 (in particular we have to avoid a match // of the string with itself at the start of the input file). if (strategy != Z_HUFFMAN_ONLY) { match_length = longest_match(hash_head); } // longest_match() sets match_start if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) { // If prev_match is also MIN_MATCH, match_start is garbage // but we will ignore the current match anyway. match_length = MIN_MATCH - 1; } } // If there was a match at the previous step and the current // match is not better, output the previous match: if (prev_length >= MIN_MATCH && match_length <= prev_length) { max_insert = strstart + lookahead - MIN_MATCH; // Do not insert strings in hash table beyond this. // check_match(strstart-1, prev_match, prev_length); bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); // Insert in hash table all strings up to the end of the match. // strstart-1 and strstart are already inserted. If there is not // enough lookahead, the last two strings are not inserted in // the hash table. lookahead -= prev_length - 1; prev_length -= 2; do { if (++strstart <= max_insert) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = strstart; } } while (--prev_length !== 0); match_available = 0; match_length = MIN_MATCH - 1; strstart++; if (bflush) { flush_block_only(false); if (strm.avail_out === 0) return NeedMore; } } else if (match_available !== 0) { // If there was no match at the previous position, output a // single literal. If there was a match but the current match // is longer, truncate the previous match to a single literal. bflush = _tr_tally(0, window[strstart - 1] & 0xff); if (bflush) { flush_block_only(false); } strstart++; lookahead--; if (strm.avail_out === 0) return NeedMore; } else { // There is no previous match to compare with, wait for // the next step to decide. match_available = 1; strstart++; lookahead--; } } if (match_available !== 0) { bflush = _tr_tally(0, window[strstart - 1] & 0xff); match_available = 0; } flush_block_only(flush == Z_FINISH); if (strm.avail_out === 0) { if (flush == Z_FINISH) return FinishStarted; else return NeedMore; } return flush == Z_FINISH ? FinishDone : BlockDone; } function deflateReset(strm) { strm.total_in = strm.total_out = 0; strm.msg = null; // that.pending = 0; that.pending_out = 0; status = BUSY_STATE; last_flush = Z_NO_FLUSH; tr_init(); lm_init(); return Z_OK; } that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) { if (!_method) _method = Z_DEFLATED; if (!memLevel) memLevel = DEF_MEM_LEVEL; if (!_strategy) _strategy = Z_DEFAULT_STRATEGY; // byte[] my_version=ZLIB_VERSION; // // if (!version || version[0] != my_version[0] // || stream_size != sizeof(z_stream)) { // return Z_VERSION_ERROR; // } strm.msg = null; if (_level == Z_DEFAULT_COMPRESSION) _level = 6; if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } strm.dstate = that; w_bits = bits; w_size = 1 << w_bits; w_mask = w_size - 1; hash_bits = memLevel + 7; hash_size = 1 << hash_bits; hash_mask = hash_size - 1; hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH); window = new Uint8Array(w_size * 2); prev = []; head = []; lit_bufsize = 1 << (memLevel + 6); // 16K elements by default // We overlay pending_buf and d_buf+l_buf. This works since the average // output size for (length,distance) codes is <= 24 bits. that.pending_buf = new Uint8Array(lit_bufsize * 4); pending_buf_size = lit_bufsize * 4; d_buf = Math.floor(lit_bufsize / 2); l_buf = (1 + 2) * lit_bufsize; level = _level; strategy = _strategy; method = _method & 0xff; return deflateReset(strm); }; that.deflateEnd = function() { if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } // Deallocate in reverse order of allocations: that.pending_buf = null; head = null; prev = null; window = null; // free that.dstate = null; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; }; that.deflateParams = function(strm, _level, _strategy) { var err = Z_OK; if (_level == Z_DEFAULT_COMPRESSION) { _level = 6; } if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) { // Flush the last buffer: err = strm.deflate(Z_PARTIAL_FLUSH); } if (level != _level) { level = _level; max_lazy_match = config_table[level].max_lazy; good_match = config_table[level].good_length; nice_match = config_table[level].nice_length; max_chain_length = config_table[level].max_chain; } strategy = _strategy; return err; }; that.deflateSetDictionary = function(strm, dictionary, dictLength) { var length = dictLength; var n, index = 0; if (!dictionary || status != INIT_STATE) return Z_STREAM_ERROR; if (length < MIN_MATCH) return Z_OK; if (length > w_size - MIN_LOOKAHEAD) { length = w_size - MIN_LOOKAHEAD; index = dictLength - length; // use the tail of the dictionary } window.set(dictionary.subarray(index, index + length), 0); strstart = length; block_start = length; // Insert all strings in the hash table (except for the last two bytes). // s->lookahead stays null, so s->ins_h will be recomputed at the next // call of fill_window. ins_h = window[0] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask; for (n = 0; n <= length - MIN_MATCH; n++) { ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; prev[n & w_mask] = head[ins_h]; head[ins_h] = n; } return Z_OK; }; that.deflate = function(_strm, flush) { var i, header, level_flags, old_flush, bstate; if (flush > Z_FINISH || flush < 0) { return Z_STREAM_ERROR; } if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) { _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)]; return Z_STREAM_ERROR; } if (_strm.avail_out === 0) { _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } strm = _strm; // just in case old_flush = last_flush; last_flush = flush; // Write the zlib header if (status == INIT_STATE) { header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8; level_flags = ((level - 1) & 0xff) >> 1; if (level_flags > 3) level_flags = 3; header |= (level_flags << 6); if (strstart !== 0) header |= PRESET_DICT; header += 31 - (header % 31); status = BUSY_STATE; putShortMSB(header); } // Flush as much pending output as possible if (that.pending !== 0) { strm.flush_pending(); if (strm.avail_out === 0) { // console.log(" avail_out==0"); // Since avail_out is 0, deflate will be called again with // more output space, but possibly with both pending and // avail_in equal to zero. There won't be anything to do, // but this is not an error situation so make sure we // return OK instead of BUF_ERROR at next call of deflate: last_flush = -1; return Z_OK; } // Make sure there is something to do and avoid duplicate // consecutive // flushes. For repeated and useless calls with Z_FINISH, we keep // returning Z_STREAM_END instead of Z_BUFF_ERROR. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) { strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } // User must not provide more input after the first FINISH: if (status == FINISH_STATE && strm.avail_in !== 0) { _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } // Start a new block or continue the current one. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) { bstate = -1; switch (config_table[level].func) { case STORED: bstate = deflate_stored(flush); break; case FAST: bstate = deflate_fast(flush); break; case SLOW: bstate = deflate_slow(flush); break; default: } if (bstate == FinishStarted || bstate == FinishDone) { status = FINISH_STATE; } if (bstate == NeedMore || bstate == FinishStarted) { if (strm.avail_out === 0) { last_flush = -1; // avoid BUF_ERROR next call, see above } return Z_OK; // If flush != Z_NO_FLUSH && avail_out === 0, the next call // of deflate should use the same flush parameter to make sure // that the flush is complete. So we don't have to output an // empty block here, this will be done at next call. This also // ensures that for a very small output buffer, we emit at most // one empty block. } if (bstate == BlockDone) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(); } else { // FULL_FLUSH or SYNC_FLUSH _tr_stored_block(0, 0, false); // For a full flush, this empty block will be recognized // as a special marker by inflate_sync(). if (flush == Z_FULL_FLUSH) { // state.head[s.hash_size-1]=0; for (i = 0; i < hash_size/*-1*/; i++) // forget history head[i] = 0; } } strm.flush_pending(); if (strm.avail_out === 0) { last_flush = -1; // avoid BUF_ERROR at next call, see above return Z_OK; } } } if (flush != Z_FINISH) return Z_OK; return Z_STREAM_END; }; } // ZStream function ZStream() { var that = this; that.next_in_index = 0; that.next_out_index = 0; // that.next_in; // next input byte that.avail_in = 0; // number of bytes available at next_in that.total_in = 0; // total nb of input bytes read so far // that.next_out; // next output byte should be put there that.avail_out = 0; // remaining free space at next_out that.total_out = 0; // total nb of bytes output so far // that.msg; // that.dstate; } ZStream.prototype = { deflateInit : function(level, bits) { var that = this; that.dstate = new Deflate(); if (!bits) bits = MAX_BITS; return that.dstate.deflateInit(that, level, bits); }, deflate : function(flush) { var that = this; if (!that.dstate) { return Z_STREAM_ERROR; } return that.dstate.deflate(that, flush); }, deflateEnd : function() { var that = this; if (!that.dstate) return Z_STREAM_ERROR; var ret = that.dstate.deflateEnd(); that.dstate = null; return ret; }, deflateParams : function(level, strategy) { var that = this; if (!that.dstate) return Z_STREAM_ERROR; return that.dstate.deflateParams(that, level, strategy); }, deflateSetDictionary : function(dictionary, dictLength) { var that = this; if (!that.dstate) return Z_STREAM_ERROR; return that.dstate.deflateSetDictionary(that, dictionary, dictLength); }, // Read a new buffer from the current input stream, update the // total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). read_buf : function(buf, start, size) { var that = this; var len = that.avail_in; if (len > size) len = size; if (len === 0) return 0; that.avail_in -= len; buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start); that.next_in_index += len; that.total_in += len; return len; }, // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). flush_pending : function() { var that = this; var len = that.dstate.pending; if (len > that.avail_out) len = that.avail_out; if (len === 0) return; // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index + // len)) { // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " + // that.next_out_index + ", " + len); // console.log("avail_out=" + that.avail_out); // } that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index); that.next_out_index += len; that.dstate.pending_out += len; that.total_out += len; that.avail_out -= len; that.dstate.pending -= len; if (that.dstate.pending === 0) { that.dstate.pending_out = 0; } } }; // Deflater function Deflater(options) { var that = this; var z = new ZStream(); var bufsize = 512; var flush = Z_NO_FLUSH; var buf = new Uint8Array(bufsize); var level = options ? options.level : Z_DEFAULT_COMPRESSION; if (typeof level == "undefined") level = Z_DEFAULT_COMPRESSION; z.deflateInit(level); z.next_out = buf; that.append = function(data, onprogress) { var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array; if (!data.length) return; z.next_in_index = 0; z.next_in = data; z.avail_in = data.length; do { z.next_out_index = 0; z.avail_out = bufsize; err = z.deflate(flush); if (err != Z_OK) throw new Error("deflating: " + z.msg); if (z.next_out_index) if (z.next_out_index == bufsize) buffers.push(new Uint8Array(buf)); else buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index))); bufferSize += z.next_out_index; if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) { onprogress(z.next_in_index); lastIndex = z.next_in_index; } } while (z.avail_in > 0 || z.avail_out === 0); array = new Uint8Array(bufferSize); buffers.forEach(function(chunk) { array.set(chunk, bufferIndex); bufferIndex += chunk.length; }); return array; }; that.flush = function() { var err, buffers = [], bufferIndex = 0, bufferSize = 0, array; do { z.next_out_index = 0; z.avail_out = bufsize; err = z.deflate(Z_FINISH); if (err != Z_STREAM_END && err != Z_OK) throw new Error("deflating: " + z.msg); if (bufsize - z.avail_out > 0) buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index))); bufferSize += z.next_out_index; } while (z.avail_in > 0 || z.avail_out === 0); z.deflateEnd(); array = new Uint8Array(bufferSize); buffers.forEach(function(chunk) { array.set(chunk, bufferIndex); bufferIndex += chunk.length; }); return array; }; } // 'zip' may not be defined in z-worker and some tests var env = global.zip || global; env.Deflater = env._jzlib_Deflater = Deflater; })(this);
{ "pile_set_name": "Github" }
; RUN: opt < %s -gvn | llvm-dis target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128" target triple = "i386-apple-darwin7" %struct..4sPragmaType = type { i8*, i32 } %struct.AggInfo = type { i8, i8, i32, %struct.ExprList*, i32, %struct.AggInfo_col*, i32, i32, i32, %struct.AggInfo_func*, i32, i32 } %struct.AggInfo_col = type { %struct.Table*, i32, i32, i32, i32, %struct.Expr* } %struct.AggInfo_func = type { %struct.Expr*, %struct.FuncDef*, i32, i32 } %struct.AuxData = type { i8*, void (i8*)* } %struct.Bitvec = type { i32, i32, i32, { [125 x i32] } } %struct.BtCursor = type { %struct.Btree*, %struct.BtShared*, %struct.BtCursor*, %struct.BtCursor*, i32 (i8*, i32, i8*, i32, i8*)*, i8*, i32, %struct.MemPage*, i32, %struct.CellInfo, i8, i8, i8*, i64, i32, i8, i32* } %struct.BtLock = type { %struct.Btree*, i32, i8, %struct.BtLock* } %struct.BtShared = type { %struct.Pager*, %struct.sqlite3*, %struct.BtCursor*, %struct.MemPage*, i8, i8, i8, i8, i8, i8, i8, i8, i32, i16, i16, i32, i32, i32, i32, i8, i32, i8*, void (i8*)*, %struct.sqlite3_mutex*, %struct.BusyHandler, i32, %struct.BtShared*, %struct.BtLock*, %struct.Btree* } %struct.Btree = type { %struct.sqlite3*, %struct.BtShared*, i8, i8, i8, i32, %struct.Btree*, %struct.Btree* } %struct.BtreeMutexArray = type { i32, [11 x %struct.Btree*] } %struct.BusyHandler = type { i32 (i8*, i32)*, i8*, i32 } %struct.CellInfo = type { i8*, i64, i32, i32, i16, i16, i16, i16 } %struct.CollSeq = type { i8*, i8, i8, i8*, i32 (i8*, i32, i8*, i32, i8*)*, void (i8*)* } %struct.Column = type { i8*, %struct.Expr*, i8*, i8*, i8, i8, i8, i8 } %struct.Context = type { i64, i32, %struct.Fifo } %struct.CountCtx = type { i64 } %struct.Cursor = type { %struct.BtCursor*, i32, i64, i64, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i64, %struct.Btree*, i32, i8*, i64, i8*, %struct.KeyInfo*, i32, i64, %struct.sqlite3_vtab_cursor*, %struct.sqlite3_module*, i32, i32, i32*, i32*, i8* } %struct.Db = type { i8*, %struct.Btree*, i8, i8, i8*, void (i8*)*, %struct.Schema* } %struct.Expr = type { i8, i8, i16, %struct.CollSeq*, %struct.Expr*, %struct.Expr*, %struct.ExprList*, %struct..4sPragmaType, %struct..4sPragmaType, i32, i32, %struct.AggInfo*, i32, i32, %struct.Select*, %struct.Table*, i32 } %struct.ExprList = type { i32, i32, i32, %struct.ExprList_item* } %struct.ExprList_item = type { %struct.Expr*, i8*, i8, i8, i8 } %struct.FKey = type { %struct.Table*, %struct.FKey*, i8*, %struct.FKey*, i32, %struct.sColMap*, i8, i8, i8, i8 } %struct.Fifo = type { i32, %struct.FifoPage*, %struct.FifoPage* } %struct.FifoPage = type { i32, i32, i32, %struct.FifoPage*, [1 x i64] } %struct.FuncDef = type { i16, i8, i8, i8, i8*, %struct.FuncDef*, void (%struct.sqlite3_context*, i32, %struct.Mem**)*, void (%struct.sqlite3_context*, i32, %struct.Mem**)*, void (%struct.sqlite3_context*)*, [1 x i8] } %struct.Hash = type { i8, i8, i32, i32, %struct.HashElem*, %struct._ht* } %struct.HashElem = type { %struct.HashElem*, %struct.HashElem*, i8*, i8*, i32 } %struct.IdList = type { %struct..4sPragmaType*, i32, i32 } %struct.Index = type { i8*, i32, i32*, i32*, %struct.Table*, i32, i8, i8, i8*, %struct.Index*, %struct.Schema*, i8*, i8** } %struct.KeyInfo = type { %struct.sqlite3*, i8, i8, i8, i32, i8*, [1 x %struct.CollSeq*] } %struct.Mem = type { %struct.CountCtx, double, %struct.sqlite3*, i8*, i32, i16, i8, i8, void (i8*)* } %struct.MemPage = type { i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i16, i16, i16, i16, i16, i16, [5 x %struct._OvflCell], %struct.BtShared*, i8*, %struct.PgHdr*, i32, %struct.MemPage* } %struct.Module = type { %struct.sqlite3_module*, i8*, i8*, void (i8*)* } %struct.Op = type { i8, i8, i8, i8, i32, i32, i32, { i32 } } %struct.Pager = type { %struct.sqlite3_vfs*, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, %struct.Bitvec*, %struct.Bitvec*, i8*, i8*, i8*, i8*, %struct.sqlite3_file*, %struct.sqlite3_file*, %struct.sqlite3_file*, %struct.BusyHandler*, %struct.PagerLruList, %struct.PgHdr*, %struct.PgHdr*, %struct.PgHdr*, i64, i64, i64, i64, i64, i32, void (%struct.PgHdr*, i32)*, void (%struct.PgHdr*, i32)*, i32, %struct.PgHdr**, i8*, [16 x i8] } %struct.PagerLruLink = type { %struct.PgHdr*, %struct.PgHdr* } %struct.PagerLruList = type { %struct.PgHdr*, %struct.PgHdr*, %struct.PgHdr* } %struct.Parse = type { %struct.sqlite3*, i32, i8*, %struct.Vdbe*, i8, i8, i8, i8, i8, i8, i8, [8 x i32], i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, [12 x i32], i32, %struct.TableLock*, i32, i32, i32, i32, i32, %struct.Expr**, i8, %struct..4sPragmaType, %struct..4sPragmaType, %struct..4sPragmaType, i8*, i8*, %struct.Table*, %struct.Trigger*, %struct.TriggerStack*, i8*, %struct..4sPragmaType, i8, %struct.Table*, i32 } %struct.PgHdr = type { %struct.Pager*, i32, %struct.PgHdr*, %struct.PgHdr*, %struct.PagerLruLink, %struct.PgHdr*, i8, i8, i8, i8, i8, i16, %struct.PgHdr*, %struct.PgHdr*, i8* } %struct.Schema = type { i32, %struct.Hash, %struct.Hash, %struct.Hash, %struct.Hash, %struct.Table*, i8, i8, i16, i32, %struct.sqlite3* } %struct.Select = type { %struct.ExprList*, i8, i8, i8, i8, i8, i8, i8, %struct.SrcList*, %struct.Expr*, %struct.ExprList*, %struct.Expr*, %struct.ExprList*, %struct.Select*, %struct.Select*, %struct.Select*, %struct.Expr*, %struct.Expr*, i32, i32, [3 x i32] } %struct.SrcList = type { i16, i16, [1 x %struct.SrcList_item] } %struct.SrcList_item = type { i8*, i8*, i8*, %struct.Table*, %struct.Select*, i8, i8, i32, %struct.Expr*, %struct.IdList*, i64 } %struct.Table = type { i8*, i32, %struct.Column*, i32, %struct.Index*, i32, %struct.Select*, i32, %struct.Trigger*, %struct.FKey*, i8*, %struct.Expr*, i32, i8, i8, i8, i8, i8, i8, i8, %struct.Module*, %struct.sqlite3_vtab*, i32, i8**, %struct.Schema* } %struct.TableLock = type { i32, i32, i8, i8* } %struct.Trigger = type { i8*, i8*, i8, i8, %struct.Expr*, %struct.IdList*, %struct..4sPragmaType, %struct.Schema*, %struct.Schema*, %struct.TriggerStep*, %struct.Trigger* } %struct.TriggerStack = type { %struct.Table*, i32, i32, i32, i32, i32, i32, %struct.Trigger*, %struct.TriggerStack* } %struct.TriggerStep = type { i32, i32, %struct.Trigger*, %struct.Select*, %struct..4sPragmaType, %struct.Expr*, %struct.ExprList*, %struct.IdList*, %struct.TriggerStep*, %struct.TriggerStep* } %struct.Vdbe = type { %struct.sqlite3*, %struct.Vdbe*, %struct.Vdbe*, i32, i32, %struct.Op*, i32, i32, i32*, %struct.Mem**, %struct.Mem*, i32, %struct.Cursor**, i32, %struct.Mem*, i8**, i32, i32, i32, %struct.Mem*, i32, i32, %struct.Fifo, i32, i32, %struct.Context*, i32, i32, i32, i32, i32, [25 x i32], i32, i32, i8**, i8*, %struct.Mem*, i8, i8, i8, i8, i8, i8, i32, i64, i32, %struct.BtreeMutexArray, i32, i8*, i32 } %struct.VdbeFunc = type { %struct.FuncDef*, i32, [1 x %struct.AuxData] } %struct._OvflCell = type { i8*, i16 } %struct._ht = type { i32, %struct.HashElem* } %struct.anon = type { double } %struct.sColMap = type { i32, i8* } %struct.sqlite3 = type { %struct.sqlite3_vfs*, i32, %struct.Db*, i32, i32, i32, i32, i8, i8, i8, i8, i32, %struct.CollSeq*, i64, i64, i32, i32, i32, %struct.sqlite3_mutex*, %struct.sqlite3InitInfo, i32, i8**, %struct.Vdbe*, i32, void (i8*, i8*)*, i8*, void (i8*, i8*, i64)*, i8*, i8*, i32 (i8*)*, i8*, void (i8*)*, i8*, void (i8*, i32, i8*, i8*, i64)*, void (i8*, %struct.sqlite3*, i32, i8*)*, void (i8*, %struct.sqlite3*, i32, i8*)*, i8*, %struct.Mem*, i8*, i8*, %struct.anon, i32 (i8*, i32, i8*, i8*, i8*, i8*)*, i8*, i32 (i8*)*, i8*, i32, %struct.Hash, %struct.Table*, %struct.sqlite3_vtab**, i32, %struct.Hash, %struct.Hash, %struct.BusyHandler, i32, [2 x %struct.Db], i8 } %struct.sqlite3InitInfo = type { i32, i32, i8 } %struct.sqlite3_context = type { %struct.FuncDef*, %struct.VdbeFunc*, %struct.Mem, %struct.Mem*, i32, %struct.CollSeq* } %struct.sqlite3_file = type { %struct.sqlite3_io_methods* } %struct.sqlite3_index_constraint = type { i32, i8, i8, i32 } %struct.sqlite3_index_constraint_usage = type { i32, i8 } %struct.sqlite3_index_info = type { i32, %struct.sqlite3_index_constraint*, i32, %struct.sqlite3_index_constraint_usage*, %struct.sqlite3_index_constraint_usage*, i32, i8*, i32, i32, double } %struct.sqlite3_io_methods = type { i32, i32 (%struct.sqlite3_file*)*, i32 (%struct.sqlite3_file*, i8*, i32, i64)*, i32 (%struct.sqlite3_file*, i8*, i32, i64)*, i32 (%struct.sqlite3_file*, i64)*, i32 (%struct.sqlite3_file*, i32)*, i32 (%struct.sqlite3_file*, i64*)*, i32 (%struct.sqlite3_file*, i32)*, i32 (%struct.sqlite3_file*, i32)*, i32 (%struct.sqlite3_file*)*, i32 (%struct.sqlite3_file*, i32, i8*)*, i32 (%struct.sqlite3_file*)*, i32 (%struct.sqlite3_file*)* } %struct.sqlite3_module = type { i32, i32 (%struct.sqlite3*, i8*, i32, i8**, %struct.sqlite3_vtab**, i8**)*, i32 (%struct.sqlite3*, i8*, i32, i8**, %struct.sqlite3_vtab**, i8**)*, i32 (%struct.sqlite3_vtab*, %struct.sqlite3_index_info*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*, %struct.sqlite3_vtab_cursor**)*, i32 (%struct.sqlite3_vtab_cursor*)*, i32 (%struct.sqlite3_vtab_cursor*, i32, i8*, i32, %struct.Mem**)*, i32 (%struct.sqlite3_vtab_cursor*)*, i32 (%struct.sqlite3_vtab_cursor*)*, i32 (%struct.sqlite3_vtab_cursor*, %struct.sqlite3_context*, i32)*, i32 (%struct.sqlite3_vtab_cursor*, i64*)*, i32 (%struct.sqlite3_vtab*, i32, %struct.Mem**, i64*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*)*, i32 (%struct.sqlite3_vtab*, i32, i8*, void (%struct.sqlite3_context*, i32, %struct.Mem**)**, i8**)*, i32 (%struct.sqlite3_vtab*, i8*)* } %struct.sqlite3_mutex = type opaque %struct.sqlite3_vfs = type { i32, i32, i32, %struct.sqlite3_vfs*, i8*, i8*, i32 (%struct.sqlite3_vfs*, i8*, %struct.sqlite3_file*, i32, i32*)*, i32 (%struct.sqlite3_vfs*, i8*, i32)*, i32 (%struct.sqlite3_vfs*, i8*, i32)*, i32 (%struct.sqlite3_vfs*, i32, i8*)*, i32 (%struct.sqlite3_vfs*, i8*, i32, i8*)*, i8* (%struct.sqlite3_vfs*, i8*)*, void (%struct.sqlite3_vfs*, i32, i8*)*, i8* (%struct.sqlite3_vfs*, i8*, i8*)*, void (%struct.sqlite3_vfs*, i8*)*, i32 (%struct.sqlite3_vfs*, i32, i8*)*, i32 (%struct.sqlite3_vfs*, i32)*, i32 (%struct.sqlite3_vfs*, double*)* } %struct.sqlite3_vtab = type { %struct.sqlite3_module*, i32, i8* } %struct.sqlite3_vtab_cursor = type { %struct.sqlite3_vtab* } define fastcc void @sqlite3Insert(%struct.Parse* %pParse, %struct.SrcList* %pTabList, %struct.ExprList* %pList, %struct.Select* %pSelect, %struct.IdList* %pColumn, i32 %onError) nounwind { entry: br i1 false, label %bb54, label %bb69.loopexit bb54: ; preds = %entry br label %bb69.loopexit bb59: ; preds = %bb63.preheader %0 = load %struct..4sPragmaType** %3, align 4 ; <%struct..4sPragmaType*> [#uses=0] br label %bb65 bb65: ; preds = %bb63.preheader, %bb59 %1 = load %struct..4sPragmaType** %4, align 4 ; <%struct..4sPragmaType*> [#uses=0] br i1 false, label %bb67, label %bb63.preheader bb67: ; preds = %bb65 %2 = getelementptr %struct.IdList* %pColumn, i32 0, i32 0 ; <%struct..4sPragmaType**> [#uses=0] unreachable bb69.loopexit: ; preds = %bb54, %entry %3 = getelementptr %struct.IdList* %pColumn, i32 0, i32 0 ; <%struct..4sPragmaType**> [#uses=1] %4 = getelementptr %struct.IdList* %pColumn, i32 0, i32 0 ; <%struct..4sPragmaType**> [#uses=1] br label %bb63.preheader bb63.preheader: ; preds = %bb69.loopexit, %bb65 br i1 false, label %bb59, label %bb65 }
{ "pile_set_name": "Github" }
#ifndef CAFFE_SILENCE_LAYER_HPP_ #define CAFFE_SILENCE_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Ignores bottom blobs while producing no top blobs. (This is useful * to suppress outputs during testing.) */ template <typename Dtype> class SilenceLayer : public Layer<Dtype> { public: explicit SilenceLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "Silence"; } virtual inline int MinBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 0; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} // We can't define Forward_gpu here, since STUB_GPU will provide // its own definition for CPU_ONLY mode. virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); }; } // namespace caffe #endif // CAFFE_SILENCE_LAYER_HPP_
{ "pile_set_name": "Github" }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Protocol buffer comparison. package proto import ( "bytes" "log" "reflect" "strings" ) /* Equal returns true iff protocol buffers a and b are equal. The arguments must both be pointers to protocol buffer structs. Equality is defined in this way: - Two messages are equal iff they are the same type, corresponding fields are equal, unknown field sets are equal, and extensions sets are equal. - Two set scalar fields are equal iff their values are equal. If the fields are of a floating-point type, remember that NaN != x for all x, including NaN. If the message is defined in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, and their corresponding elements are equal. Note a "bytes" field, although represented by []byte, is not a repeated field and the rule for the scalar fields described above applies. - Two unset fields are equal. - Two unknown field sets are equal if their current encoded state is equal. - Two extension sets are equal iff they have corresponding elements that are pairwise equal. - Two map fields are equal iff their lengths are the same, and they contain the same set of elements. Zero-length map fields are equal. - Every other combination of things are not equal. The return value is undefined if a and b are not protocol buffers. */ func Equal(a, b Message) bool { if a == nil || b == nil { return a == b } v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) if v1.Type() != v2.Type() { return false } if v1.Kind() == reflect.Ptr { if v1.IsNil() { return v2.IsNil() } if v2.IsNil() { return false } v1, v2 = v1.Elem(), v2.Elem() } if v1.Kind() != reflect.Struct { return false } return equalStruct(v1, v2) } // v1 and v2 are known to have the same type. func equalStruct(v1, v2 reflect.Value) bool { sprop := GetProperties(v1.Type()) for i := 0; i < v1.NumField(); i++ { f := v1.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } f1, f2 := v1.Field(i), v2.Field(i) if f.Type.Kind() == reflect.Ptr { if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { // both unset continue } else if n1 != n2 { // set/unset mismatch return false } b1, ok := f1.Interface().(raw) if ok { b2 := f2.Interface().(raw) // RawMessage if !bytes.Equal(b1.Bytes(), b2.Bytes()) { return false } continue } f1, f2 = f1.Elem(), f2.Elem() } if !equalAny(f1, f2, sprop.Prop[i]) { return false } } if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_InternalExtensions") if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { return false } } if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_extensions") if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { return false } } uf := v1.FieldByName("XXX_unrecognized") if !uf.IsValid() { return true } u1 := uf.Bytes() u2 := v2.FieldByName("XXX_unrecognized").Bytes() if !bytes.Equal(u1, u2) { return false } return true } // v1 and v2 are known to have the same type. // prop may be nil. func equalAny(v1, v2 reflect.Value, prop *Properties) bool { if v1.Type() == protoMessageType { m1, _ := v1.Interface().(Message) m2, _ := v2.Interface().(Message) return Equal(m1, m2) } switch v1.Kind() { case reflect.Bool: return v1.Bool() == v2.Bool() case reflect.Float32, reflect.Float64: return v1.Float() == v2.Float() case reflect.Int32, reflect.Int64: return v1.Int() == v2.Int() case reflect.Interface: // Probably a oneof field; compare the inner values. n1, n2 := v1.IsNil(), v2.IsNil() if n1 || n2 { return n1 == n2 } e1, e2 := v1.Elem(), v2.Elem() if e1.Type() != e2.Type() { return false } return equalAny(e1, e2, nil) case reflect.Map: if v1.Len() != v2.Len() { return false } for _, key := range v1.MapKeys() { val2 := v2.MapIndex(key) if !val2.IsValid() { // This key was not found in the second map. return false } if !equalAny(v1.MapIndex(key), val2, nil) { return false } } return true case reflect.Ptr: // Maps may have nil values in them, so check for nil. if v1.IsNil() && v2.IsNil() { return true } if v1.IsNil() != v2.IsNil() { return false } return equalAny(v1.Elem(), v2.Elem(), prop) case reflect.Slice: if v1.Type().Elem().Kind() == reflect.Uint8 { // short circuit: []byte // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value. if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { return true } if v1.IsNil() != v2.IsNil() { return false } return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) } if v1.Len() != v2.Len() { return false } for i := 0; i < v1.Len(); i++ { if !equalAny(v1.Index(i), v2.Index(i), prop) { return false } } return true case reflect.String: return v1.Interface().(string) == v2.Interface().(string) case reflect.Struct: return equalStruct(v1, v2) case reflect.Uint32, reflect.Uint64: return v1.Uint() == v2.Uint() } // unknown type, so not a protocol buffer log.Printf("proto: don't know how to compare %v", v1) return false } // base is the struct type that the extensions are based on. // x1 and x2 are InternalExtensions. func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { em1, _ := x1.extensionsRead() em2, _ := x2.extensionsRead() return equalExtMap(base, em1, em2) } func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { if len(em1) != len(em2) { return false } for extNum, e1 := range em1 { e2, ok := em2[extNum] if !ok { return false } m1, m2 := e1.value, e2.value if m1 != nil && m2 != nil { // Both are unencoded. if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } continue } // At least one is encoded. To do a semantically correct comparison // we need to unmarshal them first. var desc *ExtensionDesc if m := extensionMaps[base]; m != nil { desc = m[extNum] } if desc == nil { log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) continue } var err error if m1 == nil { m1, err = decodeExtension(e1.enc, desc) } if m2 == nil && err == nil { m2, err = decodeExtension(e2.enc, desc) } if err != nil { // The encoded form is invalid. log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) return false } if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } } return true }
{ "pile_set_name": "Github" }
predicate fzn_mdd_nondet_reif(array[int] of var int: x, % variables constrained by MDD int: N, % number of nodes root is node 1 array[int] of int: level, % level of each node root is level 1, T is level length(x)+1 int: E, % number of edges array[int] of int: from, % edge leaving node 1..N array[int] of set of int: label, % value of variable array[int] of int: to, % edge entering node 0..N where 0 = T node var bool: b % reification value ) = let { set of int: NODE = 1..N; set of int: EDGE = 1..E; int: L = length(x); array[0..N] of var bool: bn; array[EDGE] of var bool: be; set of int: D = dom_array(x); } in bn[0] /\ % true node is true (b <-> bn[1]) /\ % root gives truth value % T1 each node except the root enforces an outgoing edge forall(n in NODE)(bn[n] -> exists(e in EDGE where from[e] = n)(be[e])) /\ % T23 each edge enforces its endpoints forall(e in EDGE)((be[e] -> bn[from[e]]) /\ (be[e] -> bn[to[e]])) /\ % T4 each edge enforces its label forall(e in EDGE)(be[e] -> x[level[from[e]]] in label[e]) /\ % P2 each node except the root enforces an incoming edge exists(e in EDGE where to[e] = 0)(be[e]) /\ forall(n in 2..N)(bn[n] -> exists(e in EDGE where to[e] = n)(be[e])) /\ % P3 each label has a support forall(i in 1..L, d in D) (x[i] = d -> exists(e in EDGE where level[from[e]] = i /\ d in label[e])(be[e]));
{ "pile_set_name": "Github" }
// Code generated by linux/mkall.go generatePtracePair("arm", "arm64"). DO NOT EDIT. // +build linux // +build arm arm64 package unix import "unsafe" // PtraceRegsArm is the registers used by arm binaries. type PtraceRegsArm struct { Uregs [18]uint32 } // PtraceGetRegsArm fetches the registers used by arm binaries. func PtraceGetRegsArm(pid int, regsout *PtraceRegsArm) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegsArm sets the registers used by arm binaries. func PtraceSetRegsArm(pid int, regs *PtraceRegsArm) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) } // PtraceRegsArm64 is the registers used by arm64 binaries. type PtraceRegsArm64 struct { Regs [31]uint64 Sp uint64 Pc uint64 Pstate uint64 } // PtraceGetRegsArm64 fetches the registers used by arm64 binaries. func PtraceGetRegsArm64(pid int, regsout *PtraceRegsArm64) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegsArm64 sets the registers used by arm64 binaries. func PtraceSetRegsArm64(pid int, regs *PtraceRegsArm64) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) }
{ "pile_set_name": "Github" }
# perf script event handlers, generated by perf script -g perl # (c) 2009, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Basically, if this script runs successfully and # displays expected results, perl scripting support should be ok. use lib "$ENV{'PERF_EXEC_PATH'}/scripts/perl/Perf-Trace-Util/lib"; use lib "./Perf-Trace-Util/lib"; use Perf::Trace::Core; use Perf::Trace::Context; use Perf::Trace::Util; sub trace_begin { print "trace_begin\n"; } sub trace_end { print "trace_end\n"; print_unhandled(); } sub irq::softirq_entry { my ($event_name, $context, $common_cpu, $common_secs, $common_nsecs, $common_pid, $common_comm, $vec) = @_; print_header($event_name, $common_cpu, $common_secs, $common_nsecs, $common_pid, $common_comm); print_uncommon($context); printf("vec=%s\n", symbol_str("irq::softirq_entry", "vec", $vec)); } sub kmem::kmalloc { my ($event_name, $context, $common_cpu, $common_secs, $common_nsecs, $common_pid, $common_comm, $call_site, $ptr, $bytes_req, $bytes_alloc, $gfp_flags) = @_; print_header($event_name, $common_cpu, $common_secs, $common_nsecs, $common_pid, $common_comm); print_uncommon($context); printf("call_site=%p, ptr=%p, bytes_req=%u, bytes_alloc=%u, ". "gfp_flags=%s\n", $call_site, $ptr, $bytes_req, $bytes_alloc, flag_str("kmem::kmalloc", "gfp_flags", $gfp_flags)); } # print trace fields not included in handler args sub print_uncommon { my ($context) = @_; printf("common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, ", common_pc($context), trace_flag_str(common_flags($context)), common_lock_depth($context)); } my %unhandled; sub print_unhandled { if ((scalar keys %unhandled) == 0) { return; } print "\nunhandled events:\n\n"; printf("%-40s %10s\n", "event", "count"); printf("%-40s %10s\n", "----------------------------------------", "-----------"); foreach my $event_name (keys %unhandled) { printf("%-40s %10d\n", $event_name, $unhandled{$event_name}); } } sub trace_unhandled { my ($event_name, $context, $common_cpu, $common_secs, $common_nsecs, $common_pid, $common_comm) = @_; $unhandled{$event_name}++; } sub print_header { my ($event_name, $cpu, $secs, $nsecs, $pid, $comm) = @_; printf("%-20s %5u %05u.%09u %8u %-20s ", $event_name, $cpu, $secs, $nsecs, $pid, $comm); }
{ "pile_set_name": "Github" }
#include "ui/menudef.h" #include "ui/menumacros.h" // Defines // #define WINDOW_X 0 #define WINDOW_Y 0 #define WINDOW_WIDTH __WINDOW_WIDTH #define WINDOW_HEIGHT 480 #define GROUP_NAME "grpPopupRemoveFavorite" // Add Favorite Menu // menuDef { name "popupRemoveFavorite" visible 0 fullscreen 0 rect WINDOW_X WINDOW_Y WINDOW_WIDTH WINDOW_HEIGHT style WINDOW_STYLE_FILLED popup fadeClamp 0.5 fadeAmount 0.075 onOpen { setitemcolor background backcolor 0 0 0 0 ; fadein background } onESC { close popupRemoveFavorite ; open ingame_main } // Background // itemDef { name "background" rect 0 0 WINDOW_WIDTH 480 style WINDOW_STYLE_FILLED background "ui/assets/fadebox.tga" backcolor 0 0 0 0 visible 1 decoration } // Subwindows // #define SUBWINDOW_WIDTH 250 #define SUBWINDOW_HEIGHT 80 #define SUBWINDOW_X .5*(WINDOW_WIDTH-SUBWINDOW_WIDTH) #define SUBWINDOW_Y .5*(WINDOW_HEIGHT-SUBWINDOW_HEIGHT) SUBWINDOWBLACK( SUBWINDOW_X, SUBWINDOW_Y, SUBWINDOW_WIDTH, SUBWINDOW_HEIGHT, _("REMOVE FAVORITE") ) LABEL( SUBWINDOW_X+2, SUBWINDOW_Y+16, (SUBWINDOW_WIDTH)-4, 10, _("Remove this server from your favorites?"), .2, ITEM_ALIGN_CENTER, .5*((SUBWINDOW_WIDTH)-4), 8 ) // note: this isn't set for listen servers CVARLABEL( SUBWINDOW_X+2, SUBWINDOW_Y+34, (SUBWINDOW_WIDTH)-4, 10, "cl_currentServerIP", .2, ITEM_ALIGN_CENTER, .5*((SUBWINDOW_WIDTH)-4), 8 ) BUTTON( SUBWINDOW_X+6, SUBWINDOW_Y+SUBWINDOW_HEIGHT-24, .5*(SUBWINDOW_WIDTH-18), 18, _("YES"), .3, 14, uiScript removeFavoriteIngame ; close popupRemoveFavorite ; open ingame_main ) BUTTON( SUBWINDOW_X+6+.5*(SUBWINDOW_WIDTH-18)+6, SUBWINDOW_Y+SUBWINDOW_HEIGHT-24, .5*(SUBWINDOW_WIDTH-18), 18, _("NO"), .3, 14, close popupRemoveFavorite ; open ingame_main ) }
{ "pile_set_name": "Github" }
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ #include "itkImageRegionSplitterMultidimensional.h" #include "itkImageRegion.h" #include "itkTestingMacros.h" #include <iostream> int itkImageRegionSplitterMultidimensionalTest(int, char *[]) { itk::ImageRegionSplitterMultidimensional::Pointer splitter = itk::ImageRegionSplitterMultidimensional::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(splitter, ImageRegionSplitterMultidimensional, ImageRegionSplitterBase); itk::ImageRegion<2> region; region.SetSize(0, 10); region.SetSize(1, 11); region.SetIndex(0, 1); region.SetIndex(1, 10); const itk::ImageRegion<2> lpRegion = region; ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 1), 1); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 2), 2); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 3), 2); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 4), 4); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 7), 6); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 11), 9); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 12), 12); ITK_TEST_EXPECT_EQUAL(splitter->GetNumberOfSplits(lpRegion, 99), 90); region = lpRegion; splitter->GetSplit(0, 2, region); ITK_TEST_EXPECT_EQUAL(region.GetSize(0), 10); ITK_TEST_EXPECT_EQUAL(region.GetSize(1), 5); region = lpRegion; splitter->GetSplit(1, 2, region); ITK_TEST_EXPECT_EQUAL(region.GetSize(0), 10); ITK_TEST_EXPECT_EQUAL(region.GetSize(1), 6); region = lpRegion; splitter->GetSplit(0, 4, region); ITK_TEST_EXPECT_EQUAL(region.GetIndex(0), 1); ITK_TEST_EXPECT_EQUAL(region.GetIndex(1), 10); ITK_TEST_EXPECT_EQUAL(region.GetSize(0), 5); ITK_TEST_EXPECT_EQUAL(region.GetSize(1), 5); region = lpRegion; splitter->GetSplit(3, 4, region); ITK_TEST_EXPECT_EQUAL(region.GetIndex(0), 6); ITK_TEST_EXPECT_EQUAL(region.GetIndex(1), 15); ITK_TEST_EXPECT_EQUAL(region.GetSize(0), 5); ITK_TEST_EXPECT_EQUAL(region.GetSize(1), 6); return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
/** Ultra Light */ @font-face { font-family: "San Francisco"; font-weight: 100; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-ultralight-webfont.woff"); } /** Thin */ @font-face { font-family: "San Francisco"; font-weight: 200; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-thin-webfont.woff"); } /** Regular */ @font-face { font-family: "San Francisco"; font-weight: 400; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-regular-webfont.woff"); } /** Medium */ @font-face { font-family: "San Francisco"; font-weight: 500; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-medium-webfont.woff"); } /** Semi Bold */ @font-face { font-family: "San Francisco"; font-weight: 600; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-semibold-webfont.woff"); } /** Bold */ @font-face { font-family: "San Francisco"; font-weight: 700; src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-bold-webfont.woff"); }
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIDkTCCAnmgAwIBAgIBAjANBgkqhkiG9w0BAQsFADAXMRUwEwYDVQQDDAxUZXN0 IE5DIENBIDEwIBcNMTgwNTE2MDI0MDA0WhgPMjExODA1MTcwMjQwMDRaMIGeMSMw IQYDVQQKDBpHb29kIE5DIFRlc3QgQ2VydGlmaWNhdGUgMTEVMBMGA1UEAwwMd3d3 Lmdvb2Qub3JnMRUwEwYDVQQDDAxhbnkuZ29vZC5jb20xETAPBgNVBAMMCG5vdC4u ZG5zMRAwDgYDVQQDDAdub3RAZG5zMREwDwYDVQQDDAhub3QtLmRuczERMA8GA1UE AwwIbm90LmRucy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDDigxI nlYVjHtrFI+Iv/3b0jeZbs1jVnPF6ZREk46BTNAVNZsq24jKFG6yK4n9vKA/JuS7 jZe+gMX+sWh/S1IlsNDY8/Io1UsG/s1tmsvE2UrURUX4s8HnqB6AZ4Y9Cp4rSADe mD/YdekRf3HFA0IKQvIFRkpegj8uuWwILC0n/ozMNUlNmxCBlOmtFwjFxmNr9Txa ZeFvWvvc6oTubAETK4HcjLdimx1tePdd4+0mxJ/akQ3wVzUAI2ysijMmMJDzTxLs FPkw4yUtJHK0/H2yJtpoJ4wQjsWd6a8F7wY/pHszAud1M8QZJKQDzkJOMnqLKNLT OKw6dm1UG2J7iuqtAgMBAAGjXjBcMB0GA1UdDgQWBBSTKvqap2ab0z/UPrdDgc0V m88R3TAfBgNVHSMEGDAWgBQI0Zv55tVkcKDxaxqe7VLa3fVQQzAJBgNVHRMEAjAA MA8GA1UdEQQIMAaHBMCoAAEwDQYJKoZIhvcNAQELBQADggEBADcdm62qaOHbIDoa 5oUjXGHSQjV1g4BFe6DLH5/CZ0wOws3QzfQbPIxJrp3yJgDcQyZNOE/xQlq/nASS thU6cUTB07voFVnbotB8YQuNU1wM9TAJOHC9LT1Y0J2GIP6QeXts6Cz6aBlqaQEZ IrGRLuKVZePTO0Haup0mZ91XoXs3CBzkSerl0XpFL7BeugSigrhprFRPB4UC3IWb pdNar61Wk4bN/COb6utRkK3iYk5YUTqYFib9EG4VBdxYfXv/tiBIGqQLnqPbId6w q+McpSEPF1DIcCyL0vEDdIVN0SzxMfnfHMx0Qp0sh2aydIZk4xfEqXHZgZthSrse u7nhn7s= -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
@model Kooboo.CMS.Sites.Models.View @{ ViewBag.Title = "New view".Localize(); Layout = "~/Views/Shared/Blank.cshtml"; } @section Panel{ <ul class="panel"> <li> <a data-ajaxform=""> @Html.IconImage("save") @("Save".Localize())</a> </li> @foreach (var group in Kooboo.CMS.Sites.Extension.UI.TopToolbar.ToolbarButtons.GetToolbarButtons(ViewContext.RequestContext)) { @Html.Partial("_ToolbarGroupButtons", group) } <li> <a href="@ViewContext.RequestContext.GetRequestValue("return")"> @Html.IconImage("cancel") @("Back".Localize())</a> </li> </ul> } @using (Html.BeginForm()) { <div class="topbar"> <h1 class="title left">@ViewBag.Title</h1> <p class="field left"> @Html.EditorFor(m => m.Name, new { Layout = "_NoLabel.cshtml" }) </p> </div> <div class="common-form fixed"> @Html.ValidationSummary(true) @Html.Hidden("SiteName", ViewContext.RequestContext.GetRequestValue("SiteName")) @Html.Partial("TemplateEditor", Model) </div> } @Html.Partial("View.Script")
{ "pile_set_name": "Github" }
#ifndef L1GlobalTrigger_L1GlobalTriggerEvmReadoutRecord_h #define L1GlobalTrigger_L1GlobalTriggerEvmReadoutRecord_h /** * \class L1GlobalTriggerEvmReadoutRecord * * * Description: EVM readout record for L1 Global Trigger. * * Implementation: * <TODO: enter implementation details> * * \author: Vasile Mihai Ghete - HEPHY Vienna * * */ // system include files #include <string> #include <vector> #include <iosfwd> // user include files #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtfeWord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtfeExtWord.h" #include "DataFormats/L1GlobalTrigger/interface/L1TcsWord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtFdlWord.h" // forward declarations // class interface class L1GlobalTriggerEvmReadoutRecord { public: /// constructors L1GlobalTriggerEvmReadoutRecord(); L1GlobalTriggerEvmReadoutRecord(int NumberBxInEvent); L1GlobalTriggerEvmReadoutRecord(const int numberBxInEvent, const int numberFdlBoards); /// copy constructor L1GlobalTriggerEvmReadoutRecord(const L1GlobalTriggerEvmReadoutRecord&); /// destructor virtual ~L1GlobalTriggerEvmReadoutRecord(); /// assignment operator L1GlobalTriggerEvmReadoutRecord& operator=(const L1GlobalTriggerEvmReadoutRecord&); /// equal operator bool operator==(const L1GlobalTriggerEvmReadoutRecord&) const; /// unequal operator bool operator!=(const L1GlobalTriggerEvmReadoutRecord&) const; public: /// get Global Trigger decision and the decision word /// overloaded w.r.t. bxInEvent argument /// bxInEvent not given: for bunch cross with L1Accept const bool decision(int bxInEvent) const; const DecisionWord decisionWord(int bxInEvent) const; const bool decision() const; const DecisionWord decisionWord() const; /// set global decision and the decision word void setDecision(bool t, int bxInEvent); void setDecisionWord(const DecisionWord& decisionWordValue, int bxInEvent); void setDecision(bool t); void setDecisionWord(const DecisionWord& decisionWordValue); /// print global decision and algorithm decision word void printGtDecision(std::ostream& myCout, int bxInEventValue) const; void printGtDecision(std::ostream& myCout) const; /// print technical triggers void printTechnicalTrigger(std::ostream& myCout, int bxInEventValue) const; void printTechnicalTrigger(std::ostream& myCout) const; //************************************************************************** // get/set hardware-related words // // Board description: file GlobalTriggerBoardsMapper.dat // TODO xml file instead? //************************************************************************** /// get / set GTFE word (record) in the GT readout record const L1GtfeExtWord gtfeWord() const; void setGtfeWord(const L1GtfeExtWord&); /// get / set TCS word (record) in the GT readout record const L1TcsWord tcsWord() const; void setTcsWord(const L1TcsWord&); /// get the vector of L1GtFdlWord const std::vector<L1GtFdlWord> gtFdlVector() const { return m_gtFdlWord; } std::vector<L1GtFdlWord>& gtFdlVector() { return m_gtFdlWord; } /// get / set FDL word (record) in the GT readout record const L1GtFdlWord gtFdlWord(int bxInEvent) const; const L1GtFdlWord gtFdlWord() const; void setGtFdlWord(const L1GtFdlWord&, int bxInEvent); void setGtFdlWord(const L1GtFdlWord&); // other methods /// clear the record void reset(); /// pretty print the content of a L1GlobalTriggerEvmReadoutRecord void print(std::ostream& myCout) const; /// output stream operator friend std::ostream& operator<<(std::ostream&, const L1GlobalTriggerEvmReadoutRecord&); private: L1GtfeExtWord m_gtfeWord; L1TcsWord m_tcsWord; std::vector<L1GtFdlWord> m_gtFdlWord; }; #endif
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <random> // template<class IntType = int> // class negative_binomial_distribution // template <class charT, class traits> // basic_ostream<charT, traits>& // operator<<(basic_ostream<charT, traits>& os, // const negative_binomial_distribution& x); // // template <class charT, class traits> // basic_istream<charT, traits>& // operator>>(basic_istream<charT, traits>& is, // negative_binomial_distribution& x); #include <random> #include <sstream> #include <cassert> #include "test_macros.h" int main(int, char**) { { typedef std::negative_binomial_distribution<> D; D d1(7, .25); std::ostringstream os; os << d1; std::istringstream is(os.str()); D d2; is >> d2; assert(d1 == d2); } return 0; }
{ "pile_set_name": "Github" }
package zmaster587.advancedRocketry.world.biome; import net.minecraft.block.BlockFlower.EnumFlowerType; import net.minecraft.block.material.Material; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.MapGenBase; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import zmaster587.advancedRocketry.world.gen.WorldGenNoTree; import zmaster587.advancedRocketry.world.gen.WorldGenSwampTree; import java.util.Random; public class BiomeGenDeepSwamp extends Biome { public static MapGenBase swampTree; private final static WorldGenNoTree noTree = new WorldGenNoTree(false); public BiomeGenDeepSwamp(int biomeId, boolean register) { super(new BiomeProperties("DeepSwamp").setBaseHeight(-0.1f).setHeightVariation(0.2f).setRainfall(0.9f).setTemperature(0.9f).setWaterColor(14745518)); this.setRegistryName(new ResourceLocation("advancedrocketry:DeepSwamp")); this.decorator.treesPerChunk = 10; this.decorator.flowersPerChunk = 1; this.decorator.deadBushPerChunk = 1; this.decorator.mushroomsPerChunk = 8; this.decorator.reedsPerChunk = 10; this.decorator.clayPerChunk = 1; this.decorator.waterlilyPerChunk = 4; this.decorator.sandPatchesPerChunk = 0; this.decorator.grassPerChunk = 5; this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntitySlime.class, 1, 1, 1)); this.flowers.clear(); this.addFlower(Blocks.RED_FLOWER.getDefaultState(), 10); swampTree = new WorldGenSwampTree(2); } @Override @SideOnly(Side.CLIENT) public int getSkyColorByTemp(float p_76731_1_) { return 0x203020; } @Override public WorldGenAbstractTree getRandomTreeFeature(Random rand) { return this.SWAMP_FEATURE; } @Override public EnumFlowerType pickRandomFlower(Random rand, BlockPos pos) { return EnumFlowerType.BLUE_ORCHID; } @Override public void genTerrainBlocks(World worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) { double d0 = GRASS_COLOR_NOISE.getValue((double)x * 0.25D, (double)z * 0.25D); if (d0 > 0.0D) { int i = x & 15; int j = z & 15; for (int k = 255; k >= 0; --k) { if (chunkPrimerIn.getBlockState(j, k, i).getMaterial() != Material.AIR) { if (k == 62 && chunkPrimerIn.getBlockState(j, k, i).getBlock() != Blocks.WATER) { chunkPrimerIn.setBlockState(j, k, i, WATER); if (d0 < 0.12D) { chunkPrimerIn.setBlockState(j, k + 1, i, Blocks.WATERLILY.getDefaultState()); } } break; } } } this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, x, z, noiseVal); //Decoration time takes too long due to block relights, so run at terrain gen time ///swampTree.func_151539_a(null, world, x, z, block); //Arg 1 never actually used so fake it //Yes this is hacky if(x % 16 == 0 && z % 16 == 0 ) swampTree.generate(worldIn, x/16, z/16, chunkPrimerIn); } /** * Provides the basic grass color based on the biome temperature and rainfall */ @SideOnly(Side.CLIENT) public int getBiomeGrassColor(int x, int y, int z) { double d0 = GRASS_COLOR_NOISE.getValue((double)x * 0.25D, (double)z * 0.25D); return d0 < -0.1D ? 5011004 : 6975545; } /** * Provides the basic foliage color based on the biome temperature and rainfall */ @SideOnly(Side.CLIENT) public int getBiomeFoliageColor(int p_150571_1_, int p_150571_2_, int p_150571_3_) { return 6975545; } }
{ "pile_set_name": "Github" }
This patch (1.poly.synth) is a polyphonic subtractive synthesizer with a dozen or so voice parameters you can control live or via presets. Four presets are defined. To test, recall a preset (you should see numbers pop up in all the parameter controls) start the metronome and turn up the output volume to around 100.
{ "pile_set_name": "Github" }
function CVShapeElement(data, globalData, comp) { this.shapes = []; this.shapesData = data.shapes; this.stylesList = []; this.itemsData = []; this.prevViewData = []; this.shapeModifiers = []; this.processedElements = []; this.transformsManager = new ShapeTransformManager(); this.initElement(data, globalData, comp); } extendPrototype([BaseElement,TransformElement,CVBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableElement], CVShapeElement); CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement; CVShapeElement.prototype.transformHelper = {opacity:1,_opMdf:false}; CVShapeElement.prototype.dashResetter = []; CVShapeElement.prototype.createContent = function(){ this.searchShapes(this.shapesData,this.itemsData,this.prevViewData, true, []); }; CVShapeElement.prototype.createStyleElement = function(data, transforms) { var styleElem = { data: data, type: data.ty, preTransforms: this.transformsManager.addTransformSequence(transforms), transforms: [], elements: [], closed: data.hd === true }; var elementData = {}; if(data.ty == 'fl' || data.ty == 'st'){ elementData.c = PropertyFactory.getProp(this,data.c,1,255,this); if(!elementData.c.k){ styleElem.co = 'rgb('+bm_floor(elementData.c.v[0])+','+bm_floor(elementData.c.v[1])+','+bm_floor(elementData.c.v[2])+')'; } } else if (data.ty === 'gf' || data.ty === 'gs') { elementData.s = PropertyFactory.getProp(this,data.s,1,null,this); elementData.e = PropertyFactory.getProp(this,data.e,1,null,this); elementData.h = PropertyFactory.getProp(this,data.h||{k:0},0,0.01,this); elementData.a = PropertyFactory.getProp(this,data.a||{k:0},0,degToRads,this); elementData.g = new GradientProperty(this,data.g,this); } elementData.o = PropertyFactory.getProp(this,data.o,0,0.01,this); if(data.ty == 'st' || data.ty == 'gs') { styleElem.lc = this.lcEnum[data.lc] || 'round'; styleElem.lj = this.ljEnum[data.lj] || 'round'; if(data.lj == 1) { styleElem.ml = data.ml; } elementData.w = PropertyFactory.getProp(this,data.w,0,null,this); if(!elementData.w.k){ styleElem.wi = elementData.w.v; } if(data.d){ var d = new DashProperty(this,data.d,'canvas', this); elementData.d = d; if(!elementData.d.k){ styleElem.da = elementData.d.dashArray; styleElem.do = elementData.d.dashoffset[0]; } } } else { styleElem.r = data.r === 2 ? 'evenodd' : 'nonzero'; } this.stylesList.push(styleElem); elementData.style = styleElem; return elementData; }; CVShapeElement.prototype.createGroupElement = function(data) { var elementData = { it: [], prevViewData: [] }; return elementData; }; CVShapeElement.prototype.createTransformElement = function(data) { var elementData = { transform : { opacity: 1, _opMdf:false, key: this.transformsManager.getNewKey(), op: PropertyFactory.getProp(this,data.o,0,0.01,this), mProps: TransformPropertyFactory.getTransformProperty(this,data,this) } }; return elementData; }; CVShapeElement.prototype.createShapeElement = function(data) { var elementData = new CVShapeData(this, data, this.stylesList, this.transformsManager); this.shapes.push(elementData); this.addShapeToModifiers(elementData); return elementData; }; CVShapeElement.prototype.reloadShapes = function() { this._isFirstFrame = true; var i, len = this.itemsData.length; for (i = 0; i < len; i += 1) { this.prevViewData[i] = this.itemsData[i]; } this.searchShapes(this.shapesData,this.itemsData,this.prevViewData, true, []); len = this.dynamicProperties.length; for (i = 0; i < len; i += 1) { this.dynamicProperties[i].getValue(); } this.renderModifiers(); this.transformsManager.processSequences(this._isFirstFrame); }; CVShapeElement.prototype.addTransformToStyleList = function(transform) { var i, len = this.stylesList.length; for (i = 0; i < len; i += 1) { if(!this.stylesList[i].closed) { this.stylesList[i].transforms.push(transform); } } } CVShapeElement.prototype.removeTransformFromStyleList = function() { var i, len = this.stylesList.length; for (i = 0; i < len; i += 1) { if(!this.stylesList[i].closed) { this.stylesList[i].transforms.pop(); } } } CVShapeElement.prototype.closeStyles = function(styles) { var i, len = styles.length, j, jLen; for (i = 0; i < len; i += 1) { styles[i].closed = true; } } CVShapeElement.prototype.searchShapes = function(arr,itemsData, prevViewData, shouldRender, transforms){ var i, len = arr.length - 1; var j, jLen; var ownStyles = [], ownModifiers = [], processedPos, modifier, currentTransform; var ownTransforms = [].concat(transforms); for(i=len;i>=0;i-=1){ processedPos = this.searchProcessedElement(arr[i]); if(!processedPos){ arr[i]._shouldRender = shouldRender; } else { itemsData[i] = prevViewData[processedPos - 1]; } if(arr[i].ty == 'fl' || arr[i].ty == 'st'|| arr[i].ty == 'gf'|| arr[i].ty == 'gs'){ if(!processedPos){ itemsData[i] = this.createStyleElement(arr[i], ownTransforms); } else { itemsData[i].style.closed = false; } ownStyles.push(itemsData[i].style); }else if(arr[i].ty == 'gr'){ if(!processedPos){ itemsData[i] = this.createGroupElement(arr[i]); } else { jLen = itemsData[i].it.length; for(j=0;j<jLen;j+=1){ itemsData[i].prevViewData[j] = itemsData[i].it[j]; } } this.searchShapes(arr[i].it,itemsData[i].it,itemsData[i].prevViewData, shouldRender, ownTransforms); }else if(arr[i].ty == 'tr'){ if(!processedPos){ currentTransform = this.createTransformElement(arr[i]); itemsData[i] = currentTransform; } ownTransforms.push(itemsData[i]); this.addTransformToStyleList(itemsData[i]); }else if(arr[i].ty == 'sh' || arr[i].ty == 'rc' || arr[i].ty == 'el' || arr[i].ty == 'sr'){ if(!processedPos){ itemsData[i] = this.createShapeElement(arr[i]); } }else if(arr[i].ty == 'tm' || arr[i].ty == 'rd' || arr[i].ty == 'pb'){ if(!processedPos){ modifier = ShapeModifiers.getModifier(arr[i].ty); modifier.init(this,arr[i]); itemsData[i] = modifier; this.shapeModifiers.push(modifier); } else { modifier = itemsData[i]; modifier.closed = false; } ownModifiers.push(modifier); } else if(arr[i].ty == 'rp'){ if(!processedPos){ modifier = ShapeModifiers.getModifier(arr[i].ty); itemsData[i] = modifier; modifier.init(this,arr,i,itemsData); this.shapeModifiers.push(modifier); shouldRender = false; }else{ modifier = itemsData[i]; modifier.closed = true; } ownModifiers.push(modifier); } this.addProcessedElement(arr[i], i + 1); } this.removeTransformFromStyleList(); this.closeStyles(ownStyles); len = ownModifiers.length; for(i=0;i<len;i+=1){ ownModifiers[i].closed = true; } }; CVShapeElement.prototype.renderInnerContent = function() { this.transformHelper.opacity = 1; this.transformHelper._opMdf = false; this.renderModifiers(); this.transformsManager.processSequences(this._isFirstFrame); this.renderShape(this.transformHelper,this.shapesData,this.itemsData,true); }; CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) { var props, groupMatrix; if(parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) { groupTransform.opacity = parentTransform.opacity; groupTransform.opacity *= groupTransform.op.v; groupTransform._opMdf = true; } }; CVShapeElement.prototype.drawLayer = function() { var i, len = this.stylesList.length; var j, jLen, k, kLen,elems,nodes, renderer = this.globalData.renderer, ctx = this.globalData.canvasContext, type, currentStyle; for(i=0;i<len;i+=1){ currentStyle = this.stylesList[i]; type = currentStyle.type; //Skipping style when //Stroke width equals 0 //style should not be rendered (extra unused repeaters) //current opacity equals 0 //global opacity equals 0 if(((type === 'st' || type === 'gs') && currentStyle.wi === 0) || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0){ continue; } renderer.save(); elems = currentStyle.elements; if(type === 'st' || type === 'gs'){ ctx.strokeStyle = type === 'st' ? currentStyle.co : currentStyle.grd; ctx.lineWidth = currentStyle.wi; ctx.lineCap = currentStyle.lc; ctx.lineJoin = currentStyle.lj; ctx.miterLimit = currentStyle.ml || 0; } else { ctx.fillStyle = type === 'fl' ? currentStyle.co : currentStyle.grd; } renderer.ctxOpacity(currentStyle.coOp); if(type !== 'st' && type !== 'gs'){ ctx.beginPath(); } renderer.ctxTransform(currentStyle.preTransforms.finalTransform.props); jLen = elems.length; for(j=0;j<jLen;j+=1){ if(type === 'st' || type === 'gs'){ ctx.beginPath(); if(currentStyle.da){ ctx.setLineDash(currentStyle.da); ctx.lineDashOffset = currentStyle.do; } } nodes = elems[j].trNodes; kLen = nodes.length; for(k=0;k<kLen;k+=1){ if(nodes[k].t == 'm'){ ctx.moveTo(nodes[k].p[0],nodes[k].p[1]); }else if(nodes[k].t == 'c'){ ctx.bezierCurveTo(nodes[k].pts[0],nodes[k].pts[1],nodes[k].pts[2],nodes[k].pts[3],nodes[k].pts[4],nodes[k].pts[5]); }else{ ctx.closePath(); } } if(type === 'st' || type === 'gs'){ ctx.stroke(); if(currentStyle.da){ ctx.setLineDash(this.dashResetter); } } } if(type !== 'st' && type !== 'gs'){ ctx.fill(currentStyle.r); } renderer.restore(); } }; CVShapeElement.prototype.renderShape = function(parentTransform,items,data,isMain){ var i, len = items.length - 1; var groupTransform; groupTransform = parentTransform; for(i=len;i>=0;i-=1){ if(items[i].ty == 'tr'){ groupTransform = data[i].transform; this.renderShapeTransform(parentTransform, groupTransform); }else if(items[i].ty == 'sh' || items[i].ty == 'el' || items[i].ty == 'rc' || items[i].ty == 'sr'){ this.renderPath(items[i],data[i]); }else if(items[i].ty == 'fl'){ this.renderFill(items[i],data[i],groupTransform); }else if(items[i].ty == 'st'){ this.renderStroke(items[i],data[i],groupTransform); }else if(items[i].ty == 'gf' || items[i].ty == 'gs'){ this.renderGradientFill(items[i],data[i],groupTransform); }else if(items[i].ty == 'gr'){ this.renderShape(groupTransform,items[i].it,data[i].it); }else if(items[i].ty == 'tm'){ // } } if(isMain){ this.drawLayer(); } }; CVShapeElement.prototype.renderStyledShape = function(styledShape, shape){ if(this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) { var shapeNodes = styledShape.trNodes; var paths = shape.paths; var i, len, j, jLen = paths._length; shapeNodes.length = 0; var groupTransformMat = styledShape.transforms.finalTransform; for (j = 0; j < jLen; j += 1) { var pathNodes = paths.shapes[j]; if(pathNodes && pathNodes.v){ len = pathNodes._length; for (i = 1; i < len; i += 1) { if (i === 1) { shapeNodes.push({ t: 'm', p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) }); } shapeNodes.push({ t: 'c', pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i]) }); } if (len === 1) { shapeNodes.push({ t: 'm', p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) }); } if (pathNodes.c && len) { shapeNodes.push({ t: 'c', pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0]) }); shapeNodes.push({ t: 'z' }); } } } styledShape.trNodes = shapeNodes; } } CVShapeElement.prototype.renderPath = function(pathData,itemData){ if(pathData.hd !== true && pathData._shouldRender) { var i, len = itemData.styledShapes.length; for (i = 0; i < len; i += 1) { this.renderStyledShape(itemData.styledShapes[i], itemData.sh); } } }; CVShapeElement.prototype.renderFill = function(styleData,itemData, groupTransform){ var styleElem = itemData.style; if (itemData.c._mdf || this._isFirstFrame) { styleElem.co = 'rgb(' + bm_floor(itemData.c.v[0]) + ',' + bm_floor(itemData.c.v[1]) + ',' + bm_floor(itemData.c.v[2]) + ')'; } if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { styleElem.coOp = itemData.o.v * groupTransform.opacity; } }; CVShapeElement.prototype.renderGradientFill = function(styleData,itemData, groupTransform){ var styleElem = itemData.style; if(!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || (styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf))) { var ctx = this.globalData.canvasContext; var grd; var pt1 = itemData.s.v, pt2 = itemData.e.v; if (styleData.t === 1) { grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]); } else { var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); var percent = itemData.h.v >= 1 ? 0.99 : itemData.h.v <= -1 ? -0.99: itemData.h.v; var dist = rad * percent; var x = Math.cos(ang + itemData.a.v) * dist + pt1[0]; var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; var grd = ctx.createRadialGradient(x, y, 0, pt1[0], pt1[1], rad); } var i, len = styleData.g.p; var cValues = itemData.g.c; var opacity = 1; for (i = 0; i < len; i += 1){ if(itemData.g._hasOpacity && itemData.g._collapsable) { opacity = itemData.g.o[i*2 + 1]; } grd.addColorStop(cValues[i * 4] / 100,'rgba('+ cValues[i * 4 + 1] + ',' + cValues[i * 4 + 2] + ','+cValues[i * 4 + 3] + ',' + opacity + ')'); } styleElem.grd = grd; } styleElem.coOp = itemData.o.v*groupTransform.opacity; }; CVShapeElement.prototype.renderStroke = function(styleData,itemData, groupTransform){ var styleElem = itemData.style; var d = itemData.d; if(d && (d._mdf || this._isFirstFrame)){ styleElem.da = d.dashArray; styleElem.do = d.dashoffset[0]; } if(itemData.c._mdf || this._isFirstFrame){ styleElem.co = 'rgb('+bm_floor(itemData.c.v[0])+','+bm_floor(itemData.c.v[1])+','+bm_floor(itemData.c.v[2])+')'; } if(itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame){ styleElem.coOp = itemData.o.v*groupTransform.opacity; } if(itemData.w._mdf || this._isFirstFrame){ styleElem.wi = itemData.w.v; } }; CVShapeElement.prototype.destroy = function(){ this.shapesData = null; this.globalData = null; this.canvasContext = null; this.stylesList.length = 0; this.itemsData.length = 0; };
{ "pile_set_name": "Github" }
'use strict'; module.exports = require('./shim');
{ "pile_set_name": "Github" }
#!/bin/bash # # pagekite Startup script for the PageKite background service # # chkconfig: - 85 15 # description: PageKite makes localhost servers publicly visible. # processname: pagekite # config: /etc/pagekite.d/50_daemonize.rc # config: /etc/pagekite.d/10_account.rc # pidfile: /var/run/pagekite.pid # Source function library. . /etc/rc.d/init.d/functions if [ -f /etc/sysconfig/pagekite ]; then . /etc/sysconfig/pagekite fi # Start PageKite in the C locale by default. PK_LANG=${PK_LANG-"C"} # Path to the server binary, and short-form for messages. pk=/usr/bin/pagekite prog=pagekite pidfile=${PIDFILE-/var/run/pagekite.pid} lockfile=${LOCKFILE-/var/lock/subsys/pagekite} RETVAL=0 # Exit if package is unconfigured grep -c ^abort_not_configured /etc/pagekite.d/10_account.rc \ 2>/dev/null >/dev/null && exit 0 # Check for 0.3-style configuration check03x () { CONFFILE=/etc/pagekite/local.rc # FIXME true } start() { echo -n $"Starting $prog: " check03x || exit 1 touch $PK_LOGFILE chown -R $PK_UID:$PK_GID $(dirname $PK_LOGFILE) LANG=$PK_LANG daemon --pidfile=${pidfile} \ $pk --clean \ --runas=$PK_UID:$PK_GID \ --logfile=$PK_LOGFILE \ --pidfile=${pidfile} $OPTIONS \ --daemonize RETVAL=$? echo [ $RETVAL = 0 ] && touch ${lockfile} return $RETVAL } stop() { echo -n $"Stopping $prog: " killproc -p ${pidfile} $pk RETVAL=$? echo [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile} } # See how we were called. case "$1" in start) start ;; stop) stop ;; status) status -p ${pidfile} $pk RETVAL=$? ;; restart|reload) stop start ;; condrestart) if [ -f ${pidfile} ] ; then stop start fi ;; *) echo $"Usage: $prog {start|stop|restart|condrestart|reload|status}" exit 1 esac exit $RETVAL
{ "pile_set_name": "Github" }
.close { float: right; font-size: $close-font-size; font-weight: $close-font-weight; line-height: 1; color: $close-color; text-shadow: $close-text-shadow; opacity: .5; @include hover-focus { color: $close-color; text-decoration: none; opacity: .75; } // Opinionated: add "hand" cursor to non-disabled .close elements &:not(:disabled):not(.disabled) { cursor: pointer; } } // Additional properties for button version // iOS requires the button element instead of an anchor tag. // If you want the anchor version, it requires `href="#"`. // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile // stylelint-disable property-no-vendor-prefix, selector-no-qualifying-type button.close { padding: 0; background-color: transparent; border: 0; -webkit-appearance: none; } // stylelint-enable
{ "pile_set_name": "Github" }
/*! ***************************************************************************** Copyright (C) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ // NOTE: This file is obsolete and may be removed in a later release. // For CommonJS/AMD/UMD/SystemJS declarations please use 'index.d.ts'. // For standalone browser declarations, please use 'standalone.d.ts'. /// <reference path="./Reflect.d.ts" />
{ "pile_set_name": "Github" }
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import redirect from indico.modules.admin import RHAdminBase from indico.modules.legal import legal_settings from indico.modules.legal.forms import LegalMessagesForm from indico.modules.legal.views import WPDisplayPrivacyPolicy, WPDisplayTOS, WPManageLegalMessages from indico.web.flask.util import url_for from indico.web.rh import RH class RHManageLegalMessages(RHAdminBase): def _process(self): form = LegalMessagesForm(**legal_settings.get_all()) if form.validate_on_submit(): legal_settings.set_multi(form.data) return redirect(url_for('legal.manage')) return WPManageLegalMessages.render_template('manage_messages.html', 'legal_messages', form=form) class RHDisplayTOS(RH): def _process(self): url = legal_settings.get('tos_url') if url: return redirect(url) return WPDisplayTOS.render_template('tos.html', tos=legal_settings.get('tos')) class RHDisplayPrivacyPolicy(RH): def _process(self): url = legal_settings.get('privacy_policy_url') if url: return redirect(url) return WPDisplayPrivacyPolicy.render_template('privacy.html', content=legal_settings.get('privacy_policy'))
{ "pile_set_name": "Github" }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ScrollView * @flow */ 'use strict'; var EdgeInsetsPropType = require('EdgeInsetsPropType'); var Platform = require('Platform'); var PointPropType = require('PointPropType'); var RCTScrollView = require('NativeModules').UIManager.RCTScrollView; var RCTScrollViewConsts = RCTScrollView.Constants; var React = require('React'); var ReactIOSViewAttributes = require('ReactIOSViewAttributes'); var RCTUIManager = require('NativeModules').UIManager; var ScrollResponder = require('ScrollResponder'); var StyleSheet = require('StyleSheet'); var StyleSheetPropType = require('StyleSheetPropType'); var View = require('View'); var ViewStylePropTypes = require('ViewStylePropTypes'); var createReactIOSNativeComponentClass = require('createReactIOSNativeComponentClass'); var deepDiffer = require('deepDiffer'); var flattenStyle = require('flattenStyle'); var insetsDiffer = require('insetsDiffer'); var invariant = require('invariant'); var pointsDiffer = require('pointsDiffer'); var requireNativeComponent = require('requireNativeComponent'); var PropTypes = React.PropTypes; var SCROLLVIEW = 'ScrollView'; var INNERVIEW = 'InnerScrollView'; var keyboardDismissModeConstants = { 'none': RCTScrollViewConsts.KeyboardDismissMode.None, // default 'interactive': RCTScrollViewConsts.KeyboardDismissMode.Interactive, 'onDrag': RCTScrollViewConsts.KeyboardDismissMode.OnDrag, }; /** * Component that wraps platform ScrollView while providing * integration with touch locking "responder" system. * * Doesn't yet support other contained responders from blocking this scroll * view from becoming the responder. */ var ScrollView = React.createClass({ propTypes: { automaticallyAdjustContentInsets: PropTypes.bool, // true contentInset: EdgeInsetsPropType, // zeros contentOffset: PointPropType, // zeros onScroll: PropTypes.func, onScrollAnimationEnd: PropTypes.func, scrollEnabled: PropTypes.bool, // true scrollIndicatorInsets: EdgeInsetsPropType, // zeros showsHorizontalScrollIndicator: PropTypes.bool, showsVerticalScrollIndicator: PropTypes.bool, style: StyleSheetPropType(ViewStylePropTypes), scrollEventThrottle: PropTypes.number, // null /** * When true, the scroll view bounces when it reaches the end of the * content if the content is larger then the scroll view along the axis of * the scroll direction. When false, it disables all bouncing even if * the `alwaysBounce*` props are true. The default value is true. */ bounces: PropTypes.bool, /** * When true, gestures can drive zoom past min/max and the zoom will animate * to the min/max value at gesture end, otherwise the zoom will not exceed * the limits. */ bouncesZoom: PropTypes.bool, /** * When true, the scroll view bounces horizontally when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is true when `horizontal={true}` and false otherwise. */ alwaysBounceHorizontal: PropTypes.bool, /** * When true, the scroll view bounces vertically when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is false when `horizontal={true}` and true otherwise. */ alwaysBounceVertical: PropTypes.bool, /** * When true, the scroll view automatically centers the content when the * content is smaller than the scroll view bounds; when the content is * larger than the scroll view, this property has no effect. The default * value is false. */ centerContent: PropTypes.bool, /** * These styles will be applied to the scroll view content container which * wraps all of the child views. Example: * * return ( * <ScrollView contentContainerStyle={styles.contentContainer}> * </ScrollView> * ); * ... * var styles = StyleSheet.create({ * contentContainer: { * paddingVertical: 20 * } * }); */ contentContainerStyle: StyleSheetPropType(ViewStylePropTypes), /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. Reasonable choices include * - Normal: 0.998 (the default) * - Fast: 0.9 */ decelerationRate: PropTypes.number, /** * When true, the scroll view's children are arranged horizontally in a row * instead of vertically in a column. The default value is false. */ horizontal: PropTypes.bool, /** * When true, the ScrollView will try to lock to only vertical or horizontal * scrolling while dragging. The default value is false. */ directionalLockEnabled: PropTypes.bool, /** * When false, once tracking starts, won't try to drag if the touch moves. * The default value is true. */ canCancelContentTouches: PropTypes.bool, /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default), drags do not dismiss the keyboard. * - 'onDrag', the keyboard is dismissed when a drag begins. * - 'interactive', the keyboard is dismissed interactively with the drag * and moves in synchrony with the touch; dragging upwards cancels the * dismissal. */ keyboardDismissMode: PropTypes.oneOf([ 'none', // default 'interactive', 'onDrag', ]), /** * When false, tapping outside of the focused text input when the keyboard * is up dismisses the keyboard. When true, the scroll view will not catch * taps, and the keyboard will not dismiss automatically. The default value * is false. */ keyboardShouldPersistTaps: PropTypes.bool, /** * The maximum allowed zoom scale. The default value is 1.0. */ maximumZoomScale: PropTypes.number, /** * The minimum allowed zoom scale. The default value is 1.0. */ minimumZoomScale: PropTypes.number, /** * When true, the scroll view stops on multiples of the scroll view's size * when scrolling. This can be used for horizontal pagination. The default * value is false. */ pagingEnabled: PropTypes.bool, /** * When true, the scroll view scrolls to top when the status bar is tapped. * The default value is true. */ scrollsToTop: PropTypes.bool, /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example, passing * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the * top of the scroll view. This property is not supported in conjunction * with `horizontal={true}`. */ stickyHeaderIndices: PropTypes.arrayOf(PropTypes.number), /** * Experimental: When true, offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. * This canimprove scrolling performance on long lists. The default value is * false. */ removeClippedSubviews: PropTypes.bool, /** * The current scale of the scroll view content. The default value is 1.0. */ zoomScale: PropTypes.number, }, mixins: [ScrollResponder.Mixin], getInitialState: function() { return this.scrollResponderMixinGetInitialState(); }, setNativeProps: function(props: Object) { this.refs[SCROLLVIEW].setNativeProps(props); }, getInnerViewNode: function(): any { return this.refs[INNERVIEW].getNodeHandle(); }, scrollTo: function(destY?: number, destX?: number) { RCTUIManager.scrollTo( this.getNodeHandle(), destX || 0, destY || 0 ); }, scrollWithoutAnimationTo: function(destY?: number, destX?: number) { RCTUIManager.scrollWithoutAnimationTo( this.getNodeHandle(), destX || 0, destY || 0 ); }, render: function() { var contentContainerStyle = [ this.props.horizontal && styles.contentContainerHorizontal, this.props.contentContainerStyle, ]; if (__DEV__ && this.props.style) { var style = flattenStyle(this.props.style); var childLayoutProps = ['alignItems', 'justifyContent'] .filter((prop) => style && style[prop] !== undefined); invariant( childLayoutProps.length === 0, 'ScrollView child layout (' + JSON.stringify(childLayoutProps) + ') must by applied through the contentContainerStyle prop.' ); } if (__DEV__) { if (this.props.onScroll && !this.props.scrollEventThrottle) { var onScroll = this.props.onScroll; this.props.onScroll = function() { console.log( 'You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + 'cause frame drops, use a bigger number if you don\'t need as ' + 'much precision.' ); onScroll.apply(this, arguments); }; } } var contentContainer = <View ref={INNERVIEW} style={contentContainerStyle} removeClippedSubviews={this.props.removeClippedSubviews}> {this.props.children} </View>; var alwaysBounceHorizontal = this.props.alwaysBounceHorizontal !== undefined ? this.props.alwaysBounceHorizontal : this.props.horizontal; var alwaysBounceVertical = this.props.alwaysBounceVertical !== undefined ? this.props.alwaysBounceVertical : !this.props.horizontal; var props = { ...this.props, alwaysBounceHorizontal, alwaysBounceVertical, keyboardDismissMode: this.props.keyboardDismissMode ? keyboardDismissModeConstants[this.props.keyboardDismissMode] : undefined, style: ([styles.base, this.props.style]: ?Array<any>), onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, onScroll: this.scrollResponderHandleScroll, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderReject: this.scrollResponderHandleResponderReject, }; var ScrollViewClass; if (Platform.OS === 'ios') { ScrollViewClass = RCTScrollView; } else if (Platform.OS === 'android') { if (this.props.horizontal) { ScrollViewClass = AndroidHorizontalScrollView; } else { ScrollViewClass = AndroidScrollView; } } invariant( ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined' ); return ( <ScrollViewClass {...props} ref={SCROLLVIEW}> {contentContainer} </ScrollViewClass> ); } }); var styles = StyleSheet.create({ base: { flex: 1, }, contentContainerHorizontal: { alignSelf: 'flex-start', flexDirection: 'row', }, }); var validAttributes = { ...ReactIOSViewAttributes.UIView, alwaysBounceHorizontal: true, alwaysBounceVertical: true, automaticallyAdjustContentInsets: true, bounces: true, centerContent: true, contentInset: {diff: insetsDiffer}, contentOffset: {diff: pointsDiffer}, decelerationRate: true, horizontal: true, keyboardDismissMode: true, keyboardShouldPersistTaps: true, maximumZoomScale: true, minimumZoomScale: true, pagingEnabled: true, removeClippedSubviews: true, scrollEnabled: true, scrollIndicatorInsets: {diff: insetsDiffer}, scrollsToTop: true, showsHorizontalScrollIndicator: true, showsVerticalScrollIndicator: true, stickyHeaderIndices: {diff: deepDiffer}, scrollEventThrottle: true, zoomScale: true, }; if (Platform.OS === 'android') { var AndroidScrollView = createReactIOSNativeComponentClass({ validAttributes: validAttributes, uiViewClassName: 'AndroidScrollView', }); var AndroidHorizontalScrollView = createReactIOSNativeComponentClass({ validAttributes: validAttributes, uiViewClassName: 'AndroidHorizontalScrollView', }); } else if (Platform.OS === 'ios') { var RCTScrollView = requireNativeComponent('RCTScrollView', ScrollView); } module.exports = ScrollView;
{ "pile_set_name": "Github" }
/* * 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. * */ export class DomainConceptPropertyController { RestApi: any; concepts: any; properties: any; constructor(RestApi) { this.RestApi = RestApi; this.concepts = []; this.properties = []; } $onInit() { this.loadProperties(); this.loadConcepts(); } loadProperties() { this.RestApi.getOntologyProperties() .then(propertiesData => { this.properties = propertiesData.data; }); } loadConcepts() { this.RestApi.getOntologyConcepts() .then(conceptsData => { this.concepts = conceptsData.data; }); } addSupportedProperty(supportedProperties) { if (supportedProperties == undefined) supportedProperties = []; supportedProperties.push({"propertyId": ""}); } removeSupportedProperty(supportedProperties, index) { supportedProperties.splice(index, 1); } conceptRestricted(domainProperty) { return (domainProperty.requiredClass != undefined); } toggleConceptRestriction(domainProperty) { if (this.conceptRestricted(domainProperty)) domainProperty.requiredClass = undefined; else domainProperty.requiredClass = this.concepts[0].id; } conceptSelected(conceptId, currentConceptId) { return (conceptId == currentConceptId); } isSelectedProperty(availableProperty, selectedProperty) { return (availableProperty == selectedProperty); } } DomainConceptPropertyController.$inject = ['RestApi'];
{ "pile_set_name": "Github" }
export default { 'basic': 'Основні', 'advanced': 'Розширені', 'lab': 'Лабораторія', 'save': 'Зберігти та Застосувати', 'save-success-message': 'Налаштування збережено успішно', 'save-fail-message': 'Помилка при зберіганні налаштувань', 'discard': 'Відмінити', 'startup': 'Стартап', 'open-at-login': 'Запускати програму разом з запуском операційної системи', 'keep-window-state': 'Під час закриття додатка, зберігати розмір і положення вікна', 'auto-resume-all': 'Автоматично поновлювати всі невиконанні завдання', 'default-dir': 'Шлях за замовчуванням', 'mas-default-dir-tips': 'Через обмеження в App Store, рекомендовано встановити шлях за замовчення ~/Downloads', 'transfer-settings': 'Передача', 'transfer-speed-upload': 'Ліміт вивантаження', 'transfer-speed-download': 'Ліміт завантаження', 'transfer-speed-unlimited': 'Безлімітно', 'task-manage': 'Менеджер завдань', 'max-concurrent-downloads': 'Максимум активних завдань', 'max-connection-per-server': 'Максимум з\'єднання на сервер', 'new-task-show-downloading': 'Автоматично відображати завантаження після додавання завдання', 'no-confirm-before-delete-task': 'Перед видаленням завдання не потрібно підтверджувати', 'continue': 'Продовжити', 'task-completed-notify': 'Повідомлення після завершення завантаження', 'auto-purge-record': 'Автоматично чистити записи про завантаження перед закриттям додатка', 'ui': 'UI', 'appearance': 'Зовнішній вигляд', 'theme-auto': 'Автоматично', 'theme-light': 'Світлий', 'theme-dark': 'Темний', 'auto-hide-window': 'Автозахист вікон', 'run-mode': 'Виконати як', 'run-mode-standard': 'Стандартне застосування', 'run-mode-menu-bar': 'Застосування рядка меню', 'tray-speedometer': 'Лоток панелі меню показує швидкість у режимі реального часу', 'language': 'Мова', 'change-language': 'Змінити мову', 'hide-app-menu': 'Сховати меню додатка (Тільки для Windows та Linux)', 'proxy': 'Proxy', 'use-proxy': 'Застосувати Proxy', 'no-proxy-input-tips': 'Обхід налаштувань проксі для цих хостів та доменів, по одному на рядок', 'proxy-tips': 'Перегляньте посібник з проксі', 'bt-tracker': 'Tracker Сервер', 'bt-tracker-input-tips': 'Tracker сервера, один в рядок', 'bt-tracker-tips': 'Рекомендовано: ', 'sync-tracker-tips': 'Сінхронізуватись', 'auto-sync-tracker': 'Щодня оновлюйте список трекерів автоматично', 'port': 'Слухайте порти', 'bt-port': 'Порт прослуховування BT', 'dht-port': 'Порт прослуховування DHT', 'security': 'Безпека', 'rpc-secret': 'RPC Secret', 'rpc-secret-tips': 'Дивитись інструкцію RPC Secret', 'developer': 'Розробник', 'mock-user-agent': 'Макет User-Agent', 'app-log-path': 'Шлях до журналу додатка', 'download-session-path': 'Завантажити шлях сесії', 'factory-reset': 'Налаштування за замовчуванням', 'factory-reset-confirm': 'Ви впевненні, що бажаєте повернутись до налаштувань за замовчуванням?', 'lab-warning': '⚠️ Увімкнення функцій лабораторії може призвести до збою програми або втрати даних, вирішити на власний ризик!', 'download-protocol': 'Протоколи', 'protocols-default-client': 'Встановіть як клієнта за замовчуванням для таких протоколів', 'protocols-magnet': 'Magnet [ magnet:// ]', 'protocols-thunder': 'Thunder [ thunder:// ]', 'browser-extensions': 'Розширення', 'baidu-exporter': 'BaiduExporter', 'browser-extensions-tips': 'Надається спільнотою, ', 'baidu-exporter-help': 'Натисніть тут для використання', 'auto-update': 'Автоматичне оновлення', 'auto-check-update': 'Автоматично перевіряти оновлення', 'last-check-update-time': 'В останнє оновлення перевірялось' }
{ "pile_set_name": "Github" }
/* * This file is part of Hootenanny. * * Hootenanny is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------- * * The following copyright notices are generated automatically. If you * have a new notice to add, please use the format: * " * @copyright Copyright ..." * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * * @copyright Copyright (C) 2015, 2016, 2017, 2018, 2019, 2020 DigitalGlobe (http://www.digitalglobe.com/) */ // Hoot #include <hoot/core/TestUtils.h> #include <hoot/core/conflate/network/DebugNetworkMapCreator.h> #include <hoot/core/conflate/network/OsmNetworkExtractor.h> #include <hoot/core/criterion/ChainCriterion.h> #include <hoot/core/criterion/HighwayCriterion.h> #include <hoot/core/criterion/StatusCriterion.h> #include <hoot/core/io/OsmMapReaderFactory.h> #include <hoot/core/io/OsmMapWriterFactory.h> #include <hoot/core/ops/MapCleaner.h> #include <hoot/core/util/FileUtils.h> #include <hoot/core/util/MapProjector.h> #include <hoot/rnd/conflate/network/IterativeNetworkMatcher.h> namespace hoot { class IterativeNetworkMatcherTest : public HootTestFixture { CPPUNIT_TEST_SUITE(IterativeNetworkMatcherTest); CPPUNIT_TEST(toyTest); // this isn't being actively tested now, we're using vagabond for now... //CPPUNIT_TEST(edgeMatchTest); CPPUNIT_TEST_SUITE_END(); public: IterativeNetworkMatcherTest() : HootTestFixture("test-files/conflate/network/", "test-output/conflate/network/") { setResetType(ResetAll); } void writeDebugMap(OsmMapPtr map, IterativeNetworkMatcher& uut, int index) { FileUtils::makeDir("tmp"); OsmMapPtr copy(new OsmMap(map)); DebugNetworkMapCreator().addDebugElements(copy, uut.getAllEdgeScores(), uut.getAllVertexScores()); MapProjector::projectToWgs84(copy); conf().set(ConfigOptions().getWriterIncludeDebugTagsKey(), true); OsmMapWriterFactory::write(copy, QString("tmp/IterativeNetworkMatcherTest-%1.osm").arg(index, 3, 10, QLatin1Char('0'))); } /** * Extract a toy network and verify that the result is as expected. */ void edgeMatchTest() { OsmMapPtr map(new OsmMap()); OsmMapReaderFactory::read(map, _inputPath + "ToyTestE1.osm", true, Status::Unknown1); OsmMapReaderFactory::read(map, _inputPath + "ToyTestE2.osm", true, Status::Unknown2); MapCleaner().apply(map); MapProjector::projectToPlanar(map); OsmNetworkExtractor one; ElementCriterionPtr c1( new ChainCriterion(new HighwayCriterion(map), new StatusCriterion(Status::Unknown1))); one.setCriterion(c1); OsmNetworkPtr network1 = one.extractNetwork(map); ElementCriterionPtr c2( new ChainCriterion(new HighwayCriterion(map), new StatusCriterion(Status::Unknown2))); one.setCriterion(c2); OsmNetworkPtr network2 = one.extractNetwork(map); IterativeNetworkMatcherPtr uut(new IterativeNetworkMatcher()); uut->matchNetworks(map, network1, network2); // sloppy quick & dirty test to keep things moving HOOT_STR_EQUALS("[4]{(s1: [2]{Node:-225 -- Way:-232 -- Node:-230, Node:-288 -- Way:-236 -- Node:-230 (reverse)} s2: [2]{Node:-212 -- Way:-273 -- Node:-213, Node:-213 -- Way:-214 -- Node:-213}, 1), (s1: [2]{Node:-288 -- Way:-236 -- Node:-230, Node:-225 -- Way:-232 -- Node:-230 (reverse)} s2: [2]{Node:-213 -- Way:-214 -- Node:-213, Node:-212 -- Way:-273 -- Node:-213 (reverse)}, 1), (s1: [2]{Node:-33 -- Way:-45 -- Node:-37, Node:-41 -- Way:-47 -- Node:-37 (reverse)} s2: [1]{Node:-17 -- Way:-27 -- Node:-23}, 1), (s1: [2]{Node:-75 -- Way:-73 -- Node:-77, Node:-101 -- Way:-99 -- Node:-77 (reverse)} s2: [1]{Node:-144 -- Way:-148 -- Node:-151}, 1)}", uut->_edgeMatches); } /** * Extract a toy network and verify that the result is as expected. */ void toyTest() { OsmMapPtr map(new OsmMap()); OsmMapReaderFactory::read(map, _inputPath + "ToyTestB1.osm", false, Status::Unknown1); OsmMapReaderFactory::read(map, _inputPath + "ToyTestB2.osm", false, Status::Unknown2); MapCleaner().apply(map); MapProjector::projectToPlanar(map); OsmNetworkExtractor one; ElementCriterionPtr c1( new ChainCriterion(new HighwayCriterion(map), new StatusCriterion(Status::Unknown1))); one.setCriterion(c1); OsmNetworkPtr network1 = one.extractNetwork(map); ElementCriterionPtr c2( new ChainCriterion(new HighwayCriterion(map), new StatusCriterion(Status::Unknown2))); one.setCriterion(c2); OsmNetworkPtr network2 = one.extractNetwork(map); IterativeNetworkMatcherPtr uut = IterativeNetworkMatcher::create(); uut->matchNetworks(map, network1, network2); writeDebugMap(map, *uut, 0); for (int i = 1; i <= 20; ++i) { LOG_VAR(i); uut->iterate(); writeDebugMap(map, *uut, i); } // write final map and compare DebugNetworkMapCreator().addDebugElements(map, uut->getAllEdgeScores(), uut->getAllVertexScores()); MapProjector::projectToWgs84(map); conf().set(ConfigOptions().getWriterIncludeDebugTagsKey(), true); OsmMapWriterFactory::write(map, QString(_outputPath + "IterativeNetworkMatcherTestFinal.osm")); HOOT_FILE_EQUALS(_inputPath + "IterativeNetworkMatcherTestExpected.osm", _outputPath + "IterativeNetworkMatcherTestFinal.osm"); } }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(IterativeNetworkMatcherTest, "glacial"); }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @import '../styles/colors.scss'; .insights-fix-instruction-list { li { span.fix-instruction-color-box { width: 14px; height: 14px; display: inline-block; vertical-align: -5%; margin: 0px 2px; border: 1px solid $always-black; } } .screen-reader-only { position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden; } }
{ "pile_set_name": "Github" }
## {{site.data.var.ee}} Web APIs Services per Module {#eelist} The Web APIs for {{site.data.var.ee}} (formerly Magento Enterprise Edition) are available on {{site.data.var.ee}} installations only. {{site.data.var.ee}} installations automatically have access to all {{site.data.var.ce}} (formerly Magento Community Edition) web APIs. ### CustomerBalance ```http customerBalanceBalanceManagementV1 ``` ### GiftCardAccount ```http giftCardAccountGiftCardAccountManagementV1 giftCardAccountGuestGiftCardAccountManagementV1 giftRegistryGuestCartShippingMethodManagementV1 giftRegistryShippingMethodManagementV1 ``` ### GiftWrapping ```http giftWrappingWrappingRepositoryV1 ``` ### Reward ```http rewardRewardManagementV1 ``` ### RMA ```http rmaCommentManagementV1 rmaRmaAttributesManagementV1 rmaRmaManagementV1 rmaRmaRepositoryV1 rmaTrackManagementV1 ``` ### Worldpay ```http worldpayGuestPaymentInformationManagementProxyV1 ``` ## {{site.data.var.ce}} Web APIs Services per Module {#celist} The {{site.data.var.ce}} Web APIs are available on all installations. ### Analytics ```http analyticsLinkProviderV1 ``` ### AsynchronousOperations ```http asynchronousOperationsOperationRepositoryV1 ``` ### Backend ```http backendModuleServiceV1 ``` ### Bundle ```http bundleProductLinkManagementV1 bundleProductOptionManagementV1 bundleProductOptionRepositoryV1 bundleProductOptionTypeListV1 ``` ### Catalog ```http catalogAttributeSetManagementV1 catalogAttributeSetRepositoryV1 catalogBasePriceStorageV1 * catalogCategoryAttributeOptionManagementV1 catalogCategoryAttributeRepositoryV1 catalogCategoryLinkManagementV1 catalogCategoryLinkRepositoryV1 catalogCategoryListV1 * catalogCategoryManagementV1 catalogCategoryRepositoryV1 catalogCostStorageV1 * catalogProductAttributeGroupRepositoryV1 catalogProductAttributeManagementV1 catalogProductAttributeMediaGalleryManagementV1 catalogProductAttributeOptionManagementV1 catalogProductAttributeRepositoryV1 catalogProductAttributeTypesListV1 catalogProductCustomOptionRepositoryV1 catalogProductCustomOptionTypeListV1 catalogProductLinkManagementV1 catalogProductLinkRepositoryV1 catalogProductLinkTypeListV1 catalogProductMediaAttributeManagementV1 catalogProductRenderListV1 * catalogProductRepositoryV1 catalogProductTierPriceManagementV1 catalogProductTypeListV1 catalogProductWebsiteLinkRepositoryV1 catalogSpecialPriceStorageV1 * catalogTierPriceStorageV1 * ``` ### CatalogInventory ```http catalogInventoryStockRegistryV1 ``` ### Checkout ```http checkoutGuestPaymentInformationManagementV1 checkoutGuestShippingInformationManagementV1 checkoutGuestTotalsInformationManagementV1 checkoutPaymentInformationManagementV1 checkoutShippingInformationManagementV1 checkoutTotalsInformationManagementV1 ``` ### CheckoutAgreements ```http checkoutAgreementsCheckoutAgreementsRepositoryV1 ``` ### Cms ```http cmsBlockRepositoryV1 cmsPageRepositoryV1 ``` ### ConfigurableProduct ```http configurableProductConfigurableProductManagementV1 configurableProductLinkManagementV1 configurableProductOptionRepositoryV1 ``` ### Customer ```http customerAccountManagementV1 customerAddressMetadataV1 customerAddressRepositoryV1 customerCustomerMetadataV1 customerCustomerRepositoryV1 customerGroupManagementV1 customerGroupRepositoryV1 customerCustomerGroupConfigV1 ``` ### Directory ```http directoryCountryInformationAcquirerV1 directoryCurrencyInformationAcquirerV1 ``` ### Downloadable ```http downloadableLinkRepositoryV1 downloadableSampleRepositoryV1 ``` ### Eav ```http eavAttributeSetManagementV1 eavAttributeSetRepositoryV1 ``` ### GiftMessage ```http giftMessageCartRepositoryV1 giftMessageGuestCartRepositoryV1 giftMessageGuestItemRepositoryV1 giftMessageItemRepositoryV1 ``` ### Integration ```http integrationAdminTokenServiceV1 integrationCustomerTokenServiceV1 ``` ### InventoryApi ```http inventoryApiSourceRepositoryV1 inventoryApiGetSourcesAssignedToStockOrderedByPriorityV1 inventoryApiStockRepositoryV1 inventoryApiGetStockSourceLinksV1 inventoryApiStockSourceLinksSaveV1 inventoryApiStockSourceLinksDeleteV1 inventoryApiSourceItemRepositoryV1 inventoryApiSourceItemsSaveV1 inventoryApiSourceItemsDeleteV1 ``` ### InventoryCatalogApi ```http inventoryCatalogApiBulkSourceAssignV1 inventoryCatalogApiBulkSourceUnassignV1 inventoryCatalogApiBulkInventoryTransferV1 ``` ### InventoryDistanceBasedSourceSelectionApi ```http inventoryDistanceBasedSourceSelectionApiGetDistanceProviderCodeV1 inventoryDistanceBasedSourceSelectionApiGetDistanceV1 inventoryDistanceBasedSourceSelectionApiGetLatLngFromAddressV1 ``` ### InventoryLowQuantityNotificationApi ```http inventoryLowQuantityNotificationApiGetSourceItemConfigurationV1 inventoryLowQuantityNotificationApiSourceItemConfigurationsSaveV1 inventoryLowQuantityNotificationApiDeleteSourceItemsConfigurationV1 ``` ### InventorySalesApi ```http inventorySalesApiGetProductSalabilityV1 inventorySalesApiIsProductSalableV1 inventorySalesApiIsProductSalableForRequestedQtyV1 inventorySalesApiStockResolverV1 ``` ### InventorySourceSelectionApi ```http inventorySourceSelectionApiGetSourceSelectionAlgorithmListV1 inventorySourceSelectionApiSourceSelectionServiceV1 ``` ### Quote ```http quoteBillingAddressManagementV1 quoteCartItemRepositoryV1 quoteCartManagementV1 quoteCartRepositoryV1 quoteCartTotalManagementV1 quoteCartTotalRepositoryV1 quoteCouponManagementV1 quoteGuestBillingAddressManagementV1 quoteGuestCartItemRepositoryV1 quoteGuestCartManagementV1 quoteGuestCartRepositoryV1 quoteGuestCartTotalManagementV1 quoteGuestCartTotalRepositoryV1 quoteGuestCouponManagementV1 quoteGuestPaymentMethodManagementV1 quoteGuestShipmentEstimationV1 quoteGuestShippingMethodManagementV1 quotePaymentMethodManagementV1 quoteShipmentEstimationV1 quoteShippingMethodManagementV1 ``` ### Sales ```http salesCreditmemoCommentRepositoryV1 salesCreditmemoManagementV1 salesCreditmemoRepositoryV1 salesInvoiceCommentRepositoryV1 salesInvoiceManagementV1 salesInvoiceOrderV1 salesInvoiceRepositoryV1 salesOrderAddressRepositoryV1 salesOrderItemRepositoryV1 salesOrderManagementV1 salesOrderRepositoryV1 salesRefundInvoiceV1 salesRefundOrderV1 salesShipmentCommentRepositoryV1 salesShipmentManagementV1 salesShipmentRepositoryV1 salesShipmentTrackRepositoryV1 salesShipOrderV1 salesTransactionRepositoryV1 ``` ### SalesRule ```http salesRuleCouponManagementV1 salesRuleCouponRepositoryV1 salesRuleRuleRepositoryV1 ``` ### Search ```http searchV1 ``` ### Store ```http storeGroupRepositoryV1 storeStoreConfigManagerV1 storeStoreRepositoryV1 storeWebsiteRepositoryV1 ``` ### Tax ```http taxTaxClassRepositoryV1 taxTaxRateRepositoryV1 taxTaxRuleRepositoryV1 ``` ## Magento B2B See [Integrate with B2B using REST]({{page.baseurl}}/b2b/integrations.html) for a list of services provided with B2B.
{ "pile_set_name": "Github" }
%% %% Fixed EMC2 Documentation style %% \NeedsTeXFormat{LaTeX2e} \ProvidesPackage{emc2doc}[2011/02/10 EMC2 Style] %% XXX: Here starts verbatim copy of asciidoc-docbook.sty %% Just use the original package and pass the options. \RequirePackageWithOptions{docbook} % Sidebar is a boxed minipage that can contain verbatim. % Changed shadow box to double box. \renewenvironment{sidebar}[1][0.95\textwidth]{ \hspace{0mm}\newline% \noindent\begin{Sbox}\begin{minipage}{#1}% \setlength\parskip{\medskipamount}% }{ \end{minipage}\end{Sbox}\doublebox{\TheSbox}% } % For DocBook literallayout elements, see `./dblatex/dblatex-readme.txt`. \usepackage{alltt} %% XXX: Here ends verbatim copy of asciidoc-docbook.sty \usepackage{grffile}
{ "pile_set_name": "Github" }
/* * 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. */ package org.jclouds.aws.ec2.compute.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * Related to a ClusterCompute resource. */ @Retention(value = RetentionPolicy.RUNTIME) @Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Qualifier public @interface ClusterCompute { }
{ "pile_set_name": "Github" }
/* * Copyright 2015-2020 the original author or authors. * * 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 * * https://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.springframework.data.mongodb.config; import java.beans.PropertyEditorSupport; import org.springframework.lang.Nullable; import com.mongodb.ReadPreference; /** * Parse a {@link String} to a {@link ReadPreference}. * * @author Christoph Strobl * @since 1.7 */ public class ReadPreferencePropertyEditor extends PropertyEditorSupport { /* * (non-Javadoc) * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String) */ @Override public void setAsText(@Nullable String readPreferenceString) throws IllegalArgumentException { if (readPreferenceString == null) { return; } ReadPreference preference = null; try { preference = ReadPreference.valueOf(readPreferenceString); } catch (IllegalArgumentException ex) { // ignore this one and try to map it differently } if (preference != null) { setValue(preference); } else if ("PRIMARY".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.primary()); } else if ("PRIMARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.primaryPreferred()); } else if ("SECONDARY".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.secondary()); } else if ("SECONDARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.secondaryPreferred()); } else if ("NEAREST".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.nearest()); } else { throw new IllegalArgumentException( String.format("Cannot find matching ReadPreference for %s", readPreferenceString)); } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.notes; /** A note bucket that has been loaded into the process. */ abstract class InMemoryNoteBucket extends NoteBucket { /** * Number of leading digits that leads to this bucket in the note path. * * This is counted in terms of hex digits, not raw bytes. Each bucket level * is typically 2 higher than its parent, placing about 256 items in each * level of the tree. */ final int prefixLen; /** * Chain of non-note tree entries found at this path in the tree. * * During parsing of a note tree into the in-memory representation, * {@link NoteParser} keeps track of all non-note tree entries and stores * them here as a sorted linked list. That list can be merged back with the * note data that is held by the subclass, allowing the tree to be * recreated. */ NonNoteEntry nonNotes; InMemoryNoteBucket(int prefixLen) { this.prefixLen = prefixLen; } abstract InMemoryNoteBucket append(Note note); }
{ "pile_set_name": "Github" }
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/RxCocoa" "$PODS_CONFIGURATION_BUILD_DIR/RxSwift" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/RxCocoa/RxCocoa.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/RxSwift/RxSwift.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "RxCocoa" -framework "RxSwift" -framework "SwiftyJSON" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT}/Pods
{ "pile_set_name": "Github" }
import "hashes/sha256/512bitPacked" as sha256packed def main(field h0, field h1, private field a, private field b, private field c, private field d) -> (field): h = sha256packed([a, b, c, d]) h[0] == h0 h[1] == h1 return 1
{ "pile_set_name": "Github" }
// This file was procedurally generated from the following sources: // - src/class-elements/rs-static-generator-method-privatename-identifier-alt.case // - src/class-elements/productions/cls-decl-multiple-stacked-definitions.template /*--- description: Valid Static GeneratorMethod PrivateName (multiple stacked fields definitions through ASI) esid: prod-FieldDefinition features: [class-static-methods-private, class, class-fields-public] flags: [generated] includes: [propertyHelper.js] info: | ClassElement : MethodDefinition static MethodDefinition FieldDefinition ; static FieldDefinition ; ; MethodDefinition : GeneratorMethod GeneratorMethod : * ClassElementName ( UniqueFormalParameters ){ GeneratorBody } ClassElementName : PropertyName PrivateName PrivateName :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: UnicodeIDStart $ _ \ UnicodeEscapeSequence IdentifierPart:: UnicodeIDContinue $ \ UnicodeEscapeSequence <ZWNJ> <ZWJ> UnicodeIDStart:: any Unicode code point with the Unicode property "ID_Start" UnicodeIDContinue:: any Unicode code point with the Unicode property "ID_Continue" NOTE 3 The sets of code points with Unicode properties "ID_Start" and "ID_Continue" include, respectively, the code points with Unicode properties "Other_ID_Start" and "Other_ID_Continue". ---*/ class C { static * #$(value) { yield * value; } static * #_(value) { yield * value; } static * #o(value) { yield * value; } static * #℘(value) { yield * value; } static * #ZW_‌_NJ(value) { yield * value; } static * #ZW_‍_J(value) { yield * value; } foo = "foobar" bar = "barbaz"; static get $() { return this.#$; } static get _() { return this.#_; } static get o() { return this.#o; } static get ℘() { // DO NOT CHANGE THE NAME OF THIS FIELD return this.#℘; } static get ZW_‌_NJ() { // DO NOT CHANGE THE NAME OF THIS FIELD return this.#ZW_‌_NJ; } static get ZW_‍_J() { // DO NOT CHANGE THE NAME OF THIS FIELD return this.#ZW_‍_J; } } var c = new C(); assert.sameValue(c.foo, "foobar"); assert.sameValue(Object.hasOwnProperty.call(C, "foo"), false); assert.sameValue(Object.hasOwnProperty.call(C.prototype, "foo"), false); verifyProperty(c, "foo", { value: "foobar", enumerable: true, configurable: true, writable: true, }); assert.sameValue(c.bar, "barbaz"); assert.sameValue(Object.hasOwnProperty.call(C, "bar"), false); assert.sameValue(Object.hasOwnProperty.call(C.prototype, "bar"), false); verifyProperty(c, "bar", { value: "barbaz", enumerable: true, configurable: true, writable: true, }); assert.sameValue(C.$([1]).next().value, 1); assert.sameValue(C._([1]).next().value, 1); assert.sameValue(C.o([1]).next().value, 1); assert.sameValue(C.℘([1]).next().value, 1); assert.sameValue(C.ZW_‌_NJ([1]).next().value, 1); assert.sameValue(C.ZW_‍_J([1]).next().value, 1);
{ "pile_set_name": "Github" }
package io.kotless.terraform.provider.aws.data.s3 import io.kotless.terraform.TFData import io.kotless.terraform.TFFile /** * Terraform aws_s3_bucket resource. * * @see <a href="https://www.terraform.io/docs/providers/aws/r/s3_bucket.html">aws_s3_bucket</a> */ class S3Bucket(id: String) : TFData(id, "aws_s3_bucket") { val arn by text(inner = true) var bucket by text() } fun s3_bucket(id: String, configure: S3Bucket.() -> Unit) = S3Bucket(id).apply(configure) fun TFFile.s3_bucket(id: String, configure: S3Bucket.() -> Unit) { add(S3Bucket(id).apply(configure)) }
{ "pile_set_name": "Github" }
package com.neu.his.cloud.service.dms.dto.dms; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; import java.util.List; @Setter @Getter @ToString public class DmsCaseModelResult implements Serializable { @ApiModelProperty (value = "模板Id") private Long id; @ApiModelProperty (value = "主诉") private String chiefComplaint; @ApiModelProperty (value = "症状") private String historyOfPresentIllness; @ApiModelProperty (value = "历史治疗") private String historyOfTreatment; @ApiModelProperty (value = "既往史") private String pastHistory; @ApiModelProperty (value = "过敏史") private String allergies; @ApiModelProperty (value = "健康检查") private String healthCheckup; @ApiModelProperty (value = "初步诊断Id串") private List<Long> priliminaryDiseIdList; @ApiModelProperty (value = "初诊诊断id串对应诊断名字串") private List<String> priliminaryDiseStrList; @ApiModelProperty (value = "病历模板名") private String name; @ApiModelProperty (value = "状态") private Integer status; }
{ "pile_set_name": "Github" }
/** * @file re_base64.h Interface to Base64 encoding/decoding functions * * Copyright (C) 2010 Creytiv.com */ int base64_encode(const uint8_t *in, size_t ilen, char *out, size_t *olen); int base64_print(struct re_printf *pf, const uint8_t *ptr, size_t len); int base64_decode(const char *in, size_t ilen, uint8_t *out, size_t *olen);
{ "pile_set_name": "Github" }
/* * jerror.h * * Copyright (C) 1994-1995, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file defines the error and message codes for the JPEG library. * Edit this file to add new codes, or to translate the message strings to * some other language. * A set of error-reporting macros are defined too. Some applications using * the JPEG library may wish to include this file to get the error codes * and/or the macros. */ /* * To define the enum list of message codes, include this file without * defining macro JMESSAGE. To create a message string table, include it * again with a suitable JMESSAGE definition (see jerror.c for an example). */ #ifndef JMESSAGE #ifndef JERROR_H /* First time through, define the enum list */ #define JMAKE_ENUM_LIST #else /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */ #define JMESSAGE(code,string) #endif /* JERROR_H */ #endif /* JMESSAGE */ #ifdef JMAKE_ENUM_LIST typedef enum { #define JMESSAGE(code,string) code , #endif /* JMAKE_ENUM_LIST */ JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */ /* For maintenance convenience, list is alphabetical by message code name */ JMESSAGE(JERR_ARITH_NOTIMPL, "Sorry, there are legal restrictions on arithmetic coding") JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix") JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix") JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode") JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS") JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported") JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace") JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace") JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length") JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan") JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d") JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d") JMESSAGE(JERR_BAD_PROGRESSION, "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d") JMESSAGE(JERR_BAD_PROG_SCRIPT, "Invalid progressive parameters at scan script entry %d") JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors") JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d") JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d") JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access") JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small") JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here") JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet") JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d") JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request") JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d") JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x") JMESSAGE(JERR_DHT_COUNTS, "Bogus DHT counts") JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d") JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d") JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)") JMESSAGE(JERR_EMS_READ, "Read from EMS failed") JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed") JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan") JMESSAGE(JERR_FILE_READ, "Input file read error") JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?") JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet") JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow") JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry") JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels") JMESSAGE(JERR_INPUT_EMPTY, "Empty input file") JMESSAGE(JERR_INPUT_EOF, "Premature end of input file") JMESSAGE(JERR_MISMATCHED_QUANT_TABLE, "Cannot transcode due to multiple use of quantization table %d") JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data") JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change") JMESSAGE(JERR_NOTIMPL, "Not implemented yet") JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time") JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported") JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined") JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image") JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined") JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x") JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)") JMESSAGE(JERR_QUANT_COMPONENTS, "Cannot quantize more than %d color components") JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors") JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors") JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers") JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker") JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x") JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers") JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF") JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s") JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file") JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file") JMESSAGE(JERR_TFILE_WRITE, "Write failed on temporary file --- out of disk space?") JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines") JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x") JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up") JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation") JMESSAGE(JERR_XMS_READ, "Read from XMS failed") JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed") JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT) JMESSAGE(JMSG_VERSION, JVERSION) JMESSAGE(JTRC_16BIT_TABLES, "Caution: quantization tables are too coarse for baseline JPEG") JMESSAGE(JTRC_ADOBE, "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d") JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u") JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u") JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x") JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x") JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d") JMESSAGE(JTRC_DRI, "Define Restart Interval %u") JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u") JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u") JMESSAGE(JTRC_EOI, "End Of Image") JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d") JMESSAGE(JTRC_JFIF, "JFIF APP0 marker, density %dx%d %d") JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE, "Warning: thumbnail image size does not match data length %u") JMESSAGE(JTRC_JFIF_MINOR, "Unknown JFIF minor revision number %d.%02d") JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image") JMESSAGE(JTRC_MISC_MARKER, "Skipping marker 0x%02x, length %u") JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x") JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u") JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors") JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors") JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization") JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d") JMESSAGE(JTRC_RST, "RST%d") JMESSAGE(JTRC_SMOOTH_NOTIMPL, "Smoothing not supported with nonstandard sampling ratios") JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d") JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d") JMESSAGE(JTRC_SOI, "Start of Image") JMESSAGE(JTRC_SOS, "Start Of Scan: %d components") JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d") JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d") JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s") JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s") JMESSAGE(JTRC_UNKNOWN_IDS, "Unrecognized component IDs %d %d %d, assuming YCbCr") JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u") JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u") JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d") JMESSAGE(JWRN_BOGUS_PROGRESSION, "Inconsistent progression sequence for component %d coefficient %d") JMESSAGE(JWRN_EXTRANEOUS_DATA, "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x") JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment") JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code") JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d") JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file") JMESSAGE(JWRN_MUST_RESYNC, "Corrupt JPEG data: found marker 0x%02x instead of RST%d") JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG") JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines") #ifdef JMAKE_ENUM_LIST JMSG_LASTMSGCODE } J_MESSAGE_CODE; #undef JMAKE_ENUM_LIST #endif /* JMAKE_ENUM_LIST */ /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */ #undef JMESSAGE #ifndef JERROR_H #define JERROR_H /* Macros to simplify using the error and trace message stuff */ /* The first parameter is either type of cinfo pointer */ /* Fatal errors (print message and exit) */ #define ERREXIT(cinfo,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT1(cinfo,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT2(cinfo,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT3(cinfo,code,p1,p2,p3) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[2] = (p3), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[2] = (p3), \ (cinfo)->err->msg_parm.i[3] = (p4), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define ERREXITS(cinfo,code,str) \ ((cinfo)->err->msg_code = (code), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) #define MAKESTMT(stuff) do { stuff } while (0) /* Nonfatal errors (we can keep going, but the data is probably corrupt) */ #define WARNMS(cinfo,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) #define WARNMS1(cinfo,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) #define WARNMS2(cinfo,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) /* Informational/debugging messages */ #define TRACEMS(cinfo,lvl,code) \ ((cinfo)->err->msg_code = (code), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS1(cinfo,lvl,code,p1) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS2(cinfo,lvl,code,p1,p2) \ ((cinfo)->err->msg_code = (code), \ (cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[1] = (p2), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \ (cinfo)->err->msg_code = (code); \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) #define TRACEMSS(cinfo,lvl,code,str) \ ((cinfo)->err->msg_code = (code), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) #endif /* JERROR_H */
{ "pile_set_name": "Github" }
/* Set platform defines at build time for volk to pick up. */ #if defined(_WIN32) # define VK_USE_PLATFORM_WIN32_KHR #elif defined(__linux__) || defined(__unix__) # define VK_USE_PLATFORM_XLIB_KHR #elif defined(__APPLE__) # define VK_USE_PLATFORM_MACOS_MVK #else # error "Platform not supported by this example." #endif #define VOLK_IMPLEMENTATION #include "volk.h" #include "stdio.h" #include "stdlib.h" int main() { VkResult r; uint32_t version; void* ptr; /* This won't compile if the appropriate Vulkan platform define isn't set. */ ptr = #if defined(_WIN32) &vkCreateWin32SurfaceKHR; #elif defined(__linux__) || defined(__unix__) &vkCreateXlibSurfaceKHR; #elif defined(__APPLE__) &vkCreateMacOSSurfaceMVK; #else /* Platform not recogized for testing. */ NULL; #endif /* Try to initialize volk. This might not work on CI builds, but the * above should have compiled at least. */ r = volkInitialize(); if (r != VK_SUCCESS) { printf("volkInitialize failed!\n"); return -1; } version = volkGetInstanceVersion(); printf("Vulkan version %d.%d.%d initialized.\n", VK_VERSION_MAJOR(version), VK_VERSION_MINOR(version), VK_VERSION_PATCH(version)); return 0; }
{ "pile_set_name": "Github" }
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.comprehend.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Deletes a model-specific endpoint for a previously-trained custom model. All * endpoints must be deleted in order for the model to be deleted. * </p> */ public class DeleteEndpointRequest extends AmazonWebServiceRequest implements Serializable { /** * <p> * The Amazon Resource Number (ARN) of the endpoint being deleted. * </p> * <p> * <b>Constraints:</b><br/> * <b>Length: </b> - 256<br/> * <b>Pattern: * </b>arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:(document * -classifier * -endpoint|entity-recognizer-endpoint)/[a-zA-Z0-9](-*[a-zA-Z0-9])*<br/> */ private String endpointArn; /** * <p> * The Amazon Resource Number (ARN) of the endpoint being deleted. * </p> * <p> * <b>Constraints:</b><br/> * <b>Length: </b> - 256<br/> * <b>Pattern: * </b>arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:(document * -classifier * -endpoint|entity-recognizer-endpoint)/[a-zA-Z0-9](-*[a-zA-Z0-9])*<br/> * * @return <p> * The Amazon Resource Number (ARN) of the endpoint being deleted. * </p> */ public String getEndpointArn() { return endpointArn; } /** * <p> * The Amazon Resource Number (ARN) of the endpoint being deleted. * </p> * <p> * <b>Constraints:</b><br/> * <b>Length: </b> - 256<br/> * <b>Pattern: * </b>arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:(document * -classifier * -endpoint|entity-recognizer-endpoint)/[a-zA-Z0-9](-*[a-zA-Z0-9])*<br/> * * @param endpointArn <p> * The Amazon Resource Number (ARN) of the endpoint being * deleted. * </p> */ public void setEndpointArn(String endpointArn) { this.endpointArn = endpointArn; } /** * <p> * The Amazon Resource Number (ARN) of the endpoint being deleted. * </p> * <p> * Returns a reference to this object so that method calls can be chained * together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b> - 256<br/> * <b>Pattern: * </b>arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:(document * -classifier * -endpoint|entity-recognizer-endpoint)/[a-zA-Z0-9](-*[a-zA-Z0-9])*<br/> * * @param endpointArn <p> * The Amazon Resource Number (ARN) of the endpoint being * deleted. * </p> * @return A reference to this updated object so that method calls can be * chained together. */ public DeleteEndpointRequest withEndpointArn(String endpointArn) { this.endpointArn = endpointArn; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEndpointArn() != null) sb.append("EndpointArn: " + getEndpointArn()); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEndpointArn() == null) ? 0 : getEndpointArn().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteEndpointRequest == false) return false; DeleteEndpointRequest other = (DeleteEndpointRequest) obj; if (other.getEndpointArn() == null ^ this.getEndpointArn() == null) return false; if (other.getEndpointArn() != null && other.getEndpointArn().equals(this.getEndpointArn()) == false) return false; return true; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package osl import ( "bytes" "encoding/base64" "encoding/hex" "fmt" "io/ioutil" "net" "testing" "time" "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common" ) func TestOSL(t *testing.T) { configJSONTemplate := ` { "Schemes" : [ { "Epoch" : "%s", "Regions" : ["US", "CA"], "PropagationChannelIDs" : ["2995DB0C968C59C4F23E87988D9C0D41", "E742C25A6D8BA8C17F37E725FA628569", "B4A780E67695595FA486E9B900EA7335"], "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=", "SeedSpecs" : [ { "Description": "spec1", "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=", "UpstreamSubnets" : ["192.168.0.0/16", "172.16.0.0/12"], "Targets" : { "BytesRead" : 1, "BytesWritten" : 1, "PortForwardDurationNanoseconds" : 1 } }, { "Description": "spec2", "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=", "UpstreamSubnets" : ["192.168.0.0/16", "10.0.0.0/8"], "Targets" : { "BytesRead" : 10, "BytesWritten" : 10, "PortForwardDurationNanoseconds" : 10 } }, { "Description": "spec3", "ID" : "ts5LInjFHbVKX+/C5/bSJqUh+cLT5kJy92TZGLvAtPU=", "UpstreamSubnets" : ["100.64.0.0/10"], "Targets" : { "BytesRead" : 100, "BytesWritten" : 100, "PortForwardDurationNanoseconds" : 100 } } ], "SeedSpecThreshold" : 2, "SeedPeriodNanoseconds" : 5000000, "SeedPeriodKeySplits": [ { "Total": 10, "Threshold": 5 }, { "Total": 10, "Threshold": 5 } ] }, { "Epoch" : "%s", "Regions" : ["US", "CA"], "PropagationChannelIDs" : ["36F1CF2DF1250BF0C7BA0629CE3DC657", "B4A780E67695595FA486E9B900EA7335"], "MasterKey" : "fcyQy8JSxLXHt/Iom9Qj9wMnSjrsccTiiSPEsJicet4=", "SeedSpecs" : [ { "Description": "spec1", "ID" : "NXY0/4lqMxx5XIszIhMbwHobH/qb2Gl0Bw/OGndc1vM=", "UpstreamSubnets" : ["192.168.0.0/16", "172.16.0.0/12"], "Targets" : { "BytesRead" : 1, "BytesWritten" : 1, "PortForwardDurationNanoseconds" : 1 } }, { "Description": "spec2", "ID" : "o78G6muv3idtbQKXoU05tF6gTlQj1LHmNe0eUWkZGxs=", "UpstreamSubnets" : ["192.168.0.0/16", "10.0.0.0/8"], "Targets" : { "BytesRead" : 10, "BytesWritten" : 10, "PortForwardDurationNanoseconds" : 10 } }, { "Description": "spec3", "ID" : "1DlAvJYpoSEfcqMXYBV7bDEtYu3LCQO39ISD5tmi8Uo=", "UpstreamSubnets" : ["100.64.0.0/10"], "Targets" : { "BytesRead" : 0, "BytesWritten" : 0, "PortForwardDurationNanoseconds" : 0 } } ], "SeedSpecThreshold" : 2, "SeedPeriodNanoseconds" : 5000000, "SeedPeriodKeySplits": [ { "Total": 100, "Threshold": 25 } ] } ] } ` seedPeriod := 5 * time.Millisecond // "SeedPeriodNanoseconds" : 5000000 now := time.Now().UTC() epoch := now.Add(-seedPeriod).Truncate(seedPeriod) epochStr := epoch.Format(time.RFC3339Nano) configJSON := fmt.Sprintf(configJSONTemplate, epochStr, epochStr) // The first scheme requires sufficient activity within 5/10 5 millisecond // periods and 5/10 50 millisecond longer periods. The second scheme requires // sufficient activity within 25/100 5 millisecond periods. config, err := LoadConfig([]byte(configJSON)) if err != nil { t.Fatalf("LoadConfig failed: %s", err) } t.Run("ineligible client, sufficient transfer", func(t *testing.T) { clientSeedState := config.NewClientSeedState("US", "C5E8D2EDFD093B50D8D65CF59D0263CA", nil) seedPortForward := clientSeedState.NewClientSeedPortForward(net.ParseIP("192.168.0.1")) if seedPortForward != nil { t.Fatalf("expected nil client seed port forward") } }) // This clientSeedState is used across multiple tests. signalIssueSLOKs := make(chan struct{}, 1) clientSeedState := config.NewClientSeedState("US", "2995DB0C968C59C4F23E87988D9C0D41", signalIssueSLOKs) t.Run("eligible client, no transfer", func(t *testing.T) { if len(clientSeedState.GetSeedPayload().SLOKs) != 0 { t.Fatalf("expected 0 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("eligible client, insufficient transfer", func(t *testing.T) { clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")).UpdateProgress(5, 5, 5) if len(clientSeedState.GetSeedPayload().SLOKs) != 0 { t.Fatalf("expected 0 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) rolloverToNextSLOKTime := func() { // Rollover to the next SLOK time, so accrued data transfer will be reset. now := time.Now().UTC() time.Sleep(now.Add(seedPeriod).Truncate(seedPeriod).Sub(now)) } t.Run("eligible client, insufficient transfer after rollover", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")).UpdateProgress(5, 5, 5) if len(clientSeedState.GetSeedPayload().SLOKs) != 0 { t.Fatalf("expected 0 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("eligible client, sufficient transfer, one port forward", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedPortForward := clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")) clientSeedPortForward.UpdateProgress(5, 5, 5) clientSeedPortForward.UpdateProgress(5, 5, 5) select { case <-signalIssueSLOKs: default: t.Fatalf("expected issue SLOKs signal") } if len(clientSeedState.GetSeedPayload().SLOKs) != 1 { t.Fatalf("expected 1 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("eligible client, sufficient transfer, multiple port forwards", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")).UpdateProgress(5, 5, 5) clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")).UpdateProgress(5, 5, 5) select { case <-signalIssueSLOKs: default: t.Fatalf("expected issue SLOKs signal") } // Expect 2 SLOKS: 1 new, and 1 remaining in payload. if len(clientSeedState.GetSeedPayload().SLOKs) != 2 { t.Fatalf("expected 2 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("eligible client, sufficient transfer multiple SLOKs", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedState.NewClientSeedPortForward(net.ParseIP("192.168.0.1")).UpdateProgress(5, 5, 5) clientSeedState.NewClientSeedPortForward(net.ParseIP("10.0.0.1")).UpdateProgress(5, 5, 5) select { case <-signalIssueSLOKs: default: t.Fatalf("expected issue SLOKs signal") } // Expect 4 SLOKS: 2 new, and 2 remaining in payload. if len(clientSeedState.GetSeedPayload().SLOKs) != 4 { t.Fatalf("expected 4 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("clear payload", func(t *testing.T) { clientSeedState.ClearSeedPayload() if len(clientSeedState.GetSeedPayload().SLOKs) != 0 { t.Fatalf("expected 0 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("no transfer required", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedState := config.NewClientSeedState("US", "36F1CF2DF1250BF0C7BA0629CE3DC657", nil) if len(clientSeedState.GetSeedPayload().SLOKs) != 1 { t.Fatalf("expected 1 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) t.Run("concurrent schemes", func(t *testing.T) { rolloverToNextSLOKTime() clientSeedState := config.NewClientSeedState("US", "B4A780E67695595FA486E9B900EA7335", nil) clientSeedPortForward := clientSeedState.NewClientSeedPortForward(net.ParseIP("192.168.0.1")) clientSeedPortForward.UpdateProgress(10, 10, 10) if len(clientSeedState.GetSeedPayload().SLOKs) != 5 { t.Fatalf("expected 5 SLOKs, got %d", len(clientSeedState.GetSeedPayload().SLOKs)) } }) signingPublicKey, signingPrivateKey, err := common.GenerateAuthenticatedDataPackageKeys() if err != nil { t.Fatalf("GenerateAuthenticatedDataPackageKeys failed: %s", err) } pavedRegistries := make(map[string][]byte) pavedOSLFileContents := make(map[string]map[string][]byte) t.Run("pave OSLs", func(t *testing.T) { // Pave sufficient OSLs to cover simulated elapsed time of all test cases. endTime := epoch.Add(1000 * seedPeriod) // In actual deployment, paved files for each propagation channel ID // are dropped in distinct distribution sites. for _, propagationChannelID := range []string{ "2995DB0C968C59C4F23E87988D9C0D41", "E742C25A6D8BA8C17F37E725FA628569", "36F1CF2DF1250BF0C7BA0629CE3DC657"} { // Dummy server entry payloads will be the OSL ID, which the following // tests use to verify that the correct OSL file decrypts successfully. paveServerEntries := make(map[string][]string) for _, scheme := range config.Schemes { oslDuration := scheme.GetOSLDuration() oslTime := scheme.epoch for oslTime.Before(endTime) { firstSLOKRef := &slokReference{ PropagationChannelID: propagationChannelID, SeedSpecID: string(scheme.SeedSpecs[0].ID), Time: oslTime, } firstSLOK := scheme.deriveSLOK(firstSLOKRef) oslID := firstSLOK.ID paveServerEntries[hex.EncodeToString(oslID)] = []string{base64.StdEncoding.EncodeToString(oslID)} oslTime = oslTime.Add(oslDuration) } } // Note: these options are exercised in remoteServerList_test.go omitMD5SumsSchemes := []int{} omitEmptyOSLsSchemes := []int{} firstPaveFiles, err := config.Pave( endTime, propagationChannelID, signingPublicKey, signingPrivateKey, paveServerEntries, omitMD5SumsSchemes, omitEmptyOSLsSchemes, nil) if err != nil { t.Fatalf("Pave failed: %s", err) } paveFiles, err := config.Pave( endTime, propagationChannelID, signingPublicKey, signingPrivateKey, paveServerEntries, omitMD5SumsSchemes, omitEmptyOSLsSchemes, nil) if err != nil { t.Fatalf("Pave failed: %s", err) } // Check that the paved file name matches the name the client will look for. if len(paveFiles) < 1 || paveFiles[len(paveFiles)-1].Name != GetOSLRegistryURL("") { t.Fatalf("invalid registry pave file") } // Check that the content of two paves is the same: all the crypto should be // deterministic. for index, paveFile := range paveFiles { if paveFile.Name != firstPaveFiles[index].Name { t.Fatalf("Pave name mismatch") } if !bytes.Equal(paveFile.Contents, firstPaveFiles[index].Contents) { t.Fatalf("Pave content mismatch") } } // Use the paved content in the following tests. pavedRegistries[propagationChannelID] = paveFiles[len(paveFiles)-1].Contents pavedOSLFileContents[propagationChannelID] = make(map[string][]byte) for _, paveFile := range paveFiles[0:] { pavedOSLFileContents[propagationChannelID][paveFile.Name] = paveFile.Contents } } }) if len(pavedRegistries) != 3 { // Previous subtest failed. Following tests cannot be completed, so abort. t.Fatalf("pave failed") } // To ensure SLOKs are issued at precise time periods, the following tests // bypass ClientSeedState and derive SLOKs directly. expandRanges := func(ranges ...[2]int) []int { a := make([]int, 0) for _, r := range ranges { for n := r[0]; n <= r[1]; n++ { a = append(a, n) } } return a } singleSplitPropagationChannelID := "36F1CF2DF1250BF0C7BA0629CE3DC657" singleSplitScheme := config.Schemes[1] doubleSplitPropagationChannelID := "2995DB0C968C59C4F23E87988D9C0D41" doubleSplitScheme := config.Schemes[0] keySplitTestCases := []struct { description string propagationChannelID string scheme *Scheme issueSLOKTimePeriods []int issueSLOKSeedSpecIndexes []int expectedOSLCount int }{ { "single split scheme: insufficient SLOK periods", singleSplitPropagationChannelID, singleSplitScheme, expandRanges([2]int{0, 23}), []int{0, 1}, 0, }, { "single split scheme: insufficient SLOK seed specs", singleSplitPropagationChannelID, singleSplitScheme, expandRanges([2]int{0, 23}), []int{0}, 0, }, { "single split scheme: sufficient SLOKs", singleSplitPropagationChannelID, singleSplitScheme, expandRanges([2]int{0, 24}), []int{0, 1}, 1, }, { "single split scheme: sufficient SLOKs (alternative seed specs)", singleSplitPropagationChannelID, singleSplitScheme, expandRanges([2]int{0, 24}), []int{1, 2}, 1, }, { "single split scheme: more than sufficient SLOKs", singleSplitPropagationChannelID, singleSplitScheme, expandRanges([2]int{0, 49}), []int{0, 1}, 1, }, { "double split scheme: insufficient SLOK periods", doubleSplitPropagationChannelID, doubleSplitScheme, expandRanges([2]int{0, 4}, [2]int{10, 14}, [2]int{20, 24}, [2]int{30, 34}, [2]int{40, 43}), []int{0, 1}, 0, }, { "double split scheme: insufficient SLOK period spread", doubleSplitPropagationChannelID, doubleSplitScheme, expandRanges([2]int{0, 25}), []int{0, 1}, 0, }, { "double split scheme: insufficient SLOK seed specs", doubleSplitPropagationChannelID, doubleSplitScheme, expandRanges([2]int{0, 4}, [2]int{10, 14}, [2]int{20, 24}, [2]int{30, 34}, [2]int{40, 44}), []int{0}, 0, }, { "double split scheme: sufficient SLOKs", doubleSplitPropagationChannelID, doubleSplitScheme, expandRanges([2]int{0, 4}, [2]int{10, 14}, [2]int{20, 24}, [2]int{30, 34}, [2]int{40, 44}), []int{0, 1}, 1, }, { "double split scheme: sufficient SLOKs (alternative seed specs)", doubleSplitPropagationChannelID, doubleSplitScheme, expandRanges([2]int{0, 4}, [2]int{10, 14}, [2]int{20, 24}, [2]int{30, 34}, [2]int{40, 44}), []int{1, 2}, 1, }, } for _, testCase := range keySplitTestCases { t.Run(testCase.description, func(t *testing.T) { slokMap := make(map[string][]byte) for _, timePeriod := range testCase.issueSLOKTimePeriods { for _, seedSpecIndex := range testCase.issueSLOKSeedSpecIndexes { slok := testCase.scheme.deriveSLOK( &slokReference{ PropagationChannelID: testCase.propagationChannelID, SeedSpecID: string(testCase.scheme.SeedSpecs[seedSpecIndex].ID), Time: epoch.Add(time.Duration(timePeriod) * seedPeriod), }) slokMap[string(slok.ID)] = slok.Key } } startTime := time.Now() lookupSLOKs := func(slokID []byte) []byte { return slokMap[string(slokID)] } registryStreamer, err := NewRegistryStreamer( bytes.NewReader(pavedRegistries[testCase.propagationChannelID]), signingPublicKey, lookupSLOKs) if err != nil { t.Fatalf("NewRegistryStreamer failed: %s", err) } seededOSLCount := 0 for { fileSpec, err := registryStreamer.Next() if err != nil { t.Fatalf("Next failed: %s", err) } if fileSpec == nil { break } seededOSLCount += 1 oslFileContents, ok := pavedOSLFileContents[testCase.propagationChannelID][GetOSLFileURL("", fileSpec.ID)] if !ok { t.Fatalf("unknown OSL file name") } payloadReader, err := NewOSLReader( bytes.NewReader(oslFileContents), fileSpec, lookupSLOKs, signingPublicKey) if err != nil { t.Fatalf("NewOSLReader failed: %s", err) } payload, err := ioutil.ReadAll(payloadReader) if err != nil { t.Fatalf("ReadAll failed: %s", err) } // The decrypted OSL should contain its own ID. if string(payload) != base64.StdEncoding.EncodeToString(fileSpec.ID) { t.Fatalf("unexpected OSL file contents") } } t.Logf("registry size: %d", len(pavedRegistries[testCase.propagationChannelID])) t.Logf("SLOK count: %d", len(slokMap)) t.Logf("seeded OSL count: %d", seededOSLCount) t.Logf("elapsed time: %s", time.Since(startTime)) if seededOSLCount != testCase.expectedOSLCount { t.Fatalf("expected %d OSLs got %d", testCase.expectedOSLCount, seededOSLCount) } }) } }
{ "pile_set_name": "Github" }
Miscellaneous routines ********************** .. toctree:: .. currentmodule:: numpy Performance tuning ------------------ .. autosummary:: :toctree: generated/ setbufsize getbufsize Memory ranges ------------- .. autosummary:: :toctree: generated/ shares_memory may_share_memory byte_bounds Array mixins ------------ .. autosummary:: :toctree: generated/ lib.mixins.NDArrayOperatorsMixin NumPy version comparison ------------------------ .. autosummary:: :toctree: generated/ lib.NumpyVersion Utility ------- .. autosummary:: :toctree: generated/ get_include show_config deprecate deprecate_with_doc Matlab-like Functions --------------------- .. autosummary:: :toctree: generated/ who disp
{ "pile_set_name": "Github" }