code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.synthetic;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil;
import org.jetbrains.plugins.groovy.transformations.TransformationContext;
public class GrTraitField extends GrLightField implements PsiMirrorElement {
private static final Logger LOG = Logger.getInstance(GrTraitField.class);
private final PsiField myField;
public GrTraitField(@NotNull GrField field, GrTypeDefinition clazz, PsiSubstitutor substitutor, @Nullable TransformationContext context) {
super(clazz, getNewNameForField(field), substitutor.substitute(field.getType()), field);
GrLightModifierList modifierList = getModifierList();
for (String modifier : PsiModifier.MODIFIERS) {
boolean hasModifierProperty;
GrModifierList fieldModifierList = field.getModifierList();
if (context == null || fieldModifierList == null) {
hasModifierProperty = field.hasModifierProperty(modifier);
} else {
hasModifierProperty = context.hasModifierProperty(fieldModifierList, modifier);
}
if (hasModifierProperty) {
modifierList.addModifier(modifier);
}
}
modifierList.copyAnnotations(field.getModifierList());
myField = field;
}
@NotNull
private static String getNewNameForField(@NotNull PsiField field) {
PsiClass containingClass = field.getContainingClass();
LOG.assertTrue(containingClass != null);
return GrTraitUtil.getTraitFieldPrefix(containingClass) + field.getName();
}
@NotNull
@Override
public PsiField getPrototype() {
return myField;
}
}
| siosio/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrTraitField.java | Java | apache-2.0 | 2,141 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Insights.OutputClasses;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using System.Management.Automation;
using System.Threading;
namespace Microsoft.Azure.Commands.Insights.Diagnostics
{
/// <summary>
/// Gets the logs and metrics for the resource.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AzureRmDiagnosticSetting"), OutputType(typeof(PSServiceDiagnosticSettings))]
public class GetAzureRmDiagnosticSettingCommand : ManagementCmdletBase
{
#region Parameters declarations
/// <summary>
/// Gets or sets the resourceId parameter of the cmdlet
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceId")]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }
#endregion
protected override void ProcessRecordInternal()
{
ServiceDiagnosticSettingsResource result = this.InsightsManagementClient.ServiceDiagnosticSettings.GetAsync(resourceUri: this.ResourceId, cancellationToken: CancellationToken.None).Result;
PSServiceDiagnosticSettings psResult = new PSServiceDiagnosticSettings(result);
WriteObject(psResult);
}
}
}
| seanbamsft/azure-powershell | src/ResourceManager/Insights/Commands.Insights/Diagnostics/GetAzureRmDiagnosticSettingCommand.cs | C# | apache-2.0 | 2,092 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.action.search.type;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.fetch.FetchSearchResultProvider;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.search.query.QuerySearchResultProvider;
import org.elasticsearch.threadpool.ThreadPool;
import static org.elasticsearch.action.search.type.TransportSearchHelper.buildScrollId;
/**
*
*/
public class TransportSearchCountAction extends TransportSearchTypeAction {
@Inject
public TransportSearchCountAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) {
super(settings, threadPool, clusterService, searchService, searchPhaseController, actionFilters);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<QuerySearchResultProvider> {
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
}
@Override
protected String firstPhaseName() {
return "query";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QuerySearchResultProvider> listener) {
searchService.sendExecuteQuery(node, request, listener);
}
@Override
protected void moveToSecondPhase() throws Exception {
// no need to sort, since we know we have no hits back
final InternalSearchResponse internalResponse = searchPhaseController.merge(SearchPhaseController.EMPTY_DOCS, firstResults, (AtomicArray<? extends FetchSearchResultProvider>) AtomicArray.empty());
String scrollId = null;
if (request.scroll() != null) {
scrollId = buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successfulOps.get(), buildTookInMillis(), buildShardFailures()));
}
}
}
| dmiszkiewicz/elasticsearch | src/main/java/org/elasticsearch/action/search/type/TransportSearchCountAction.java | Java | apache-2.0 | 3,920 |
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.stratos.common.beans.topology;
import org.apache.stratos.common.beans.PropertyBean;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "clusters")
public class ClusterBean {
private String alias;
private String serviceName;
private String clusterId;
private List<MemberBean> member;
private String tenantRange;
private List<String> hostNames;
private boolean isLbCluster;
private List<PropertyBean> property;
private List<InstanceBean> instances;
public List<InstanceBean> getInstances() {
return instances;
}
public void setInstances(List<InstanceBean> instances) {
this.instances = instances;
}
@Override
public String toString() {
return "Cluster [serviceName=" + getServiceName() + ", clusterId=" + getClusterId() + ", member=" + getMember()
+ ", tenantRange=" + getTenantRange() + ", hostNames=" + getHostNames() + ", isLbCluster=" + isLbCluster()
+ ", property=" + getProperty() + "]";
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getClusterId() {
return clusterId;
}
public void setClusterId(String clusterId) {
this.clusterId = clusterId;
}
public List<MemberBean> getMember() {
return member;
}
public void setMember(List<MemberBean> member) {
this.member = member;
}
public String getTenantRange() {
return tenantRange;
}
public void setTenantRange(String tenantRange) {
this.tenantRange = tenantRange;
}
public List<String> getHostNames() {
return hostNames;
}
public void setHostNames(List<String> hostNames) {
this.hostNames = hostNames;
}
public boolean isLbCluster() {
return isLbCluster;
}
public void setLbCluster(boolean isLbCluster) {
this.isLbCluster = isLbCluster;
}
public List<PropertyBean> getProperty() {
return property;
}
public void setProperty(List<PropertyBean> property) {
this.property = property;
}
}
| pkdevbox/stratos | components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/topology/ClusterBean.java | Java | apache-2.0 | 3,225 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.screens.datasource.management.client.dbexplorer.schemas;
import com.google.gwt.view.client.AsyncDataProvider;
import org.uberfire.client.mvp.UberElement;
import org.uberfire.ext.widgets.common.client.common.HasBusyIndicator;
public interface DatabaseSchemaExplorerView
extends UberElement< DatabaseSchemaExplorerView.Presenter >, HasBusyIndicator {
interface Presenter {
void onOpen( DatabaseSchemaRow row );
}
interface Handler {
void onOpen( String schemaName );
}
void setDataProvider( AsyncDataProvider< DatabaseSchemaRow > dataProvider );
void redraw( );
} | romartin/kie-wb-common | kie-wb-common-screens/kie-wb-common-datasource-mgmt/kie-wb-common-datasource-mgmt-client/src/main/java/org/kie/workbench/common/screens/datasource/management/client/dbexplorer/schemas/DatabaseSchemaExplorerView.java | Java | apache-2.0 | 1,272 |
//===--- BasicInstructionPropertyDumper.cpp -------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
namespace {
class BasicInstructionPropertyDumper : public SILModuleTransform {
void run() override {
for (auto &Fn : *getModule()) {
unsigned Count = 0;
llvm::outs() << "@" << Fn.getName() << "\n";
for (auto &BB : Fn) {
for (auto &I : BB) {
llvm::outs() << "Inst #: " << Count++ << "\n " << I;
llvm::outs() << " Mem Behavior: " << I.getMemoryBehavior() << "\n";
llvm::outs() << " Release Behavior: " << I.getReleasingBehavior()
<< "\n";
}
}
}
}
llvm::StringRef getName() override {
return "BasicInstructionPropertyDumper";
}
};
} // end anonymous namespace
SILTransform *swift::createBasicInstructionPropertyDumper() {
return new BasicInstructionPropertyDumper();
}
| russbishop/swift | lib/SILOptimizer/UtilityPasses/BasicInstructionPropertyDumper.cpp | C++ | apache-2.0 | 1,568 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/apps/chrome_native_app_window_views_aura.h"
#include "apps/ui/views/app_window_frame_view.h"
#include "ash/ash_constants.h"
#include "ash/frame/custom_frame_view_ash.h"
#include "ash/screen_util.h"
#include "ash/shell.h"
#include "ash/wm/immersive_fullscreen_controller.h"
#include "ash/wm/panels/panel_frame_view.h"
#include "ash/wm/window_properties.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_state_delegate.h"
#include "ash/wm/window_state_observer.h"
#include "chrome/browser/ui/ash/ash_util.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_context_menu.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/views/apps/app_window_easy_resize_window_targeter.h"
#include "chrome/browser/ui/views/apps/shaped_app_window_targeter.h"
#include "chrome/browser/web_applications/web_app.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/base/hit_test.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/widget/widget.h"
#if defined(OS_CHROMEOS)
#include "ash/shell_window_ids.h"
#endif
#if defined(OS_LINUX)
#include "chrome/browser/shell_integration_linux.h"
#endif
using extensions::AppWindow;
namespace {
// This class handles a user's fullscreen request (Shift+F4/F4).
class NativeAppWindowStateDelegate : public ash::wm::WindowStateDelegate,
public ash::wm::WindowStateObserver,
public aura::WindowObserver {
public:
NativeAppWindowStateDelegate(AppWindow* app_window,
extensions::NativeAppWindow* native_app_window)
: app_window_(app_window),
window_state_(
ash::wm::GetWindowState(native_app_window->GetNativeWindow())) {
// Add a window state observer to exit fullscreen properly in case
// fullscreen is exited without going through AppWindow::Restore(). This
// is the case when exiting immersive fullscreen via the "Restore" window
// control.
// TODO(pkotwicz): This is a hack. Remove ASAP. http://crbug.com/319048
window_state_->AddObserver(this);
window_state_->window()->AddObserver(this);
}
~NativeAppWindowStateDelegate() override {
if (window_state_) {
window_state_->RemoveObserver(this);
window_state_->window()->RemoveObserver(this);
}
}
private:
// Overridden from ash::wm::WindowStateDelegate.
bool ToggleFullscreen(ash::wm::WindowState* window_state) override {
// Windows which cannot be maximized should not be fullscreened.
DCHECK(window_state->IsFullscreen() || window_state->CanMaximize());
if (window_state->IsFullscreen())
app_window_->Restore();
else if (window_state->CanMaximize())
app_window_->OSFullscreen();
return true;
}
// Overridden from ash::wm::WindowStateDelegate.
bool RestoreAlwaysOnTop(ash::wm::WindowState* window_state) override {
app_window_->RestoreAlwaysOnTop();
return true;
}
// Overridden from ash::wm::WindowStateObserver:
void OnPostWindowStateTypeChange(ash::wm::WindowState* window_state,
ash::wm::WindowStateType old_type) override {
// Since the window state might get set by a window manager, it is possible
// to come here before the application set its |BaseWindow|.
if (!window_state->IsFullscreen() && !window_state->IsMinimized() &&
app_window_->GetBaseWindow() &&
app_window_->GetBaseWindow()->IsFullscreenOrPending()) {
app_window_->Restore();
// Usually OnNativeWindowChanged() is called when the window bounds are
// changed as a result of a state type change. Because the change in state
// type has already occurred, we need to call OnNativeWindowChanged()
// explicitly.
app_window_->OnNativeWindowChanged();
}
}
// Overridden from aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override {
window_state_->RemoveObserver(this);
window_state_->window()->RemoveObserver(this);
window_state_ = NULL;
}
// Not owned.
AppWindow* app_window_;
ash::wm::WindowState* window_state_;
DISALLOW_COPY_AND_ASSIGN(NativeAppWindowStateDelegate);
};
} // namespace
ChromeNativeAppWindowViewsAura::ChromeNativeAppWindowViewsAura() {
}
ChromeNativeAppWindowViewsAura::~ChromeNativeAppWindowViewsAura() {
}
void ChromeNativeAppWindowViewsAura::InitializeWindow(
AppWindow* app_window,
const AppWindow::CreateParams& create_params) {
ChromeNativeAppWindowViews::InitializeWindow(app_window, create_params);
// Restore docked state on ash desktop and ignore it elsewhere.
if (create_params.state == ui::SHOW_STATE_DOCKED &&
chrome::GetHostDesktopTypeForNativeWindow(widget()->GetNativeWindow()) ==
chrome::HOST_DESKTOP_TYPE_ASH) {
widget()->GetNativeWindow()->SetProperty(aura::client::kShowStateKey,
create_params.state);
}
}
void ChromeNativeAppWindowViewsAura::OnBeforeWidgetInit(
const AppWindow::CreateParams& create_params,
views::Widget::InitParams* init_params,
views::Widget* widget) {
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
std::string app_name = web_app::GenerateApplicationNameFromExtensionId(
app_window()->extension_id());
// Set up a custom WM_CLASS for app windows. This allows task switchers in
// X11 environments to distinguish them from main browser windows.
init_params->wm_class_name = web_app::GetWMClassFromAppName(app_name);
init_params->wm_class_class = shell_integration_linux::GetProgramClassName();
const char kX11WindowRoleApp[] = "app";
init_params->wm_role_name = std::string(kX11WindowRoleApp);
#endif
ChromeNativeAppWindowViews::OnBeforeWidgetInit(create_params, init_params,
widget);
#if defined(OS_CHROMEOS)
if (create_params.is_ime_window) {
// Puts ime windows into ime window container.
init_params->parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(),
ash::kShellWindowId_ImeWindowParentContainer);
}
#endif
}
void ChromeNativeAppWindowViewsAura::OnBeforePanelWidgetInit(
bool use_default_bounds,
views::Widget::InitParams* init_params,
views::Widget* widget) {
ChromeNativeAppWindowViews::OnBeforePanelWidgetInit(use_default_bounds,
init_params,
widget);
if (ash::Shell::HasInstance() && use_default_bounds) {
// Open a new panel on the target root.
init_params->bounds = ash::ScreenUtil::ConvertRectToScreen(
ash::Shell::GetTargetRootWindow(), gfx::Rect(GetPreferredSize()));
}
}
views::NonClientFrameView*
ChromeNativeAppWindowViewsAura::CreateNonStandardAppFrame() {
apps::AppWindowFrameView* frame =
new apps::AppWindowFrameView(widget(), this, HasFrameColor(),
ActiveFrameColor(), InactiveFrameColor());
frame->Init();
// For Aura windows on the Ash desktop the sizes are different and the user
// can resize the window from slightly outside the bounds as well.
if (chrome::IsNativeWindowInAsh(widget()->GetNativeWindow())) {
frame->SetResizeSizes(ash::kResizeInsideBoundsSize,
ash::kResizeOutsideBoundsSize,
ash::kResizeAreaCornerSize);
}
#if !defined(OS_CHROMEOS)
// For non-Ash windows, install an easy resize window targeter, which ensures
// that the root window (not the app) receives mouse events on the edges.
if (chrome::GetHostDesktopTypeForNativeWindow(widget()->GetNativeWindow()) !=
chrome::HOST_DESKTOP_TYPE_ASH) {
aura::Window* window = widget()->GetNativeWindow();
int resize_inside = frame->resize_inside_bounds_size();
gfx::Insets inset(resize_inside, resize_inside, resize_inside,
resize_inside);
// Add the AppWindowEasyResizeWindowTargeter on the window, not its root
// window. The root window does not have a delegate, which is needed to
// handle the event in Linux.
window->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
new AppWindowEasyResizeWindowTargeter(window, inset, this)));
}
#endif
return frame;
}
gfx::Rect ChromeNativeAppWindowViewsAura::GetRestoredBounds() const {
gfx::Rect* bounds =
widget()->GetNativeWindow()->GetProperty(ash::kRestoreBoundsOverrideKey);
if (bounds && !bounds->IsEmpty())
return *bounds;
return ChromeNativeAppWindowViews::GetRestoredBounds();
}
ui::WindowShowState ChromeNativeAppWindowViewsAura::GetRestoredState() const {
// Use kRestoreShowStateKey in case a window is minimized/hidden.
ui::WindowShowState restore_state = widget()->GetNativeWindow()->GetProperty(
aura::client::kRestoreShowStateKey);
if (widget()->GetNativeWindow()->GetProperty(
ash::kRestoreBoundsOverrideKey)) {
// If an override is given, we use that restore state (after filtering).
restore_state = widget()->GetNativeWindow()->GetProperty(
ash::kRestoreShowStateOverrideKey);
} else {
// Otherwise first normal states are checked.
if (IsMaximized())
return ui::SHOW_STATE_MAXIMIZED;
if (IsFullscreen()) {
if (immersive_fullscreen_controller_.get() &&
immersive_fullscreen_controller_->IsEnabled()) {
// Restore windows which were previously in immersive fullscreen to
// maximized. Restoring the window to a different fullscreen type
// makes for a bad experience.
return ui::SHOW_STATE_MAXIMIZED;
}
return ui::SHOW_STATE_FULLSCREEN;
}
if (widget()->GetNativeWindow()->GetProperty(
aura::client::kShowStateKey) == ui::SHOW_STATE_DOCKED ||
widget()->GetNativeWindow()->GetProperty(
aura::client::kRestoreShowStateKey) == ui::SHOW_STATE_DOCKED) {
return ui::SHOW_STATE_DOCKED;
}
}
// Whitelist states to return so that invalid and transient states
// are not saved and used to restore windows when they are recreated.
switch (restore_state) {
case ui::SHOW_STATE_NORMAL:
case ui::SHOW_STATE_MAXIMIZED:
case ui::SHOW_STATE_FULLSCREEN:
return restore_state;
case ui::SHOW_STATE_DEFAULT:
case ui::SHOW_STATE_MINIMIZED:
case ui::SHOW_STATE_INACTIVE:
case ui::SHOW_STATE_DOCKED:
case ui::SHOW_STATE_END:
return ui::SHOW_STATE_NORMAL;
}
return ui::SHOW_STATE_NORMAL;
}
bool ChromeNativeAppWindowViewsAura::IsAlwaysOnTop() const {
return app_window()->window_type_is_panel()
? ash::wm::GetWindowState(widget()->GetNativeWindow())
->panel_attached()
: widget()->IsAlwaysOnTop();
}
void ChromeNativeAppWindowViewsAura::ShowContextMenuForView(
views::View* source,
const gfx::Point& p,
ui::MenuSourceType source_type) {
#if defined(OS_CHROMEOS)
scoped_ptr<ui::MenuModel> model =
CreateMultiUserContextMenu(app_window()->GetNativeWindow());
if (!model.get())
return;
// Only show context menu if point is in caption.
gfx::Point point_in_view_coords(p);
views::View::ConvertPointFromScreen(widget()->non_client_view(),
&point_in_view_coords);
int hit_test =
widget()->non_client_view()->NonClientHitTest(point_in_view_coords);
if (hit_test == HTCAPTION) {
menu_runner_.reset(new views::MenuRunner(
model.get(),
views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU));
if (menu_runner_->RunMenuAt(source->GetWidget(), NULL,
gfx::Rect(p, gfx::Size(0, 0)),
views::MENU_ANCHOR_TOPLEFT, source_type) ==
views::MenuRunner::MENU_DELETED) {
return;
}
}
#endif
}
views::NonClientFrameView*
ChromeNativeAppWindowViewsAura::CreateNonClientFrameView(
views::Widget* widget) {
if (chrome::IsNativeViewInAsh(widget->GetNativeView())) {
// Set the delegate now because CustomFrameViewAsh sets the
// WindowStateDelegate if one is not already set.
ash::wm::GetWindowState(GetNativeWindow())
->SetDelegate(
scoped_ptr<ash::wm::WindowStateDelegate>(
new NativeAppWindowStateDelegate(app_window(), this)).Pass());
if (IsFrameless())
return CreateNonStandardAppFrame();
if (app_window()->window_type_is_panel()) {
views::NonClientFrameView* frame_view =
new ash::PanelFrameView(widget, ash::PanelFrameView::FRAME_ASH);
frame_view->set_context_menu_controller(this);
return frame_view;
}
ash::CustomFrameViewAsh* custom_frame_view =
new ash::CustomFrameViewAsh(widget);
// Non-frameless app windows can be put into immersive fullscreen.
immersive_fullscreen_controller_.reset(
new ash::ImmersiveFullscreenController());
custom_frame_view->InitImmersiveFullscreenControllerForView(
immersive_fullscreen_controller_.get());
custom_frame_view->GetHeaderView()->set_context_menu_controller(this);
if (HasFrameColor()) {
custom_frame_view->SetFrameColors(ActiveFrameColor(),
InactiveFrameColor());
}
return custom_frame_view;
}
return ChromeNativeAppWindowViews::CreateNonClientFrameView(widget);
}
void ChromeNativeAppWindowViewsAura::SetFullscreen(int fullscreen_types) {
ChromeNativeAppWindowViews::SetFullscreen(fullscreen_types);
if (immersive_fullscreen_controller_.get()) {
// |immersive_fullscreen_controller_| should only be set if immersive
// fullscreen is the fullscreen type used by the OS.
immersive_fullscreen_controller_->SetEnabled(
ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP,
(fullscreen_types & AppWindow::FULLSCREEN_TYPE_OS) != 0);
// Autohide the shelf instead of hiding the shelf completely when only in
// OS fullscreen.
ash::wm::WindowState* window_state =
ash::wm::GetWindowState(widget()->GetNativeWindow());
window_state->set_hide_shelf_when_fullscreen(fullscreen_types !=
AppWindow::FULLSCREEN_TYPE_OS);
DCHECK(ash::Shell::HasInstance());
ash::Shell::GetInstance()->UpdateShelfVisibility();
}
}
void ChromeNativeAppWindowViewsAura::UpdateShape(scoped_ptr<SkRegion> region) {
bool had_shape = !!shape();
ChromeNativeAppWindowViews::UpdateShape(region.Pass());
aura::Window* native_window = widget()->GetNativeWindow();
if (shape() && !had_shape) {
native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
new ShapedAppWindowTargeter(native_window, this)));
} else if (!shape() && had_shape) {
native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>());
}
}
| Chilledheart/chromium | chrome/browser/ui/views/apps/chrome_native_app_window_views_aura.cc | C++ | bsd-3-clause | 15,174 |
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace Examples.FirstAutomappedProject
{
/// <summary>
/// This is a convention that will be applied to all entities in your application. What this particular
/// convention does is to specify that many-to-one, one-to-many, and many-to-many relationships will all
/// have their Cascade option set to All.
/// </summary>
class CascadeConvention : IReferenceConvention, IHasManyConvention, IHasManyToManyConvention
{
public void Apply(IManyToOneInstance instance)
{
instance.Cascade.All();
}
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Cascade.All();
}
public void Apply(IManyToManyCollectionInstance instance)
{
instance.Cascade.All();
}
}
} | HermanSchoenfeld/fluent-nhibernate | src/Examples.FirstAutomappedProject/CascadeConvention.cs | C# | bsd-3-clause | 923 |
from SimpleCV import Camera, Image, Color, TemporalColorTracker, ROI, Display
import matplotlib.pyplot as plt
cam = Camera(1)
tct = TemporalColorTracker()
img = cam.getImage()
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
tct.train(cam,roi=roi,maxFrames=250,pkWndw=20)
# Matplot Lib example plotting
plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'}
for key in tct.data.keys():
plt.plot(tct.data[key],plotc[key])
for pt in tct.peaks[key]:
plt.plot(pt[0],pt[1],'r*')
for pt in tct.valleys[key]:
plt.plot(pt[0],pt[1],'b*')
plt.grid()
plt.show()
disp = Display((800,600))
while disp.isNotDone():
img = cam.getImage()
result = tct.recognize(img)
plt.plot(tct._rtData,'r-')
plt.grid()
plt.savefig('temp.png')
plt.clf()
plotImg = Image('temp.png')
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
roi.draw(width=3)
img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
img = img.applyLayers()
img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5)
img.save(disp)
| beni55/SimpleCV | SimpleCV/MachineLearning/TestTemporalColorTracker.py | Python | bsd-3-clause | 1,136 |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/bits.h"
#include "src/base/division-by-constant.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/machine-operator-reducer.h"
#include "src/compiler/typer.h"
#include "test/unittests/compiler/graph-unittest.h"
#include "test/unittests/compiler/node-test-utils.h"
#include "testing/gmock-support.h"
using testing::AllOf;
using testing::BitEq;
using testing::Capture;
using testing::CaptureEq;
namespace v8 {
namespace internal {
namespace compiler {
class MachineOperatorReducerTest : public TypedGraphTest {
public:
explicit MachineOperatorReducerTest(int num_parameters = 2)
: TypedGraphTest(num_parameters), machine_(zone()) {}
protected:
Reduction Reduce(Node* node) {
JSOperatorBuilder javascript(zone());
JSGraph jsgraph(isolate(), graph(), common(), &javascript, &machine_);
MachineOperatorReducer reducer(&jsgraph);
return reducer.Reduce(node);
}
Matcher<Node*> IsTruncatingDiv(const Matcher<Node*>& dividend_matcher,
const int32_t divisor) {
base::MagicNumbersForDivision<uint32_t> const mag =
base::SignedDivisionByConstant(bit_cast<uint32_t>(divisor));
int32_t const multiplier = bit_cast<int32_t>(mag.multiplier);
int32_t const shift = bit_cast<int32_t>(mag.shift);
Matcher<Node*> quotient_matcher =
IsInt32MulHigh(dividend_matcher, IsInt32Constant(multiplier));
if (divisor > 0 && multiplier < 0) {
quotient_matcher = IsInt32Add(quotient_matcher, dividend_matcher);
} else if (divisor < 0 && multiplier > 0) {
quotient_matcher = IsInt32Sub(quotient_matcher, dividend_matcher);
}
if (shift) {
quotient_matcher = IsWord32Sar(quotient_matcher, IsInt32Constant(shift));
}
return IsInt32Add(quotient_matcher,
IsWord32Shr(dividend_matcher, IsInt32Constant(31)));
}
MachineOperatorBuilder* machine() { return &machine_; }
private:
MachineOperatorBuilder machine_;
};
template <typename T>
class MachineOperatorReducerTestWithParam
: public MachineOperatorReducerTest,
public ::testing::WithParamInterface<T> {
public:
explicit MachineOperatorReducerTestWithParam(int num_parameters = 2)
: MachineOperatorReducerTest(num_parameters) {}
~MachineOperatorReducerTestWithParam() OVERRIDE {}
};
namespace {
const float kFloat32Values[] = {
-std::numeric_limits<float>::infinity(), -2.70497e+38f, -1.4698e+37f,
-1.22813e+35f, -1.20555e+35f, -1.34584e+34f,
-1.0079e+32f, -6.49364e+26f, -3.06077e+25f,
-1.46821e+25f, -1.17658e+23f, -1.9617e+22f,
-2.7357e+20f, -1.48708e+13f, -1.89633e+12f,
-4.66622e+11f, -2.22581e+11f, -1.45381e+10f,
-1.3956e+09f, -1.32951e+09f, -1.30721e+09f,
-1.19756e+09f, -9.26822e+08f, -6.35647e+08f,
-4.00037e+08f, -1.81227e+08f, -5.09256e+07f,
-964300.0f, -192446.0f, -28455.0f,
-27194.0f, -26401.0f, -20575.0f,
-17069.0f, -9167.0f, -960.178f,
-113.0f, -62.0f, -15.0f,
-7.0f, -0.0256635f, -4.60374e-07f,
-3.63759e-10f, -4.30175e-14f, -5.27385e-15f,
-1.48084e-15f, -1.05755e-19f, -3.2995e-21f,
-1.67354e-23f, -1.11885e-23f, -1.78506e-30f,
-5.07594e-31f, -3.65799e-31f, -1.43718e-34f,
-1.27126e-38f, -0.0f, 0.0f,
1.17549e-38f, 1.56657e-37f, 4.08512e-29f,
3.31357e-28f, 6.25073e-22f, 4.1723e-13f,
1.44343e-09f, 5.27004e-08f, 9.48298e-08f,
5.57888e-07f, 4.89988e-05f, 0.244326f,
12.4895f, 19.0f, 47.0f,
106.0f, 538.324f, 564.536f,
819.124f, 7048.0f, 12611.0f,
19878.0f, 20309.0f, 797056.0f,
1.77219e+09f, 1.51116e+11f, 4.18193e+13f,
3.59167e+16f, 3.38211e+19f, 2.67488e+20f,
1.78831e+21f, 9.20914e+21f, 8.35654e+23f,
1.4495e+24f, 5.94015e+25f, 4.43608e+30f,
2.44502e+33f, 2.61152e+33f, 1.38178e+37f,
1.71306e+37f, 3.31899e+38f, 3.40282e+38f,
std::numeric_limits<float>::infinity()};
const double kFloat64Values[] = {
-V8_INFINITY, -4.23878e+275, -5.82632e+265, -6.60355e+220, -6.26172e+212,
-2.56222e+211, -4.82408e+201, -1.84106e+157, -1.63662e+127, -1.55772e+100,
-1.67813e+72, -2.3382e+55, -3.179e+30, -1.441e+09, -1.0647e+09,
-7.99361e+08, -5.77375e+08, -2.20984e+08, -32757, -13171,
-9970, -3984, -107, -105, -92,
-77, -61, -0.000208163, -1.86685e-06, -1.17296e-10,
-9.26358e-11, -5.08004e-60, -1.74753e-65, -1.06561e-71, -5.67879e-79,
-5.78459e-130, -2.90989e-171, -7.15489e-243, -3.76242e-252, -1.05639e-263,
-4.40497e-267, -2.19666e-273, -4.9998e-276, -5.59821e-278, -2.03855e-282,
-5.99335e-283, -7.17554e-284, -3.11744e-309, -0.0, 0.0,
2.22507e-308, 1.30127e-270, 7.62898e-260, 4.00313e-249, 3.16829e-233,
1.85244e-228, 2.03544e-129, 1.35126e-110, 1.01182e-106, 5.26333e-94,
1.35292e-90, 2.85394e-83, 1.78323e-77, 5.4967e-57, 1.03207e-25,
4.57401e-25, 1.58738e-05, 2, 125, 2310,
9636, 14802, 17168, 28945, 29305,
4.81336e+07, 1.41207e+08, 4.65962e+08, 1.40499e+09, 2.12648e+09,
8.80006e+30, 1.4446e+45, 1.12164e+54, 2.48188e+89, 6.71121e+102,
3.074e+112, 4.9699e+152, 5.58383e+166, 4.30654e+172, 7.08824e+185,
9.6586e+214, 2.028e+223, 6.63277e+243, 1.56192e+261, 1.23202e+269,
5.72883e+289, 8.5798e+290, 1.40256e+294, 1.79769e+308, V8_INFINITY};
const int32_t kInt32Values[] = {
std::numeric_limits<int32_t>::min(), -1914954528, -1698749618,
-1578693386, -1577976073, -1573998034,
-1529085059, -1499540537, -1299205097,
-1090814845, -938186388, -806828902,
-750927650, -520676892, -513661538,
-453036354, -433622833, -282638793,
-28375, -27788, -22770,
-18806, -14173, -11956,
-11200, -10212, -8160,
-3751, -2758, -1522,
-121, -120, -118,
-117, -106, -84,
-80, -74, -59,
-52, -48, -39,
-35, -17, -11,
-10, -9, -7,
-5, 0, 9,
12, 17, 23,
29, 31, 33,
35, 40, 47,
55, 56, 62,
64, 67, 68,
69, 74, 79,
84, 89, 90,
97, 104, 118,
124, 126, 127,
7278, 17787, 24136,
24202, 25570, 26680,
30242, 32399, 420886487,
642166225, 821912648, 822577803,
851385718, 1212241078, 1411419304,
1589626102, 1596437184, 1876245816,
1954730266, 2008792749, 2045320228,
std::numeric_limits<int32_t>::max()};
const int64_t kInt64Values[] = {
std::numeric_limits<int64_t>::min(), V8_INT64_C(-8974392461363618006),
V8_INT64_C(-8874367046689588135), V8_INT64_C(-8269197512118230839),
V8_INT64_C(-8146091527100606733), V8_INT64_C(-7550917981466150848),
V8_INT64_C(-7216590251577894337), V8_INT64_C(-6464086891160048440),
V8_INT64_C(-6365616494908257190), V8_INT64_C(-6305630541365849726),
V8_INT64_C(-5982222642272245453), V8_INT64_C(-5510103099058504169),
V8_INT64_C(-5496838675802432701), V8_INT64_C(-4047626578868642657),
V8_INT64_C(-4033755046900164544), V8_INT64_C(-3554299241457877041),
V8_INT64_C(-2482258764588614470), V8_INT64_C(-1688515425526875335),
V8_INT64_C(-924784137176548532), V8_INT64_C(-725316567157391307),
V8_INT64_C(-439022654781092241), V8_INT64_C(-105545757668917080),
V8_INT64_C(-2088319373), V8_INT64_C(-2073699916),
V8_INT64_C(-1844949911), V8_INT64_C(-1831090548),
V8_INT64_C(-1756711933), V8_INT64_C(-1559409497),
V8_INT64_C(-1281179700), V8_INT64_C(-1211513985),
V8_INT64_C(-1182371520), V8_INT64_C(-785934753),
V8_INT64_C(-767480697), V8_INT64_C(-705745662),
V8_INT64_C(-514362436), V8_INT64_C(-459916580),
V8_INT64_C(-312328082), V8_INT64_C(-302949707),
V8_INT64_C(-285499304), V8_INT64_C(-125701262),
V8_INT64_C(-95139843), V8_INT64_C(-32768),
V8_INT64_C(-27542), V8_INT64_C(-23600),
V8_INT64_C(-18582), V8_INT64_C(-17770),
V8_INT64_C(-9086), V8_INT64_C(-9010),
V8_INT64_C(-8244), V8_INT64_C(-2890),
V8_INT64_C(-103), V8_INT64_C(-34),
V8_INT64_C(-27), V8_INT64_C(-25),
V8_INT64_C(-9), V8_INT64_C(-7),
V8_INT64_C(0), V8_INT64_C(2),
V8_INT64_C(38), V8_INT64_C(58),
V8_INT64_C(65), V8_INT64_C(93),
V8_INT64_C(111), V8_INT64_C(1003),
V8_INT64_C(1267), V8_INT64_C(12797),
V8_INT64_C(23122), V8_INT64_C(28200),
V8_INT64_C(30888), V8_INT64_C(42648848),
V8_INT64_C(116836693), V8_INT64_C(263003643),
V8_INT64_C(571039860), V8_INT64_C(1079398689),
V8_INT64_C(1145196402), V8_INT64_C(1184846321),
V8_INT64_C(1758281648), V8_INT64_C(1859991374),
V8_INT64_C(1960251588), V8_INT64_C(2042443199),
V8_INT64_C(296220586027987448), V8_INT64_C(1015494173071134726),
V8_INT64_C(1151237951914455318), V8_INT64_C(1331941174616854174),
V8_INT64_C(2022020418667972654), V8_INT64_C(2450251424374977035),
V8_INT64_C(3668393562685561486), V8_INT64_C(4858229301215502171),
V8_INT64_C(4919426235170669383), V8_INT64_C(5034286595330341762),
V8_INT64_C(5055797915536941182), V8_INT64_C(6072389716149252074),
V8_INT64_C(6185309910199801210), V8_INT64_C(6297328311011094138),
V8_INT64_C(6932372858072165827), V8_INT64_C(8483640924987737210),
V8_INT64_C(8663764179455849203), V8_INT64_C(8877197042645298254),
V8_INT64_C(8901543506779157333), std::numeric_limits<int64_t>::max()};
const uint32_t kUint32Values[] = {
0x00000000, 0x00000001, 0xffffffff, 0x1b09788b, 0x04c5fce8, 0xcc0de5bf,
0x273a798e, 0x187937a3, 0xece3af83, 0x5495a16b, 0x0b668ecc, 0x11223344,
0x0000009e, 0x00000043, 0x0000af73, 0x0000116b, 0x00658ecc, 0x002b3b4c,
0x88776655, 0x70000000, 0x07200000, 0x7fffffff, 0x56123761, 0x7fffff00,
0x761c4761, 0x80000000, 0x88888888, 0xa0000000, 0xdddddddd, 0xe0000000,
0xeeeeeeee, 0xfffffffd, 0xf0000000, 0x007fffff, 0x003fffff, 0x001fffff,
0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff, 0x0000ffff, 0x00007fff,
0x00003fff, 0x00001fff, 0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff};
struct ComparisonBinaryOperator {
const Operator* (MachineOperatorBuilder::*constructor)();
const char* constructor_name;
};
std::ostream& operator<<(std::ostream& os,
ComparisonBinaryOperator const& cbop) {
return os << cbop.constructor_name;
}
const ComparisonBinaryOperator kComparisonBinaryOperators[] = {
#define OPCODE(Opcode) \
{ &MachineOperatorBuilder::Opcode, #Opcode } \
,
MACHINE_COMPARE_BINOP_LIST(OPCODE)
#undef OPCODE
};
} // namespace
// -----------------------------------------------------------------------------
// Unary operators
namespace {
struct UnaryOperator {
const Operator* (MachineOperatorBuilder::*constructor)();
const char* constructor_name;
};
std::ostream& operator<<(std::ostream& os, const UnaryOperator& unop) {
return os << unop.constructor_name;
}
static const UnaryOperator kUnaryOperators[] = {
{&MachineOperatorBuilder::ChangeInt32ToFloat64, "ChangeInt32ToFloat64"},
{&MachineOperatorBuilder::ChangeUint32ToFloat64, "ChangeUint32ToFloat64"},
{&MachineOperatorBuilder::ChangeFloat64ToInt32, "ChangeFloat64ToInt32"},
{&MachineOperatorBuilder::ChangeFloat64ToUint32, "ChangeFloat64ToUint32"},
{&MachineOperatorBuilder::ChangeInt32ToInt64, "ChangeInt32ToInt64"},
{&MachineOperatorBuilder::ChangeUint32ToUint64, "ChangeUint32ToUint64"},
{&MachineOperatorBuilder::TruncateFloat64ToInt32, "TruncateFloat64ToInt32"},
{&MachineOperatorBuilder::TruncateInt64ToInt32, "TruncateInt64ToInt32"}};
} // namespace
typedef MachineOperatorReducerTestWithParam<UnaryOperator>
MachineUnaryOperatorReducerTest;
TEST_P(MachineUnaryOperatorReducerTest, Parameter) {
const UnaryOperator unop = GetParam();
Reduction reduction =
Reduce(graph()->NewNode((machine()->*unop.constructor)(), Parameter(0)));
EXPECT_FALSE(reduction.Changed());
}
INSTANTIATE_TEST_CASE_P(MachineOperatorReducerTest,
MachineUnaryOperatorReducerTest,
::testing::ValuesIn(kUnaryOperators));
// -----------------------------------------------------------------------------
// ChangeFloat64ToFloat32
TEST_F(MachineOperatorReducerTest, ChangeFloat64ToFloat32WithConstant) {
TRACED_FOREACH(float, x, kFloat32Values) {
Reduction reduction = Reduce(graph()->NewNode(
machine()->ChangeFloat32ToFloat64(), Float32Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq<double>(x)));
}
}
// -----------------------------------------------------------------------------
// ChangeFloat64ToInt32
TEST_F(MachineOperatorReducerTest,
ChangeFloat64ToInt32WithChangeInt32ToFloat64) {
Node* value = Parameter(0);
Reduction reduction = Reduce(graph()->NewNode(
machine()->ChangeFloat64ToInt32(),
graph()->NewNode(machine()->ChangeInt32ToFloat64(), value)));
ASSERT_TRUE(reduction.Changed());
EXPECT_EQ(value, reduction.replacement());
}
TEST_F(MachineOperatorReducerTest, ChangeFloat64ToInt32WithConstant) {
TRACED_FOREACH(int32_t, x, kInt32Values) {
Reduction reduction = Reduce(graph()->NewNode(
machine()->ChangeFloat64ToInt32(), Float64Constant(FastI2D(x))));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsInt32Constant(x));
}
}
// -----------------------------------------------------------------------------
// ChangeFloat64ToUint32
TEST_F(MachineOperatorReducerTest,
ChangeFloat64ToUint32WithChangeUint32ToFloat64) {
Node* value = Parameter(0);
Reduction reduction = Reduce(graph()->NewNode(
machine()->ChangeFloat64ToUint32(),
graph()->NewNode(machine()->ChangeUint32ToFloat64(), value)));
ASSERT_TRUE(reduction.Changed());
EXPECT_EQ(value, reduction.replacement());
}
TEST_F(MachineOperatorReducerTest, ChangeFloat64ToUint32WithConstant) {
TRACED_FOREACH(uint32_t, x, kUint32Values) {
Reduction reduction = Reduce(graph()->NewNode(
machine()->ChangeFloat64ToUint32(), Float64Constant(FastUI2D(x))));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsInt32Constant(bit_cast<int32_t>(x)));
}
}
// -----------------------------------------------------------------------------
// ChangeInt32ToFloat64
TEST_F(MachineOperatorReducerTest, ChangeInt32ToFloat64WithConstant) {
TRACED_FOREACH(int32_t, x, kInt32Values) {
Reduction reduction = Reduce(
graph()->NewNode(machine()->ChangeInt32ToFloat64(), Int32Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastI2D(x))));
}
}
// -----------------------------------------------------------------------------
// ChangeInt32ToInt64
TEST_F(MachineOperatorReducerTest, ChangeInt32ToInt64WithConstant) {
TRACED_FOREACH(int32_t, x, kInt32Values) {
Reduction reduction = Reduce(
graph()->NewNode(machine()->ChangeInt32ToInt64(), Int32Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsInt64Constant(x));
}
}
// -----------------------------------------------------------------------------
// ChangeUint32ToFloat64
TEST_F(MachineOperatorReducerTest, ChangeUint32ToFloat64WithConstant) {
TRACED_FOREACH(uint32_t, x, kUint32Values) {
Reduction reduction =
Reduce(graph()->NewNode(machine()->ChangeUint32ToFloat64(),
Int32Constant(bit_cast<int32_t>(x))));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastUI2D(x))));
}
}
// -----------------------------------------------------------------------------
// ChangeUint32ToUint64
TEST_F(MachineOperatorReducerTest, ChangeUint32ToUint64WithConstant) {
TRACED_FOREACH(uint32_t, x, kUint32Values) {
Reduction reduction =
Reduce(graph()->NewNode(machine()->ChangeUint32ToUint64(),
Int32Constant(bit_cast<int32_t>(x))));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(),
IsInt64Constant(bit_cast<int64_t>(static_cast<uint64_t>(x))));
}
}
// -----------------------------------------------------------------------------
// TruncateFloat64ToFloat32
TEST_F(MachineOperatorReducerTest,
TruncateFloat64ToFloat32WithChangeFloat32ToFloat64) {
Node* value = Parameter(0);
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateFloat64ToFloat32(),
graph()->NewNode(machine()->ChangeFloat32ToFloat64(), value)));
ASSERT_TRUE(reduction.Changed());
EXPECT_EQ(value, reduction.replacement());
}
TEST_F(MachineOperatorReducerTest, TruncateFloat64ToFloat32WithConstant) {
TRACED_FOREACH(double, x, kFloat64Values) {
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateFloat64ToFloat32(), Float64Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(),
IsFloat32Constant(BitEq(DoubleToFloat32(x))));
}
}
// -----------------------------------------------------------------------------
// TruncateFloat64ToInt32
TEST_F(MachineOperatorReducerTest,
TruncateFloat64ToInt32WithChangeInt32ToFloat64) {
Node* value = Parameter(0);
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateFloat64ToInt32(),
graph()->NewNode(machine()->ChangeInt32ToFloat64(), value)));
ASSERT_TRUE(reduction.Changed());
EXPECT_EQ(value, reduction.replacement());
}
TEST_F(MachineOperatorReducerTest, TruncateFloat64ToInt32WithConstant) {
TRACED_FOREACH(double, x, kFloat64Values) {
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateFloat64ToInt32(), Float64Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(), IsInt32Constant(DoubleToInt32(x)));
}
}
TEST_F(MachineOperatorReducerTest, TruncateFloat64ToInt32WithPhi) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
Node* const merge = graph()->start();
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateFloat64ToInt32(),
graph()->NewNode(common()->Phi(kMachFloat64, 2), p0, p1, merge)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(),
IsPhi(kMachInt32, IsTruncateFloat64ToInt32(p0),
IsTruncateFloat64ToInt32(p1), merge));
}
// -----------------------------------------------------------------------------
// TruncateInt64ToInt32
TEST_F(MachineOperatorReducerTest, TruncateInt64ToInt32WithChangeInt32ToInt64) {
Node* value = Parameter(0);
Reduction reduction = Reduce(graph()->NewNode(
machine()->TruncateInt64ToInt32(),
graph()->NewNode(machine()->ChangeInt32ToInt64(), value)));
ASSERT_TRUE(reduction.Changed());
EXPECT_EQ(value, reduction.replacement());
}
TEST_F(MachineOperatorReducerTest, TruncateInt64ToInt32WithConstant) {
TRACED_FOREACH(int64_t, x, kInt64Values) {
Reduction reduction = Reduce(
graph()->NewNode(machine()->TruncateInt64ToInt32(), Int64Constant(x)));
ASSERT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(),
IsInt32Constant(bit_cast<int32_t>(
static_cast<uint32_t>(bit_cast<uint64_t>(x)))));
}
}
// -----------------------------------------------------------------------------
// Word32And
TEST_F(MachineOperatorReducerTest, Word32AndWithWord32ShlWithConstant) {
Node* const p0 = Parameter(0);
TRACED_FORRANGE(int32_t, l, 1, 31) {
TRACED_FORRANGE(int32_t, k, 1, l) {
// (x << L) & (-1 << K) => x << L
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l)),
Int32Constant(-1 << k)));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(), IsWord32Shl(p0, IsInt32Constant(l)));
// (-1 << K) & (x << L) => x << L
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Word32And(), Int32Constant(-1 << k),
graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l))));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(), IsWord32Shl(p0, IsInt32Constant(l)));
}
}
}
TEST_F(MachineOperatorReducerTest, Word32AndWithWord32AndWithConstant) {
Node* const p0 = Parameter(0);
TRACED_FOREACH(int32_t, k, kInt32Values) {
TRACED_FOREACH(int32_t, l, kInt32Values) {
if (k == 0 || k == -1 || l == 0 || l == -1) continue;
// (x & K) & L => x & (K & L)
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Word32And(), p0, Int32Constant(k)),
Int32Constant(l)));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(),
(k & l) ? IsWord32And(p0, IsInt32Constant(k & l))
: IsInt32Constant(0));
// (K & x) & L => x & (K & L)
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Word32And(), Int32Constant(k), p0),
Int32Constant(l)));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(),
(k & l) ? IsWord32And(p0, IsInt32Constant(k & l))
: IsInt32Constant(0));
}
}
}
TEST_F(MachineOperatorReducerTest, Word32AndWithInt32AddAndConstant) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
TRACED_FORRANGE(int32_t, l, 1, 31) {
TRACED_FOREACH(int32_t, k, kInt32Values) {
if ((k << l) == 0) continue;
// (x + (K << L)) & (-1 << L) => (x & (-1 << L)) + (K << L)
Reduction const r = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Int32Add(), p0, Int32Constant(k << l)),
Int32Constant(-1 << l)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)),
IsInt32Constant(k << l)));
}
Node* s1 = graph()->NewNode(machine()->Word32Shl(), p1, Int32Constant(l));
// (y << L + x) & (-1 << L) => (x & (-1 << L)) + y << L
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), s1, p0),
Int32Constant(-1 << l)));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1));
// (x + y << L) & (-1 << L) => (x & (-1 << L)) + y << L
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, s1),
Int32Constant(-1 << l)));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1));
}
}
TEST_F(MachineOperatorReducerTest, Word32AndWithInt32MulAndConstant) {
Node* const p0 = Parameter(0);
TRACED_FORRANGE(int32_t, l, 1, 31) {
TRACED_FOREACH(int32_t, k, kInt32Values) {
if ((k << l) == 0) continue;
// (x * (K << L)) & (-1 << L) => x * (K << L)
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Int32Mul(), p0, Int32Constant(k << l)),
Int32Constant(-1 << l)));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l)));
// ((K << L) * x) & (-1 << L) => x * (K << L)
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Int32Mul(), Int32Constant(k << l), p0),
Int32Constant(-1 << l)));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l)));
}
}
}
TEST_F(MachineOperatorReducerTest,
Word32AndWithInt32AddAndInt32MulAndConstant) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
TRACED_FORRANGE(int32_t, l, 1, 31) {
TRACED_FOREACH(int32_t, k, kInt32Values) {
if ((k << l) == 0) continue;
// (y * (K << L) + x) & (-1 << L) => (x & (-1 << L)) + y * (K << L)
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Int32Add(),
graph()->NewNode(machine()->Int32Mul(), p1,
Int32Constant(k << l)),
p0),
Int32Constant(-1 << l)));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)),
IsInt32Mul(p1, IsInt32Constant(k << l))));
// (x + y * (K << L)) & (-1 << L) => (x & (-1 << L)) + y * (K << L)
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Word32And(),
graph()->NewNode(machine()->Int32Add(), p0,
graph()->NewNode(machine()->Int32Mul(), p1,
Int32Constant(k << l))),
Int32Constant(-1 << l)));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)),
IsInt32Mul(p1, IsInt32Constant(k << l))));
}
}
}
TEST_F(MachineOperatorReducerTest, Word32AndWithComparisonAndConstantOne) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
TRACED_FOREACH(ComparisonBinaryOperator, cbop, kComparisonBinaryOperators) {
Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1);
// cmp & 1 => cmp
Reduction const r1 =
Reduce(graph()->NewNode(machine()->Word32And(), cmp, Int32Constant(1)));
ASSERT_TRUE(r1.Changed());
EXPECT_EQ(cmp, r1.replacement());
// 1 & cmp => cmp
Reduction const r2 =
Reduce(graph()->NewNode(machine()->Word32And(), Int32Constant(1), cmp));
ASSERT_TRUE(r2.Changed());
EXPECT_EQ(cmp, r2.replacement());
}
}
// -----------------------------------------------------------------------------
// Word32Xor
TEST_F(MachineOperatorReducerTest, Word32XorWithWord32XorAndMinusOne) {
Node* const p0 = Parameter(0);
// (x ^ -1) ^ -1 => x
Reduction r1 = Reduce(graph()->NewNode(
machine()->Word32Xor(),
graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1)),
Int32Constant(-1)));
ASSERT_TRUE(r1.Changed());
EXPECT_EQ(r1.replacement(), p0);
// -1 ^ (x ^ -1) => x
Reduction r2 = Reduce(graph()->NewNode(
machine()->Word32Xor(), Int32Constant(-1),
graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1))));
ASSERT_TRUE(r2.Changed());
EXPECT_EQ(r2.replacement(), p0);
// (-1 ^ x) ^ -1 => x
Reduction r3 = Reduce(graph()->NewNode(
machine()->Word32Xor(),
graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0),
Int32Constant(-1)));
ASSERT_TRUE(r3.Changed());
EXPECT_EQ(r3.replacement(), p0);
// -1 ^ (-1 ^ x) => x
Reduction r4 = Reduce(graph()->NewNode(
machine()->Word32Xor(), Int32Constant(-1),
graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0)));
ASSERT_TRUE(r4.Changed());
EXPECT_EQ(r4.replacement(), p0);
}
// -----------------------------------------------------------------------------
// Word32Ror
TEST_F(MachineOperatorReducerTest, ReduceToWord32RorWithParameters) {
Node* value = Parameter(0);
Node* shift = Parameter(1);
Node* sub = graph()->NewNode(machine()->Int32Sub(), Int32Constant(32), shift);
// Testing rotate left.
Node* shl_l = graph()->NewNode(machine()->Word32Shl(), value, shift);
Node* shr_l = graph()->NewNode(machine()->Word32Shr(), value, sub);
// (x << y) | (x >>> (32 - y)) => x ror (32 - y)
Node* node1 = graph()->NewNode(machine()->Word32Or(), shl_l, shr_l);
Reduction reduction1 = Reduce(node1);
EXPECT_TRUE(reduction1.Changed());
EXPECT_EQ(reduction1.replacement(), node1);
EXPECT_THAT(reduction1.replacement(), IsWord32Ror(value, sub));
// (x >>> (32 - y)) | (x << y) => x ror (32 - y)
Node* node2 = graph()->NewNode(machine()->Word32Or(), shr_l, shl_l);
Reduction reduction2 = Reduce(node2);
EXPECT_TRUE(reduction2.Changed());
EXPECT_EQ(reduction2.replacement(), node2);
EXPECT_THAT(reduction2.replacement(), IsWord32Ror(value, sub));
// Testing rotate right.
Node* shl_r = graph()->NewNode(machine()->Word32Shl(), value, sub);
Node* shr_r = graph()->NewNode(machine()->Word32Shr(), value, shift);
// (x << (32 - y)) | (x >>> y) => x ror y
Node* node3 = graph()->NewNode(machine()->Word32Or(), shl_r, shr_r);
Reduction reduction3 = Reduce(node3);
EXPECT_TRUE(reduction3.Changed());
EXPECT_EQ(reduction3.replacement(), node3);
EXPECT_THAT(reduction3.replacement(), IsWord32Ror(value, shift));
// (x >>> y) | (x << (32 - y)) => x ror y
Node* node4 = graph()->NewNode(machine()->Word32Or(), shr_r, shl_r);
Reduction reduction4 = Reduce(node4);
EXPECT_TRUE(reduction4.Changed());
EXPECT_EQ(reduction4.replacement(), node4);
EXPECT_THAT(reduction4.replacement(), IsWord32Ror(value, shift));
}
TEST_F(MachineOperatorReducerTest, ReduceToWord32RorWithConstant) {
Node* value = Parameter(0);
TRACED_FORRANGE(int32_t, k, 0, 31) {
Node* shl =
graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(k));
Node* shr =
graph()->NewNode(machine()->Word32Shr(), value, Int32Constant(32 - k));
// (x << K) | (x >>> ((32 - K) - y)) => x ror (32 - K)
Node* node1 = graph()->NewNode(machine()->Word32Or(), shl, shr);
Reduction reduction1 = Reduce(node1);
EXPECT_TRUE(reduction1.Changed());
EXPECT_EQ(reduction1.replacement(), node1);
EXPECT_THAT(reduction1.replacement(),
IsWord32Ror(value, IsInt32Constant(32 - k)));
// (x >>> (32 - K)) | (x << K) => x ror (32 - K)
Node* node2 = graph()->NewNode(machine()->Word32Or(), shr, shl);
Reduction reduction2 = Reduce(node2);
EXPECT_TRUE(reduction2.Changed());
EXPECT_EQ(reduction2.replacement(), node2);
EXPECT_THAT(reduction2.replacement(),
IsWord32Ror(value, IsInt32Constant(32 - k)));
}
}
TEST_F(MachineOperatorReducerTest, Word32RorWithZeroShift) {
Node* value = Parameter(0);
Node* node =
graph()->NewNode(machine()->Word32Ror(), value, Int32Constant(0));
Reduction reduction = Reduce(node);
EXPECT_TRUE(reduction.Changed());
EXPECT_EQ(reduction.replacement(), value);
}
TEST_F(MachineOperatorReducerTest, Word32RorWithConstants) {
TRACED_FOREACH(int32_t, x, kUint32Values) {
TRACED_FORRANGE(int32_t, y, 0, 31) {
Node* node = graph()->NewNode(machine()->Word32Ror(), Int32Constant(x),
Int32Constant(y));
Reduction reduction = Reduce(node);
EXPECT_TRUE(reduction.Changed());
EXPECT_THAT(reduction.replacement(),
IsInt32Constant(base::bits::RotateRight32(x, y)));
}
}
}
// -----------------------------------------------------------------------------
// Word32Sar
TEST_F(MachineOperatorReducerTest, Word32SarWithWord32ShlAndComparison) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
TRACED_FOREACH(ComparisonBinaryOperator, cbop, kComparisonBinaryOperators) {
Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1);
// cmp << 31 >> 31 => 0 - cmp
Reduction const r = Reduce(graph()->NewNode(
machine()->Word32Sar(),
graph()->NewNode(machine()->Word32Shl(), cmp, Int32Constant(31)),
Int32Constant(31)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), cmp));
}
}
TEST_F(MachineOperatorReducerTest, Word32SarWithWord32ShlAndLoad) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
{
Node* const l = graph()->NewNode(machine()->Load(kMachInt8), p0, p1,
graph()->start(), graph()->start());
Reduction const r = Reduce(graph()->NewNode(
machine()->Word32Sar(),
graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(24)),
Int32Constant(24)));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(l, r.replacement());
}
{
Node* const l = graph()->NewNode(machine()->Load(kMachInt16), p0, p1,
graph()->start(), graph()->start());
Reduction const r = Reduce(graph()->NewNode(
machine()->Word32Sar(),
graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(16)),
Int32Constant(16)));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(l, r.replacement());
}
}
// -----------------------------------------------------------------------------
// Word32Shl
TEST_F(MachineOperatorReducerTest, Word32ShlWithZeroShift) {
Node* p0 = Parameter(0);
Node* node = graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(0));
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_EQ(p0, r.replacement());
}
TEST_F(MachineOperatorReducerTest, Word32ShlWithWord32Sar) {
Node* p0 = Parameter(0);
TRACED_FORRANGE(int32_t, x, 1, 31) {
Node* node = graph()->NewNode(
machine()->Word32Shl(),
graph()->NewNode(machine()->Word32Sar(), p0, Int32Constant(x)),
Int32Constant(x));
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
int32_t m = bit_cast<int32_t>(~((1U << x) - 1U));
EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m)));
}
}
TEST_F(MachineOperatorReducerTest,
Word32ShlWithWord32SarAndInt32AddAndConstant) {
Node* const p0 = Parameter(0);
TRACED_FOREACH(int32_t, k, kInt32Values) {
TRACED_FORRANGE(int32_t, l, 1, 31) {
if ((k << l) == 0) continue;
// (x + (K << L)) >> L << L => (x & (-1 << L)) + (K << L)
Reduction const r = Reduce(graph()->NewNode(
machine()->Word32Shl(),
graph()->NewNode(machine()->Word32Sar(),
graph()->NewNode(machine()->Int32Add(), p0,
Int32Constant(k << l)),
Int32Constant(l)),
Int32Constant(l)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)),
IsInt32Constant(k << l)));
}
}
}
TEST_F(MachineOperatorReducerTest, Word32ShlWithWord32Shr) {
Node* p0 = Parameter(0);
TRACED_FORRANGE(int32_t, x, 1, 31) {
Node* node = graph()->NewNode(
machine()->Word32Shl(),
graph()->NewNode(machine()->Word32Shr(), p0, Int32Constant(x)),
Int32Constant(x));
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
int32_t m = bit_cast<int32_t>(~((1U << x) - 1U));
EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m)));
}
}
// -----------------------------------------------------------------------------
// Int32Sub
TEST_F(MachineOperatorReducerTest, Int32SubWithConstant) {
Node* const p0 = Parameter(0);
TRACED_FOREACH(int32_t, k, kInt32Values) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Int32Sub(), p0, Int32Constant(k)));
ASSERT_TRUE(r.Changed());
if (k == 0) {
EXPECT_EQ(p0, r.replacement());
} else {
EXPECT_THAT(r.replacement(), IsInt32Add(p0, IsInt32Constant(-k)));
}
}
}
// -----------------------------------------------------------------------------
// Int32Div
TEST_F(MachineOperatorReducerTest, Int32DivWithConstant) {
Node* const p0 = Parameter(0);
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(0), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(r.replacement(), p0);
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(-1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), p0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(2), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0),
IsInt32Constant(1)));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(-2), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsInt32Sub(
IsInt32Constant(0),
IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0),
IsInt32Constant(1))));
}
TRACED_FORRANGE(int32_t, shift, 2, 30) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Int32Div(), p0,
Int32Constant(1 << shift), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsWord32Sar(IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)),
IsInt32Constant(32 - shift)),
p0),
IsInt32Constant(shift)));
}
TRACED_FORRANGE(int32_t, shift, 2, 31) {
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0,
Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift),
graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsInt32Sub(
IsInt32Constant(0),
IsWord32Sar(
IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)),
IsInt32Constant(32 - shift)),
p0),
IsInt32Constant(shift))));
}
TRACED_FOREACH(int32_t, divisor, kInt32Values) {
if (divisor < 0) {
if (base::bits::IsPowerOfTwo32(-divisor)) continue;
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0),
IsTruncatingDiv(p0, -divisor)));
} else if (divisor > 0) {
if (base::bits::IsPowerOfTwo32(divisor)) continue;
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsTruncatingDiv(p0, divisor));
}
}
}
TEST_F(MachineOperatorReducerTest, Int32DivWithParameters) {
Node* const p0 = Parameter(0);
Reduction const r =
Reduce(graph()->NewNode(machine()->Int32Div(), p0, p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0)));
}
// -----------------------------------------------------------------------------
// Uint32Div
TEST_F(MachineOperatorReducerTest, Uint32DivWithConstant) {
Node* const p0 = Parameter(0);
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Div(), Int32Constant(0), p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Div(), p0, Int32Constant(0), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Div(), p0, Int32Constant(1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(r.replacement(), p0);
}
TRACED_FOREACH(uint32_t, dividend, kUint32Values) {
TRACED_FOREACH(uint32_t, divisor, kUint32Values) {
Reduction const r = Reduce(
graph()->NewNode(machine()->Uint32Div(), Uint32Constant(dividend),
Uint32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Constant(bit_cast<int32_t>(
base::bits::UnsignedDiv32(dividend, divisor))));
}
}
TRACED_FORRANGE(uint32_t, shift, 1, 31) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Uint32Div(), p0,
Uint32Constant(1u << shift), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsWord32Shr(p0, IsInt32Constant(bit_cast<int32_t>(shift))));
}
}
TEST_F(MachineOperatorReducerTest, Uint32DivWithParameters) {
Node* const p0 = Parameter(0);
Reduction const r = Reduce(
graph()->NewNode(machine()->Uint32Div(), p0, p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0)));
}
// -----------------------------------------------------------------------------
// Int32Mod
TEST_F(MachineOperatorReducerTest, Int32ModWithConstant) {
Node* const p0 = Parameter(0);
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), Int32Constant(0), p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), p0, Int32Constant(0), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), p0, Int32Constant(1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), p0, Int32Constant(-1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
TRACED_FOREACH(int32_t, dividend, kInt32Values) {
TRACED_FOREACH(int32_t, divisor, kInt32Values) {
Reduction const r = Reduce(
graph()->NewNode(machine()->Int32Mod(), Int32Constant(dividend),
Int32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Constant(base::bits::SignedMod32(dividend, divisor)));
}
}
TRACED_FORRANGE(int32_t, shift, 1, 30) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Int32Mod(), p0,
Int32Constant(1 << shift), graph()->start()));
int32_t const mask = (1 << shift) - 1;
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)),
IsInt32Sub(IsInt32Constant(0),
IsWord32And(IsInt32Sub(IsInt32Constant(0), p0),
IsInt32Constant(mask))),
IsWord32And(p0, IsInt32Constant(mask))));
}
TRACED_FORRANGE(int32_t, shift, 1, 31) {
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), p0,
Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift),
graph()->start()));
int32_t const mask = bit_cast<int32_t, uint32_t>((1U << shift) - 1);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)),
IsInt32Sub(IsInt32Constant(0),
IsWord32And(IsInt32Sub(IsInt32Constant(0), p0),
IsInt32Constant(mask))),
IsWord32And(p0, IsInt32Constant(mask))));
}
TRACED_FOREACH(int32_t, divisor, kInt32Values) {
if (divisor == 0 || base::bits::IsPowerOfTwo32(Abs(divisor))) continue;
Reduction const r = Reduce(graph()->NewNode(
machine()->Int32Mod(), p0, Int32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Sub(p0, IsInt32Mul(IsTruncatingDiv(p0, Abs(divisor)),
IsInt32Constant(Abs(divisor)))));
}
}
TEST_F(MachineOperatorReducerTest, Int32ModWithParameters) {
Node* const p0 = Parameter(0);
Reduction const r =
Reduce(graph()->NewNode(machine()->Int32Mod(), p0, p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
// -----------------------------------------------------------------------------
// Uint32Mod
TEST_F(MachineOperatorReducerTest, Uint32ModWithConstant) {
Node* const p0 = Parameter(0);
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Mod(), p0, Int32Constant(0), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Mod(), Int32Constant(0), p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
{
Reduction const r = Reduce(graph()->NewNode(
machine()->Uint32Mod(), p0, Int32Constant(1), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
TRACED_FOREACH(uint32_t, dividend, kUint32Values) {
TRACED_FOREACH(uint32_t, divisor, kUint32Values) {
Reduction const r = Reduce(
graph()->NewNode(machine()->Uint32Mod(), Uint32Constant(dividend),
Uint32Constant(divisor), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Constant(bit_cast<int32_t>(
base::bits::UnsignedMod32(dividend, divisor))));
}
}
TRACED_FORRANGE(uint32_t, shift, 1, 31) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Uint32Mod(), p0,
Uint32Constant(1u << shift), graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsWord32And(p0, IsInt32Constant(
bit_cast<int32_t>((1u << shift) - 1u))));
}
}
TEST_F(MachineOperatorReducerTest, Uint32ModWithParameters) {
Node* const p0 = Parameter(0);
Reduction const r = Reduce(
graph()->NewNode(machine()->Uint32Mod(), p0, p0, graph()->start()));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
}
// -----------------------------------------------------------------------------
// Int32Add
TEST_F(MachineOperatorReducerTest, Int32AddWithInt32SubWithConstantZero) {
Node* const p0 = Parameter(0);
Node* const p1 = Parameter(1);
Reduction const r1 = Reduce(graph()->NewNode(
machine()->Int32Add(),
graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p0), p1));
ASSERT_TRUE(r1.Changed());
EXPECT_THAT(r1.replacement(), IsInt32Sub(p1, p0));
Reduction const r2 = Reduce(graph()->NewNode(
machine()->Int32Add(), p0,
graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p1)));
ASSERT_TRUE(r2.Changed());
EXPECT_THAT(r2.replacement(), IsInt32Sub(p0, p1));
}
// -----------------------------------------------------------------------------
// Int32AddWithOverflow
TEST_F(MachineOperatorReducerTest, Int32AddWithOverflowWithZero) {
Node* p0 = Parameter(0);
{
Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(),
Int32Constant(0), p0);
Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
r = Reduce(graph()->NewNode(common()->Projection(0), add));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(p0, r.replacement());
}
{
Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), p0,
Int32Constant(0));
Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
r = Reduce(graph()->NewNode(common()->Projection(0), add));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(p0, r.replacement());
}
}
TEST_F(MachineOperatorReducerTest, Int32AddWithOverflowWithConstant) {
TRACED_FOREACH(int32_t, x, kInt32Values) {
TRACED_FOREACH(int32_t, y, kInt32Values) {
int32_t z;
Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(),
Int32Constant(x), Int32Constant(y));
Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Constant(base::bits::SignedAddOverflow32(x, y, &z)));
r = Reduce(graph()->NewNode(common()->Projection(0), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(z));
}
}
}
// -----------------------------------------------------------------------------
// Int32SubWithOverflow
TEST_F(MachineOperatorReducerTest, Int32SubWithOverflowWithZero) {
Node* p0 = Parameter(0);
Node* add =
graph()->NewNode(machine()->Int32SubWithOverflow(), p0, Int32Constant(0));
Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(0));
r = Reduce(graph()->NewNode(common()->Projection(0), add));
ASSERT_TRUE(r.Changed());
EXPECT_EQ(p0, r.replacement());
}
TEST_F(MachineOperatorReducerTest, Int32SubWithOverflowWithConstant) {
TRACED_FOREACH(int32_t, x, kInt32Values) {
TRACED_FOREACH(int32_t, y, kInt32Values) {
int32_t z;
Node* add = graph()->NewNode(machine()->Int32SubWithOverflow(),
Int32Constant(x), Int32Constant(y));
Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsInt32Constant(base::bits::SignedSubOverflow32(x, y, &z)));
r = Reduce(graph()->NewNode(common()->Projection(0), add));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(), IsInt32Constant(z));
}
}
}
// -----------------------------------------------------------------------------
// Uint32LessThan
TEST_F(MachineOperatorReducerTest, Uint32LessThanWithWord32Sar) {
Node* const p0 = Parameter(0);
TRACED_FORRANGE(uint32_t, shift, 1, 3) {
const uint32_t limit = (kMaxInt >> shift) - 1;
Node* const node = graph()->NewNode(
machine()->Uint32LessThan(),
graph()->NewNode(machine()->Word32Sar(), p0, Uint32Constant(shift)),
Uint32Constant(limit));
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsUint32LessThan(
p0, IsInt32Constant(bit_cast<int32_t>(limit << shift))));
}
}
// -----------------------------------------------------------------------------
// Float64Mul
TEST_F(MachineOperatorReducerTest, Float64MulWithMinusOne) {
Node* const p0 = Parameter(0);
{
Reduction r = Reduce(
graph()->NewNode(machine()->Float64Mul(), p0, Float64Constant(-1.0)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0));
}
{
Reduction r = Reduce(
graph()->NewNode(machine()->Float64Mul(), Float64Constant(-1.0), p0));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0));
}
}
// -----------------------------------------------------------------------------
// Float64InsertLowWord32
TEST_F(MachineOperatorReducerTest, Float64InsertLowWord32WithConstant) {
TRACED_FOREACH(double, x, kFloat64Values) {
TRACED_FOREACH(uint32_t, y, kUint32Values) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Float64InsertLowWord32(),
Float64Constant(x), Uint32Constant(y)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(
r.replacement(),
IsFloat64Constant(BitEq(bit_cast<double>(
(bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF00000000)) | y))));
}
}
}
// -----------------------------------------------------------------------------
// Float64InsertHighWord32
TEST_F(MachineOperatorReducerTest, Float64InsertHighWord32WithConstant) {
TRACED_FOREACH(double, x, kFloat64Values) {
TRACED_FOREACH(uint32_t, y, kUint32Values) {
Reduction const r =
Reduce(graph()->NewNode(machine()->Float64InsertHighWord32(),
Float64Constant(x), Uint32Constant(y)));
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsFloat64Constant(BitEq(bit_cast<double>(
(bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF)) |
(static_cast<uint64_t>(y) << 32)))));
}
}
}
// -----------------------------------------------------------------------------
// Store
TEST_F(MachineOperatorReducerTest, StoreRepWord8WithWord32And) {
const StoreRepresentation rep(kRepWord8, kNoWriteBarrier);
Node* const base = Parameter(0);
Node* const index = Parameter(1);
Node* const value = Parameter(2);
Node* const effect = graph()->start();
Node* const control = graph()->start();
TRACED_FOREACH(uint32_t, x, kUint32Values) {
Node* const node =
graph()->NewNode(machine()->Store(rep), base, index,
graph()->NewNode(machine()->Word32And(), value,
Uint32Constant(x | 0xffu)),
effect, control);
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsStore(rep, base, index, value, effect, control));
}
}
TEST_F(MachineOperatorReducerTest, StoreRepWord8WithWord32SarAndWord32Shl) {
const StoreRepresentation rep(kRepWord8, kNoWriteBarrier);
Node* const base = Parameter(0);
Node* const index = Parameter(1);
Node* const value = Parameter(2);
Node* const effect = graph()->start();
Node* const control = graph()->start();
TRACED_FORRANGE(int32_t, x, 1, 24) {
Node* const node = graph()->NewNode(
machine()->Store(rep), base, index,
graph()->NewNode(
machine()->Word32Sar(),
graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)),
Int32Constant(x)),
effect, control);
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsStore(rep, base, index, value, effect, control));
}
}
TEST_F(MachineOperatorReducerTest, StoreRepWord16WithWord32And) {
const StoreRepresentation rep(kRepWord16, kNoWriteBarrier);
Node* const base = Parameter(0);
Node* const index = Parameter(1);
Node* const value = Parameter(2);
Node* const effect = graph()->start();
Node* const control = graph()->start();
TRACED_FOREACH(uint32_t, x, kUint32Values) {
Node* const node =
graph()->NewNode(machine()->Store(rep), base, index,
graph()->NewNode(machine()->Word32And(), value,
Uint32Constant(x | 0xffffu)),
effect, control);
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsStore(rep, base, index, value, effect, control));
}
}
TEST_F(MachineOperatorReducerTest, StoreRepWord16WithWord32SarAndWord32Shl) {
const StoreRepresentation rep(kRepWord16, kNoWriteBarrier);
Node* const base = Parameter(0);
Node* const index = Parameter(1);
Node* const value = Parameter(2);
Node* const effect = graph()->start();
Node* const control = graph()->start();
TRACED_FORRANGE(int32_t, x, 1, 16) {
Node* const node = graph()->NewNode(
machine()->Store(rep), base, index,
graph()->NewNode(
machine()->Word32Sar(),
graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)),
Int32Constant(x)),
effect, control);
Reduction r = Reduce(node);
ASSERT_TRUE(r.Changed());
EXPECT_THAT(r.replacement(),
IsStore(rep, base, index, value, effect, control));
}
}
} // namespace compiler
} // namespace internal
} // namespace v8
| sgraham/nope | v8/test/unittests/compiler/machine-operator-reducer-unittest.cc | C++ | bsd-3-clause | 59,530 |
require 'rubygems'
require 'rubygems/user_interaction'
require 'uri'
##
# RemoteFetcher handles the details of fetching gems and gem information from
# a remote source.
class Gem::RemoteFetcher
BuiltinSSLCerts = File.expand_path("./ssl_certs/*.pem", File.dirname(__FILE__))
include Gem::UserInteraction
##
# A FetchError exception wraps up the various possible IO and HTTP failures
# that could happen while downloading from the internet.
class FetchError < Gem::Exception
##
# The URI which was being accessed when the exception happened.
attr_accessor :uri
def initialize(message, uri)
super message
@uri = uri
end
def to_s # :nodoc:
"#{super} (#{uri})"
end
end
@fetcher = nil
##
# Cached RemoteFetcher instance.
def self.fetcher
@fetcher ||= self.new Gem.configuration[:http_proxy]
end
##
# Initialize a remote fetcher using the source URI and possible proxy
# information.
#
# +proxy+
# * [String]: explicit specification of proxy; overrides any environment
# variable setting
# * nil: respect environment variables (HTTP_PROXY, HTTP_PROXY_USER,
# HTTP_PROXY_PASS)
# * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy
def initialize(proxy = nil)
require 'net/http'
require 'stringio'
require 'time'
require 'uri'
Socket.do_not_reverse_lookup = true
@connections = {}
@requests = Hash.new 0
@proxy_uri =
case proxy
when :no_proxy then nil
when nil then get_proxy_from_env
when URI::HTTP then proxy
else URI.parse(proxy)
end
@user_agent = user_agent
end
##
# Given a name and requirement, downloads this gem into cache and returns the
# filename. Returns nil if the gem cannot be located.
#--
# Should probably be integrated with #download below, but that will be a
# larger, more emcompassing effort. -erikh
def download_to_cache dependency
found = Gem::SpecFetcher.fetcher.fetch dependency, true, true,
dependency.prerelease?
return if found.empty?
spec, source_uri = found.sort_by { |(s,_)| s.version }.last
download spec, source_uri
end
##
# Moves the gem +spec+ from +source_uri+ to the cache dir unless it is
# already there. If the source_uri is local the gem cache dir copy is
# always replaced.
def download(spec, source_uri, install_dir = Gem.dir)
Gem.ensure_gem_subdirectories(install_dir) rescue nil
if File.writable?(install_dir)
cache_dir = File.join install_dir, "cache"
else
cache_dir = File.join Gem.user_dir, "cache"
end
gem_file_name = File.basename spec.cache_file
local_gem_path = File.join cache_dir, gem_file_name
FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir
# Always escape URI's to deal with potential spaces and such
unless URI::Generic === source_uri
source_uri = URI.parse(URI.const_defined?(:DEFAULT_PARSER) ?
URI::DEFAULT_PARSER.escape(source_uri.to_s) :
URI.escape(source_uri.to_s))
end
scheme = source_uri.scheme
# URI.parse gets confused by MS Windows paths with forward slashes.
scheme = nil if scheme =~ /^[a-z]$/i
case scheme
when 'http', 'https' then
unless File.exist? local_gem_path then
begin
say "Downloading gem #{gem_file_name}" if
Gem.configuration.really_verbose
remote_gem_path = source_uri + "gems/#{gem_file_name}"
gem = self.fetch_path remote_gem_path
rescue Gem::RemoteFetcher::FetchError
raise if spec.original_platform == spec.platform
alternate_name = "#{spec.original_name}.gem"
say "Failed, downloading gem #{alternate_name}" if
Gem.configuration.really_verbose
remote_gem_path = source_uri + "gems/#{alternate_name}"
gem = self.fetch_path remote_gem_path
end
File.open local_gem_path, 'wb' do |fp|
fp.write gem
end
end
when 'file' then
begin
path = source_uri.path
path = File.dirname(path) if File.extname(path) == '.gem'
remote_gem_path = correct_for_windows_path(File.join(path, 'gems', gem_file_name))
FileUtils.cp(remote_gem_path, local_gem_path)
rescue Errno::EACCES
local_gem_path = source_uri.to_s
end
say "Using local gem #{local_gem_path}" if
Gem.configuration.really_verbose
when nil then # TODO test for local overriding cache
source_path = if Gem.win_platform? && source_uri.scheme &&
!source_uri.path.include?(':') then
"#{source_uri.scheme}:#{source_uri.path}"
else
source_uri.path
end
source_path = unescape source_path
begin
FileUtils.cp source_path, local_gem_path unless
File.identical?(source_path, local_gem_path)
rescue Errno::EACCES
local_gem_path = source_uri.to_s
end
say "Using local gem #{local_gem_path}" if
Gem.configuration.really_verbose
else
raise Gem::InstallError, "unsupported URI scheme #{source_uri.scheme}"
end
local_gem_path
end
##
# File Fetcher. Dispatched by +fetch_path+. Use it instead.
def fetch_file uri, *_
Gem.read_binary correct_for_windows_path uri.path
end
##
# HTTP Fetcher. Dispatched by +fetch_path+. Use it instead.
def fetch_http uri, last_modified = nil, head = false, depth = 0
fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get
response = request uri, fetch_type, last_modified
case response
when Net::HTTPOK, Net::HTTPNotModified then
head ? response : response.body
when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPSeeOther,
Net::HTTPTemporaryRedirect then
raise FetchError.new('too many redirects', uri) if depth > 10
location = URI.parse response['Location']
if https?(uri) && !https?(location)
raise FetchError.new("redirecting to non-https resource: #{location}", uri)
end
fetch_http(location, last_modified, head, depth + 1)
else
raise FetchError.new("bad response #{response.message} #{response.code}", uri)
end
end
alias :fetch_https :fetch_http
##
# Downloads +uri+ and returns it as a String.
def fetch_path(uri, mtime = nil, head = false)
uri = URI.parse uri unless URI::Generic === uri
raise ArgumentError, "bad uri: #{uri}" unless uri
raise ArgumentError, "uri scheme is invalid: #{uri.scheme.inspect}" unless
uri.scheme
data = send "fetch_#{uri.scheme}", uri, mtime, head
data = Gem.gunzip data if data and not head and uri.to_s =~ /gz$/
data
rescue FetchError
raise
rescue Timeout::Error
raise FetchError.new('timed out', uri.to_s)
rescue IOError, SocketError, SystemCallError => e
raise FetchError.new("#{e.class}: #{e}", uri.to_s)
end
##
# Returns the size of +uri+ in bytes.
def fetch_size(uri) # TODO: phase this out
response = fetch_path(uri, nil, true)
response['content-length'].to_i
end
def escape(str)
return unless str
@uri_parser ||= uri_escaper
@uri_parser.escape str
end
def unescape(str)
return unless str
@uri_parser ||= uri_escaper
@uri_parser.unescape str
end
def uri_escaper
URI::Parser.new
rescue NameError
URI
end
##
# Returns an HTTP proxy URI if one is set in the environment variables.
def get_proxy_from_env
env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']
return nil if env_proxy.nil? or env_proxy.empty?
uri = URI.parse(normalize_uri(env_proxy))
if uri and uri.user.nil? and uri.password.nil? then
# Probably we have http_proxy_* variables?
uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'])
uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'])
end
uri
end
##
# Normalize the URI by adding "http://" if it is missing.
def normalize_uri(uri)
(uri =~ /^(https?|ftp|file):/) ? uri : "http://#{uri}"
end
##
# Creates or an HTTP connection based on +uri+, or retrieves an existing
# connection, using a proxy if needed.
def connection_for(uri)
net_http_args = [uri.host, uri.port]
if @proxy_uri then
net_http_args += [
@proxy_uri.host,
@proxy_uri.port,
@proxy_uri.user,
@proxy_uri.password
]
end
connection_id = [Thread.current.object_id, *net_http_args].join ':'
@connections[connection_id] ||= Net::HTTP.new(*net_http_args)
connection = @connections[connection_id]
if https?(uri) and !connection.started? then
configure_connection_for_https(connection)
# Don't refactor this with the else branch. We don't want the
# http-only code path to not depend on anything in OpenSSL.
#
begin
connection.start
rescue OpenSSL::SSL::SSLError, Errno::EHOSTDOWN => e
raise FetchError.new(e.message, uri)
end
else
begin
connection.start unless connection.started?
rescue Errno::EHOSTDOWN => e
raise FetchError.new(e.message, uri)
end
end
connection
end
def configure_connection_for_https(connection)
require 'net/https'
connection.use_ssl = true
connection.verify_mode =
Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER
store = OpenSSL::X509::Store.new
if Gem.configuration.ssl_ca_cert
if File.directory? Gem.configuration.ssl_ca_cert
store.add_path Gem.configuration.ssl_ca_cert
else
store.add_file Gem.configuration.ssl_ca_cert
end
else
store.set_default_paths
add_rubygems_trusted_certs(store)
end
connection.cert_store = store
end
def add_rubygems_trusted_certs(store)
Dir.glob(BuiltinSSLCerts).each do |ssl_cert_file|
store.add_file ssl_cert_file
end
end
def correct_for_windows_path(path)
if path[0].chr == '/' && path[1].chr =~ /[a-z]/i && path[2].chr == ':'
path = path[1..-1]
else
path
end
end
##
# Read the data from the (source based) URI, but if it is a file:// URI,
# read from the filesystem instead.
def open_uri_or_path(uri, last_modified = nil, head = false, depth = 0)
raise "NO: Use fetch_path instead"
# TODO: deprecate for fetch_path
end
##
# Performs a Net::HTTP request of type +request_class+ on +uri+ returning
# a Net::HTTP response object. request maintains a table of persistent
# connections to reduce connect overhead.
def request(uri, request_class, last_modified = nil)
request = request_class.new uri.request_uri
unless uri.nil? || uri.user.nil? || uri.user.empty? then
request.basic_auth uri.user, uri.password
end
request.add_field 'User-Agent', @user_agent
request.add_field 'Connection', 'keep-alive'
request.add_field 'Keep-Alive', '30'
if last_modified then
last_modified = last_modified.utc
request.add_field 'If-Modified-Since', last_modified.rfc2822
end
yield request if block_given?
connection = connection_for uri
retried = false
bad_response = false
begin
@requests[connection.object_id] += 1
say "#{request.method} #{uri}" if
Gem.configuration.really_verbose
file_name = File.basename(uri.path)
# perform download progress reporter only for gems
if request.response_body_permitted? && file_name =~ /\.gem$/
reporter = ui.download_reporter
response = connection.request(request) do |incomplete_response|
if Net::HTTPOK === incomplete_response
reporter.fetch(file_name, incomplete_response.content_length)
downloaded = 0
data = ''
incomplete_response.read_body do |segment|
data << segment
downloaded += segment.length
reporter.update(downloaded)
end
reporter.done
if incomplete_response.respond_to? :body=
incomplete_response.body = data
else
incomplete_response.instance_variable_set(:@body, data)
end
end
end
else
response = connection.request request
end
say "#{response.code} #{response.message}" if
Gem.configuration.really_verbose
rescue Net::HTTPBadResponse
say "bad response" if Gem.configuration.really_verbose
reset connection
raise FetchError.new('too many bad responses', uri) if bad_response
bad_response = true
retry
# HACK work around EOFError bug in Net::HTTP
# NOTE Errno::ECONNABORTED raised a lot on Windows, and make impossible
# to install gems.
rescue EOFError, Timeout::Error,
Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE
requests = @requests[connection.object_id]
say "connection reset after #{requests} requests, retrying" if
Gem.configuration.really_verbose
raise FetchError.new('too many connection resets', uri) if retried
reset connection
retried = true
retry
end
response
end
##
# Resets HTTP connection +connection+.
def reset(connection)
@requests.delete connection.object_id
connection.finish
connection.start
end
def user_agent
ua = "RubyGems/#{Gem::VERSION} #{Gem::Platform.local}"
ruby_version = RUBY_VERSION
ruby_version += 'dev' if RUBY_PATCHLEVEL == -1
ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}"
if RUBY_PATCHLEVEL >= 0 then
ua << " patchlevel #{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then
ua << " revision #{RUBY_REVISION}"
end
ua << ")"
ua << " #{RUBY_ENGINE}" if defined?(RUBY_ENGINE) and RUBY_ENGINE != 'ruby'
ua
end
def https?(uri)
uri.scheme.downcase == 'https'
end
end
| yob/debian-rubinius | lib/rubygems/remote_fetcher.rb | Ruby | bsd-3-clause | 14,114 |
namespace std {
template<typename T>
class allocator {
public:
void in_base();
};
template<typename T, typename Alloc = std::allocator<T> >
class vector : Alloc {
public:
void foo();
void stop();
};
template<typename Alloc> class vector<bool, Alloc>;
}
void f() {
std::vector<int> v;
v.foo();
// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:18:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
// CHECK-CC1: allocator<<#typename T#>>
// CHECK-CC1-NEXT: vector<<#typename T#>{#, <#typename Alloc#>#}>
// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:19:5 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s
// CHECK-CC2: foo
// CHECK-CC2: in_base
// CHECK-CC2: stop
}
template <typename> struct X;
template <typename T> struct X<T*> { X(double); };
X<int*> x(42);
// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:32:11 %s -o - | FileCheck -check-prefix=CHECK-CONSTRUCTOR %s
// CHECK-CONSTRUCTOR: OVERLOAD: X(<#double#>)
// (rather than X<type-parameter-0-0 *>(<#double#>)
| endlessm/chromium-browser | third_party/llvm/clang/test/CodeCompletion/templates.cpp | C++ | bsd-3-clause | 1,042 |
// ==========================================
// RECESS
// RULE: .js prefixes should not be styled
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under the Apache License v2.0
// http://www.apache.org/licenses/LICENSE-2.0
// ==========================================
'use strict'
var util = require('../util')
, RULE = {
type: 'noJSPrefix'
, exp: /^\.js\-/
, message: '.js prefixes should not be styled'
}
// validation method
module.exports = function (def, data) {
// default validation to true
var isValid = true
// return if no selector to validate
if (!def.selectors) return isValid
// loop over selectors
def.selectors.forEach(function (selector) {
// loop over selector entities
selector.elements.forEach(function (element) {
var extract
// continue to next element if .js- prefix not styled
if (!RULE.exp.test(element.value)) return
// calculate line number for the extract
extract = util.getLine(element.index - element.value.length, data)
extract = util.padLine(extract)
// highlight invalid styling of .js- prefix
extract += element.value.replace(RULE.exp, '.js-'.magenta)
// set invalid flag to false
isValid = false
// set error object on defintion token
util.throwError(def, {
type: RULE.type
, message: RULE.message
, extract: extract
})
})
})
// return valid state
return isValid
} | jdsimcoe/briansimcoe | workspace/grunt/node_modules/grunt-recess/node_modules/recess/lib/lint/no-JS-prefix.js | JavaScript | mit | 1,504 |
/*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2010 Bryce Lelbach
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)
================================================_==============================*/
#if !defined(BOOST_SPIRIT_X3_STRING_TRAITS_OCTOBER_2008_1252PM)
#define BOOST_SPIRIT_X3_STRING_TRAITS_OCTOBER_2008_1252PM
#include <string>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/identity.hpp>
namespace boost { namespace spirit { namespace x3 { namespace traits
{
///////////////////////////////////////////////////////////////////////////
// Determine if T is a character type
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct is_char : mpl::false_ {};
template <typename T>
struct is_char<T const> : is_char<T> {};
template <>
struct is_char<char> : mpl::true_ {};
template <>
struct is_char<wchar_t> : mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
// Determine if T is a string
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct is_string : mpl::false_ {};
template <typename T>
struct is_string<T const> : is_string<T> {};
template <>
struct is_string<char const*> : mpl::true_ {};
template <>
struct is_string<wchar_t const*> : mpl::true_ {};
template <>
struct is_string<char*> : mpl::true_ {};
template <>
struct is_string<wchar_t*> : mpl::true_ {};
template <std::size_t N>
struct is_string<char[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char const[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t const[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char const(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t const(&)[N]> : mpl::true_ {};
template <typename T, typename Traits, typename Allocator>
struct is_string<std::basic_string<T, Traits, Allocator> > : mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
// Get the underlying char type of a string
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct char_type_of;
template <typename T>
struct char_type_of<T const> : char_type_of<T> {};
template <>
struct char_type_of<char> : mpl::identity<char> {};
template <>
struct char_type_of<wchar_t> : mpl::identity<wchar_t> {};
template <>
struct char_type_of<char const*> : mpl::identity<char const> {};
template <>
struct char_type_of<wchar_t const*> : mpl::identity<wchar_t const> {};
template <>
struct char_type_of<char*> : mpl::identity<char> {};
template <>
struct char_type_of<wchar_t*> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char[N]> : mpl::identity<char> {};
template <std::size_t N>
struct char_type_of<wchar_t[N]> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char const[N]> : mpl::identity<char const> {};
template <std::size_t N>
struct char_type_of<wchar_t const[N]> : mpl::identity<wchar_t const> {};
template <std::size_t N>
struct char_type_of<char(&)[N]> : mpl::identity<char> {};
template <std::size_t N>
struct char_type_of<wchar_t(&)[N]> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char const(&)[N]> : mpl::identity<char const> {};
template <std::size_t N>
struct char_type_of<wchar_t const(&)[N]> : mpl::identity<wchar_t const> {};
template <typename T, typename Traits, typename Allocator>
struct char_type_of<std::basic_string<T, Traits, Allocator> >
: mpl::identity<T> {};
///////////////////////////////////////////////////////////////////////////
// Get the C string from a string
///////////////////////////////////////////////////////////////////////////
template <typename String>
struct extract_c_string;
template <typename String>
struct extract_c_string
{
typedef typename char_type_of<String>::type char_type;
template <typename T>
static T const* call (T* str)
{
return (T const*)str;
}
template <typename T>
static T const* call (T const* str)
{
return str;
}
};
// Forwarder that strips const
template <typename T>
struct extract_c_string<T const>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T const str)
{
return extract_c_string<T>::call(str);
}
};
// Forwarder that strips references
template <typename T>
struct extract_c_string<T&>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T& str)
{
return extract_c_string<T>::call(str);
}
};
// Forwarder that strips const references
template <typename T>
struct extract_c_string<T const&>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T const& str)
{
return extract_c_string<T>::call(str);
}
};
template <typename T, typename Traits, typename Allocator>
struct extract_c_string<std::basic_string<T, Traits, Allocator> >
{
typedef T char_type;
typedef std::basic_string<T, Traits, Allocator> string;
static T const* call (string const& str)
{
return str.c_str();
}
};
template <typename T>
typename extract_c_string<T*>::char_type const*
get_c_string(T* str)
{
return extract_c_string<T*>::call(str);
}
template <typename T>
typename extract_c_string<T const*>::char_type const*
get_c_string(T const* str)
{
return extract_c_string<T const*>::call(str);
}
template <typename String>
typename extract_c_string<String>::char_type const*
get_c_string(String& str)
{
return extract_c_string<String>::call(str);
}
template <typename String>
typename extract_c_string<String>::char_type const*
get_c_string(String const& str)
{
return extract_c_string<String>::call(str);
}
///////////////////////////////////////////////////////////////////////////
// Get the begin/end iterators from a string
///////////////////////////////////////////////////////////////////////////
// Implementation for C-style strings.
template <typename T>
inline T const* get_string_begin(T const* str) { return str; }
template <typename T>
inline T* get_string_begin(T* str) { return str; }
template <typename T>
inline T const* get_string_end(T const* str)
{
T const* last = str;
while (*last)
last++;
return last;
}
template <typename T>
inline T* get_string_end(T* str)
{
T* last = str;
while (*last)
last++;
return last;
}
// Implementation for containers (includes basic_string).
template <typename T, typename Str>
inline typename Str::const_iterator get_string_begin(Str const& str)
{ return str.begin(); }
template <typename T, typename Str>
inline typename Str::iterator
get_string_begin(Str& str)
{ return str.begin(); }
template <typename T, typename Str>
inline typename Str::const_iterator get_string_end(Str const& str)
{ return str.end(); }
template <typename T, typename Str>
inline typename Str::iterator
get_string_end(Str& str)
{ return str.end(); }
}}}}
#endif
| nginnever/zogminer | tests/deps/boost/spirit/home/x3/support/traits/string_traits.hpp | C++ | mit | 8,750 |
module.exports.twitter = function twitter(username) {
// Creates the canonical twitter URL without the '@'
return 'https://twitter.com/' + username.replace(/^@/, '');
};
module.exports.facebook = function facebook(username) {
// Handles a starting slash, this shouldn't happen, but just in case
return 'https://www.facebook.com/' + username.replace(/^\//, '');
};
| EdwardStudy/myghostblog | versions/2.16.4/core/server/lib/social/urls.js | JavaScript | mit | 381 |
var utils = exports;
var uglify = require('uglify-js');
utils.extend = function extend(target, source) {
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
};
utils.beautify = function beautify(code) {
var ast = uglify.parser.parse(code);
return uglify.uglify.gen_code(ast, { beautify: true });
};
utils.expressionify = function expressionify(code) {
try {
var ast = uglify.parser.parse('(function(){\n' + code + '\n})');
} catch(e) {
console.error(e.message + ' on ' + (e.line - 1) + ':' + e.pos);
console.error('in');
console.error(code);
throw e;
}
ast[1] = ast[1][0][1][3];
function traverse(ast) {
if (!Array.isArray(ast)) return ast;
switch (ast[0]) {
case 'toplevel':
if (ast[1].length === 1 && ast[1][0][0] !== 'block') {
return ast;
} else {
var children = ast[1][0][0] === 'block' ? ast[1][0][1] : ast[1];
return ['toplevel', [[
'call', [
'dot', [
'function', null, [],
children.map(function(child, i, children) {
return (i == children.length - 1) ? traverse(child) : child;
})
],
'call'
],
[ ['name', 'this'] ]
]]];
}
case 'block':
// Empty blocks can't be processed
if (ast[1].length <= 0) return ast;
var last = ast[1][ast[1].length - 1];
return [
ast[0],
ast[1].slice(0, -1).concat([traverse(last)])
];
case 'while':
case 'for':
case 'switch':
return ast;
case 'if':
return [
'if',
ast[1],
traverse(ast[2]),
traverse(ast[3])
];
case 'stat':
return [
'stat',
traverse(ast[1])
];
default:
if (ast[0] === 'return') return ast;
return [
'return',
ast
]
}
return ast;
}
return uglify.uglify.gen_code(traverse(ast)).replace(/;$/, '');
};
utils.localify = function localify(code, id) {
var ast = uglify.parser.parse(code);
if (ast[1].length !== 1 || ast[1][0][0] !== 'stat') {
throw new TypeError('Incorrect code for local: ' + code);
}
var vars = [],
set = [],
unset = [];
function traverse(node) {
if (node[0] === 'assign') {
if (node[1] !== true) {
throw new TypeError('Incorrect assignment in local');
}
if (node[2][0] === 'dot' || node[2][0] === 'sub') {
var host = ['name', '$l' + id++];
vars.push(host[1]);
set.push(['assign', true, host, node[2][1]]);
node[2][1] = host;
if (node[2][0] === 'sub') {
var property = ['name', '$l' + id++];
vars.push(property[1]);
set.push(['assign', true, property, node[2][2]]);
node[2][2] = property;
}
}
var target = ['name', '$l' + id++];
vars.push(target[1]);
set.push(['assign', true, target, node[2]]);
set.push(['assign', true, node[2], node[3]]);
unset.push(['assign', true, node[2], target]);
} else if (node[0] === 'seq') {
traverse(node[1]);
traverse(node[2]);
} else {
throw new TypeError(
'Incorrect code for local (' + node[0] + '): ' + code
);
}
}
traverse(ast[1][0][1]);
function generate(seqs) {
return uglify.uglify.gen_code(seqs.reduce(function (current, acc) {
return ['seq', current, acc];
}));
}
return {
vars: vars,
before: generate(set.concat([['name', 'true']])),
afterSuccess: generate(unset.concat([['name', 'true']])),
afterFail: generate(unset.concat([['name', 'false']]))
};
};
utils.merge = function merge(a, b) {
Object.keys(b).forEach(function(key) {
a[key] = b[key];
});
};
| CoderPuppy/loke-lang | node_modules/ometajs/lib/ometajs/utils.js | JavaScript | mit | 3,898 |
//
// header.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef HTTP_SERVER3_HEADER_HPP
#define HTTP_SERVER3_HEADER_HPP
#include <string>
namespace http {
namespace server3 {
struct header
{
std::string name;
std::string value;
};
} // namespace server3
} // namespace http
#endif // HTTP_SERVER3_HEADER_HPP
| vslavik/poedit | deps/boost/libs/asio/example/cpp03/http/server3/header.hpp | C++ | mit | 534 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options object.
* To hide one or more series by default, set legend.hidden to an array of
* label strings.
*
* At the moment, this only works with line and point graphs.
*
* Example:
*
* var plotdata = [
* {
* data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]],
* label: "graph 1"
* },
* {
* data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]],
* label: "graph 2"
* }
* ];
*
* plot = $.plot($("#placeholder"), plotdata, {
* series: {
* points: { show: true },
* lines: { show: true }
* },
* legend: {
* hideable: true,
* hidden: ["graph 1", "graph 2"]
* }
* });
*
*/
(function ($) {
var options = { };
var drawnOnce = false;
function init(plot) {
function findPlotSeries(label) {
var plotdata = plot.getData();
for (var i = 0; i < plotdata.length; i++) {
if (plotdata[i].label == label) {
return plotdata[i];
}
}
return null;
}
function plotLabelClicked(label, mouseOut) {
var series = findPlotSeries(label);
if (!series) {
return;
}
var switchedOff = false;
if (typeof series.points.oldShow === "undefined") {
series.points.oldShow = false;
}
if (typeof series.lines.oldShow === "undefined") {
series.lines.oldShow = false;
}
if (series.points.show && !series.points.oldShow) {
series.points.show = false;
series.points.oldShow = true;
switchedOff = true;
}
if (series.lines.show && !series.lines.oldShow) {
series.lines.show = false;
series.lines.oldShow = true;
switchedOff = true;
}
if (switchedOff) {
series.oldColor = series.color;
series.color = "#fff";
} else {
var switchedOn = false;
if (!series.points.show && series.points.oldShow) {
series.points.show = true;
series.points.oldShow = false;
switchedOn = true;
}
if (!series.lines.show && series.lines.oldShow) {
series.lines.show = true;
series.lines.oldShow = false;
switchedOn = true;
}
if (switchedOn) {
series.color = series.oldColor;
}
}
// HACK: Reset the data, triggering recalculation of graph bounds
plot.setData(plot.getData());
plot.setupGrid();
plot.draw();
}
function plotLabelHandlers(plot, options) {
$(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); })
.mouseleave(function() { $(this).css("cursor", "default"); })
.unbind("click").click(function() { plotLabelClicked($(this).parent().text()); });
if (!drawnOnce) {
drawnOnce = true;
if (options.legend.hidden) {
for (var i = 0; i < options.legend.hidden.length; i++) {
plotLabelClicked(options.legend.hidden[i], true);
}
}
}
}
function checkOptions(plot, options) {
if (!options.legend.hideable) {
return;
}
options.legend.labelFormatter = function(label, series) {
return '<span class="graphlabel">' + label + '</span>';
};
// Really just needed for initial draw; the mouse-enter/leave
// functions will call plotLabelHandlers() directly, since they
// only call setupGrid().
plot.hooks.draw.push(function (plot, ctx) {
plotLabelHandlers(plot, options);
});
}
plot.hooks.processOptions.push(checkOptions);
function hideDatapointsIfNecessary(plot, s, datapoints) {
if (!plot.getOptions().legend.hideable) {
return;
}
if (!s.points.show && !s.lines.show) {
s.datapoints.format = [ null, null ];
}
}
plot.hooks.processDatapoints.push(hideDatapointsIfNecessary);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'hiddenGraphs',
version: '1.0'
});
})(jQuery);
| mehulsbhatt/torque | web/static/js/jquery.flot.hiddengraphs.js | JavaScript | mit | 5,081 |
module ActiveRecord
# = Active Record Through Association
module Associations
module ThroughAssociation #:nodoc:
delegate :source_reflection, :through_reflection, :to => :reflection
protected
# We merge in these scopes for two reasons:
#
# 1. To get the default_scope conditions for any of the other reflections in the chain
# 2. To get the type conditions for any STI models in the chain
def target_scope
scope = super
reflection.chain.drop(1).each do |reflection|
relation = reflection.klass.all
scope.merge!(
relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)
end
scope
end
private
# Construct attributes for :through pointing to owner and associate. This is used by the
# methods which create and delete records on the association.
#
# We only support indirectly modifying through associations which have a belongs_to source.
# This is the "has_many :tags, through: :taggings" situation, where the join model
# typically has a belongs_to on both side. In other words, associations which could also
# be represented as has_and_belongs_to_many associations.
#
# We do not support creating/deleting records on the association where the source has
# some other type, because this opens up a whole can of worms, and in basically any
# situation it is more natural for the user to just create or modify their join records
# directly as required.
def construct_join_attributes(*records)
ensure_mutable
if source_reflection.association_primary_key(reflection.klass) == reflection.klass.primary_key
join_attributes = { source_reflection.name => records }
else
join_attributes = {
source_reflection.foreign_key =>
records.map { |record|
record.send(source_reflection.association_primary_key(reflection.klass))
}
}
end
if options[:source_type]
join_attributes[source_reflection.foreign_type] =
records.map { |record| record.class.base_class.name }
end
if records.count == 1
Hash[join_attributes.map { |k, v| [k, v.first] }]
else
join_attributes
end
end
# Note: this does not capture all cases, for example it would be crazy to try to
# properly support stale-checking for nested associations.
def stale_state
if through_reflection.belongs_to?
owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s
end
end
def foreign_key_present?
through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil?
end
def ensure_mutable
unless source_reflection.belongs_to?
if reflection.has_one?
raise HasOneThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
else
raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
end
end
end
def ensure_not_nested
if reflection.nested?
if reflection.has_one?
raise HasOneThroughNestedAssociationsAreReadonly.new(owner, reflection)
else
raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection)
end
end
end
def build_record(attributes)
inverse = source_reflection.inverse_of
target = through_association.target
if inverse && target && !target.is_a?(Array)
attributes[inverse.foreign_key] = target.id
end
super(attributes)
end
end
end
end
| susancal/Waitr | vendor/cache/ruby/2.3.0/gems/activerecord-5.0.0/lib/active_record/associations/through_association.rb | Ruby | mit | 4,003 |
<TS language="af_ZA" version="2.0">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>Skep 'n nuwe adres</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Maak 'n kopie van die huidige adres na die stelsel klipbord</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Verwyder</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Wagfrase Dialoog</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Tik wagfrase in</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Nuwe wagfrase</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Herhaal nuwe wagfrase</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Enkripteer beursie</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Verander wagfrase</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Bevestig beursie enkripsie.</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Die beursie is nou bewaak</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Tik in die ou wagfrase en die nuwe wagfrase vir die beursie.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Die beursie kon nie bewaak word nie</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Beursie bewaaking het misluk as gevolg van 'n interne fout. Die beursie is nie bewaak nie!</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Die wagfrase stem nie ooreen nie</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Beursie oopsluiting het misluk</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Die wagfrase wat ingetik was om die beursie oop te sluit, was verkeerd.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Beursie dekripsie het misluk</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Die beursie se wagfrase verandering was suksesvol.</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>Sinchroniseer met die netwerk ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Oorsig</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Wys algemene oorsig van die beursie</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transaksies</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Besoek transaksie geskiedenis</translation>
</message>
<message>
<source>E&xit</source>
<translation>S&luit af</translation>
</message>
<message>
<source>Quit application</source>
<translation>Sluit af</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Wys inligting oor Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opsies</translation>
</message>
<message>
<source>Bitcoin</source>
<translation>Bitcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Beursie</translation>
</message>
<message>
<source>&File</source>
<translation>&Lêer</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Instellings</translation>
</message>
<message>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Blad nutsbalk</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 agter</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Ontvangs van laaste blok is %1 terug.</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<source>Information</source>
<translation>Informasie</translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Nuwe ontvangende adres</translation>
</message>
<message>
<source>New sending address</source>
<translation>Nuwe stuurende adres</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Wysig ontvangende adres</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Wysig stuurende adres</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Kon nie die beursie oopsluit nie.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opsies</translation>
</message>
<message>
<source>W&allet</source>
<translation>&Beursie</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Vorm</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>&Information</source>
<translation>Informasie</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>&Bedrag:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Boodskap:</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Stuur Munstukke</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Transaksie fooi:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Stuur aan vele ontvangers op eens</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balans:</translation>
</message>
<message>
<source>S&end</source>
<translation>S&tuur</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>&Bedrag:</translation>
</message>
<message>
<source>Message:</source>
<translation>Boodskap:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>&Sign Message</source>
<translation>&Teken boodskap</translation>
</message>
<message>
<source>Signature</source>
<translation>Handtekening</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Teken &Boodskap</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<source>To</source>
<translation>Na</translation>
</message>
<message>
<source>own address</source>
<translation>eie adres</translation>
</message>
<message>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<source>Credit</source>
<translation>Krediet</translation>
</message>
<message>
<source>not accepted</source>
<translation>nie aanvaar nie</translation>
</message>
<message>
<source>Debit</source>
<translation>Debiet</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Transaksie fooi</translation>
</message>
<message>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>Transaksie ID</translation>
</message>
<message>
<source>Transaction</source>
<translation>Transaksie</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<source>Received from</source>
<translation>Ontvang van</translation>
</message>
<message>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Betalings Aan/na jouself</translation>
</message>
<message>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n.v.t)</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tyd wat die transaksie ontvang was.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Tipe transaksie.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<source>Today</source>
<translation>Vandag</translation>
</message>
<message>
<source>This week</source>
<translation>Hierdie week</translation>
</message>
<message>
<source>This month</source>
<translation>Hierdie maand</translation>
</message>
<message>
<source>Last month</source>
<translation>Verlede maand</translation>
</message>
<message>
<source>This year</source>
<translation>Hierdie jaar</translation>
</message>
<message>
<source>Range...</source>
<translation>Reeks...</translation>
</message>
<message>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<source>To yourself</source>
<translation>Aan/na jouself</translation>
</message>
<message>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<source>Other</source>
<translation>Ander</translation>
</message>
<message>
<source>Min amount</source>
<translation>Min bedrag</translation>
</message>
<message>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>Reeks:</translation>
</message>
<message>
<source>to</source>
<translation>aan</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Stuur Munstukke</translation>
</message>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Opsies:</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Fout: Hardeskyf spasie is baie laag!</translation>
</message>
<message>
<source>Information</source>
<translation>Informasie</translation>
</message>
<message>
<source>This help message</source>
<translation>Hierdie help boodskap</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Laai adresse...</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Laai blok indeks...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Laai beursie...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Klaar gelaai</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
</TS> | Bitcoin-com/BUcash | src/qt/locale/bitcoin_af_ZA.ts | TypeScript | mit | 20,485 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.Serialization;
namespace Orleans.Runtime.MembershipService
{
[Serializable]
internal class InMemoryMembershipTable
{
private readonly SerializationManager serializationManager;
private readonly Dictionary<SiloAddress, Tuple<MembershipEntry, string>> siloTable;
private TableVersion tableVersion;
private long lastETagCounter;
public InMemoryMembershipTable(SerializationManager serializationManager)
{
this.serializationManager = serializationManager;
siloTable = new Dictionary<SiloAddress, Tuple<MembershipEntry, string>>();
lastETagCounter = 0;
tableVersion = new TableVersion(0, NewETag());
}
public MembershipTableData Read(SiloAddress key)
{
return siloTable.ContainsKey(key) ?
new MembershipTableData((Tuple<MembershipEntry, string>)this.serializationManager.DeepCopy(siloTable[key]), tableVersion)
: new MembershipTableData(tableVersion);
}
public MembershipTableData ReadAll()
{
return new MembershipTableData(siloTable.Values.Select(tuple =>
new Tuple<MembershipEntry, string>((MembershipEntry)this.serializationManager.DeepCopy(tuple.Item1), tuple.Item2)).ToList(), tableVersion);
}
public TableVersion ReadTableVersion()
{
return tableVersion;
}
public bool Insert(MembershipEntry entry, TableVersion version)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data != null) return false;
if (!tableVersion.VersionEtag.Equals(version.VersionEtag)) return false;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(
entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture));
tableVersion = new TableVersion(version.Version, NewETag());
return true;
}
public bool Update(MembershipEntry entry, string etag, TableVersion version)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data == null) return false;
if (!data.Item2.Equals(etag) || !tableVersion.VersionEtag.Equals(version.VersionEtag)) return false;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(
entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture));
tableVersion = new TableVersion(version.Version, NewETag());
return true;
}
public void UpdateIAmAlive(MembershipEntry entry)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data == null) return;
data.Item1.IAmAliveTime = entry.IAmAliveTime;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(data.Item1, NewETag());
}
public override string ToString()
{
return String.Format("Table = {0}, ETagCounter={1}", ReadAll().ToString(), lastETagCounter);
}
private string NewETag()
{
return lastETagCounter++.ToString(CultureInfo.InvariantCulture);
}
}
}
| shlomiw/orleans | src/OrleansRuntime/MembershipService/InMemoryMembershipTable.cs | C# | mit | 3,500 |
///////////////////////////////////////////////////////////////////////////////
// moment.hpp
//
// Copyright 2005 Eric Niebler. 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)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#define BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
namespace boost { namespace numeric
{
/// INTERNAL ONLY
///
template<typename T>
T const &pow(T const &x, mpl::int_<1>)
{
return x;
}
/// INTERNAL ONLY
///
template<typename T, int N>
T pow(T const &x, mpl::int_<N>)
{
using namespace operators;
T y = numeric::pow(x, mpl::int_<N/2>());
T z = y * y;
return (N % 2) ? (z * x) : z;
}
}}
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// moment_impl
template<typename N, typename Sample>
struct moment_impl
: accumulator_base // TODO: also depends_on sum of powers
{
BOOST_MPL_ASSERT_RELATION(N::value, >, 0);
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
template<typename Args>
moment_impl(Args const &args)
: sum(args[sample | Sample()])
{
}
template<typename Args>
void operator ()(Args const &args)
{
this->sum += numeric::pow(args[sample], N());
}
template<typename Args>
result_type result(Args const &args) const
{
return numeric::fdiv(this->sum, count(args));
}
// make this accumulator serializeable
template<class Archive>
void serialize(Archive & ar, const unsigned int file_version)
{
ar & sum;
}
private:
Sample sum;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::moment
//
namespace tag
{
template<int N>
struct moment
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::moment_impl<mpl::int_<N>, mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::moment
//
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, moment, (int))
}
using extract::moment;
// So that moment<N> can be automatically substituted with
// weighted_moment<N> when the weight parameter is non-void
template<int N>
struct as_weighted_feature<tag::moment<N> >
{
typedef tag::weighted_moment<N> type;
};
template<int N>
struct feature_of<tag::weighted_moment<N> >
: feature_of<tag::moment<N> >
{
};
}} // namespace boost::accumulators
#endif
| kumakoko/KumaGL | third_lib/boost/1.75.0/boost/accumulators/statistics/moment.hpp | C++ | mit | 3,436 |
/*
* W.J. van der Laan 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired)
{
if(!guiref)
return false;
if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Dogecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Dogecoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("Dogecoin");
QApplication::setOrganizationDomain("dogecoin-noexist-domain.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("Dogecoin-Qt-testnet");
else
QApplication::setApplicationName("Dogecoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if(GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
#if MAC_OSX
// QSplashScreen on Mac seems to always stay on top. Ugh.
splash.setWindowFlags(Qt::FramelessWindowHint);
#endif
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
#ifndef Q_OS_MAC
// Regenerate startup link, to fix links to old versions
// OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs)
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
#endif
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if(AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel *walletModel = 0;
if(pwalletMain)
walletModel = new WalletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
if(walletModel)
{
window.addWallet("~Default", walletModel);
window.setCurrentWallet("~Default");
}
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// bitcoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
delete walletModel;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
}
else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| PoundCoinz/PoundCoinz | src/qt/bitcoin.cpp | C++ | mit | 10,783 |
//DO NOT DELETE THIS, this is in use...
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.MacroContainerController",
function($scope, dialogService, entityResource, macroService){
$scope.renderModel = [];
$scope.allowOpenButton = true;
$scope.allowRemoveButton = true;
$scope.sortableOptions = {};
if($scope.model.value){
var macros = $scope.model.value.split('>');
angular.forEach(macros, function(syntax, key){
if(syntax && syntax.length > 10){
//re-add the char we split on
syntax = syntax + ">";
var parsed = macroService.parseMacroSyntax(syntax);
if(!parsed){
parsed = {};
}
parsed.syntax = syntax;
collectDetails(parsed);
$scope.renderModel.push(parsed);
setSortingState($scope.renderModel);
}
});
}
function collectDetails(macro){
macro.details = "";
macro.icon = "icon-settings-alt";
if(macro.macroParamsDictionary){
angular.forEach((macro.macroParamsDictionary), function(value, key){
macro.details += key + ": " + value + " ";
});
}
}
function openDialog(index){
var dialogData = {
allowedMacros: $scope.model.config.allowed
};
if(index !== null && $scope.renderModel[index]) {
var macro = $scope.renderModel[index];
dialogData["macroData"] = macro;
}
$scope.macroPickerOverlay = {};
$scope.macroPickerOverlay.view = "macropicker";
$scope.macroPickerOverlay.dialogData = dialogData;
$scope.macroPickerOverlay.show = true;
$scope.macroPickerOverlay.submit = function(model) {
var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine);
collectDetails(macroObject);
//update the raw syntax and the list...
if(index !== null && $scope.renderModel[index]) {
$scope.renderModel[index] = macroObject;
} else {
$scope.renderModel.push(macroObject);
}
setSortingState($scope.renderModel);
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
$scope.macroPickerOverlay.close = function(oldModel) {
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
}
$scope.edit =function(index){
openDialog(index);
};
$scope.add = function () {
if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) {
//cannot add more than the max
return;
}
openDialog();
};
$scope.remove =function(index){
$scope.renderModel.splice(index, 1);
setSortingState($scope.renderModel);
};
$scope.clear = function() {
$scope.model.value = "";
$scope.renderModel = [];
};
var unsubscribe = $scope.$on("formSubmitting", function (ev, args) {
var syntax = [];
angular.forEach($scope.renderModel, function(value, key){
syntax.push(value.syntax);
});
$scope.model.value = syntax.join("");
});
//when the scope is destroyed we need to unsubscribe
$scope.$on('$destroy', function () {
unsubscribe();
});
function trim(str, chr) {
var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g');
return str.replace(rgxtrim, '');
}
function setSortingState(items) {
// disable sorting if the list only consist of one item
if(items.length > 1) {
$scope.sortableOptions.disabled = false;
} else {
$scope.sortableOptions.disabled = true;
}
}
});
| abryukhov/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/propertyeditors/macrocontainer/macrocontainer.controller.js | JavaScript | mit | 3,569 |
/*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2010 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.env.data.model;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import omero.IllegalArgumentException;
import org.openmicroscopy.shoola.env.data.login.UserCredentials;
import omero.gateway.model.ExperimenterData;
import omero.gateway.model.GroupData;
/**
* Holds information about the group, users to handle.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* @since 3.0-Beta4
*/
public class AdminObject
{
/** Indicates to create a group. */
public static final int CREATE_GROUP = 0;
/** Indicates to create a group. */
public static final int CREATE_EXPERIMENTER = 1;
/** Indicates to update a group. */
public static final int UPDATE_GROUP = 2;
/** Indicates to update experimenter. */
public static final int UPDATE_EXPERIMENTER = 3;
/** Indicates to reset the password. */
public static final int RESET_PASSWORD = 4;
/** Indicates to add experimenters to group. */
public static final int ADD_EXPERIMENTER_TO_GROUP = 5;
/** Indicates to reset the password. */
public static final int ACTIVATE_USER = 6;
/**
* Validates the index.
*
* @param index The value to control.
*/
private void checkIndex(int index)
{
switch (index) {
case CREATE_EXPERIMENTER:
case CREATE_GROUP:
case UPDATE_GROUP:
case UPDATE_EXPERIMENTER:
case RESET_PASSWORD:
case ADD_EXPERIMENTER_TO_GROUP:
case ACTIVATE_USER:
return;
default:
throw new IllegalArgumentException("Index not supported");
}
}
/**
* Can be the group to create or the group to add the experimenters to
* depending on the index.
*/
private GroupData group;
/** The collection of groups to create. */
private List<GroupData> groups;
/**
* Can be the owners of the group or the experimenters to create
* depending on the index.
*/
private Map<ExperimenterData, UserCredentials> experimenters;
/** One of the constants defined by this class. */
private int index;
/** Indicates the permissions associated to the group. */
private int permissions = -1;
/**
* Creates a new instance.
*
* @param group The group to handle.
* @param experimenters The experimenters to handle.
* @param index One of the constants defined by this class.
*/
public AdminObject(GroupData group, Map<ExperimenterData, UserCredentials>
experimenters, int index)
{
checkIndex(index);
this.group = group;
this.experimenters = experimenters;
this.index = index;
this.permissions = -1;
}
/**
* Creates a new instance.
*
* @param group The group to handle.
* @param values The experimenters to handle.
*/
public AdminObject(GroupData group, Collection<ExperimenterData> values)
{
if (values != null) {
Iterator<ExperimenterData> i = values.iterator();
experimenters = new HashMap<ExperimenterData, UserCredentials>();
while (i.hasNext()) {
experimenters.put(i.next(), null);
}
}
this.group = group;
this.index = ADD_EXPERIMENTER_TO_GROUP;
this.permissions = -1;
}
/**
* Creates a new instance.
*
* @param experimenters The experimenters to handle.
* @param index One of the constants defined by this class.
*/
public AdminObject(Map<ExperimenterData, UserCredentials> experimenters,
int index)
{
this(null, experimenters, index);
}
/**
* Sets the permissions associated to the group.
*
* @param permissions The value to set. One of the constants defined
* by this class.
*/
public void setPermissions(int permissions)
{
switch (permissions) {
case GroupData.PERMISSIONS_PRIVATE:
case GroupData.PERMISSIONS_GROUP_READ:
case GroupData.PERMISSIONS_GROUP_READ_LINK:
case GroupData.PERMISSIONS_GROUP_READ_WRITE:
case GroupData.PERMISSIONS_PUBLIC_READ:
case GroupData.PERMISSIONS_PUBLIC_READ_WRITE:
this.permissions = permissions;
break;
default:
this.permissions = GroupData.PERMISSIONS_PRIVATE;
}
}
/**
* Returns the permissions associated to the group.
*
* @return See above.
*/
public int getPermissions() { return permissions; }
/**
* Returns the experimenters to create.
*
* @return See above
*/
public Map<ExperimenterData, UserCredentials> getExperimenters()
{
return experimenters;
}
/**
* Returns the group to create or to add the experimenters to.
*
* @return See above.
*/
public GroupData getGroup() { return group; }
/**
* Sets the groups.
*
* @param groups The value to handle.
*/
public void setGroups(List<GroupData> groups) { this.groups = groups; }
/**
* Returns the groups to add the new users to.
*
* @return See above.
*/
public List<GroupData> getGroups() { return groups; }
/**
* Returns one of the constants defined by this class.
*
* @return See above.
*/
public int getIndex() { return index; }
}
| knabar/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/env/data/model/AdminObject.java | Java | gpl-2.0 | 6,106 |
<?php
/*
Widget Name: Editor
Description: A widget which allows editing of content using the TinyMCE editor.
Author: SiteOrigin
Author URI: https://siteorigin.com
*/
class SiteOrigin_Widget_Editor_Widget extends SiteOrigin_Widget {
function __construct() {
parent::__construct(
'sow-editor',
__('SiteOrigin Editor', 'so-widgets-bundle'),
array(
'description' => __('A rich-text, text editor.', 'so-widgets-bundle'),
'help' => 'https://siteorigin.com/widgets-bundle/editor-widget/'
),
array(),
false,
plugin_dir_path(__FILE__)
);
}
function initialize_form(){
return array(
'title' => array(
'type' => 'text',
'label' => __('Title', 'so-widgets-bundle'),
),
'text' => array(
'type' => 'tinymce',
'rows' => 20
),
'autop' => array(
'type' => 'checkbox',
'default' => true,
'label' => __('Automatically add paragraphs', 'so-widgets-bundle'),
),
);
}
function unwpautop($string) {
$string = str_replace("<p>", "", $string);
$string = str_replace(array("<br />", "<br>", "<br/>"), "\n", $string);
$string = str_replace("</p>", "\n\n", $string);
return $string;
}
public function get_template_variables( $instance, $args ) {
$instance = wp_parse_args(
$instance,
array( 'text' => '' )
);
$instance['text'] = $this->unwpautop( $instance['text'] );
$instance['text'] = apply_filters( 'widget_text', $instance['text'] );
// Run some known stuff
if( !empty($GLOBALS['wp_embed']) ) {
$instance['text'] = $GLOBALS['wp_embed']->autoembed( $instance['text'] );
}
if (function_exists('wp_make_content_images_responsive')) {
$instance['text'] = wp_make_content_images_responsive( $instance['text'] );
}
if( $instance['autop'] ) {
$instance['text'] = wpautop( $instance['text'] );
}
$instance['text'] = do_shortcode( shortcode_unautop( $instance['text'] ) );
return array(
'text' => $instance['text'],
);
}
function get_style_name($instance) {
// We're not using a style
return false;
}
}
siteorigin_widget_register( 'sow-editor', __FILE__, 'SiteOrigin_Widget_Editor_Widget' );
| Analytical-Engine-Interactive/loopylogic | wp-content/plugins/so-widgets-bundle/widgets/editor/editor.php | PHP | gpl-2.0 | 2,126 |
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
// ---------------------------------------------------------------------------------------------
// GC graphics pipeline
// ---------------------------------------------------------------------------------------------
// 3d commands are issued through the fifo. The GPU draws to the 2MB EFB.
// The efb can be copied back into ram in two forms: as textures or as XFB.
// The XFB is the region in RAM that the VI chip scans out to the television.
// So, after all rendering to EFB is done, the image is copied into one of two XFBs in RAM.
// Next frame, that one is scanned out and the other one gets the copy. = double buffering.
// ---------------------------------------------------------------------------------------------
#include <cinttypes>
#include <cmath>
#include <string>
#include "Common/Atomic.h"
#include "Common/Event.h"
#include "Common/Profiler.h"
#include "Common/StringUtil.h"
#include "Common/Timer.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/Host.h"
#include "Core/Movie.h"
#include "Core/FifoPlayer/FifoRecorder.h"
#include "Core/HW/VideoInterface.h"
#include "VideoCommon/AVIDump.h"
#include "VideoCommon/BPMemory.h"
#include "VideoCommon/CommandProcessor.h"
#include "VideoCommon/CPMemory.h"
#include "VideoCommon/Debugger.h"
#include "VideoCommon/Fifo.h"
#include "VideoCommon/FPSCounter.h"
#include "VideoCommon/FramebufferManagerBase.h"
#include "VideoCommon/MainBase.h"
#include "VideoCommon/OpcodeDecoding.h"
#include "VideoCommon/RenderBase.h"
#include "VideoCommon/Statistics.h"
#include "VideoCommon/TextureCacheBase.h"
#include "VideoCommon/VideoConfig.h"
#include "VideoCommon/XFMemory.h"
// TODO: Move these out of here.
int frameCount;
int OSDChoice;
static int OSDTime;
Renderer *g_renderer = nullptr;
std::mutex Renderer::s_criticalScreenshot;
std::string Renderer::s_sScreenshotName;
Common::Event Renderer::s_screenshotCompleted;
volatile bool Renderer::s_bScreenshot;
// The framebuffer size
int Renderer::s_target_width;
int Renderer::s_target_height;
// TODO: Add functionality to reinit all the render targets when the window is resized.
int Renderer::s_backbuffer_width;
int Renderer::s_backbuffer_height;
PostProcessingShaderImplementation* Renderer::m_post_processor;
TargetRectangle Renderer::target_rc;
int Renderer::s_last_efb_scale;
bool Renderer::XFBWrited;
PEControl::PixelFormat Renderer::prev_efb_format = PEControl::INVALID_FMT;
unsigned int Renderer::efb_scale_numeratorX = 1;
unsigned int Renderer::efb_scale_numeratorY = 1;
unsigned int Renderer::efb_scale_denominatorX = 1;
unsigned int Renderer::efb_scale_denominatorY = 1;
Renderer::Renderer()
: frame_data()
, bLastFrameDumped(false)
{
UpdateActiveConfig();
TextureCache::OnConfigChanged(g_ActiveConfig);
#if defined _WIN32 || defined HAVE_LIBAV
bAVIDumping = false;
#endif
OSDChoice = 0;
OSDTime = 0;
}
Renderer::~Renderer()
{
// invalidate previous efb format
prev_efb_format = PEControl::INVALID_FMT;
efb_scale_numeratorX = efb_scale_numeratorY = efb_scale_denominatorX = efb_scale_denominatorY = 1;
#if defined _WIN32 || defined HAVE_LIBAV
if (SConfig::GetInstance().m_DumpFrames && bLastFrameDumped && bAVIDumping)
AVIDump::Stop();
#else
if (pFrameDump.IsOpen())
pFrameDump.Close();
#endif
}
void Renderer::RenderToXFB(u32 xfbAddr, const EFBRectangle& sourceRc, u32 fbStride, u32 fbHeight, float Gamma)
{
CheckFifoRecording();
if (!fbStride || !fbHeight)
return;
XFBWrited = true;
if (g_ActiveConfig.bUseXFB)
{
FramebufferManagerBase::CopyToXFB(xfbAddr, fbStride, fbHeight, sourceRc, Gamma);
}
else
{
// below div two to convert from bytes to pixels - it expects width, not stride
Swap(xfbAddr, fbStride/2, fbStride/2, fbHeight, sourceRc, Gamma);
}
}
int Renderer::EFBToScaledX(int x)
{
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO: // fractional
return FramebufferManagerBase::ScaleToVirtualXfbWidth(x);
default:
return x * (int)efb_scale_numeratorX / (int)efb_scale_denominatorX;
};
}
int Renderer::EFBToScaledY(int y)
{
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO: // fractional
return FramebufferManagerBase::ScaleToVirtualXfbHeight(y);
default:
return y * (int)efb_scale_numeratorY / (int)efb_scale_denominatorY;
};
}
void Renderer::CalculateTargetScale(int x, int y, int* scaledX, int* scaledY)
{
if (g_ActiveConfig.iEFBScale == SCALE_AUTO || g_ActiveConfig.iEFBScale == SCALE_AUTO_INTEGRAL)
{
*scaledX = x;
*scaledY = y;
}
else
{
*scaledX = x * (int)efb_scale_numeratorX / (int)efb_scale_denominatorX;
*scaledY = y * (int)efb_scale_numeratorY / (int)efb_scale_denominatorY;
}
}
// return true if target size changed
bool Renderer::CalculateTargetSize(unsigned int framebuffer_width, unsigned int framebuffer_height)
{
int newEFBWidth, newEFBHeight;
newEFBWidth = newEFBHeight = 0;
// TODO: Ugly. Clean up
switch (s_last_efb_scale)
{
case SCALE_AUTO:
case SCALE_AUTO_INTEGRAL:
newEFBWidth = FramebufferManagerBase::ScaleToVirtualXfbWidth(EFB_WIDTH);
newEFBHeight = FramebufferManagerBase::ScaleToVirtualXfbHeight(EFB_HEIGHT);
if (s_last_efb_scale == SCALE_AUTO_INTEGRAL)
{
newEFBWidth = ((newEFBWidth-1) / EFB_WIDTH + 1) * EFB_WIDTH;
newEFBHeight = ((newEFBHeight-1) / EFB_HEIGHT + 1) * EFB_HEIGHT;
}
efb_scale_numeratorX = newEFBWidth;
efb_scale_denominatorX = EFB_WIDTH;
efb_scale_numeratorY = newEFBHeight;
efb_scale_denominatorY = EFB_HEIGHT;
break;
case SCALE_1X:
efb_scale_numeratorX = efb_scale_numeratorY = 1;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
break;
case SCALE_1_5X:
efb_scale_numeratorX = efb_scale_numeratorY = 3;
efb_scale_denominatorX = efb_scale_denominatorY = 2;
break;
case SCALE_2X:
efb_scale_numeratorX = efb_scale_numeratorY = 2;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
break;
case SCALE_2_5X:
efb_scale_numeratorX = efb_scale_numeratorY = 5;
efb_scale_denominatorX = efb_scale_denominatorY = 2;
break;
default:
efb_scale_numeratorX = efb_scale_numeratorY = s_last_efb_scale - 3;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
int maxSize;
maxSize = GetMaxTextureSize();
if ((unsigned)maxSize < EFB_WIDTH * efb_scale_numeratorX / efb_scale_denominatorX)
{
efb_scale_numeratorX = efb_scale_numeratorY = (maxSize / EFB_WIDTH);
efb_scale_denominatorX = efb_scale_denominatorY = 1;
}
break;
}
if (s_last_efb_scale > SCALE_AUTO_INTEGRAL)
CalculateTargetScale(EFB_WIDTH, EFB_HEIGHT, &newEFBWidth, &newEFBHeight);
if (newEFBWidth != s_target_width || newEFBHeight != s_target_height)
{
s_target_width = newEFBWidth;
s_target_height = newEFBHeight;
return true;
}
return false;
}
void Renderer::ConvertStereoRectangle(const TargetRectangle& rc, TargetRectangle& leftRc, TargetRectangle& rightRc)
{
// Resize target to half its original size
TargetRectangle drawRc = rc;
if (g_ActiveConfig.iStereoMode == STEREO_TAB)
{
// The height may be negative due to flipped rectangles
int height = rc.bottom - rc.top;
drawRc.top += height / 4;
drawRc.bottom -= height / 4;
}
else
{
int width = rc.right - rc.left;
drawRc.left += width / 4;
drawRc.right -= width / 4;
}
// Create two target rectangle offset to the sides of the backbuffer
leftRc = drawRc, rightRc = drawRc;
if (g_ActiveConfig.iStereoMode == STEREO_TAB)
{
leftRc.top -= s_backbuffer_height / 4;
leftRc.bottom -= s_backbuffer_height / 4;
rightRc.top += s_backbuffer_height / 4;
rightRc.bottom += s_backbuffer_height / 4;
}
else
{
leftRc.left -= s_backbuffer_width / 4;
leftRc.right -= s_backbuffer_width / 4;
rightRc.left += s_backbuffer_width / 4;
rightRc.right += s_backbuffer_width / 4;
}
}
void Renderer::SetScreenshot(const std::string& filename)
{
std::lock_guard<std::mutex> lk(s_criticalScreenshot);
s_sScreenshotName = filename;
s_bScreenshot = true;
}
// Create On-Screen-Messages
void Renderer::DrawDebugText()
{
std::string final_yellow, final_cyan;
if (g_ActiveConfig.bShowFPS || SConfig::GetInstance().m_ShowFrameCount)
{
if (g_ActiveConfig.bShowFPS)
final_cyan += StringFromFormat("FPS: %d", g_renderer->m_fps_counter.m_fps);
if (g_ActiveConfig.bShowFPS && SConfig::GetInstance().m_ShowFrameCount)
final_cyan += " - ";
if (SConfig::GetInstance().m_ShowFrameCount)
{
final_cyan += StringFromFormat("Frame: %llu", (unsigned long long) Movie::g_currentFrame);
if (Movie::IsPlayingInput())
final_cyan += StringFromFormat(" / %llu", (unsigned long long) Movie::g_totalFrames);
}
final_cyan += "\n";
final_yellow += "\n";
}
if (SConfig::GetInstance().m_ShowLag)
{
final_cyan += StringFromFormat("Lag: %" PRIu64 "\n", Movie::g_currentLagCount);
final_yellow += "\n";
}
if (SConfig::GetInstance().m_ShowInputDisplay)
{
final_cyan += Movie::GetInputDisplay();
final_yellow += "\n";
}
// OSD Menu messages
if (OSDChoice > 0)
{
OSDTime = Common::Timer::GetTimeMs() + 3000;
OSDChoice = -OSDChoice;
}
if ((u32)OSDTime > Common::Timer::GetTimeMs())
{
std::string res_text;
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO:
res_text = "Auto (fractional)";
break;
case SCALE_AUTO_INTEGRAL:
res_text = "Auto (integral)";
break;
case SCALE_1X:
res_text = "Native";
break;
case SCALE_1_5X:
res_text = "1.5x";
break;
case SCALE_2X:
res_text = "2x";
break;
case SCALE_2_5X:
res_text = "2.5x";
break;
default:
res_text = StringFromFormat("%dx", g_ActiveConfig.iEFBScale - 3);
break;
}
const char* ar_text = "";
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_AUTO:
ar_text = "Auto";
break;
case ASPECT_STRETCH:
ar_text = "Stretch";
break;
case ASPECT_ANALOG:
ar_text = "Force 4:3";
break;
case ASPECT_ANALOG_WIDE:
ar_text = "Force 16:9";
}
const char* const efbcopy_text = g_ActiveConfig.bSkipEFBCopyToRam ? "to Texture" : "to RAM";
// The rows
const std::string lines[] =
{
std::string("Internal Resolution: ") + res_text,
std::string("Aspect Ratio: ") + ar_text + (g_ActiveConfig.bCrop ? " (crop)" : ""),
std::string("Copy EFB: ") + efbcopy_text,
std::string("Fog: ") + (g_ActiveConfig.bDisableFog ? "Disabled" : "Enabled"),
};
enum { lines_count = sizeof(lines) / sizeof(*lines) };
// The latest changed setting in yellow
for (int i = 0; i != lines_count; ++i)
{
if (OSDChoice == -i - 1)
final_yellow += lines[i];
final_yellow += '\n';
}
// The other settings in cyan
for (int i = 0; i != lines_count; ++i)
{
if (OSDChoice != -i - 1)
final_cyan += lines[i];
final_cyan += '\n';
}
}
final_cyan += Common::Profiler::ToString();
if (g_ActiveConfig.bOverlayStats)
final_cyan += Statistics::ToString();
if (g_ActiveConfig.bOverlayProjStats)
final_cyan += Statistics::ToStringProj();
//and then the text
g_renderer->RenderText(final_cyan, 20, 20, 0xFF00FFFF);
g_renderer->RenderText(final_yellow, 20, 20, 0xFFFFFF00);
}
void Renderer::UpdateDrawRectangle(int backbuffer_width, int backbuffer_height)
{
float FloatGLWidth = (float)backbuffer_width;
float FloatGLHeight = (float)backbuffer_height;
float FloatXOffset = 0;
float FloatYOffset = 0;
// The rendering window size
const float WinWidth = FloatGLWidth;
const float WinHeight = FloatGLHeight;
// Update aspect ratio hack values
// Won't take effect until next frame
// Don't know if there is a better place for this code so there isn't a 1 frame delay
if (g_ActiveConfig.bWidescreenHack)
{
float source_aspect = VideoInterface::GetAspectRatio(g_aspect_wide);
float target_aspect;
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_STRETCH:
target_aspect = WinWidth / WinHeight;
break;
case ASPECT_ANALOG:
target_aspect = VideoInterface::GetAspectRatio(false);
break;
case ASPECT_ANALOG_WIDE:
target_aspect = VideoInterface::GetAspectRatio(true);
break;
default:
// ASPECT_AUTO
target_aspect = source_aspect;
break;
}
float adjust = source_aspect / target_aspect;
if (adjust > 1)
{
// Vert+
g_Config.fAspectRatioHackW = 1;
g_Config.fAspectRatioHackH = 1 / adjust;
}
else
{
// Hor+
g_Config.fAspectRatioHackW = adjust;
g_Config.fAspectRatioHackH = 1;
}
}
else
{
// Hack is disabled
g_Config.fAspectRatioHackW = 1;
g_Config.fAspectRatioHackH = 1;
}
// Check for force-settings and override.
// The rendering window aspect ratio as a proportion of the 4:3 or 16:9 ratio
float Ratio;
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_ANALOG_WIDE:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(true);
break;
case ASPECT_ANALOG:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(false);
break;
default:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(g_aspect_wide);
break;
}
if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH)
{
if (Ratio > 1.0f)
{
// Scale down and center in the X direction.
FloatGLWidth /= Ratio;
FloatXOffset = (WinWidth - FloatGLWidth) / 2.0f;
}
// The window is too high, we have to limit the height
else
{
// Scale down and center in the Y direction.
FloatGLHeight *= Ratio;
FloatYOffset = FloatYOffset + (WinHeight - FloatGLHeight) / 2.0f;
}
}
// -----------------------------------------------------------------------
// Crop the picture from Analog to 4:3 or from Analog (Wide) to 16:9.
// Output: FloatGLWidth, FloatGLHeight, FloatXOffset, FloatYOffset
// ------------------
if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH && g_ActiveConfig.bCrop)
{
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_ANALOG_WIDE:
Ratio = (16.0f / 9.0f) / VideoInterface::GetAspectRatio(true);
break;
case ASPECT_ANALOG:
Ratio = (4.0f / 3.0f) / VideoInterface::GetAspectRatio(false);
break;
default:
Ratio = (!g_aspect_wide ? (4.0f / 3.0f) : (16.0f / 9.0f)) / VideoInterface::GetAspectRatio(g_aspect_wide);
break;
}
if (Ratio <= 1.0f)
{
Ratio = 1.0f / Ratio;
}
// The width and height we will add (calculate this before FloatGLWidth and FloatGLHeight is adjusted)
float IncreasedWidth = (Ratio - 1.0f) * FloatGLWidth;
float IncreasedHeight = (Ratio - 1.0f) * FloatGLHeight;
// The new width and height
FloatGLWidth = FloatGLWidth * Ratio;
FloatGLHeight = FloatGLHeight * Ratio;
// Adjust the X and Y offset
FloatXOffset = FloatXOffset - (IncreasedWidth * 0.5f);
FloatYOffset = FloatYOffset - (IncreasedHeight * 0.5f);
}
int XOffset = (int)(FloatXOffset + 0.5f);
int YOffset = (int)(FloatYOffset + 0.5f);
int iWhidth = (int)ceil(FloatGLWidth);
int iHeight = (int)ceil(FloatGLHeight);
iWhidth -= iWhidth % 4; // ensure divisibility by 4 to make it compatible with all the video encoders
iHeight -= iHeight % 4;
target_rc.left = XOffset;
target_rc.top = YOffset;
target_rc.right = XOffset + iWhidth;
target_rc.bottom = YOffset + iHeight;
}
void Renderer::SetWindowSize(int width, int height)
{
if (width < 1)
width = 1;
if (height < 1)
height = 1;
// Scale the window size by the EFB scale.
CalculateTargetScale(width, height, &width, &height);
Host_RequestRenderWindowSize(width, height);
}
void Renderer::CheckFifoRecording()
{
bool wasRecording = g_bRecordFifoData;
g_bRecordFifoData = FifoRecorder::GetInstance().IsRecording();
if (g_bRecordFifoData)
{
if (!wasRecording)
{
RecordVideoMemory();
}
FifoRecorder::GetInstance().EndFrame(CommandProcessor::fifo.CPBase, CommandProcessor::fifo.CPEnd);
}
}
void Renderer::RecordVideoMemory()
{
u32 *bpmem_ptr = (u32*)&bpmem;
u32 cpmem[256];
// The FIFO recording format splits XF memory into xfmem and xfregs; follow
// that split here.
u32 *xfmem_ptr = (u32*)&xfmem;
u32 *xfregs_ptr = (u32*)&xfmem + FifoDataFile::XF_MEM_SIZE;
u32 xfregs_size = sizeof(XFMemory) / 4 - FifoDataFile::XF_MEM_SIZE;
memset(cpmem, 0, 256 * 4);
FillCPMemoryArray(cpmem);
FifoRecorder::GetInstance().SetVideoMemory(bpmem_ptr, cpmem, xfmem_ptr, xfregs_ptr, xfregs_size);
}
void Renderer::Swap(u32 xfbAddr, u32 fbWidth, u32 fbStride, u32 fbHeight, const EFBRectangle& rc, float Gamma)
{
// TODO: merge more generic parts into VideoCommon
g_renderer->SwapImpl(xfbAddr, fbWidth, fbStride, fbHeight, rc, Gamma);
if (XFBWrited)
g_renderer->m_fps_counter.Update();
frameCount++;
GFX_DEBUGGER_PAUSE_AT(NEXT_FRAME, true);
// Begin new frame
// Set default viewport and scissor, for the clear to work correctly
// New frame
stats.ResetFrame();
Core::Callback_VideoCopiedToXFB(XFBWrited || (g_ActiveConfig.bUseXFB && g_ActiveConfig.bUseRealXFB));
XFBWrited = false;
}
void Renderer::PokeEFB(EFBAccessType type, const std::vector<EfbPokeData>& data)
{
for (EfbPokeData poke : data)
{
AccessEFB(type, poke.x, poke.y, poke.data);
}
}
| aroulin/dolphin | Source/Core/VideoCommon/RenderBase.cpp | C++ | gpl-2.0 | 17,004 |
<?php
wp_enqueue_script( 'pods' );
wp_enqueue_style( 'pods-form' );
if ( empty( $fields ) || !is_array( $fields ) )
$fields = $obj->pod->fields;
if ( !isset( $duplicate ) )
$duplicate = false;
else
$duplicate = (boolean) $duplicate;
$groups = PodsInit::$meta->groups_get( $pod->pod_data[ 'type' ], $pod->pod_data[ 'name' ], $fields );
$group_fields = array();
$submittable_fields = array();
foreach ( $groups as $g => $group ) {
// unset fields
foreach ( $group[ 'fields' ] as $k => $field ) {
if ( in_array( $field[ 'name' ], array( 'created', 'modified' ) ) ) {
unset( $group[ 'fields' ][ $k ] );
continue;
}
elseif ( false === PodsForm::permission( $field[ 'type' ], $field[ 'name' ], $field[ 'options' ], $group[ 'fields' ], $pod, $pod->id() ) ) {
if ( pods_var( 'hidden', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'type' ] = 'hidden';
}
elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'readonly' ] = true;
}
else {
unset( $group[ 'fields' ][ $k ] );
continue;
}
}
elseif ( !pods_has_permissions( $field[ 'options' ] ) ) {
if ( pods_var( 'hidden', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'type' ] = 'hidden';
}
elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'readonly' ] = true;
}
}
if ( !pods_var( 'readonly', $field, false ) ) {
$submittable_fields[ $field[ 'name' ]] = $group[ 'fields' ][ $k ];
}
$group_fields[ $field[ 'name' ] ] = $group[ 'fields' ][ $k ];
}
$groups[ $g ] = $group;
}
if ( !isset( $thank_you_alt ) )
$thank_you_alt = $thank_you;
$uri_hash = wp_create_nonce( 'pods_uri_' . $_SERVER[ 'REQUEST_URI' ] );
$field_hash = wp_create_nonce( 'pods_fields_' . implode( ',', array_keys( $submittable_fields ) ) );
$uid = @session_id();
if ( is_user_logged_in() )
$uid = 'user_' . get_current_user_id();
$nonce = wp_create_nonce( 'pods_form_' . $pod->pod . '_' . $uid . '_' . ( $duplicate ? 0 : $pod->id() ) . '_' . $uri_hash . '_' . $field_hash );
if ( isset( $_POST[ '_pods_nonce' ] ) ) {
$action = __( 'saved', 'pods' );
if ( 'create' == pods_var_raw( 'do', 'post', 'save' ) )
$action = __( 'created', 'pods' );
elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'duplicated', 'pods' );
try {
$params = pods_unslash( (array) $_POST );
$id = $pod->api->process_form( $params, $pod, $submittable_fields, $thank_you );
$message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) )
$message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>';
$error = sprintf( __( '<strong>Error:</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < $id )
echo $obj->message( $message );
else
echo $obj->error( $error );
}
catch ( Exception $e ) {
echo $obj->error( $e->getMessage() );
}
}
elseif ( isset( $_GET[ 'do' ] ) ) {
$action = __( 'saved', 'pods' );
if ( 'create' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'created', 'pods' );
elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'duplicated', 'pods' );
$message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) )
$message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>';
$error = sprintf( __( '<strong>Error:</strong> %s not %s.', 'pods' ), $obj->item, $action );
if ( 0 < $pod->id() )
echo $obj->message( $message );
else
echo $obj->error( $error );
}
if ( !isset( $label ) )
$label = __( 'Save', 'pods' );
$do = 'create';
if ( 0 < $pod->id() ) {
if ( $duplicate )
$do = 'duplicate';
else
$do = 'save';
}
?>
<form action="" method="post" class="pods-submittable pods-form pods-form-pod-<?php echo $pod->pod; ?> pods-submittable-ajax">
<div class="pods-submittable-fields">
<?php
echo PodsForm::field( 'action', 'pods_admin', 'hidden' );
echo PodsForm::field( 'method', 'process_form', 'hidden' );
echo PodsForm::field( 'do', $do, 'hidden' );
echo PodsForm::field( '_pods_nonce', $nonce, 'hidden' );
echo PodsForm::field( '_pods_pod', $pod->pod, 'hidden' );
echo PodsForm::field( '_pods_id', ( $duplicate ? 0 : $pod->id() ), 'hidden' );
echo PodsForm::field( '_pods_uri', $uri_hash, 'hidden' );
echo PodsForm::field( '_pods_form', implode( ',', array_keys( $submittable_fields ) ), 'hidden' );
echo PodsForm::field( '_pods_location', $_SERVER[ 'REQUEST_URI' ], 'hidden' );
foreach ( $group_fields as $field ) {
if ( 'hidden' != $field[ 'type' ] )
continue;
echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), 'hidden' );
}
/**
* Action that runs before the meta boxes for an Advanced Content Type
*
* Occurs at the top of #poststuff
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_meta_box_pre', $pod, $obj );
?>
<div id="poststuff" class="metabox-holder has-right-sidebar"> <!-- class "has-right-sidebar" preps for a sidebar... always present? -->
<div id="side-info-column" class="inner-sidebar">
<?php
/**
* Action that runs before the sidebar of the editor for an Advanced Content Type
*
* Occurs at the top of #side-info-column
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_sidebar', $pod, $obj );
?>
<div id="side-sortables" class="meta-box-sortables ui-sortable">
<!-- BEGIN PUBLISH DIV -->
<div id="submitdiv" class="postbox">
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle"><span><?php _e( 'Manage', 'pods' ); ?></span></h3>
<div class="inside">
<div class="submitbox" id="submitpost">
<?php
if ( 0 < $pod->id() && ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) || 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) ) {
?>
<div id="minor-publishing">
<?php
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) {
?>
<div id="minor-publishing-actions">
<div id="preview-action">
<a class="button" href="<?php echo $pod->field( 'detail_url' ); ?>" target="_blank"><?php echo sprintf( __( 'View %s', 'pods' ), $obj->item ); ?></a>
</div>
<div class="clear"></div>
</div>
<?php
}
if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) ) {
?>
<div id="misc-publishing-actions">
<?php
$datef = __( 'M j, Y @ G:i' );
if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) ) {
$date = date_i18n( $datef, strtotime( $pod->field( 'created' ) ) );
?>
<div class="misc-pub-section curtime">
<span id="timestamp"><?php _e( 'Created on', 'pods' ); ?>: <b><?php echo $date; ?></b></span>
</div>
<?php
}
if ( isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) && $pod->display( 'created' ) != $pod->display( 'modified' ) ) {
$date = date_i18n( $datef, strtotime( $pod->field( 'modified' ) ) );
?>
<div class="misc-pub-section curtime">
<span id="timestamp"><?php _e( 'Last Modified', 'pods' ); ?>: <b><?php echo $date; ?></b></span>
</div>
<?php
}
?>
<?php
/**
* Action that runs after the misc publish actions area for an Advanced Content Type
*
* Occurs at the end of #misc-publishing-actions
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_misc_pub_actions', $pod, $obj );
?>
</div>
<?php
}
?>
</div>
<!-- /#minor-publishing -->
<?php
}
?>
<div id="major-publishing-actions">
<?php
if ( pods_is_admin( array( 'pods', 'pods_delete_' . $pod->pod ) ) && null !== $pod->id() && !$duplicate && !in_array( 'delete', (array) $obj->actions_disabled ) && !in_array( 'delete', (array) $obj->actions_hidden ) ) {
?>
<div id="delete-action">
<a class="submitdelete deletion" href="<?php echo pods_var_update( array( 'action' => 'delete' ) ) ?>" onclick="return confirm('You are about to permanently delete this item\n Choose \'Cancel\' to stop, \'OK\' to delete.');"><?php _e( 'Delete', 'pods' ); ?></a>
</div>
<!-- /#delete-action -->
<?php } ?>
<div id="publishing-action">
<img class="waiting" src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" alt="" />
<input type="submit" name="publish" id="publish" class="button button-primary button-large" value="<?php echo esc_attr( $label ); ?>" accesskey="p" />
<?php
/**
* Action that runs after the publish button for an Advanced Content Type
*
* Occurs at the end of #publishing-action
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_submit_area', $pod, $obj );
?>
</div>
<!-- /#publishing-action -->
<div class="clear"></div>
</div>
<?php
/**
* Action that runs after the publish area for an Advanced Content Type
*
* Occurs at the end of #submitpost
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_publish_area', $pod, $obj );
?>
<!-- /#major-publishing-actions -->
</div>
<!-- /#submitpost -->
</div>
<!-- /.inside -->
</div>
<!-- /#submitdiv --><!-- END PUBLISH DIV --><!-- TODO: minor column fields -->
<?php
if ( pods_var_raw( 'action' ) == 'edit' && !$duplicate && !in_array( 'navigate', (array) $obj->actions_disabled ) && !in_array( 'navigate', (array) $obj->actions_hidden ) ) {
if ( !isset( $singular_label ) )
$singular_label = ucwords( str_replace( '_', ' ', $pod->pod_data[ 'name' ] ) );
$singular_label = pods_var_raw( 'label', $pod->pod_data[ 'options' ], $singular_label, null, true );
$singular_label = pods_var_raw( 'label_singular', $pod->pod_data[ 'options' ], $singular_label, null, true );
$pod->params = $obj->get_params( null, 'manage' );
$prev_next = apply_filters( 'pods_ui_prev_next_ids', array(), $pod, $obj );
if ( empty( $prev_next ) ) {
$prev_next = array(
'prev' => $pod->prev_id(),
'next' => $pod->next_id()
);
}
$prev = $prev_next[ 'prev' ];
$next = $prev_next[ 'next' ];
if ( 0 < $prev || 0 < $next ) {
?>
<div id="navigatediv" class="postbox">
<?php
/**
* Action that runs before the post navagiation in the editor for an Advanced Content Type
*
* Occurs at the top of #navigatediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_navigation', $pod, $obj );
?>
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle"><span><?php _e( 'Navigate', 'pods' ); ?></span></h3>
<div class="inside">
<div class="pods-admin" id="navigatebox">
<div id="navigation-actions">
<?php
if ( 0 < $prev ) {
?>
<a class="previous-item" href="<?php echo pods_var_update( array( 'id' => $prev ), null, 'do' ); ?>">
<span>«</span>
<?php echo sprintf( __( 'Previous %s', 'pods' ), $singular_label ); ?>
</a>
<?php
}
if ( 0 < $next ) {
?>
<a class="next-item" href="<?php echo pods_var_update( array( 'id' => $next ), null, 'do' ); ?>">
<?php echo sprintf( __( 'Next %s', 'pods' ), $singular_label ); ?>
<span>»</span>
</a>
<?php
}
?>
<div class="clear"></div>
</div>
<!-- /#navigation-actions -->
</div>
<!-- /#navigatebox -->
</div>
<!-- /.inside -->
<?php
/**
* Action that runs after the post navagiation in the editor for an Advanced Content Type
*
* Occurs at the bottom of #navigatediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_navigation', $pod, $obj );
?>
</div> <!-- /#navigatediv -->
<?php
}
}
?>
</div>
<!-- /#side-sortables -->
<?php
/**
* Action that runs after the sidebar of the editor for an Advanced Content Type
*
* Occurs at the bottom of #side-info-column
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_sidebar', $pod, $obj );
?>
</div>
<!-- /#side-info-column -->
<div id="post-body">
<div id="post-body-content">
<?php
$more = false;
if ( $pod->pod_data[ 'field_index' ] != $pod->pod_data[ 'field_id' ] ) {
foreach ( $group_fields as $field ) {
if ( $pod->pod_data[ 'field_index' ] != $field[ 'name' ] || 'text' != $field[ 'type' ] )
continue;
$more = true;
$extra = '';
$max_length = (int) pods_var( 'maxlength', $field[ 'options' ], pods_var( $field[ 'type' ] . '_max_length', $field[ 'options' ], 0 ), null, true );
if ( 0 < $max_length )
$extra .= ' maxlength="' . $max_length . '"';
/**
* Filter that lets you make the title field readonly
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
if ( pods_v( 'readonly', $field[ 'options' ], pods_v( 'readonly', $field, false ) ) || apply_filters( 'pods_ui_form_title_readonly', false, $pod, $obj ) ) {
?>
<div id="titlediv">
<div id="titlewrap">
<h3><?php echo esc_html( $pod->index() ); ?></h3>
<input type="hidden" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="pods-form-ui-field-name-pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> />
</div>
<!-- /#titlewrap -->
</div>
<!-- /#titlediv -->
<?php
}
else {
?>
<div id="titlediv">
<?php
/**
* Action that runs before the title field of the editor for an Advanced Content Type
*
* Occurs at the top of #titlediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_title', $pod, $obj );
?>
<div id="titlewrap">
<label class="screen-reader-text" id="title-prompt-text" for="title"><?php echo apply_filters( 'pods_enter_name_here', __( 'Enter name here', 'pods' ), $pod, $fields ); ?></label>
<input type="text" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="pods-form-ui-field-name-pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> />
<?php
/**
* Action that runs after the title field of the editor for an Advanced Content Type
*
* Occurs at the bottom of #titlediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_title', $pod, $obj );
?>
</div>
<!-- /#titlewrap -->
<div class="inside">
<div id="edit-slug-box">
</div>
<!-- /#edit-slug-box -->
</div>
<!-- /.inside -->
</div>
<!-- /#titlediv -->
<?php
}
unset( $group_fields[ $field[ 'name' ] ] );
}
}
if ( 0 < count( $groups ) ) {
if ( $more && 1 == count( $groups ) ) {
$first_group = current( $groups );
if ( 1 == count( $first_group[ 'fields' ] ) && isset( $first_group[ 'fields' ][ $pod->pod_data[ 'field_index' ] ] ) ) {
$groups = array();
}
}
if ( 0 < count( $groups ) ) {
?>
<div id="normal-sortables" class="meta-box-sortables ui-sortable">
<?php
foreach ( $groups as $group ) {
if ( empty( $group[ 'fields' ] ) ) {
continue;
}
/**
* Action that runs before the main fields metabox in the editor for an Advanced Content Type
*
* Occurs at the top of #normal-sortables
*
* @param obj $pod Current Pods object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_metabox', $pod );
?>
<div id="pods-meta-box-<?php echo sanitize_title( $group[ 'label' ] ); ?>" class="postbox" style="">
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle">
<span>
<?php
if ( ! $more && 1 == count( $groups ) ) {
$title = __( 'Fields', 'pods' );
}
else {
$title = $group[ 'label' ];
}
/** This filter is documented in classes/PodsMeta.php */
echo apply_filters( 'pods_meta_default_box_title', $title, $pod, $fields, $pod->api->pod_data[ 'type' ], $pod->pod );
?>
</span>
</h3>
<div class="inside">
<?php
if ( false === apply_filters( 'pods_meta_box_override', false, $pod, $group, $obj ) ) {
?>
<table class="form-table pods-metabox">
<?php
foreach ( $group[ 'fields' ] as $field ) {
if ( 'hidden' == $field[ 'type' ] || $more === $field[ 'name' ] || !isset( $group_fields[ $field[ 'name' ] ] ) )
continue;
?>
<tr class="form-field pods-field pods-field-input <?php echo 'pods-form-ui-row-type-' . $field[ 'type' ] . ' pods-form-ui-row-name-' . PodsForm::clean( $field[ 'name' ], true ); ?>">
<th scope="row" valign="top"><?php echo PodsForm::label( 'pods_field_' . $field[ 'name' ], $field[ 'label' ], $field[ 'help' ], $field ); ?></th>
<td>
<?php echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), $field[ 'type' ], $field, $pod, $pod->id() ); ?>
<?php echo PodsForm::comment( 'pods_field_' . $field[ 'name' ], $field[ 'description' ], $field ); ?>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
</div>
<!-- /.inside -->
</div>
<!-- /#pods-meta-box -->
<?php
}
/**
* Action that runs after the main fields metabox in the editor for an Advanced Content Type
*
* Occurs at the bottom of #normal-sortables
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_metabox', $pod, $obj );
?>
</div>
<!-- /#normal-sortables -->
<?php
}
}
?>
<!--<div id="advanced-sortables" class="meta-box-sortables ui-sortable">
</div>
/#advanced-sortables -->
</div>
<!-- /#post-body-content -->
<br class="clear" />
</div>
<!-- /#post-body -->
<br class="clear" />
</div>
<!-- /#poststuff -->
</div>
</form>
<!-- /#pods-record -->
<script type="text/javascript">
if ( 'undefined' == typeof ajaxurl ) {
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
}
jQuery( function ( $ ) {
$( document ).Pods( 'validate' );
$( document ).Pods( 'submit' );
$( document ).Pods( 'dependency' );
$( document ).Pods( 'confirm' );
$( document ).Pods( 'exit_confirm' );
} );
if ( 'undefined' == typeof pods_form_thank_you ) {
var pods_form_thank_you = null;
}
var pods_admin_submit_callback = function ( id ) {
id = parseInt( id );
var thank_you = '<?php echo pods_slash( $thank_you ); ?>';
var thank_you_alt = '<?php echo pods_slash( $thank_you_alt ); ?>';
if ( 'undefined' != typeof pods_form_thank_you && null !== pods_form_thank_you ) {
thank_you = pods_form_thank_you;
}
if ( 'NaN' == id )
document.location = thank_you_alt.replace( 'X_ID_X', 0 );
else
document.location = thank_you.replace( 'X_ID_X', id );
}
</script>
| nbrouse-deep/chefmatefrontburner_com | wp-content/plugins/pods/ui/admin/form.php | PHP | gpl-2.0 | 30,874 |
/*
* Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Death_knight_darkreaver
SD%Complete: 100
SDComment:
SDCategory: Scholomance
EndScriptData */
#include "ScriptPCH.h"
class boss_death_knight_darkreaver : public CreatureScript
{
public:
boss_death_knight_darkreaver() : CreatureScript("boss_death_knight_darkreaver") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_death_knight_darkreaverAI (pCreature);
}
struct boss_death_knight_darkreaverAI : public ScriptedAI
{
boss_death_knight_darkreaverAI(Creature *c) : ScriptedAI(c) {}
void Reset()
{
}
void DamageTaken(Unit * /*done_by*/, uint32 &damage)
{
if (me->GetHealth() <= damage)
DoCast(me, 23261, true); //Summon Darkreaver's Fallen Charger
}
void EnterCombat(Unit * /*who*/)
{
}
};
};
void AddSC_boss_death_knight_darkreaver()
{
new boss_death_knight_darkreaver();
}
| sureandrew/trinitycore | src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp | C++ | gpl-2.0 | 1,778 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "bladerunner/script/scene_script.h"
namespace BladeRunner {
enum kCT04Loops {
kCT04LoopInshot = 0,
kCT04LoopMainLoop = 1
};
void SceneScriptCT04::InitializeScene() {
if (Game_Flag_Query(kFlagCT03toCT04)) {
Scene_Loop_Start_Special(kSceneLoopModeLoseControl, kCT04LoopInshot, false);
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-150.0f, -621.3f, 357.0f, 533);
} else {
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-82.86f, -621.3f, 769.03f, 1020);
}
Scene_Exit_Add_2D_Exit(0, 590, 0, 639, 479, 1);
Scene_Exit_Add_2D_Exit(1, 194, 84, 320, 274, 0);
if (_vm->_cutContent) {
Scene_Exit_Add_2D_Exit(2, 0, 440, 590, 479, 2);
}
Ambient_Sounds_Add_Looping_Sound(kSfxCTRAIN1, 50, 1, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTAMBR1, 15, -100, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTRUNOFF, 34, 100, 1);
Ambient_Sounds_Add_Sound(kSfxSPIN2B, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxSPIN3A, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 0, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 20, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 40, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 50, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Sound(kSfxTHNDER3, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxTHNDER4, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
}
void SceneScriptCT04::SceneLoaded() {
Obstacle_Object("DUMPSTER", true);
Obstacle_Object("RIGHTWALL01", true);
Obstacle_Object("BACK-BLDNG", true);
Clickable_Object("DUMPSTER");
Footstep_Sounds_Set(0, 1);
if (Game_Flag_Query(kFlagCT03toCT04)) {
Game_Flag_Reset(kFlagCT03toCT04);
}
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Change_Animation_Mode(kActorTransient, 38);
}
}
bool SceneScriptCT04::MouseClick(int x, int y) {
return false;
}
bool SceneScriptCT04::ClickedOn3DObject(const char *objectName, bool a2) {
if (objectName) { // this can be only "DUMPSTER"
if (!Game_Flag_Query(kFlagCT04HomelessTalk)
&& !Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault
) {
Game_Flag_Set(kFlagCT04HomelessTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
if ( Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& !Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)
&& !Game_Flag_Query(kFlagCT04HomelessBodyFound)
&& !Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)
&& Global_Variable_Query(kVariableChapter) == 1
) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -147.41f, -621.3f, 724.57f, 0, true, false, false)) {
Player_Loses_Control();
Actor_Face_Heading(kActorMcCoy, 792, false);
Actor_Put_In_Set(kActorTransient, kSetFreeSlotI);
Actor_Set_At_XYZ(kActorTransient, 0, 0, 0, 0);
Actor_Change_Animation_Mode(kActorMcCoy, 40);
Actor_Voice_Over(320, kActorVoiceOver);
Actor_Voice_Over(330, kActorVoiceOver);
Actor_Voice_Over(340, kActorVoiceOver);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpster);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return false;
}
if (Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)) {
if (Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)) {
Actor_Voice_Over(270, kActorVoiceOver);
Actor_Voice_Over(280, kActorVoiceOver);
} else if (Game_Flag_Query(kFlagCT04HomelessBodyFound)) {
Actor_Voice_Over(250, kActorVoiceOver);
Actor_Voice_Over(260, kActorVoiceOver);
} else {
Actor_Voice_Over(230, kActorVoiceOver);
Actor_Voice_Over(240, kActorVoiceOver);
Game_Flag_Reset(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return true;
}
if (!Game_Flag_Query(kFlagCT04LicensePlaceFound)) {
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Actor_Clue_Acquire(kActorMcCoy, kClueLicensePlate, true, -1);
Item_Pickup_Spin_Effect(kModelAnimationLicensePlate, 392, 225);
Game_Flag_Set(kFlagCT04LicensePlaceFound);
return true;
}
}
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Ambient_Sounds_Play_Sound(kSfxGARBAGE, 45, 30, 30, 0);
Actor_Voice_Over(1810, kActorVoiceOver);
Actor_Voice_Over(1820, kActorVoiceOver);
return true;
}
}
return false;
}
void SceneScriptCT04::dialogueWithHomeless() {
Dialogue_Menu_Clear_List();
if (Global_Variable_Query(kVariableChinyen) > 10
|| Query_Difficulty_Level() == kGameDifficultyEasy
) {
DM_Add_To_List_Never_Repeat_Once_Selected(410, 8, 4, -1); // YES
}
DM_Add_To_List_Never_Repeat_Once_Selected(420, 2, 6, 8); // NO
Dialogue_Menu_Appear(320, 240);
int answer = Dialogue_Menu_Query_Input();
Dialogue_Menu_Disappear();
switch (answer) {
case 410: // YES
Actor_Says(kActorTransient, 10, 14); // Thanks. The big man. He kind of limping.
Actor_Says(kActorTransient, 20, 14); // That way.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, 5);
if (Query_Difficulty_Level() != kGameDifficultyEasy) {
Global_Variable_Decrement(kVariableChinyen, 10);
}
break;
case 420: // NO
Actor_Says(kActorMcCoy, 430, 3);
Actor_Says(kActorTransient, 30, 14); // Hey, that'd work.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, -5);
break;
}
}
bool SceneScriptCT04::ClickedOnActor(int actorId) {
if (actorId == kActorTransient) {
if (Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)) {
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Voice_Over(290, kActorVoiceOver);
Actor_Voice_Over(300, kActorVoiceOver);
Actor_Voice_Over(310, kActorVoiceOver);
}
} else {
Actor_Set_Targetable(kActorTransient, false);
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
if (!Game_Flag_Query(kFlagCT04HomelessTalk)) {
if (Game_Flag_Query(kFlagZubenRetired)) {
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
} else {
Music_Stop(3);
Actor_Says(kActorMcCoy, 425, kAnimationModeTalk);
Actor_Says(kActorTransient, 0, 13); // Hey, maybe spare some chinyen?
dialogueWithHomeless();
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04HomelessTalk);
} else {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
}
}
}
return true;
}
return false;
}
bool SceneScriptCT04::ClickedOnItem(int itemId, bool a2) {
return false;
}
bool SceneScriptCT04::ClickedOnExit(int exitId) {
if (exitId == 1) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -82.86f, -621.3f, 769.03f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04toCT05);
Set_Enter(kSetCT05, kSceneCT05);
}
return true;
}
if (exitId == 0) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -187.0f, -621.3f, 437.0f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
if (_vm->_cutContent) {
if (exitId == 2) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -106.94f, -619.08f, 429.20f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
}
return false;
}
bool SceneScriptCT04::ClickedOn2DRegion(int region) {
return false;
}
void SceneScriptCT04::SceneFrameAdvanced(int frame) {
if (Game_Flag_Query(kFlagCT04BodyDumped)) {
Game_Flag_Reset(kFlagCT04BodyDumped);
Sound_Play(kSfxGARBAGE4, 100, 80, 80, 50);
}
}
void SceneScriptCT04::ActorChangedGoal(int actorId, int newGoal, int oldGoal, bool currentSet) {
}
void SceneScriptCT04::PlayerWalkedIn() {
}
void SceneScriptCT04::PlayerWalkedOut() {
}
void SceneScriptCT04::DialogueQueueFlushed(int a1) {
}
} // End of namespace BladeRunner
| alexbevi/scummvm | engines/bladerunner/script/scene/ct04.cpp | C++ | gpl-2.0 | 9,795 |
/*
* Copyright (c) 2018, 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 p2;
public class c2 {
int i;
public void method2() { i = 5; System.out.println("c2 method2 called"); }
}
| JetBrains/jdk8u_hotspot | test/runtime/ClassUnload/p2/c2.java | Java | gpl-2.0 | 1,173 |
<?php
/**
* Advanced OpenWorkflow, Automating SugarCRM.
* @package Advanced OpenWorkflow for SugarCRM
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* 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 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
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author SalesAgility <info@salesagility.com>
*/
class actionBase
{
public $id;
public function __construct($id = '')
{
$this->id = $id;
}
/**
* @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
*/
public function actionBase($id = '')
{
$deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->deprecated($deprecatedMessage);
} else {
trigger_error($deprecatedMessage, E_USER_DEPRECATED);
}
self::__construct($id);
}
public function loadJS()
{
return array();
}
public function edit_display($line, SugarBean $bean = null, $params = array())
{
return '';
}
public function run_action(SugarBean $bean, $params = array(), $in_save=false)
{
return true;
}
}
| lionixevolve/LionixCRM | modules/AOW_Actions/actions/actionBase.php | PHP | agpl-3.0 | 1,987 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2008 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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 full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// check CompressedSparsityPattern::copy constructor with offdiagonals
#include "sparsity_pattern_common.h"
int main ()
{
std::ofstream logfile("output");
logfile.setf(std::ios::fixed);
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
copy_with_offdiagonals_2<CompressedSparsityPattern> ();
}
| johntfoster/dealii | tests/lac/compressed_sparsity_pattern_05.cc | C++ | lgpl-2.1 | 1,031 |
// @allowJs: true
// @checkJs: true
// @noEmit: true
// @Filename: templateTagOnClasses.js
/**
* @template T
* @typedef {(t: T) => T} Id
*/
/** @template T */
class Foo {
/** @typedef {(t: T) => T} Id2 */
/** @param {T} x */
constructor (x) {
this.a = x
}
/**
*
* @param {T} x
* @param {Id<T>} y
* @param {Id2} alpha
* @return {T}
*/
foo(x, y, alpha) {
return alpha(y(x))
}
}
var f = new Foo(1)
var g = new Foo(false)
f.a = g.a
| weswigham/TypeScript | tests/cases/conformance/jsdoc/jsdocTemplateClass.ts | TypeScript | apache-2.0 | 508 |
"""Extension argument processing code
"""
__all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias',
'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI',
'IDENTIFIER_SELECT']
import copy
import warnings
import urllib
from openid import oidutil
from openid import kvform
try:
ElementTree = oidutil.importElementTree()
except ImportError:
# No elementtree found, so give up, but don't fail to import,
# since we have fallbacks.
ElementTree = None
# This doesn't REALLY belong here, but where is better?
IDENTIFIER_SELECT = 'http://specs.openid.net/auth/2.0/identifier_select'
# URI for Simple Registration extension, the only commonly deployed
# OpenID 1.x extension, and so a special case
SREG_URI = 'http://openid.net/sreg/1.0'
# The OpenID 1.X namespace URI
OPENID1_NS = 'http://openid.net/signon/1.0'
THE_OTHER_OPENID1_NS = 'http://openid.net/signon/1.1'
OPENID1_NAMESPACES = OPENID1_NS, THE_OTHER_OPENID1_NS
# The OpenID 2.0 namespace URI
OPENID2_NS = 'http://specs.openid.net/auth/2.0'
# The namespace consisting of pairs with keys that are prefixed with
# "openid." but not in another namespace.
NULL_NAMESPACE = oidutil.Symbol('Null namespace')
# The null namespace, when it is an allowed OpenID namespace
OPENID_NS = oidutil.Symbol('OpenID namespace')
# The top-level namespace, excluding all pairs with keys that start
# with "openid."
BARE_NS = oidutil.Symbol('Bare namespace')
# Limit, in bytes, of identity provider and return_to URLs, including
# response payload. See OpenID 1.1 specification, Appendix D.
OPENID1_URL_LIMIT = 2047
# All OpenID protocol fields. Used to check namespace aliases.
OPENID_PROTOCOL_FIELDS = [
'ns', 'mode', 'error', 'return_to', 'contact', 'reference',
'signed', 'assoc_type', 'session_type', 'dh_modulus', 'dh_gen',
'dh_consumer_public', 'claimed_id', 'identity', 'realm',
'invalidate_handle', 'op_endpoint', 'response_nonce', 'sig',
'assoc_handle', 'trust_root', 'openid',
]
class UndefinedOpenIDNamespace(ValueError):
"""Raised if the generic OpenID namespace is accessed when there
is no OpenID namespace set for this message."""
class InvalidOpenIDNamespace(ValueError):
"""Raised if openid.ns is not a recognized value.
For recognized values, see L{Message.allowed_openid_namespaces}
"""
def __str__(self):
s = "Invalid OpenID Namespace"
if self.args:
s += " %r" % (self.args[0],)
return s
# Sentinel used for Message implementation to indicate that getArg
# should raise an exception instead of returning a default.
no_default = object()
# Global namespace / alias registration map. See
# registerNamespaceAlias.
registered_aliases = {}
class NamespaceAliasRegistrationError(Exception):
"""
Raised when an alias or namespace URI has already been registered.
"""
pass
def registerNamespaceAlias(namespace_uri, alias):
"""
Registers a (namespace URI, alias) mapping in a global namespace
alias map. Raises NamespaceAliasRegistrationError if either the
namespace URI or alias has already been registered with a
different value. This function is required if you want to use a
namespace with an OpenID 1 message.
"""
global registered_aliases
if registered_aliases.get(alias) == namespace_uri:
return
if namespace_uri in registered_aliases.values():
raise NamespaceAliasRegistrationError, \
'Namespace uri %r already registered' % (namespace_uri,)
if alias in registered_aliases:
raise NamespaceAliasRegistrationError, \
'Alias %r already registered' % (alias,)
registered_aliases[alias] = namespace_uri
class Message(object):
"""
In the implementation of this object, None represents the global
namespace as well as a namespace with no key.
@cvar namespaces: A dictionary specifying specific
namespace-URI to alias mappings that should be used when
generating namespace aliases.
@ivar ns_args: two-level dictionary of the values in this message,
grouped by namespace URI. The first level is the namespace
URI.
"""
allowed_openid_namespaces = [OPENID1_NS, THE_OTHER_OPENID1_NS, OPENID2_NS]
def __init__(self, openid_namespace=None):
"""Create an empty Message.
@raises InvalidOpenIDNamespace: if openid_namespace is not in
L{Message.allowed_openid_namespaces}
"""
self.args = {}
self.namespaces = NamespaceMap()
if openid_namespace is None:
self._openid_ns_uri = None
else:
implicit = openid_namespace in OPENID1_NAMESPACES
self.setOpenIDNamespace(openid_namespace, implicit)
def fromPostArgs(cls, args):
"""Construct a Message containing a set of POST arguments.
"""
self = cls()
# Partition into "openid." args and bare args
openid_args = {}
for key, value in args.items():
if isinstance(value, list):
raise TypeError("query dict must have one value for each key, "
"not lists of values. Query is %r" % (args,))
try:
prefix, rest = key.split('.', 1)
except ValueError:
prefix = None
if prefix != 'openid':
self.args[(BARE_NS, key)] = value
else:
openid_args[rest] = value
self._fromOpenIDArgs(openid_args)
return self
fromPostArgs = classmethod(fromPostArgs)
def fromOpenIDArgs(cls, openid_args):
"""Construct a Message from a parsed KVForm message.
@raises InvalidOpenIDNamespace: if openid.ns is not in
L{Message.allowed_openid_namespaces}
"""
self = cls()
self._fromOpenIDArgs(openid_args)
return self
fromOpenIDArgs = classmethod(fromOpenIDArgs)
def _fromOpenIDArgs(self, openid_args):
ns_args = []
# Resolve namespaces
for rest, value in openid_args.iteritems():
try:
ns_alias, ns_key = rest.split('.', 1)
except ValueError:
ns_alias = NULL_NAMESPACE
ns_key = rest
if ns_alias == 'ns':
self.namespaces.addAlias(value, ns_key)
elif ns_alias == NULL_NAMESPACE and ns_key == 'ns':
# null namespace
self.setOpenIDNamespace(value, False)
else:
ns_args.append((ns_alias, ns_key, value))
# Implicitly set an OpenID namespace definition (OpenID 1)
if not self.getOpenIDNamespace():
self.setOpenIDNamespace(OPENID1_NS, True)
# Actually put the pairs into the appropriate namespaces
for (ns_alias, ns_key, value) in ns_args:
ns_uri = self.namespaces.getNamespaceURI(ns_alias)
if ns_uri is None:
# we found a namespaced arg without a namespace URI defined
ns_uri = self._getDefaultNamespace(ns_alias)
if ns_uri is None:
ns_uri = self.getOpenIDNamespace()
ns_key = '%s.%s' % (ns_alias, ns_key)
else:
self.namespaces.addAlias(ns_uri, ns_alias, implicit=True)
self.setArg(ns_uri, ns_key, value)
def _getDefaultNamespace(self, mystery_alias):
"""OpenID 1 compatibility: look for a default namespace URI to
use for this alias."""
global registered_aliases
# Only try to map an alias to a default if it's an
# OpenID 1.x message.
if self.isOpenID1():
return registered_aliases.get(mystery_alias)
else:
return None
def setOpenIDNamespace(self, openid_ns_uri, implicit):
"""Set the OpenID namespace URI used in this message.
@raises InvalidOpenIDNamespace: if the namespace is not in
L{Message.allowed_openid_namespaces}
"""
if openid_ns_uri not in self.allowed_openid_namespaces:
raise InvalidOpenIDNamespace(openid_ns_uri)
self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit)
self._openid_ns_uri = openid_ns_uri
def getOpenIDNamespace(self):
return self._openid_ns_uri
def isOpenID1(self):
return self.getOpenIDNamespace() in OPENID1_NAMESPACES
def isOpenID2(self):
return self.getOpenIDNamespace() == OPENID2_NS
def fromKVForm(cls, kvform_string):
"""Create a Message from a KVForm string"""
return cls.fromOpenIDArgs(kvform.kvToDict(kvform_string))
fromKVForm = classmethod(fromKVForm)
def copy(self):
return copy.deepcopy(self)
def toPostArgs(self):
"""Return all arguments with openid. in front of namespaced arguments.
"""
args = {}
# Add namespace definitions to the output
for ns_uri, alias in self.namespaces.iteritems():
if self.namespaces.isImplicit(ns_uri):
continue
if alias == NULL_NAMESPACE:
ns_key = 'openid.ns'
else:
ns_key = 'openid.ns.' + alias
args[ns_key] = oidutil.toUnicode(ns_uri).encode('UTF-8')
for (ns_uri, ns_key), value in self.args.iteritems():
key = self.getKey(ns_uri, ns_key)
# Ensure the resulting value is an UTF-8 encoded bytestring.
args[key] = oidutil.toUnicode(value).encode('UTF-8')
return args
def toArgs(self):
"""Return all namespaced arguments, failing if any
non-namespaced arguments exist."""
# FIXME - undocumented exception
post_args = self.toPostArgs()
kvargs = {}
for k, v in post_args.iteritems():
if not k.startswith('openid.'):
raise ValueError(
'This message can only be encoded as a POST, because it '
'contains arguments that are not prefixed with "openid."')
else:
kvargs[k[7:]] = v
return kvargs
def toFormMarkup(self, action_url, form_tag_attrs=None,
submit_text=u"Continue"):
"""Generate HTML form markup that contains the values in this
message, to be HTTP POSTed as x-www-form-urlencoded UTF-8.
@param action_url: The URL to which the form will be POSTed
@type action_url: str
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@type form_tag_attrs: {unicode: unicode}
@param submit_text: The text that will appear on the submit
button for this form.
@type submit_text: unicode
@returns: A string containing (X)HTML markup for a form that
encodes the values in this Message object.
@rtype: str or unicode
"""
if ElementTree is None:
raise RuntimeError('This function requires ElementTree.')
assert action_url is not None
form = ElementTree.Element(u'form')
if form_tag_attrs:
for name, attr in form_tag_attrs.iteritems():
form.attrib[name] = attr
form.attrib[u'action'] = oidutil.toUnicode(action_url)
form.attrib[u'method'] = u'post'
form.attrib[u'accept-charset'] = u'UTF-8'
form.attrib[u'enctype'] = u'application/x-www-form-urlencoded'
for name, value in self.toPostArgs().iteritems():
attrs = {u'type': u'hidden',
u'name': oidutil.toUnicode(name),
u'value': oidutil.toUnicode(value)}
form.append(ElementTree.Element(u'input', attrs))
submit = ElementTree.Element(u'input',
{u'type':'submit', u'value':oidutil.toUnicode(submit_text)})
form.append(submit)
return ElementTree.tostring(form, encoding='utf-8')
def toURL(self, base_url):
"""Generate a GET URL with the parameters in this message
attached as query parameters."""
return oidutil.appendArgs(base_url, self.toPostArgs())
def toKVForm(self):
"""Generate a KVForm string that contains the parameters in
this message. This will fail if the message contains arguments
outside of the 'openid.' prefix.
"""
return kvform.dictToKV(self.toArgs())
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = self.toPostArgs().items()
args.sort()
return urllib.urlencode(args)
def _fixNS(self, namespace):
"""Convert an input value into the internally used values of
this object
@param namespace: The string or constant to convert
@type namespace: str or unicode or BARE_NS or OPENID_NS
"""
if namespace == OPENID_NS:
if self._openid_ns_uri is None:
raise UndefinedOpenIDNamespace('OpenID namespace not set')
else:
namespace = self._openid_ns_uri
if namespace != BARE_NS and type(namespace) not in [str, unicode]:
raise TypeError(
"Namespace must be BARE_NS, OPENID_NS or a string. got %r"
% (namespace,))
if namespace != BARE_NS and ':' not in namespace:
fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r'
warnings.warn(fmt % (namespace,), DeprecationWarning)
if namespace == 'sreg':
fmt = 'Using %r instead of "sreg" as namespace'
warnings.warn(fmt % (SREG_URI,), DeprecationWarning,)
return SREG_URI
return namespace
def hasKey(self, namespace, ns_key):
namespace = self._fixNS(namespace)
return (namespace, ns_key) in self.args
def getKey(self, namespace, ns_key):
"""Get the key for a particular namespaced argument"""
namespace = self._fixNS(namespace)
if namespace == BARE_NS:
return ns_key
ns_alias = self.namespaces.getAlias(namespace)
# No alias is defined, so no key can exist
if ns_alias is None:
return None
if ns_alias == NULL_NAMESPACE:
tail = ns_key
else:
tail = '%s.%s' % (ns_alias, ns_key)
return 'openid.' + tail
def getArg(self, namespace, key, default=None):
"""Get a value for a namespaced key.
@param namespace: The namespace in the message for this key
@type namespace: str
@param key: The key to get within this namespace
@type key: str
@param default: The value to use if this key is absent from
this message. Using the special value
openid.message.no_default will result in this method
raising a KeyError instead of returning the default.
@rtype: str or the type of default
@raises KeyError: if default is no_default
@raises UndefinedOpenIDNamespace: if the message has not yet
had an OpenID namespace set
"""
namespace = self._fixNS(namespace)
args_key = (namespace, key)
try:
return self.args[args_key]
except KeyError:
if default is no_default:
raise KeyError((namespace, key))
else:
return default
def getArgs(self, namespace):
"""Get the arguments that are defined for this namespace URI
@returns: mapping from namespaced keys to values
@returntype: dict
"""
namespace = self._fixNS(namespace)
return dict([
(ns_key, value)
for ((pair_ns, ns_key), value)
in self.args.iteritems()
if pair_ns == namespace
])
def updateArgs(self, namespace, updates):
"""Set multiple key/value pairs in one call
@param updates: The values to set
@type updates: {unicode:unicode}
"""
namespace = self._fixNS(namespace)
for k, v in updates.iteritems():
self.setArg(namespace, k, v)
def setArg(self, namespace, key, value):
"""Set a single argument in this namespace"""
assert key is not None
assert value is not None
namespace = self._fixNS(namespace)
self.args[(namespace, key)] = value
if not (namespace is BARE_NS):
self.namespaces.add(namespace)
def delArg(self, namespace, key):
namespace = self._fixNS(namespace)
del self.args[(namespace, key)]
def __repr__(self):
return "<%s.%s %r>" % (self.__class__.__module__,
self.__class__.__name__,
self.args)
def __eq__(self, other):
return self.args == other.args
def __ne__(self, other):
return not (self == other)
def getAliasedArg(self, aliased_key, default=None):
if aliased_key == 'ns':
return self.getOpenIDNamespace()
if aliased_key.startswith('ns.'):
uri = self.namespaces.getNamespaceURI(aliased_key[3:])
if uri is None:
if default == no_default:
raise KeyError
else:
return default
else:
return uri
try:
alias, key = aliased_key.split('.', 1)
except ValueError:
# need more than x values to unpack
ns = None
else:
ns = self.namespaces.getNamespaceURI(alias)
if ns is None:
key = aliased_key
ns = self.getOpenIDNamespace()
return self.getArg(ns, key, default)
class NamespaceMap(object):
"""Maintains a bijective map between namespace uris and aliases.
"""
def __init__(self):
self.alias_to_namespace = {}
self.namespace_to_alias = {}
self.implicit_namespaces = []
def getAlias(self, namespace_uri):
return self.namespace_to_alias.get(namespace_uri)
def getNamespaceURI(self, alias):
return self.alias_to_namespace.get(alias)
def iterNamespaceURIs(self):
"""Return an iterator over the namespace URIs"""
return iter(self.namespace_to_alias)
def iterAliases(self):
"""Return an iterator over the aliases"""
return iter(self.alias_to_namespace)
def iteritems(self):
"""Iterate over the mapping
@returns: iterator of (namespace_uri, alias)
"""
return self.namespace_to_alias.iteritems()
def addAlias(self, namespace_uri, desired_alias, implicit=False):
"""Add an alias from this namespace URI to the desired alias
"""
# Check that desired_alias is not an openid protocol field as
# per the spec.
assert desired_alias not in OPENID_PROTOCOL_FIELDS, \
"%r is not an allowed namespace alias" % (desired_alias,)
# Check that desired_alias does not contain a period as per
# the spec.
if type(desired_alias) in [str, unicode]:
assert '.' not in desired_alias, \
"%r must not contain a dot" % (desired_alias,)
# Check that there is not a namespace already defined for
# the desired alias
current_namespace_uri = self.alias_to_namespace.get(desired_alias)
if (current_namespace_uri is not None
and current_namespace_uri != namespace_uri):
fmt = ('Cannot map %r to alias %r. '
'%r is already mapped to alias %r')
msg = fmt % (
namespace_uri,
desired_alias,
current_namespace_uri,
desired_alias)
raise KeyError(msg)
# Check that there is not already a (different) alias for
# this namespace URI
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None and alias != desired_alias:
fmt = ('Cannot map %r to alias %r. '
'It is already mapped to alias %r')
raise KeyError(fmt % (namespace_uri, desired_alias, alias))
assert (desired_alias == NULL_NAMESPACE or
type(desired_alias) in [str, unicode]), repr(desired_alias)
assert namespace_uri not in self.implicit_namespaces
self.alias_to_namespace[desired_alias] = namespace_uri
self.namespace_to_alias[namespace_uri] = desired_alias
if implicit:
self.implicit_namespaces.append(namespace_uri)
return desired_alias
def add(self, namespace_uri):
"""Add this namespace URI to the mapping, without caring what
alias it ends up with"""
# See if this namespace is already mapped to an alias
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None:
return alias
# Fall back to generating a numerical alias
i = 0
while True:
alias = 'ext' + str(i)
try:
self.addAlias(namespace_uri, alias)
except KeyError:
i += 1
else:
return alias
assert False, "Not reached"
def isDefined(self, namespace_uri):
return namespace_uri in self.namespace_to_alias
def __contains__(self, namespace_uri):
return self.isDefined(namespace_uri)
def isImplicit(self, namespace_uri):
return namespace_uri in self.implicit_namespaces
| gquirozbogner/contentbox-master | third_party/openid/message.py | Python | apache-2.0 | 21,795 |
# Apipie DSL functions.
module Apipie
# DSL is a module that provides #api, #error, #param, #error.
module DSL
module Base
attr_reader :apipie_resource_descriptions, :api_params
private
def _apipie_dsl_data
@_apipie_dsl_data ||= _apipie_dsl_data_init
end
def _apipie_dsl_data_clear
@_apipie_dsl_data = nil
end
def _apipie_dsl_data_init
@_apipie_dsl_data = {
:api => false,
:api_args => [],
:api_from_routes => nil,
:errors => [],
:params => [],
:headers => [],
:resouce_id => nil,
:short_description => nil,
:description => nil,
:examples => [],
:see => [],
:formats => nil,
:api_versions => [],
:meta => nil,
:show => true
}
end
end
module Resource
# by default, the resource id is derived from controller_name
# it can be overwritten with.
#
# resource_id "my_own_resource_id"
def resource_id(resource_id)
Apipie.set_resource_id(@controller, resource_id)
end
def name(name)
_apipie_dsl_data[:resource_name] = name
end
def api_base_url(url)
_apipie_dsl_data[:api_base_url] = url
end
def short(short)
_apipie_dsl_data[:short_description] = short
end
alias :short_description :short
def path(path)
_apipie_dsl_data[:path] = path
end
def app_info(app_info)
_apipie_dsl_data[:app_info] = app_info
end
end
module Action
def def_param_group(name, &block)
Apipie.add_param_group(self, name, &block)
end
#
# # load paths from routes and don't provide description
# api
#
def api(method, path, desc = nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:api] = true
_apipie_dsl_data[:api_args] << [method, path, desc, options]
end
# # load paths from routes
# api! "short description",
#
def api!(desc = nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:api] = true
_apipie_dsl_data[:api_from_routes] = { :desc => desc, :options =>options }
end
# Reference other similar method
#
# api :PUT, '/articles/:id'
# see "articles#create"
# def update; end
def see(*args)
return unless Apipie.active_dsl?
_apipie_dsl_data[:see] << args
end
# Show some example of what does the described
# method return.
def example(example) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:examples] << example.strip_heredoc
end
# Determine if the method should be included
# in the documentation
def show(show)
return unless Apipie.active_dsl?
_apipie_dsl_data[:show] = show
end
# Describe whole resource
#
# Example:
# api :desc => "Show user profile", :path => "/users/", :version => '1.0 - 3.4.2012'
# param :id, Fixnum, :desc => "User ID", :required => true
# desc <<-EOS
# Long description...
# EOS
def resource_description(options = {}, &block) #:doc:
return unless Apipie.active_dsl?
raise ArgumentError, "Block expected" unless block_given?
dsl_data = ResourceDescriptionDsl.eval_dsl(self, &block)
versions = dsl_data[:api_versions]
@apipie_resource_descriptions = versions.map do |version|
Apipie.define_resource_description(self, version, dsl_data)
end
Apipie.set_controller_versions(self, versions)
end
end
module Common
def api_versions(*versions)
_apipie_dsl_data[:api_versions].concat(versions)
end
alias :api_version :api_versions
# Describe the next method.
#
# Example:
# desc "print hello world"
# def hello_world
# puts "hello world"
# end
#
def desc(description) #:doc:
return unless Apipie.active_dsl?
if _apipie_dsl_data[:description]
raise "Double method description."
end
_apipie_dsl_data[:description] = description
end
alias :description :desc
alias :full_description :desc
# describe next method with document in given path
# in convension, these doc located under "#{Rails.root}/doc"
# Example:
# document "hello_world.md"
# def hello_world
# puts "hello world"
# end
def document path
content = File.open(File.join(Rails.root, Apipie.configuration.doc_path, path)).read
desc content
end
# Describe available request/response formats
#
# formats ['json', 'jsonp', 'xml']
def formats(formats) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:formats] = formats
end
# Describe additional metadata
#
# meta :author => { :name => 'John', :surname => 'Doe' }
def meta(meta) #:doc:
_apipie_dsl_data[:meta] = meta
end
# Describe possible errors
#
# Example:
# error :desc => "speaker is sleeping", :code => 500, :meta => [:some, :more, :data]
# error 500, "speaker is sleeping"
# def hello_world
# return 500 if self.speaker.sleeping?
# puts "hello world"
# end
#
def error(code_or_options, desc=nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:errors] << [code_or_options, desc, options]
end
def _apipie_define_validators(description)
# [re]define method only if validation is turned on
if description && (Apipie.configuration.validate == true ||
Apipie.configuration.validate == :implicitly ||
Apipie.configuration.validate == :explicitly)
_apipie_save_method_params(description.method, description.params)
unless instance_methods.include?(:apipie_validations)
define_method(:apipie_validations) do
method_params = self.class._apipie_get_method_params(action_name)
if Apipie.configuration.validate_presence?
method_params.each do |_, param|
# check if required parameters are present
raise ParamMissing.new(param.name) if param.required && !params.has_key?(param.name)
end
end
if Apipie.configuration.validate_value?
method_params.each do |_, param|
# params validations
param.validate(params[:"#{param.name}"]) if params.has_key?(param.name)
end
end
# Only allow params passed in that are defined keys in the api
# Auto skip the default params (format, controller, action)
if Apipie.configuration.validate_key?
params.reject{|k,_| %w[format controller action].include?(k.to_s) }.each_key do |param|
# params allowed
raise UnknownParam.new(param) if method_params.select {|_,p| p.name.to_s == param.to_s}.empty?
end
end
if Apipie.configuration.process_value?
@api_params ||= {}
method_params.each do |_, param|
# params processing
@api_params[param.as] = param.process_value(params[:"#{param.name}"]) if params.has_key?(param.name)
end
end
end
end
if (Apipie.configuration.validate == :implicitly || Apipie.configuration.validate == true)
old_method = instance_method(description.method)
define_method(description.method) do |*args|
apipie_validations
# run the original method code
old_method.bind(self).call(*args)
end
end
end
end
def _apipie_save_method_params(method, params)
@method_params ||= {}
@method_params[method] = params
end
def _apipie_get_method_params(method)
@method_params[method]
end
# Describe request header.
# Headers can't be validated with config.validate_presence = true
#
# Example:
# header 'ClientId', "client-id"
# def show
# render :text => headers['HTTP_CLIENT_ID']
# end
#
def header(header_name, description, options = {}) #:doc
return unless Apipie.active_dsl?
_apipie_dsl_data[:headers] << {
name: header_name,
description: description,
options: options
}
end
end
# this describes the params, it's in separate module because it's
# used in Validators as well
module Param
# Describe method's parameter
#
# Example:
# param :greeting, String, :desc => "arbitrary text", :required => true
# def hello_world(greeting)
# puts greeting
# end
#
def param(param_name, validator, desc_or_options = nil, options = {}, &block) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:params] << [param_name,
validator,
desc_or_options,
options.merge(:param_group => @_current_param_group),
block]
end
# Reuses param group for this method. The definition is looked up
# in scope of this controller. If the group was defined in
# different controller, the second param can be used to specify it.
# when using action_aware parmas, you can specify :as =>
# :create or :update to explicitly say how it should behave
def param_group(name, scope_or_options = nil, options = {})
if scope_or_options.is_a? Hash
options.merge!(scope_or_options)
scope = options[:scope]
else
scope = scope_or_options
end
scope ||= _default_param_group_scope
@_current_param_group = {
:scope => scope,
:name => name,
:options => options,
:from_concern => scope.apipie_concern?
}
self.instance_exec(&Apipie.get_param_group(scope, name))
ensure
@_current_param_group = nil
end
# where the group definition should be looked up when no scope
# given. This is expected to return a controller.
def _default_param_group_scope
self
end
end
module Controller
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Action
include Apipie::DSL::Param
# defines the substitutions to be made in the API paths deifned
# in concerns included. For example:
#
# There is this method defined in concern:
#
# api GET ':controller_path/:id'
# def show
# # ...
# end
#
# If you include the concern into some controller, you can
# specify the value for :controller_path like this:
#
# apipie_concern_subst(:controller_path => '/users')
# include ::Concerns::SampleController
#
# The resulting path will be '/users/:id'.
#
# It has to be specified before the concern is included.
#
# If not specified, the default predefined substitions are
#
# {:conroller_path => controller.controller_path,
# :resource_id => `resource_id_from_apipie` }
def apipie_concern_subst(subst_hash)
_apipie_concern_subst.merge!(subst_hash)
end
def _apipie_concern_subst
@_apipie_concern_subst ||= {:controller_path => self.controller_path,
:resource_id => Apipie.get_resource_name(self)}
end
def _apipie_perform_concern_subst(string)
return _apipie_concern_subst.reduce(string) do |ret, (key, val)|
ret.gsub(":#{key}", val)
end
end
def apipie_concern?
false
end
# create method api and redefine newly added method
def method_added(method_name) #:doc:
super
return if !Apipie.active_dsl? || !_apipie_dsl_data[:api]
return if _apipie_dsl_data[:api_args].blank? && _apipie_dsl_data[:api_from_routes].blank?
# remove method description if exists and create new one
Apipie.remove_method_description(self, _apipie_dsl_data[:api_versions], method_name)
description = Apipie.define_method_description(self, method_name, _apipie_dsl_data)
_apipie_dsl_data_clear
_apipie_define_validators(description)
ensure
_apipie_dsl_data_clear
end
end
module Concern
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Action
include Apipie::DSL::Param
# the concern was included into a controller
def included(controller)
super
_apipie_concern_data.each do |method_name, _apipie_dsl_data|
# remove method description if exists and create new one
description = Apipie.define_method_description(controller, method_name, _apipie_dsl_data)
controller._apipie_define_validators(description)
end
end
def _apipie_concern_data
@_apipie_concern_data ||= []
end
def apipie_concern?
true
end
# create method api and redefine newly added method
def method_added(method_name) #:doc:
super
return if ! Apipie.active_dsl? || !_apipie_dsl_data[:api]
_apipie_concern_data << [method_name, _apipie_dsl_data.merge(:from_concern => true)]
ensure
_apipie_dsl_data_clear
end
end
class ResourceDescriptionDsl
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Resource
include Apipie::DSL::Param
def initialize(controller)
@controller = controller
end
def _eval_dsl(&block)
instance_eval(&block)
return _apipie_dsl_data
end
# evaluates resource description DSL and returns results
def self.eval_dsl(controller, &block)
dsl_data = self.new(controller)._eval_dsl(&block)
if dsl_data[:api_versions].empty?
dsl_data[:api_versions] = Apipie.controller_versions(controller)
end
dsl_data
end
end
end # module DSL
end # module Apipie
| vassilevsky/apipie-rails | lib/apipie/dsl_definition.rb | Ruby | apache-2.0 | 14,932 |
/*
* 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 stubgenerator.traitStaticPropertiesStub;
public class JavaXImpl extends GroovyXImpl {
public static void main(String[] args) {
new JavaXImpl();
}
}
| jwagenleitner/incubator-groovy | src/test-resources/stubgenerator/traitStaticPropertiesStub/JavaXImpl.java | Java | apache-2.0 | 995 |
isClear = true;
function context(description, spec) {
describe(description, spec);
};
function build() {
$('body').append('<div id="element"></div>');
};
function buildDivTarget() {
$('body').append('<div id="hint"></div>');
};
function buildComboboxTarget() {
$('body').append(
'<select id="hint">' +
'<option value="Cancel this rating!">cancel hint default</option>' +
'<option value="cancel-hint-custom">cancel hint custom</option>' +
'<option value="">cancel number default</option>' +
'<option value="0">cancel number custom</option>' +
'<option value="bad">bad hint imutable</option>' +
'<option value="1">bad number imutable</option>' +
'<option value="targetText">targetText is setted without targetKeep</option>' +
'<option value="score: bad">targetFormat</option>' +
'</select>'
);
};
function buildTextareaTarget() {
$('body').append('<textarea id="hint"></textarea>');
};
function buildTextTarget() {
$('body').append('<input id="hint" type="text" />');
};
function clear() {
if (isClear) {
$('#element').remove();
$('#hint').remove();
}
};
describe('Raty', function() {
beforeEach(function() { build(); });
afterEach(function() { clear(); });
it ('has the right values', function() {
// given
var raty = $.fn.raty
// when
var opt = raty.defaults
// then
expect(opt.cancel).toBeFalsy();
expect(opt.cancelHint).toEqual('Cancel this rating!');
expect(opt.cancelOff).toEqual('cancel-off.png');
expect(opt.cancelOn).toEqual('cancel-on.png');
expect(opt.cancelPlace).toEqual('left');
expect(opt.click).toBeUndefined();
expect(opt.half).toBeFalsy();
expect(opt.halfShow).toBeTruthy();
expect(opt.hints).toContain('bad', 'poor', 'regular', 'good', 'gorgeous');
expect(opt.iconRange).toBeUndefined();
expect(opt.mouseover).toBeUndefined();
expect(opt.noRatedMsg).toEqual('Not rated yet!');
expect(opt.number).toBe(5);
expect(opt.path).toEqual('');
expect(opt.precision).toBeFalsy();
expect(opt.readOnly).toBeFalsy();
expect(opt.round.down).toEqual(.25);
expect(opt.round.full).toEqual(.6);
expect(opt.round.up).toEqual(.76);
expect(opt.score).toBeUndefined();
expect(opt.scoreName).toEqual('score');
expect(opt.single).toBeFalsy();
expect(opt.size).toBe(16);
expect(opt.space).toBeTruthy();
expect(opt.starHalf).toEqual('star-half.png');
expect(opt.starOff).toEqual('star-off.png');
expect(opt.starOn).toEqual('star-on.png');
expect(opt.target).toBeUndefined();
expect(opt.targetFormat).toEqual('{score}');
expect(opt.targetKeep).toBeFalsy();
expect(opt.targetText).toEqual('');
expect(opt.targetType).toEqual('hint');
expect(opt.width).toBeUndefined();
});
describe('common features', function() {
it ('is chainable', function() {
// given
var self = $('#element');
// when
var ref = self.raty();
// then
expect(ref).toBe(self);
});
it ('creates the default markup', function() {
// given
var self = $('#element');
// when
self.raty();
// then
var imgs = self.children('img'),
score = self.children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
});
});
describe('#star', function() {
it ('starts all off', function() {
// given
var self = $('#element');
// when
self.raty();
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
context('on :mouseover', function() {
it ('turns on the stars', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
});
context('and :mouseout', function() {
it ('clears all stars', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
context('on rating', function() {
it ('changes the score', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(1).mouseover().click();
// then
expect(self.children('input')).toHaveValue(2);
});
context('on :mouseout', function() {
it ('keeps the stars on', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover().click().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
});
});
});
});
describe('options', function() {
describe('#numberMax', function() {
it ('limits to 20 stars', function() {
// given
var self = $('#element').raty({ number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(self.children('img').length).toEqual(20);
expect(self.children('input')).toHaveValue(20);
});
context('with custom numberMax', function() {
it ('chages the limit', function() {
// given
var self = $('#element').raty({ numberMax: 10, number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(self.children('img').length).toEqual(10);
expect(self.children('input')).toHaveValue(10);
});
});
});
describe('#starOff', function() {
it ('changes the icons', function() {
// given
var self = $('#element');
// when
self.raty({ starOff: 'icon.png' });
// then
expect(self.children('img')).toHaveAttr('src', 'icon.png');
});
});
describe('#starOn', function() {
it ('changes the icons', function() {
// given
var self = $('#element').raty({ starOn: 'icon.png' }),
imgs = self.children('img');
// when
imgs.eq(3).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(1)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(2)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(3)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
});
describe('#iconRange', function() {
it ('uses icon intervals', function() {
// given
var self = $('#element');
// when
self.raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
context('when off icon is not especified', function() {
it ('uses the :starOff icon', function() {
// given
var self = $('#element');
// when
self.raty({
iconRange: [
{ range: 2, on: 'on.png', off: 'off.png' },
{ range: 3, on: 'on.png', off: 'off.png' },
{ range: 4, on: 'on.png', off: 'off.png' },
{ range: 5, on: 'on.png' }
]
});
// then
expect(self.children('img').eq(4)).toHaveAttr('src', 'star-off.png');
});
});
context('on mouseover', function() {
it ('uses the on icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd.png');
});
context('when on icon is not especified', function() {
it ('uses the :starOn icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, off: 'off.png', on: 'on.png' },
{ range: 3, off: 'off.png', on: 'on.png' },
{ range: 4, off: 'off.png', on: 'on.png' },
{ range: 5, off: 'off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'on.png');
expect(imgs.eq(2)).toHaveAttr('src', 'on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'on.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-on.png');
});
});
});
context('on mouseout', function() {
it ('changes to off icons', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' },
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
self.mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
it ('keeps the score value', function() {
// given
var self = $('#element').raty({
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
],
score : 1
});
// when
self.children('img').eq(4).mouseover();
self.mouseleave();
// then
expect(self.children('input')).toHaveValue(1);
});
context('when off icon is not especified', function() {
it ('uses the :starOff icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'on.png', off: 'off.png' },
{ range: 3, on: 'on.png', off: 'off.png' },
{ range: 4, on: 'on.png', off: 'off.png' },
{ range: 5, on: 'on.png' }
]
}),
img = self.children('img').eq(4);
// when
img.mouseover();
self.mouseleave();
// then
expect(img).toHaveAttr('src', 'star-off.png');
});
});
});
});
describe('#click', function() {
it ('has `this` as the self element', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('self', this);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('self')).toBe(self);
});
it ('is called on star click', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('clicked', true);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('clicked')).toBeTruthy();
});
it ('receives the score', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('score')).toEqual(1);
});
context('with :cancel', function() {
it ('executes cancel click callback', function() {
// given
var self = $('#element').raty({
cancel: true,
click : function(score) {
$(this).data('score', null);
}
});
// when
self.children('.raty-cancel').mouseover().click().mouseleave();
// then
expect(self.data('score')).toBeNull();
});
});
});
describe('#score', function() {
it ('starts with value', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
expect(self.children('input')).toHaveValue(1);
});
it ('turns on 1 stars', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ score: function() { return 1; } });
// then
expect(self.raty('score')).toEqual(1);
});
context('with negative number', function() {
it ('gets none score', function() {
// given
var self = $('#element');
// when
self.raty({ score: -1 });
// then
expect(self.children('input').val()).toEqual('');
});
});
context('with :readOnly', function() {
it ('becomes readOnly too', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self.children('input')).toHaveAttr('readonly', 'readonly');
});
});
});
describe('#scoreName', function() {
it ('changes the score field name', function() {
// given
var self = $('#element');
// when
self.raty({ scoreName: 'entity.score' });
// then
expect(self.children('input')).toHaveAttr('name', 'entity.score');
});
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ scoreName: function() { return 'custom'; } });
// then
expect(self.data('settings').scoreName).toEqual('custom');
});
describe('#readOnly', function() {
it ('Applies "Not rated yet!" on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self.children('img')).toHaveAttr('title', 'Not rated yet!');
});
it ('removes the pointer cursor', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self).not.toHaveCss({ cursor: 'pointer' });
expect(self).not.toHaveCss({ cursor: 'default' });
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: function() { return true; } });
// then
expect(self.data('settings').readOnly).toEqual(true);
});
it ('avoids trigger mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
imgs.eq(1).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('avoids trigger click', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
imgs.eq(1).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
it ('avoids trigger mouseleave', function() {
// given
var self = $('#element').raty({
readOnly: true,
mouseout: function() {
$(this).data('mouseleave', true);
}
}),
imgs = self.children('img');
imgs.eq(1).mouseover();
// when
self.mouseleave();
// then
expect(self.data('mouseleave')).toBeFalsy();
});
context('with :score', function() {
context('as integer', function() {
it ('applies the score title on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, score: 3 });
// then
expect(self.children('img')).toHaveAttr('title', 'regular');
});
});
context('as float', function() {
it ('applies the integer score title on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, score: 3.1 });
// then
expect(self.children('img')).toHaveAttr('title', 'regular');
});
});
});
context('with :cancel', function() {
it ('hides the button', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, readOnly: true, path: '../lib/img' });
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
});
describe('#hints', function() {
it ('changes the hints', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['1', '/', 'c', '-', '#'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', '/');
expect(imgs.eq(2)).toHaveAttr('title', 'c');
expect(imgs.eq(3)).toHaveAttr('title', '-');
expect(imgs.eq(4)).toHaveAttr('title', '#');
});
it ('receives the number of the star when is undefined', function() {
// given
var self = $('#element');
// when
self.raty({ hints: [undefined, 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
it ('receives empty when is empty string', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['', 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', '');
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
it ('receives the number of the star when is null', function() {
// given
var self = $('#element');
// when
self.raty({ hints: [null, 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
context('whe has less hint than stars', function() {
it ('receives the default hint index', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['1', '2', '3', '4'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', 2);
expect(imgs.eq(2)).toHaveAttr('title', 3);
expect(imgs.eq(3)).toHaveAttr('title', 4);
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
});
context('whe has more stars than hints', function() {
it ('sets star number', function() {
// given
var self = $('#element');
// when
self.raty({ number: 6, hints: ['a', 'b', 'c', 'd', 'e'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 'a');
expect(imgs.eq(1)).toHaveAttr('title', 'b');
expect(imgs.eq(2)).toHaveAttr('title', 'c');
expect(imgs.eq(3)).toHaveAttr('title', 'd');
expect(imgs.eq(4)).toHaveAttr('title', 'e');
expect(imgs.eq(5)).toHaveAttr('title', 6);
});
});
});
describe('#mouseover', function() {
it ('receives the score as int', function() {
// given
var self = $('#element').raty({
mouseover: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover();
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
mouseover: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('img:first').mouseover();
// then
expect(self.data('evt').type).toEqual('mouseover');
});
context('with :cancel', function() {
it ('receives null as score', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseover : function(score) {
self.data('null', score);
}
});
// when
self.children('.raty-cancel').mouseover();
// then
expect(self.data('null')).toBeNull();
});
});
});
describe('#mouseout', function() {
it ('receives the score as int', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover().click().mouseout();
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
mouseout: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('img:first').mouseover().click().mouseout();
// then
expect(self.data('evt').type).toEqual('mouseout');
});
context('without score setted', function() {
it ('pass undefined on callback', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseout: function(score) {
self.data('undefined', score === undefined);
}
});
// when
self.children('img:first').mouseenter().mouseleave();
// then
expect(self.data('undefined')).toBeTruthy();
});
});
context('with :score rated', function() {
it ('pass the score on callback', function() {
// given
var self = $('#element').raty({
score : 1,
mouseout: function(score) {
self.data('score', score);
}
});
// when
self.children('img:first').mouseenter().mouseleave();
// then
expect(self.data('score')).toEqual(1);
});
});
context('with :cancel', function() {
it ('receives the event', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseout: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('.raty-cancel').mouseover().click().mouseout();
// then
expect(self.data('evt').type).toEqual('mouseout');
});
context('without score setted', function() {
it ('pass undefined on callback', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
self.data('undefined', score === undefined);
},
cancel : true
});
// when
self.children('.raty-cancel').mouseenter().mouseleave();
// then
expect(self.data('undefined')).toBeTruthy();
});
});
context('with :score rated', function() {
it ('pass the score on callback', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
self.data('score', score);
},
cancel : true,
score : 1
});
// when
self.children('.raty-cancel').mouseenter().mouseleave();
// then
expect(self.data('score')).toEqual(1);
});
});
});
});
describe('#number', function() {
it ('changes the number of stars', function() {
// given
var self = $('#element');
// when
self.raty({ number: 1 });
// then
expect(self.children('img').length).toEqual(1);
});
it ('accepts number as string', function() {
// given
var self = $('#element');
// when
self.raty({ number: '10' });
// then
expect(self.children('img').length).toEqual(10);
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ number: function() { return 1; } });
// then
expect(self.children('img').length).toEqual(1);
});
});
describe('#path', function() {
context('without last slash', function() {
it ('receives the slash', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path' });
// then
expect(self[0].opt.path).toEqual('path/');
});
});
context('with last slash', function() {
it ('keeps it', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path/' });
// then
expect(self[0].opt.path).toEqual('path/');
});
});
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path' });
// then
expect(self.children('img')).toHaveAttr('src', 'path/star-off.png');
});
context('without path', function() {
it ('sets receives empty', function() {
// given
var self = $('#element');
// when
self.raty({ path: null });
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
context('with :cancel', function() {
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, path: 'path' })
// then
expect(self.children('.raty-cancel')).toHaveAttr('src', 'path/cancel-off.png');
});
});
context('with :iconRange', function() {
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({
path : 'path',
iconRange: [{ range: 5 }]
});
// then
expect(self.children('img')).toHaveAttr('src', 'path/star-off.png');
});
});
});
describe('#cancelOff', function() {
it ('changes the icon', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelOff: 'off.png' });
// then
expect(self.children('.raty-cancel')).toHaveAttr('src', 'off.png');
});
});
describe('#cancelOn', function() {
it ('changes the icon', function() {
// given
var self = $('#element').raty({ cancel: true, cancelOn: 'icon.png' });
// when
var cancel = self.children('.raty-cancel').mouseover();
// then
expect(cancel).toHaveAttr('src', 'icon.png');
});
});
describe('#cancelHint', function() {
it ('changes the cancel hint', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelHint: 'hint' });
// then
expect(self.children('.raty-cancel')).toHaveAttr('title', 'hint');
});
});
describe('#cancelPlace', function() {
it ('changes the place off cancel button', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelPlace: 'right' });
// then
var cancel = self.children('img:last');
expect(cancel).toHaveClass('raty-cancel');
expect(cancel).toHaveAttr('title', 'Cancel this rating!');
expect(cancel).toHaveAttr('alt', 'x');
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
});
describe('#cancel', function() {
it ('creates the element', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true });
// then
var cancel = self.children('.raty-cancel');
expect(cancel).toHaveClass('raty-cancel');
expect(cancel).toHaveAttr('title', 'Cancel this rating!');
expect(cancel).toHaveAttr('alt', 'x');
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
context('on mouseover', function() {
it ('turns on', function() {
// given
var self = $('#element').raty({ cancel: true });
// when
var cancel = self.children('.raty-cancel').mouseover();
// then
expect(cancel).toHaveAttr('src', 'cancel-on.png');
});
context('with :score', function() {
it ('turns off the stars', function() {
// given
var self = $('#element').raty({ score: 3, cancel: true }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.children('.raty-cancel').mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
context('when :mouseout', function() {
it ('turns on', function() {
// given
var self = $('#element').raty({ cancel: true });
// when
var cancel = self.children('.raty-cancel').mouseover().mouseout();
// then
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
context('with :score', function() {
it ('turns the star on again', function() {
// given
var self = $('#element').raty({ score: 4, cancel: true }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.children('.raty-cancel').mouseover().mouseout();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
});
});
context('on click', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({ cancel: true, score: 1 });
// when
self.children('.raty-cancel').click().mouseout();
// then
var stars = self.children('img:not(.raty-cancel)');
expect(stars).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
});
context('when starts :readOnly', function() {
it ('starts hidden', function() {
// given
var self = $('#element').raty({ cancel: true, readOnly: true, path: '../img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
context('on click', function() {
it ('does not cancel the rating', function() {
// given
var self = $('#element').raty({ cancel: true, readOnly: true, score: 5 });
// when
self.children('.raty-cancel').click().mouseout();
// then
var stars = self.children('img:not(.raty-cancel)');
expect(stars).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('5');
});
});
});
context('when become :readOnly', function() {
it ('becomes hidden', function() {
// given
var self = $('#element').raty({ cancel: true, path: '../img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
});
describe('#targetType', function() {
beforeEach(function() { buildDivTarget(); });
context('with missing target', function() {
it ('throws error', function() {
// given
var self = $('#element');
// when
var lambda = function() { self.raty({ target: 'missing' }); };
// then
expect(lambda).toThrow(new Error('Target selector invalid or missing!'));
});
});
context('as hint', function() {
it ('receives the hint', function() {
// given
var self = $('#element').raty({ target: '#hint', targetType: 'hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('bad');
});
context('with :cancel', function() {
it ('receives the :cancelHint', function() {
// given
var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'hint' });
// when
self.children('.raty-cancel').mouseover();
// then
expect($('#hint')).toHaveHtml('Cancel this rating!');
});
});
});
context('as score', function() {
it ('receives the score', function() {
// given
var self = $('#element').raty({ target: '#hint', targetType: 'score' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml(1);
});
context('with :cancel', function() {
it ('receives the :cancelHint', function() {
// given
var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'score' });
// when
self.children('.raty-cancel').mouseover();
// then
expect($('#hint')).toHaveHtml('Cancel this rating!');
});
});
});
});
describe('#targetText', function() {
beforeEach(function() { buildDivTarget(); });
it ('set target with none value', function() {
// given
var self = $('#element');
// when
self.raty({ target: '#hint', targetText: 'none' });
// then
expect($('#hint')).toHaveHtml('none');
});
});
describe('#targetFormat', function() {
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
it ('stars empty', function() {
// given
var self = $('#element');
// when
self.raty({ target: '#hint', targetFormat: 'score: {score}' });
// then
expect($('#hint')).toBeEmpty();
});
context('with missing score key', function() {
it ('throws error', function() {
// given
var self = $('#element');
// when
var lambda = function() { self.raty({ target: '#hint', targetFormat: '' }); };
// then
expect(lambda).toThrow(new Error('Template "{score}" missing!'));
});
});
context('on mouseover', function() {
it ('set target with format on mouseover', function() {
// given
var self = $('#element').raty({ target: '#hint', targetFormat: 'score: {score}' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('score: bad');
});
});
context('on mouseout', function() {
it ('clears the target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetFormat: 'score: {score}'
});
// when
self.children('img:first').mouseover().mouseout();
// then
expect($('#hint')).toBeEmpty();
});
context('with :targetKeep', function() {
context('without score', function() {
it ('clears the target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetFormat: 'score: {score}',
targetKeep : true
});
// when
self.children('img:first').mouseover().mouseleave();
// then
expect($('#hint')).toBeEmpty();
});
});
context('with score', function() {
it ('keeps the template', function() {
// given
var self = $('#element').raty({
score : 1,
target : '#hint',
targetFormat: 'score: {score}',
targetKeep : true
});
// when
self.children('img:first').mouseover().mouseleave();
// then
expect($('#hint')).toHaveHtml('score: bad');
});
});
});
});
});
});
describe('#precision', function() {
beforeEach(function() { buildDivTarget(); });
it ('enables the :half options', function() {
// given
var self = $('#element');
// when
self.raty({ precision: true });
// then
expect(self.data('settings').half).toBeTruthy();
});
it ('changes the :targetType to score', function() {
// given
var self = $('#element');
// when
self.raty({ precision: true });
// then
expect(self.data('settings').targetType).toEqual('score');
});
context('with :target', function() {
context('with :targetKeep', function() {
context('with :score', function() {
it ('sets the float with one fractional number', function() {
// given
var self = $('#element');
// when
self.raty({
precision : true,
score : 1.23,
target : '#hint',
targetKeep: true,
targetType: 'score'
});
// then
expect($('#hint')).toHaveHtml('1.2');
});
});
});
});
});
describe('#target', function() {
context('on mouseover', function() {
context('as div', function() {
beforeEach(function() { buildDivTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('bad');
});
});
context('as text field', function() {
beforeEach(function() { buildTextTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
context('as textarea', function() {
beforeEach(function() { buildTextareaTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
context('as combobox', function() {
beforeEach(function() { buildComboboxTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
});
context('on mouseout', function() {
context('as div', function() {
beforeEach(function() { buildDivTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover().click().mouseleave();
// then
expect($('#hint')).toBeEmpty();
});
});
context('as textarea', function() {
beforeEach(function() { buildTextareaTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
context('as text field', function() {
beforeEach(function() { buildTextTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
context('as combobox', function() {
beforeEach(function() { buildComboboxTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
});
});
describe('#size', function() {
it ('calculate the right icon size', function() {
// given
var self = $('#element'),
size = 24,
stars = 5,
space = 4;
// when
self.raty({ size: size });
// then
expect(self.width()).toEqual((stars * size) + (stars * space));
});
context('with :cancel', function() {
it ('addes the cancel and space witdh', function() {
// given
var self = $('#element'),
size = 24,
stars = 5,
cancel = size,
space = 4;
// when
self.raty({ cancel: true, size: size });
// then
expect(self.width()).toEqual(cancel + space + (stars * size) + (stars * space));
});
});
});
describe('#space', function() {
context('when off', function() {
it ('takes off the space', function() {
// given
var self = $('#element');
size = 16,
stars = 5;
// when
self.raty({ space: false });
// then
expect(self.width()).toEqual(size * stars);
});
context('with :cancel', function() {
it ('takes off the space', function() {
// given
var self = $('#element');
size = 16,
stars = 5,
cancel = size;
// when
self.raty({ cancel: true, space: false });
// then
expect(self.width()).toEqual(cancel + (size * stars));
});
});
});
});
describe('#single', function() {
context('on mouseover', function() {
it ('turns on just one icon', function() {
// given
var self = $('#element').raty({ single: true }),
imgs = self.children('img');
// when
imgs.eq(2).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
context('with :iconRange', function() {
it ('shows just on icon', function() {
// given
var self = $('#element').raty({
single : true,
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(3).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
});
});
context('on click', function() {
context('on mouseout', function() {
it ('keeps the score', function() {
// given
var self = $('#element').raty({ single: true })
imgs = self.children('img');
// when
imgs.eq(2).mouseover().click().mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
context('and :iconRange', function() {
it ('keeps the score', function() {
// given
var self = $('#element').raty({
single : true,
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(3).mouseover().click().mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
});
});
});
});
describe('#width', function() {
it ('set custom width', function() {
// given
var self = $('#element');
// when
self.raty({ width: 200 });
// then
expect(self.width()).toEqual(200);
});
describe('when it is false', function() {
it ('does not apply the style', function() {
// given
var self = $('#element');
// when
self.raty({ width: false });
// then
expect(self).not.toHaveCss({ width: '100px' });
});
});
describe('when :readOnly', function() {
it ('set custom width when readOnly', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, width: 200 });
// then
expect(self.width()).toEqual(200);
});
});
});
describe('#half', function() {
context('as false', function() {
context('#halfShow', function() {
context('as false', function() {
it ('rounds down while less the full limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : false,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .5 // score.5 < full.6 === 0
});
var imgs = self.children('img');
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
});
it ('rounds full when equal the full limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : false,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 == full.6 === 1
});
var imgs = self.children('img');
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
});
});
context('as true', function() {
context('#halfShow', function() {
context('as false', function() {
it ('ignores round down while less down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .24 // score.24 < down.25 === 0
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('0.24');
});
it ('ignores half while greater then down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .26 // score.26 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('0.26');
});
it ('ignores half while equal full limit, ignoring it', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('0.6');
});
it ('ignores half while greater than down limit and less than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .75 // score.75 > down.25 and score.75 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('0.75');
});
it ('ignores full while equal or greater than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .76 // score.76 == up.76 === 1
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
context('as true', function() {
it ('rounds down while less down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .24 // score.24 < down.25 === 0
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
});
it ('receives half while greater then down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .26 // score.26 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives half while equal full limit, ignoring it', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives half while greater than down limit and less than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .75 // score.75 > down.25 and score.75 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives full while equal or greater than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .76 // score.76 == up.76 === 1
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :precision', function() {
context('and :targetType as score', function() {
context('and :targetKeep', function() {
context('and :targetType as score', function() {
it ('set .5 increment value target with half option and no precision', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
precision : false,
score : 1.5,
target : '#hint',
targetKeep: true,
targetType: 'score'
});
// then
expect($('#hint')).toHaveHtml('1.5');
});
});
});
});
});
});
});
});
});
describe('class bind', function() {
beforeEach(function() {
$('body').append('<div class="element"></div><div class="element"></div>');
});
afterEach(function() {
$('.element').remove();
});
it ('is chainable', function() {
// given
var self = $('.element');
// when
var refs = self.raty();
// then
expect(refs.eq(0)).toBe(self.eq(0));
expect(refs.eq(1)).toBe(self.eq(1));
});
it ('creates the default markup', function() {
// given
var self = $('.element');
// when
self.raty();
// then
var imgs = self.eq(0).children('img'),
score = self.eq(0).children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
imgs = self.eq(1).children('img');
score = self.eq(0).children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
});
});
describe('functions', function() {
describe('GET #score', function() {
it ('accepts number as string', function() {
// given
var self = $('#element');
// when
self.raty({ score: '1' });
// then
expect(self.children('input')).toHaveValue(1);
});
it ('accepts float string', function() {
// given
var self = $('#element');
// when
self.raty({ score: '1.5' });
// then
expect(self.children('input')).toHaveValue(1.5);
});
context('with integer score', function() {
it ('gets as int', function() {
// given
var self = $('#element').raty({ score: 1 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(1);
});
});
context('with float score', function() {
it ('gets as float', function() {
// given
var self = $('#element').raty({ score: 1.5 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(1.5);
});
});
context('with score zero', function() {
it ('gets null to emulate cancel', function() {
// given
var self = $('#element').raty({ score: 0 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(null);
});
});
context('with score greater than :numberMax', function() {
it ('gets the max', function() {
// given
var self = $('#element').raty({ number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(self.data('settings').numberMax);
});
});
});
describe('SET #score', function() {
it ('sets the score', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
expect(self.raty('score')).toEqual(1);
});
describe('with :click', function() {
it ('calls the click callback', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.raty('score', 5);
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
});
});
describe('without :click', function() {
it ('does not throw exception', function() {
// given
var self = $('#element').raty();
// when
var lambda = function() { self.raty('score', 1); };
// then
expect(lambda).not.toThrow(new Error('You must add the "click: function(score, evt) { }" callback.'));
});
});
describe('with :readOnly', function() {
it ('does not set the score', function() {
// given
var self = $('#element').raty({ readOnly: true });
// when
self.raty('score', 5);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
});
describe('#set', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('set', { number: 1 });
// then
expect(ref).toBe(self);
});
it ('changes the declared options', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('set', { scoreName: 'change-just-it' });
// then
expect(ref.children('input')).toHaveAttr('name', 'change-just-it');
});
it ('does not change other none declared options', function() {
// given
var self = $('#element').raty({ number: 6 });
// when
var ref = self.raty('set', { scoreName: 'change-just-it' });
// then
expect(ref.children('img').length).toEqual(6);
});
context('with external bind on wrapper', function() {
it ('keeps it', function() {
// given
var self = $('#element').on('click', function() {
$(this).data('externalClick', true);
}).raty();
// when
self.raty('set', {}).click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
context('when :readOnly by function', function() {
it ('is removes the readonly data info', function() {
// given
var self = $('#element').raty().raty('readOnly', true);
// when
var ref = self.raty('set', { readOnly: false });
// then
expect(self).not.toHaveData('readonly');
});
});
});
describe('#readOnly', function() {
context('changes to true', function() {
it ('sets score as readonly', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self.children('input')).toHaveAttr('readonly', 'readonly');
});
it ('removes the pointer cursor', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self).not.toHaveCss({ cursor: 'pointer' });
expect(self).not.toHaveCss({ cursor: 'default' });
});
it ('Applies "Not rated yet!" on stars', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self.children('img')).toHaveAttr('title', 'Not rated yet!');
});
it ('avoids trigger mouseover', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
self.raty('readOnly', true);
// when
imgs.eq(0).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('avoids trigger click', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
self.raty('readOnly', true);
// when
imgs.eq(0).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
context('with :score', function() {
it ('applies the score title on stars', function() {
// given
var self = $('#element').raty({ score: 1 });
// when
self.raty('readOnly', true);
// then
expect(self.children('img')).toHaveAttr('title', 'bad');
});
});
context('with :cancel', function() {
it ('hides the button', function() {
// given
var self = $('#element').raty({ cancel: true, path: '../lib/img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
context('with external bind on wrapper', function() {
it ('keeps it', function() {
// given
var self = $('#element').on('click', function() {
$(this).data('externalClick', true);
}).raty();
// when
self.raty('readOnly', true).click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
context('with external bind on stars', function() {
it ('keeps it', function() {
// given
var self = $('#element').raty(),
star = self.children('img').first();
star.on('click', function() {
self.data('externalClick', true);
});
// when
self.raty('readOnly', true);
star.click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
});
context('changes to false', function() {
it ('removes the :readOnly of the score', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', false);
// then
expect(self.children('input')).not.toHaveAttr('readonly', 'readonly');
});
it ('applies the pointer cursor on wrapper', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', false);
// then
expect(self).toHaveCss({ cursor: 'pointer' });
});
it ('Removes the "Not rated yet!" off the stars', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
self.raty('readOnly', false);
// then
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
it ('triggers mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
self.raty('readOnly', false);
// when
imgs.eq(0).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
it ('triggers click', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
self.raty('readOnly', false);
// when
imgs.eq(0).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
expect(self.children('input')).toHaveValue('1');
});
context('with :score', function() {
it ('removes the score title off the stars', function() {
// given
var self = $('#element').raty({ readOnly: true, score: 3 });
// when
self.raty('readOnly', false);
// then
var imgs = self.children('img')
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
});
context('with :cancel', function() {
it ('shows the button', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true, path: '../lib/img' });
// when
self.raty('readOnly', false);
// then
expect(self.children('.raty-cancel')).toBeVisible();
expect(self.children('.raty-cancel')).not.toHaveCss({ display: 'block' });
});
it ('rebinds the mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true }),
cancel = self.children('.raty-cancel'),
imgs = self.children('img:not(.raty-cancel)');
// when
self.raty('readOnly', false);
cancel.mouseover();
// then
expect(cancel).toHaveAttr('src', 'cancel-on.png');
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('rebinds the click', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true, score: 5 }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.raty('readOnly', false);
self.children('.raty-cancel').click().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
});
describe('#cancel', function() {
describe('with :readOnly', function() {
it ('does not cancel', function() {
// given
var self = $('#element').raty({ readOnly: true, score: 5 });
// when
self.raty('cancel');
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
});
});
context('without click trigger', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({
score: 1,
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('cancel');
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
expect(self.data('clicked')).toBeFalsy();
});
});
context('with click trigger', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({
score: 1,
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('cancel', true);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
expect(self.data('clicked')).toBeTruthy();
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :targetKeep', function() {
it ('sets the :targetText on target', function() {
// given
var hint = $('#hint').html('dirty'),
self = $('#element').raty({
cancel : true,
target : '#hint',
targetKeep: true,
targetText: 'targetText'
});
// when
self.raty('cancel');
// then
expect(hint).toHaveHtml('targetText');
});
});
});
});
describe('#click', function() {
it ('clicks on star', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('click', 1);
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
expect(self.data('clicked')).toBeTruthy();
});
it ('receives the score', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.raty('click', 1);
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
click: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.raty('click', 1);
// then
expect(self.data('evt').type).toEqual('click');
});
describe('with :readOnly', function() {
it ('does not set the score', function() {
// given
var self = $('#element').raty({ readOnly: true });
// when
self.raty('click', 1);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
context('without :click', function() {
it ('throws error', function() {
// given
var self = $('#element').raty();
// when
var lambda = function() { self.raty('click', 1); };
// then
expect(lambda).toThrow(new Error('You must add the "click: function(score, evt) { }" callback.'));
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :targetKeep', function() {
it ('sets the score on target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetKeep: true,
click : function() { }
});
// when
self.raty('click', 1);
// then
expect($('#hint')).toHaveHtml('bad');
});
});
});
});
describe('#reload', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('reload');
// then
expect(ref).toBe(self);
});
it ('reloads with the same configuration', function() {
// given
var self = $('#element').raty({ number: 6 });
// when
var ref = self.raty('reload');
// then
expect(ref.children('img').length).toEqual(6);
});
context('when :readOnly by function', function() {
it ('is removes the readonly data info', function() {
// given
var self = $('#element').raty().raty('readOnly', true);
// when
var ref = self.raty('reload');
// then
expect(self).not.toHaveData('readonly');
});
});
});
describe('#destroy', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('destroy');
// then
expect(ref).toBe(self);
});
it ('clear the content', function() {
// given
var self = $('#element').raty();
// when
self.raty('destroy');
// then
expect(self).toBeEmpty();
});
it ('removes the trigger mouseleave', function() {
// given
var self = $('#element').raty({
mouseout: function() {
console.log(this);
$(this).data('mouseleave', true);
}
});
self.raty('destroy');
// when
self.mouseleave();
// then
expect(self.data('mouseleave')).toBeFalsy();
});
it ('resets the style attributes', function() {
// given
var self = $('#element').css({ cursor: 'help', width: 10 }).raty();
// when
self.raty('destroy');
// then
expect(self[0].style.cursor).toEqual('help');
expect(self[0].style.width).toEqual('10px');
});
});
});
});
| cognitoedtech/assy | subdomain/offline/3rd_party/raty/spec/spec.js | JavaScript | apache-2.0 | 81,498 |
package org.apache.maven.artifact.manager;
/*
* 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.
*/
import java.util.List;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.proxy.ProxyInfo;
/**
* Manages <a href="https://maven.apache.org/wagon">Wagon</a> related operations in Maven.
*
* @author <a href="michal.maczka@dimatics.com">Michal Maczka </a>
*/
@Deprecated
public interface WagonManager
extends org.apache.maven.repository.legacy.WagonManager
{
/**
* this method is only here for backward compat (project-info-reports:dependencies)
* the default implementation will return an empty AuthenticationInfo
*/
AuthenticationInfo getAuthenticationInfo( String id );
ProxyInfo getProxy( String protocol );
void getArtifact( Artifact artifact, ArtifactRepository repository )
throws TransferFailedException, ResourceDoesNotExistException;
void getArtifact( Artifact artifact, List<ArtifactRepository> remoteRepositories )
throws TransferFailedException, ResourceDoesNotExistException;
ArtifactRepository getMirrorRepository( ArtifactRepository repository );
}
| lbndev/maven | maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java | Java | apache-2.0 | 2,151 |
<?php
/*
* $Id: SizeSelector.php 526 2009-08-11 12:11:17Z mrook $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
/**
* Selector that filters files based on their size.
*
* @author Hans Lellelid <hans@xmpl.org> (Phing)
* @author Bruce Atherton <bruce@callenish.com> (Ant)
* @package phing.types.selectors
*/
class SizeSelector extends BaseExtendSelector {
private $size = -1;
private $multiplier = 1;
private $sizelimit = -1;
private $cmp = 2;
const SIZE_KEY = "value";
const UNITS_KEY = "units";
const WHEN_KEY = "when";
private static $sizeComparisons = array("less", "more", "equal");
private static $byteUnits = array("K", "k", "kilo", "KILO",
"Ki", "KI", "ki", "kibi", "KIBI",
"M", "m", "mega", "MEGA",
"Mi", "MI", "mi", "mebi", "MEBI",
"G", "g", "giga", "GIGA",
"Gi", "GI", "gi", "gibi", "GIBI",
"T", "t", "tera", "TERA",
/* You wish! */ "Ti", "TI", "ti", "tebi", "TEBI"
);
public function toString() {
$buf = "{sizeselector value: ";
$buf .= $this->sizelimit;
$buf .= "compare: ";
if ($this->cmp === 0) {
$buf .= "less";
} elseif ($this->cmp === 1) {
$buf .= "more";
} else {
$buf .= "equal";
}
$buf .= "}";
return $buf;
}
/**
* A size selector needs to know what size to base its selecting on.
* This will be further modified by the multiplier to get an
* actual size limit.
*
* @param size the size to select against expressed in units
*/
public function setValue($size) {
$this->size = $size;
if (($this->multiplier !== 0) && ($this->size > -1)) {
$this->sizelimit = $size * $this->multiplier;
}
}
/**
* Sets the units to use for the comparison. This is a little
* complicated because common usage has created standards that
* play havoc with capitalization rules. Thus, some people will
* use "K" for indicating 1000's, when the SI standard calls for
* "k". Others have tried to introduce "K" as a multiple of 1024,
* but that falls down when you reach "M", since "m" is already
* defined as 0.001.
* <p>
* To get around this complexity, a number of standards bodies
* have proposed the 2^10 standard, and at least one has adopted
* it. But we are still left with a populace that isn't clear on
* how capitalization should work.
* <p>
* We therefore ignore capitalization as much as possible.
* Completely mixed case is not possible, but all upper and lower
* forms are accepted for all long and short forms. Since we have
* no need to work with the 0.001 case, this practice works here.
* <p>
* This function translates all the long and short forms that a
* unit prefix can occur in and translates them into a single
* multiplier.
*
* @param $units The units to compare the size to.
* @return void
*/
public function setUnits($units) {
$i = array_search($units, self::$byteUnits, true);
if ($i === false) $i = -1; // make it java-like
$this->multiplier = 0;
if (($i > -1) && ($i < 4)) {
$this->multiplier = 1000;
} elseif (($i > 3) && ($i < 9)) {
$this->multiplier = 1024;
} elseif (($i > 8) && ($i < 13)) {
$this->multiplier = 1000000;
} elseif (($i > 12) && ($i < 18)) {
$this->multiplier = 1048576;
} elseif (($i > 17) && ($i < 22)) {
$this->multiplier = 1000000000;
} elseif (($i > 21) && ($i < 27)) {
$this->multiplier = 1073741824;
} elseif (($i > 26) && ($i < 31)) {
$this->multiplier = 1000000000000;
} elseif (($i > 30) && ($i < 36)) {
$this->multiplier = 1099511627776;
}
if (($this->multiplier > 0) && ($this->size > -1)) {
$this->sizelimit = $this->size * $this->multiplier;
}
}
/**
* This specifies when the file should be selected, whether it be
* when the file matches a particular size, when it is smaller,
* or whether it is larger.
*
* @param cmp The comparison to perform, an EnumeratedAttribute
*/
public function setWhen($cmp) {
$c = array_search($cmp, self::$sizeComparisons, true);
if ($c !== false) {
$this->cmp = $c;
}
}
/**
* When using this as a custom selector, this method will be called.
* It translates each parameter into the appropriate setXXX() call.
*
* @param parameters the complete set of parameters for this selector
*/
public function setParameters($parameters) {
parent::setParameters($parameters);
if ($parameters !== null) {
for ($i = 0, $size=count($parameters); $i < $size; $i++) {
$paramname = $parameters[$i]->getName();
switch(strtolower($paramname)) {
case self::SIZE_KEY:
try {
$this->setValue($parameters[$i]->getValue());
} catch (Exception $nfe) {
$this->setError("Invalid size setting "
. $parameters[$i]->getValue());
}
break;
case self::UNITS_KEY:
$this->setUnits($parameters[$i]->getValue());
break;
case self::WHEN_KEY:
$this->setWhen($parameters[$i]->getValue());
break;
default:
$this->setError("Invalid parameter " . $paramname);
}
}
}
}
/**
* <p>Checks to make sure all settings are kosher. In this case, it
* means that the size attribute has been set (to a positive value),
* that the multiplier has a valid setting, and that the size limit
* is valid. Since the latter is a calculated value, this can only
* fail due to a programming error.
* </p>
* <p>If a problem is detected, the setError() method is called.
* </p>
*/
public function verifySettings() {
if ($this->size < 0) {
$this->setError("The value attribute is required, and must be positive");
} elseif ($this->multiplier < 1) {
$this->setError("Invalid Units supplied, must be K,Ki,M,Mi,G,Gi,T,or Ti");
} elseif ($this->sizelimit < 0) {
$this->setError("Internal error: Code is not setting sizelimit correctly");
}
}
/**
* The heart of the matter. This is where the selector gets to decide
* on the inclusion of a file in a particular fileset.
*
* @param basedir A PhingFile object for the base directory
* @param filename The name of the file to check
* @param file A PhingFile object for this filename
* @return whether the file should be selected or not
*/
public function isSelected(PhingFile $basedir, $filename, PhingFile $file) {
$this->validate();
// Directory size never selected for
if ($file->isDirectory()) {
return true;
}
if ($this->cmp === 0) {
return ($file->length() < $this->sizelimit);
} elseif ($this->cmp === 1) {
return ($file->length() > $this->sizelimit);
} else {
return ($file->length() === $this->sizelimit);
}
}
}
| ArcherCraftStore/ArcherVMPeridot | php/pear/phing/types/selectors/SizeSelector.php | PHP | apache-2.0 | 8,816 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Accurate Software Design, LLC.
* Portions created by the Initial Developer are Copyright (C) 2006-2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See listed authors below.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.archive.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4chee.archive.common.PPSStatus;
import org.dcm4chee.archive.conf.AttributeFilter;
import org.dcm4chee.archive.util.DicomObjectUtils;
/**
* @author Damien Evans <damien.daddy@gmail.com>
* @author Justin Falk <jfalkmu@gmail.com>
* @author Gunter Zeilinger <gunterze@gmail.com>
* @version $Revision$ $Date$
* @since Feb 29, 2008
*/
@Entity
@Table(name = "mpps")
public class MPPS extends BaseEntity implements Serializable {
private static final long serialVersionUID = -599495313070741738L;
@Column(name = "created_time")
private Date createdTime;
@Column(name = "updated_time")
private Date updatedTime;
@Column(name = "mpps_iuid", unique = true, nullable = false)
private String sopInstanceUID;
@Column(name = "pps_start")
private Date startDateTime;
@Column(name = "station_aet")
private String performedStationAET;
@Column(name = "modality")
private String modality;
@Column(name = "accession_no")
private String accessionNumber;
@Column(name = "mpps_status", nullable = false)
private PPSStatus status;
// JPA definition in orm.xml
private byte[] encodedAttributes;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "drcode_fk")
private Code discontinuationReasonCode;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "patient_fk")
private Patient patient;
@OneToMany(mappedBy = "modalityPerformedProcedureStep", fetch = FetchType.LAZY)
private Set<Series> series;
public Date getCreatedTime() {
return createdTime;
}
public Date getUpdatedTime() {
return updatedTime;
}
public String getSopInstanceUID() {
return sopInstanceUID;
}
public Date getStartDateTime() {
return startDateTime;
}
public String getPerformedStationAET() {
return performedStationAET;
}
public String getModality() {
return modality;
}
public String getAccessionNumber() {
return accessionNumber;
}
public PPSStatus getStatus() {
return status;
}
public byte[] getEncodedAttributes() {
return encodedAttributes;
}
public Code getDiscontinuationReasonCode() {
return discontinuationReasonCode;
}
public void setDiscontinuationReasonCode(Code discontinuationReasonCode) {
this.discontinuationReasonCode = discontinuationReasonCode;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Set<Series> getSeries() {
return series;
}
public void setSeries(Set<Series> series) {
this.series = series;
}
@Override
public String toString() {
return "MPPS[pk=" + pk
+ ", iuid=" + sopInstanceUID
+ ", status=" + status
+ ", accno=" + accessionNumber
+ ", start=" + startDateTime
+ ", mod=" + modality
+ ", aet=" + performedStationAET
+ "]";
}
public void onPrePersist() {
createdTime = new Date();
}
public void onPreUpdate() {
updatedTime = new Date();
}
public DicomObject getAttributes() {
return DicomObjectUtils.decode(encodedAttributes);
}
public void setAttributes(DicomObject attrs) {
this.sopInstanceUID = attrs.getString(Tag.SOPInstanceUID);
this.startDateTime = attrs.getDate(
Tag.PerformedProcedureStepStartDate,
Tag.PerformedProcedureStepStartTime);
this.performedStationAET = attrs.getString(Tag.PerformedStationAETitle);
this.modality = attrs.getString(Tag.Modality);
this.accessionNumber = attrs.getString(new int[] {
Tag.ScheduledStepAttributesSequence, 0, Tag.AccessionNumber });
if (this.accessionNumber == null)
this.accessionNumber = attrs.getString(Tag.AccessionNumber);
this.status = PPSStatus.valueOf(attrs.getString(
Tag.PerformedProcedureStepStatus).replace(' ', '_'));
this.encodedAttributes = DicomObjectUtils.encode(AttributeFilter.getExcludePatientAttributeFilter().filter(attrs),
UID.DeflatedExplicitVRLittleEndian);
}
}
| medicayun/medicayundicom | dcm4chee-arc3-entities/trunk/src/main/java/org/dcm4chee/archive/entity/MPPS.java | Java | apache-2.0 | 6,621 |
/*
* 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.
*/
/**
* Implementations of serializer and derserializer interfaces.
*/
package org.apache.reef.wake.avro.impl;
| markusweimer/incubator-reef | lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/avro/impl/package-info.java | Java | apache-2.0 | 920 |
/*
* 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.solr.update.processor;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.plugin.PluginInfoInitialized;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.SolrException;
import org.apache.solr.core.PluginInfo;
import org.apache.solr.core.SolrCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.ArrayList;
/**
* Manages a chain of UpdateRequestProcessorFactories.
* <p>
* Chains can be configured via solrconfig.xml using the following syntax...
* </p>
* <pre class="prettyprint">
* <updateRequestProcessorChain name="key" default="true">
* <processor class="package.Class1" />
* <processor class="package.Class2" >
* <str name="someInitParam1">value</str>
* <int name="someInitParam2">42</int>
* </processor>
* <processor class="solr.LogUpdateProcessorFactory" >
* <int name="maxNumToLog">100</int>
* </processor>
* <processor class="solr.RunUpdateProcessorFactory" />
* </updateRequestProcessorChain>
* </pre>
* <p>
* Multiple Chains can be defined, each with a distinct name. The name of
* a chain used to handle an update request may be specified using the request
* param <code>update.chain</code>. If no chain is explicitly selected
* by name, then Solr will attempt to determine a default chain:
* </p>
* <ul>
* <li>A single configured chain may explicitly be declared with
* <code>default="true"</code> (see example above)</li>
* <li>If no chain is explicitly declared as the default, Solr will look for
* any chain that does not have a name, and treat it as the default</li>
* <li>As a last resort, Solr will create an implicit default chain
* consisting of:<ul>
* <li>{@link LogUpdateProcessorFactory}</li>
* <li>{@link DistributedUpdateProcessorFactory}</li>
* <li>{@link RunUpdateProcessorFactory}</li>
* </ul></li>
* </ul>
*
* <p>
* Allmost all processor chains should end with an instance of
* <code>RunUpdateProcessorFactory</code> unless the user is explicitly
* executing the update commands in an alternative custom
* <code>UpdateRequestProcessorFactory</code>. If a chain includes
* <code>RunUpdateProcessorFactory</code> but does not include a
* <code>DistributingUpdateProcessorFactory</code>, it will be added
* automatically by {@link #init init()}.
* </p>
*
* @see UpdateRequestProcessorFactory
* @see #init
* @see #createProcessor
* @since solr 1.3
*/
public final class UpdateRequestProcessorChain implements PluginInfoInitialized
{
public final static Logger log = LoggerFactory.getLogger(UpdateRequestProcessorChain.class);
private UpdateRequestProcessorFactory[] chain;
private final SolrCore solrCore;
public UpdateRequestProcessorChain(SolrCore solrCore) {
this.solrCore = solrCore;
}
/**
* Initializes the chain using the factories specified by the <code>PluginInfo</code>.
* if the chain includes the <code>RunUpdateProcessorFactory</code>, but
* does not include an implementation of the
* <code>DistributingUpdateProcessorFactory</code> interface, then an
* instance of <code>DistributedUpdateProcessorFactory</code> will be
* injected immediately prior to the <code>RunUpdateProcessorFactory</code>.
*
* @see DistributingUpdateProcessorFactory
* @see RunUpdateProcessorFactory
* @see DistributedUpdateProcessorFactory
*/
@Override
public void init(PluginInfo info) {
final String infomsg = "updateRequestProcessorChain \"" +
(null != info.name ? info.name : "") + "\"" +
(info.isDefault() ? " (default)" : "");
log.info("creating " + infomsg);
// wrap in an ArrayList so we know we know we can do fast index lookups
// and that add(int,Object) is supported
List<UpdateRequestProcessorFactory> list = new ArrayList
(solrCore.initPlugins(info.getChildren("processor"),UpdateRequestProcessorFactory.class,null));
if(list.isEmpty()){
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
infomsg + " require at least one processor");
}
int numDistrib = 0;
int runIndex = -1;
// hi->lo incase multiple run instances, add before first one
// (no idea why someone might use multiple run instances, but just in case)
for (int i = list.size()-1; 0 <= i; i--) {
UpdateRequestProcessorFactory factory = list.get(i);
if (factory instanceof DistributingUpdateProcessorFactory) {
numDistrib++;
}
if (factory instanceof RunUpdateProcessorFactory) {
runIndex = i;
}
}
if (1 < numDistrib) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
infomsg + " may not contain more then one " +
"instance of DistributingUpdateProcessorFactory");
}
if (0 <= runIndex && 0 == numDistrib) {
// by default, add distrib processor immediately before run
DistributedUpdateProcessorFactory distrib
= new DistributedUpdateProcessorFactory();
distrib.init(new NamedList());
list.add(runIndex, distrib);
log.info("inserting DistributedUpdateProcessorFactory into " + infomsg);
}
chain = list.toArray(new UpdateRequestProcessorFactory[list.size()]);
}
/**
* Creates a chain backed directly by the specified array. Modifications to
* the array will affect future calls to <code>createProcessor</code>
*/
public UpdateRequestProcessorChain( UpdateRequestProcessorFactory[] chain,
SolrCore solrCore) {
this.chain = chain;
this.solrCore = solrCore;
}
/**
* Uses the factories in this chain to creates a new
* <code>UpdateRequestProcessor</code> instance specific for this request.
* If the <code>DISTRIB_UPDATE_PARAM</code> is present in the request and is
* non-blank, then any factory in this chain prior to the instance of
* <code>{@link DistributingUpdateProcessorFactory}</code> will be skipped,
* except for the log update processor factory.
*
* @see UpdateRequestProcessorFactory#getInstance
* @see DistributingUpdateProcessorFactory#DISTRIB_UPDATE_PARAM
*/
public UpdateRequestProcessor createProcessor(SolrQueryRequest req,
SolrQueryResponse rsp)
{
UpdateRequestProcessor processor = null;
UpdateRequestProcessor last = null;
final String distribPhase = req.getParams().get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM);
final boolean skipToDistrib = distribPhase != null;
boolean afterDistrib = true; // we iterate backwards, so true to start
for (int i = chain.length-1; i>=0; i--) {
UpdateRequestProcessorFactory factory = chain[i];
if (skipToDistrib) {
if (afterDistrib) {
if (factory instanceof DistributingUpdateProcessorFactory) {
afterDistrib = false;
}
} else if (!(factory instanceof UpdateRequestProcessorFactory.RunAlways)) {
// skip anything that doesn't have the marker interface
continue;
}
}
processor = factory.getInstance(req, rsp, last);
last = processor == null ? last : processor;
}
return last;
}
/**
* Returns the underlying array of factories used in this chain.
* Modifications to the array will affect future calls to
* <code>createProcessor</code>
*/
public UpdateRequestProcessorFactory[] getFactories() {
return chain;
}
}
| williamchengit/TestRepo | solr/core/src/java/org/apache/solr/update/processor/UpdateRequestProcessorChain.java | Java | apache-2.0 | 8,567 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.pim.cli;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.pim.impl.PimInterface;
import org.onosproject.pim.impl.PimInterfaceService;
import java.util.Set;
/**
* Lists the interfaces where PIM is enabled.
*/
@Command(scope = "onos", name = "pim-interfaces",
description = "Lists the interfaces where PIM is enabled")
public class PimInterfacesListCommand extends AbstractShellCommand {
private static final String FORMAT = "interfaceName=%s, holdTime=%s, priority=%s, genId=%s";
private static final String ROUTE_FORMAT = " %s";
@Override
protected void execute() {
PimInterfaceService interfaceService = get(PimInterfaceService.class);
Set<PimInterface> interfaces = interfaceService.getPimInterfaces();
interfaces.forEach(pimIntf -> {
print(FORMAT, pimIntf.getInterface().name(),
pimIntf.getHoldtime(), pimIntf.getPriority(),
pimIntf.getGenerationId());
pimIntf.getRoutes().forEach(route -> print(ROUTE_FORMAT, route));
});
}
}
| donNewtonAlpha/onos | apps/pim/src/main/java/org/onosproject/pim/cli/PimInterfacesListCommand.java | Java | apache-2.0 | 1,782 |
// Copyright 2014 The Oppia 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.
/**
* @fileoverview Unit tests for the editor prerequisites page.
*/
describe('Signup controller', function() {
describe('SignupCtrl', function() {
var scope, ctrl, $httpBackend, rootScope, mockAlertsService, urlParams;
beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS));
beforeEach(inject(function(_$httpBackend_, $http, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/signuphandler/data').respond({
username: 'myUsername',
has_agreed_to_latest_terms: false
});
rootScope = $rootScope;
mockAlertsService = {
addWarning: function() {}
};
spyOn(mockAlertsService, 'addWarning');
scope = {
getUrlParams: function() {
return {
return_url: 'return_url'
};
}
};
ctrl = $controller('Signup', {
$scope: scope,
$http: $http,
$rootScope: rootScope,
alertsService: mockAlertsService
});
}));
it('should show warning if user has not agreed to terms', function() {
scope.submitPrerequisitesForm(false, null);
expect(mockAlertsService.addWarning).toHaveBeenCalledWith(
'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS');
});
it('should get data correctly from the server', function() {
$httpBackend.flush();
expect(scope.username).toBe('myUsername');
expect(scope.hasAgreedToLatestTerms).toBe(false);
});
it('should show a loading message until the data is retrieved', function() {
expect(rootScope.loadingMessage).toBe('I18N_SIGNUP_LOADING');
$httpBackend.flush();
expect(rootScope.loadingMessage).toBeFalsy();
});
it('should show warning if terms are not agreed to', function() {
scope.submitPrerequisitesForm(false, '');
expect(mockAlertsService.addWarning).toHaveBeenCalledWith(
'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS');
});
it('should show warning if no username provided', function() {
scope.updateWarningText('');
expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME');
scope.submitPrerequisitesForm(false);
expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME');
});
it('should show warning if username is too long', function() {
scope.updateWarningText(
'abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_MORE_50_CHARS');
});
it('should show warning if username has non-alphanumeric characters',
function() {
scope.updateWarningText('a-a');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_ONLY_ALPHANUM');
});
it('should show warning if username has \'admin\' in it', function() {
scope.updateWarningText('administrator');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_WITH_ADMIN');
});
});
});
| mit0110/oppia | core/templates/dev/head/profile/SignupSpec.js | JavaScript | apache-2.0 | 3,641 |
(function (enyo, scope) {
/**
* The {@link enyo.RepeaterChildSupport} [mixin]{@glossary mixin} contains methods and
* properties that are automatically applied to all children of {@link enyo.DataRepeater}
* to assist in selection support. (See {@link enyo.DataRepeater} for details on how to
* use selection support.) This mixin also [adds]{@link enyo.Repeater#decorateEvent} the
* `model`, `child` ([control]{@link enyo.Control} instance), and `index` properties to
* all [events]{@glossary event} emitted from the repeater's children.
*
* @mixin enyo.RepeaterChildSupport
* @public
*/
enyo.RepeaterChildSupport = {
/*
* @private
*/
name: 'RepeaterChildSupport',
/**
* Indicates whether the current child is selected in the [repeater]{@link enyo.DataRepeater}.
*
* @type {Boolean}
* @default false
* @public
*/
selected: false,
/*
* @method
* @private
*/
selectedChanged: enyo.inherit(function (sup) {
return function () {
if (this.repeater.selection) {
this.addRemoveClass(this.selectedClass || 'selected', this.selected);
// for efficiency purposes, we now directly call this method as opposed to
// forcing a synchronous event dispatch
var idx = this.repeater.collection.indexOf(this.model);
if (this.selected && !this.repeater.isSelected(this.model)) {
this.repeater.select(idx);
} else if (!this.selected && this.repeater.isSelected(this.model)) {
this.repeater.deselect(idx);
}
}
sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
decorateEvent: enyo.inherit(function (sup) {
return function (sender, event) {
event.model = this.model;
event.child = this;
event.index = this.repeater.collection.indexOf(this.model);
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionHandler: function () {
if (this.repeater.selection && !this.get('disabled')) {
if (!this.repeater.groupSelection || !this.selected) {
this.set('selected', !this.selected);
}
}
},
/**
* Deliberately used to supersede the default method and set
* [owner]{@link enyo.Component#owner} to this [control]{@link enyo.Control} so that there
* are no name collisions in the instance [owner]{@link enyo.Component#owner}, and also so
* that [bindings]{@link enyo.Binding} will correctly map to names.
*
* @method
* @private
*/
createClientComponents: enyo.inherit(function () {
return function (components) {
this.createComponents(components, {owner: this});
};
}),
/**
* Used so that we don't stomp on any built-in handlers for the `ontap`
* {@glossary event}.
*
* @method
* @private
*/
dispatchEvent: enyo.inherit(function (sup) {
return function (name, event, sender) {
if (!event._fromRepeaterChild) {
if (!!~enyo.indexOf(name, this.repeater.selectionEvents)) {
this._selectionHandler();
event._fromRepeaterChild = true;
}
}
return sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
constructed: enyo.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
var r = this.repeater,
s = r.selectionProperty;
// this property will only be set if the instance of the repeater needs
// to track the selected state from the view and model and keep them in sync
if (s) {
var bnd = this.binding({
from: 'model.' + s,
to: 'selected',
oneWay: false/*,
kind: enyo.BooleanBinding*/
});
this._selectionBindingId = bnd.euid;
}
};
}),
/*
* @method
* @private
*/
destroy: enyo.inherit(function (sup) {
return function () {
if (this._selectionBindingId) {
var b$ = enyo.Binding.find(this._selectionBindingId);
if (b$) {
b$.destroy();
}
}
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionBindingId: null
};
})(enyo, this);
| KyleMaas/org.webosports.app.maps | enyo/source/ui/data/RepeaterChildSupport.js | JavaScript | apache-2.0 | 3,961 |
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package csidriver
import (
"testing"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
"k8s.io/kubernetes/pkg/apis/storage"
"k8s.io/kubernetes/pkg/features"
)
func getValidCSIDriver(name string) *storage.CSIDriver {
enabled := true
return &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
}
}
func TestCSIDriverStrategy(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
if Strategy.NamespaceScoped() {
t.Errorf("CSIDriver must not be namespace scoped")
}
if Strategy.AllowCreateOnUpdate() {
t.Errorf("CSIDriver should not allow create on update")
}
csiDriver := getValidCSIDriver("valid-csidriver")
Strategy.PrepareForCreate(ctx, csiDriver)
errs := Strategy.Validate(ctx, csiDriver)
if len(errs) != 0 {
t.Errorf("unexpected error validating %v", errs)
}
// Update of spec is disallowed
newCSIDriver := csiDriver.DeepCopy()
attachNotRequired := false
newCSIDriver.Spec.AttachRequired = &attachNotRequired
Strategy.PrepareForUpdate(ctx, newCSIDriver, csiDriver)
errs = Strategy.ValidateUpdate(ctx, newCSIDriver, csiDriver)
if len(errs) == 0 {
t.Errorf("Expected a validation error")
}
}
func TestCSIDriverPrepareForCreate(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
attachRequired := true
podInfoOnMount := true
storageCapacity := true
tests := []struct {
name string
withCapacity bool
withInline bool
}{
{
name: "inline enabled",
withInline: true,
},
{
name: "inline disabled",
withInline: false,
},
{
name: "capacity enabled",
withCapacity: true,
},
{
name: "capacity disabled",
withCapacity: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIStorageCapacity, test.withCapacity)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, test.withInline)()
csiDriver := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
StorageCapacity: &storageCapacity,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
}
Strategy.PrepareForCreate(ctx, csiDriver)
errs := Strategy.Validate(ctx, csiDriver)
if len(errs) != 0 {
t.Errorf("unexpected validating errors: %v", errs)
}
if test.withCapacity {
if csiDriver.Spec.StorageCapacity == nil || *csiDriver.Spec.StorageCapacity != storageCapacity {
t.Errorf("StorageCapacity modified: %v", csiDriver.Spec.StorageCapacity)
}
} else {
if csiDriver.Spec.StorageCapacity != nil {
t.Errorf("StorageCapacity not stripped: %v", csiDriver.Spec.StorageCapacity)
}
}
if test.withInline {
if len(csiDriver.Spec.VolumeLifecycleModes) != 1 {
t.Errorf("VolumeLifecycleModes modified: %v", csiDriver.Spec)
}
} else {
if len(csiDriver.Spec.VolumeLifecycleModes) != 0 {
t.Errorf("VolumeLifecycleModes not stripped: %v", csiDriver.Spec)
}
}
})
}
}
func TestCSIDriverPrepareForUpdate(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
attachRequired := true
podInfoOnMount := true
driverWithoutModes := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
},
}
driverWithPersistent := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
}
driverWithEphemeral := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleEphemeral,
},
},
}
enabled := true
disabled := false
driverWithoutCapacity := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
}
driverWithCapacityEnabled := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
StorageCapacity: &enabled,
},
}
driverWithCapacityDisabled := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
StorageCapacity: &disabled,
},
}
var resultEmpty []storage.VolumeLifecycleMode
resultPersistent := []storage.VolumeLifecycleMode{storage.VolumeLifecyclePersistent}
resultEphemeral := []storage.VolumeLifecycleMode{storage.VolumeLifecycleEphemeral}
tests := []struct {
name string
old, update *storage.CSIDriver
withCapacity, withoutCapacity *bool
withInline, withoutInline []storage.VolumeLifecycleMode
}{
{
name: "before: no capacity, update: no capacity",
old: driverWithoutCapacity,
update: driverWithoutCapacity,
withCapacity: nil,
withoutCapacity: nil,
},
{
name: "before: no capacity, update: enabled",
old: driverWithoutCapacity,
update: driverWithCapacityEnabled,
withCapacity: &enabled,
withoutCapacity: nil,
},
{
name: "before: capacity enabled, update: disabled",
old: driverWithCapacityEnabled,
update: driverWithCapacityDisabled,
withCapacity: &disabled,
withoutCapacity: &disabled,
},
{
name: "before: capacity enabled, update: no capacity",
old: driverWithCapacityEnabled,
update: driverWithoutCapacity,
withCapacity: nil,
withoutCapacity: nil,
},
{
name: "before: no mode, update: no mode",
old: driverWithoutModes,
update: driverWithoutModes,
withInline: resultEmpty,
withoutInline: resultEmpty,
},
{
name: "before: no mode, update: persistent",
old: driverWithoutModes,
update: driverWithPersistent,
withInline: resultPersistent,
withoutInline: resultEmpty,
},
{
name: "before: persistent, update: ephemeral",
old: driverWithPersistent,
update: driverWithEphemeral,
withInline: resultEphemeral,
withoutInline: resultEphemeral,
},
{
name: "before: persistent, update: no mode",
old: driverWithPersistent,
update: driverWithoutModes,
withInline: resultEmpty,
withoutInline: resultEmpty,
},
}
runAll := func(t *testing.T, withCapacity, withInline bool) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIStorageCapacity, withCapacity)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, withInline)()
csiDriver := test.update.DeepCopy()
Strategy.PrepareForUpdate(ctx, csiDriver, test.old)
if withCapacity {
require.Equal(t, test.withCapacity, csiDriver.Spec.StorageCapacity)
} else {
require.Equal(t, test.withoutCapacity, csiDriver.Spec.StorageCapacity)
}
if withInline {
require.Equal(t, test.withInline, csiDriver.Spec.VolumeLifecycleModes)
} else {
require.Equal(t, test.withoutInline, csiDriver.Spec.VolumeLifecycleModes)
}
})
}
}
t.Run("with capacity", func(t *testing.T) {
runAll(t, true, false)
})
t.Run("without capacity", func(t *testing.T) {
runAll(t, false, false)
})
t.Run("with inline volumes", func(t *testing.T) {
runAll(t, false, true)
})
t.Run("without inline volumes", func(t *testing.T) {
runAll(t, false, false)
})
}
func TestCSIDriverValidation(t *testing.T) {
enabled := true
disabled := true
tests := []struct {
name string
csiDriver *storage.CSIDriver
expectError bool
}{
{
"valid csidriver",
getValidCSIDriver("foo"),
false,
},
{
"true for all flags",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
},
false,
},
{
"false for all flags",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &disabled,
PodInfoOnMount: &disabled,
StorageCapacity: &disabled,
},
},
false,
},
{
"invalid driver name",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "*foo#",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
},
true,
},
{
"invalid volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleMode("no-such-mode"),
},
},
},
true,
},
{
"persistent volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
},
false,
},
{
"ephemeral volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleEphemeral,
},
},
},
false,
},
{
"both volume modes",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
storage.VolumeLifecycleEphemeral,
},
},
},
false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
testValidation := func(csiDriver *storage.CSIDriver, apiVersion string) field.ErrorList {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
return Strategy.Validate(ctx, csiDriver)
}
err := testValidation(test.csiDriver, "v1")
if len(err) > 0 && !test.expectError {
t.Errorf("Validation of v1 object failed: %+v", err)
}
if len(err) == 0 && test.expectError {
t.Errorf("Validation of v1 object unexpectedly succeeded")
}
})
}
}
| johscheuer/kubernetes | pkg/registry/storage/csidriver/strategy_test.go | GO | apache-2.0 | 12,773 |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from cpp_namespace_environment import CppNamespaceEnvironment
from model import Model, UnixName
from schema_loader import SchemaLoader
def _GenerateFilenames(full_namespace):
# Try to find the file defining the namespace. Eg. for
# nameSpace.sub_name_space.Type' the following heuristics looks for:
# 1. name_space_sub_name_space.json,
# 2. name_space_sub_name_space.idl,
# 3. sub_name_space.json,
# 4. sub_name_space.idl,
# 5. etc.
sub_namespaces = full_namespace.split('.')
filenames = [ ]
basename = None
for namespace in reversed(sub_namespaces):
if basename is not None:
basename = UnixName(namespace + '.' + basename)
else:
basename = UnixName(namespace)
for ext in ['json', 'idl']:
filenames.append('%s.%s' % (basename, ext))
return filenames
class NamespaceResolver(object):
'''Resolves a type name into the namespace the type belongs to.
- |root| path to the root directory.
- |path| path to the directory with the API header files, relative to the
root.
- |include_rules| List containing tuples with (path, cpp_namespace_pattern)
used when searching for types.
- |cpp_namespace_pattern| Default namespace pattern
'''
def __init__(self, root, path, include_rules, cpp_namespace_pattern):
self._root = root
self._include_rules = [(path, cpp_namespace_pattern)] + include_rules
def ResolveNamespace(self, full_namespace):
'''Returns the model.Namespace object associated with the |full_namespace|,
or None if one can't be found.
'''
filenames = _GenerateFilenames(full_namespace)
for path, cpp_namespace in self._include_rules:
cpp_namespace_environment = None
if cpp_namespace:
cpp_namespace_environment = CppNamespaceEnvironment(cpp_namespace)
for filename in reversed(filenames):
filepath = os.path.join(path, filename);
if os.path.exists(os.path.join(self._root, filepath)):
schema = SchemaLoader(self._root).LoadSchema(filepath)[0]
return Model().AddNamespace(
schema,
filepath,
environment=cpp_namespace_environment)
return None
def ResolveType(self, full_name, default_namespace):
'''Returns the model.Namespace object where the type with the given
|full_name| is defined, or None if one can't be found.
'''
name_parts = full_name.rsplit('.', 1)
if len(name_parts) == 1:
if full_name not in default_namespace.types:
return None
return default_namespace
full_namespace, type_name = full_name.rsplit('.', 1)
namespace = self.ResolveNamespace(full_namespace)
if namespace and type_name in namespace.types:
return namespace
return None
| scheib/chromium | tools/json_schema_compiler/namespace_resolver.py | Python | bsd-3-clause | 2,904 |
/*!
* Copyright (c) 2015, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var vows = require('vows');
var assert = require('assert');
var async = require('async');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
var CookieJar = tough.CookieJar;
var atNow = Date.now();
function at(offset) {
return {now: new Date(atNow + offset)};
}
vows
.describe('Regression tests')
.addBatch({
"Issue 1": {
topic: function () {
var cj = new CookieJar();
cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) {
this.callback(err, {cj: cj, cookie: cookie});
}.bind(this));
},
"stored a cookie": function (t) {
assert.ok(t.cookie);
},
"getting it back": {
topic: function (t) {
t.cj.getCookies('http://domain/some/path/file', function (err, cookies) {
this.callback(err, {cj: t.cj, cookies: cookies || []});
}.bind(this));
},
"got one cookie": function (t) {
assert.lengthOf(t.cookies, 1);
},
"it's the right one": function (t) {
var c = t.cookies[0];
assert.equal(c.key, 'hello');
assert.equal(c.value, 'world');
}
}
}
})
.addBatch({
"trailing semi-colon set into cj": {
topic: function () {
var cb = this.callback;
var cj = new CookieJar();
var ex = 'http://www.example.com';
var tasks = [];
tasks.push(function (next) {
cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next);
});
tasks.push(function (next) {
cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next);
});
async.parallel(tasks, function (err, cookies) {
cb(null, {
cj: cj,
cookies: cookies
});
});
},
"check number of cookies": function (t) {
assert.lengthOf(t.cookies, 2, "didn't set");
},
"check *broken_path* was set properly": function (t) {
assert.equal(t.cookies[0].key, "broken_path");
assert.equal(t.cookies[0].value, "testme");
assert.equal(t.cookies[0].path, "/");
},
"check *b* was set properly": function (t) {
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
},
"retrieve the cookie": {
topic: function (t) {
var cb = this.callback;
t.cj.getCookies('http://www.example.com', {}, function (err, cookies) {
t.cookies = cookies;
cb(err, t);
});
},
"get the cookie": function (t) {
assert.lengthOf(t.cookies, 2);
assert.equal(t.cookies[0].key, 'broken_path');
assert.equal(t.cookies[0].value, 'testme');
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
}
}
}
})
.addBatch({
"tough-cookie throws exception on malformed URI (GH-32)": {
topic: function () {
var url = "http://www.example.com/?test=100%";
var cj = new CookieJar();
cj.setCookieSync("Test=Test", url);
return cj.getCookieStringSync(url);
},
"cookies are set": function (cookieStr) {
assert.strictEqual(cookieStr, "Test=Test");
}
}
})
.export(module);
| vendavo/yowie | yowie-web/node_modules/bower/node_modules/request/node_modules/tough-cookie/test/regression_test.js | JavaScript | mit | 4,995 |
<?php
return [
'Names' => [
'CDF' => [
0 => 'FC',
1 => 'franc congolais',
],
],
];
| Nyholm/symfony | src/Symfony/Component/Intl/Resources/data/currencies/fr_CD.php | PHP | mit | 132 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.StreamAnalytics;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines headers for Update operation.
/// </summary>
public partial class FunctionsUpdateHeaders
{
/// <summary>
/// Initializes a new instance of the FunctionsUpdateHeaders class.
/// </summary>
public FunctionsUpdateHeaders()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the FunctionsUpdateHeaders class.
/// </summary>
/// <param name="eTag">The current entity tag for the function. This is
/// an opaque string. You can use it to detect whether the resource has
/// changed between requests. You can also use it in the If-Match or
/// If-None-Match headers for write operations for optimistic
/// concurrency.</param>
public FunctionsUpdateHeaders(string eTag = default(string))
{
ETag = eTag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the current entity tag for the function. This is an
/// opaque string. You can use it to detect whether the resource has
/// changed between requests. You can also use it in the If-Match or
/// If-None-Match headers for write operations for optimistic
/// concurrency.
/// </summary>
[JsonProperty(PropertyName = "ETag")]
public string ETag { get; set; }
}
}
| DheerendraRathor/azure-sdk-for-net | src/SDKs/StreamAnalytics/Management.StreamAnalytics/Generated/Models/FunctionsUpdateHeaders.cs | C# | mit | 2,128 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Promise = require('bluebird');
var MongoClient = require('mongodb');
function defaultSerializeFunction(session) {
// Copy each property of the session to a new object
var obj = {};
var prop = void 0;
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
} else {
obj[prop] = session[prop];
}
}
return obj;
}
function computeTransformFunctions(options, defaultStringify) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || function (x) {
return x;
}
};
}
if (options.stringify === false || defaultStringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: function (x) {
return x;
}
};
}
if (options.stringify === true || defaultStringify === true) {
return {
serialize: JSON.stringify,
unserialize: JSON.parse
};
}
}
module.exports = function connectMongo(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
var MongoStore = function (_Store) {
_inherits(MongoStore, _Store);
function MongoStore(options) {
_classCallCheck(this, MongoStore);
options = options || {};
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
var _ret;
return _ret = new MemoryStore(), _possibleConstructorReturn(_this, _ret);
}
/* Options */
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MongoStore).call(this, options));
_this.ttl = options.ttl || 1209600; // 14 days
_this.collectionName = options.collection || 'sessions';
_this.autoRemove = options.autoRemove || 'native';
_this.autoRemoveInterval = options.autoRemoveInterval || 10;
_this.transformFunctions = computeTransformFunctions(options, true);
_this.options = options;
_this.changeState('init');
var newConnectionCallback = function (err, db) {
if (err) {
_this.connectionFailed(err);
} else {
_this.handleNewConnectionAsync(db);
}
};
if (options.url) {
// New native connection using url + mongoOptions
MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback);
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
_this.handleNewConnectionAsync(options.mongooseConnection.db);
} else {
options.mongooseConnection.once('open', function () {
return _this.handleNewConnectionAsync(options.mongooseConnection.db);
});
}
} else if (options.db && options.db.listCollections) {
// Re-use existing or upcoming native connection
if (options.db.openCalled || options.db.openCalled === undefined) {
// openCalled is undefined in mongodb@2.x
_this.handleNewConnectionAsync(options.db);
} else {
options.db.open(newConnectionCallback);
}
} else if (options.dbPromise) {
options.dbPromise.then(function (db) {
return _this.handleNewConnectionAsync(db);
}).catch(function (err) {
return _this.connectionFailed(err);
});
} else {
throw new Error('Connection strategy not found');
}
_this.changeState('connecting');
return _this;
}
_createClass(MongoStore, [{
key: 'connectionFailed',
value: function connectionFailed(err) {
this.changeState('disconnected');
throw err;
}
}, {
key: 'handleNewConnectionAsync',
value: function handleNewConnectionAsync(db) {
var _this2 = this;
this.db = db;
return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () {
return _this2.changeState('connected');
});
}
}, {
key: 'setAutoRemoveAsync',
value: function setAutoRemoveAsync() {
var _this3 = this;
switch (this.autoRemove) {
case 'native':
return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 });
case 'interval':
var removeQuery = { expires: { $lt: new Date() } };
this.timer = setInterval(function () {
return _this3.collection.remove(removeQuery, { w: 0 });
}, this.autoRemoveInterval * 1000 * 60);
this.timer.unref();
return Promise.resolve();
default:
return Promise.resolve();
}
}
}, {
key: 'changeState',
value: function changeState(newState) {
if (newState !== this.state) {
this.state = newState;
this.emit(newState);
}
}
}, {
key: 'setCollection',
value: function setCollection(collection) {
if (this.timer) {
clearInterval(this.timer);
}
this.collectionReadyPromise = undefined;
this.collection = collection;
// Promisify used collection methods
['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) {
collection[method + 'Async'] = Promise.promisify(collection[method], collection);
});
return this;
}
}, {
key: 'collectionReady',
value: function collectionReady() {
var _this4 = this;
var promise = this.collectionReadyPromise;
if (!promise) {
promise = new Promise(function (resolve, reject) {
switch (_this4.state) {
case 'connected':
resolve(_this4.collection);
break;
case 'connecting':
_this4.once('connected', function () {
return resolve(_this4.collection);
});
break;
case 'disconnected':
reject(new Error('Not connected'));
break;
}
});
this.collectionReadyPromise = promise;
}
return promise;
}
}, {
key: 'computeStorageId',
value: function computeStorageId(sessionId) {
if (this.options.transformId && typeof this.options.transformId === 'function') {
return this.options.transformId(sessionId);
} else {
return sessionId;
}
}
/* Public API */
}, {
key: 'get',
value: function get(sid, callback) {
var _this5 = this;
return this.collectionReady().then(function (collection) {
return collection.findOneAsync({
_id: _this5.computeStorageId(sid),
$or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }]
});
}).then(function (session) {
if (session) {
var s = _this5.transformFunctions.unserialize(session.session);
if (_this5.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified;
}
_this5.emit('touch', sid);
return s;
}
}).nodeify(callback);
}
}, {
key: 'set',
value: function set(sid, session, callback) {
var _this6 = this;
// removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified;
}
var s;
try {
s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) };
} catch (err) {
return callback(err);
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires);
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000);
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date();
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true });
}).then(function () {
return _this6.emit('set', sid);
}).nodeify(callback);
}
}, {
key: 'touch',
value: function touch(sid, session, callback) {
var _this7 = this;
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
// if the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
var timeElapsed = currentDate.getTime() - session.lastModified;
if (timeElapsed < touchAfter) {
return callback();
} else {
updateFields.lastModified = currentDate;
}
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires);
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000);
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields });
}).then(function (result) {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch');
} else {
_this7.emit('touch', sid);
}
}).nodeify(callback);
}
}, {
key: 'destroy',
value: function destroy(sid, callback) {
var _this8 = this;
return this.collectionReady().then(function (collection) {
return collection.removeAsync({ _id: _this8.computeStorageId(sid) });
}).then(function () {
return _this8.emit('destroy', sid);
}).nodeify(callback);
}
}, {
key: 'length',
value: function length(callback) {
return this.collectionReady().then(function (collection) {
return collection.countAsync({});
}).nodeify(callback);
}
}, {
key: 'clear',
value: function clear(callback) {
return this.collectionReady().then(function (collection) {
return collection.dropAsync();
}).nodeify(callback);
}
}, {
key: 'close',
value: function close() {
if (this.db) {
this.db.close();
}
}
}]);
return MongoStore;
}(Store);
return MongoStore;
}; | luoshichang/learnNode | node_modules/connect-mongo/src-es5/index.js | JavaScript | mit | 15,400 |
from __future__ import division, absolute_import, print_function
import sys
import collections
import pickle
import warnings
from os import path
import numpy as np
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_raises, assert_warns
)
class TestFromrecords(TestCase):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
if sys.version_info[0] >= 3:
assert_equal(r['col2'].dtype.kind, 'U')
assert_equal(r['col2'].dtype.itemsize, 12)
else:
assert_equal(r['col2'].dtype.kind, 'S')
assert_equal(r['col2'].dtype.itemsize, 3)
assert_equal(r['col3'].dtype.kind, 'f')
def test_fromrecords_0len(self):
""" Verify fromrecords works with a 0-length input """
dtype = [('a', np.float), ('b', np.float)]
r = np.rec.fromrecords([], dtype=dtype)
assert_equal(r.shape, (0,))
def test_fromrecords_2d(self):
data = [
[(1, 2), (3, 4), (5, 6)],
[(6, 5), (4, 3), (2, 1)]
]
expected_a = [[1, 3, 5], [6, 4, 2]]
expected_b = [[2, 4, 6], [5, 3, 1]]
# try with dtype
r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
assert_equal(r1['a'], expected_a)
assert_equal(r1['b'], expected_b)
# try with names
r2 = np.rec.fromrecords(data, names=['a', 'b'])
assert_equal(r2['a'], expected_a)
assert_equal(r2['b'], expected_b)
assert_equal(r1, r2)
def test_method_array(self):
r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big')
assert_equal(r[1].item(), (25444, b'efg', 1633837924))
def test_method_array2(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1].item(), (2, 22.0, b'b'))
def test_recarray_slices(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1::2][1].item(), (4, 44.0, b'd'))
def test_recarray_fromarrays(self):
x1 = np.array([1, 2, 3, 4])
x2 = np.array(['a', 'dd', 'xyz', '12'])
x3 = np.array([1.1, 2, 3, 4])
r = np.rec.fromarrays([x1, x2, x3], names='a,b,c')
assert_equal(r[1].item(), (2, 'dd', 2.0))
x1[1] = 34
assert_equal(r.a, np.array([1, 2, 3, 4]))
def test_recarray_fromfile(self):
data_dir = path.join(path.dirname(__file__), 'data')
filename = path.join(data_dir, 'recarray_from_file.fits')
fd = open(filename, 'rb')
fd.seek(2880 * 2)
r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.seek(2880 * 2)
r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.close()
assert_equal(r1, r2)
def test_recarray_from_obj(self):
count = 10
a = np.zeros(count, dtype='O')
b = np.zeros(count, dtype='f8')
c = np.zeros(count, dtype='f8')
for i in range(len(a)):
a[i] = list(range(1, 10))
mine = np.rec.fromarrays([a, b, c], names='date,data1,data2')
for i in range(len(a)):
assert_((mine.date[i] == list(range(1, 10))))
assert_((mine.data1[i] == 0.0))
assert_((mine.data2[i] == 0.0))
def test_recarray_from_repr(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
recordarr = np.rec.array(a)
recarr = a.view(np.recarray)
recordview = a.view(np.dtype((np.record, a.dtype)))
recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np})
recarr_r = eval("numpy." + repr(recarr), {'numpy': np})
recordview_r = eval("numpy." + repr(recordview), {'numpy': np})
assert_equal(type(recordarr_r), np.recarray)
assert_equal(recordarr_r.dtype.type, np.record)
assert_equal(recordarr, recordarr_r)
assert_equal(type(recarr_r), np.recarray)
assert_equal(recarr_r.dtype.type, np.record)
assert_equal(recarr, recarr_r)
assert_equal(type(recordview_r), np.ndarray)
assert_equal(recordview.dtype.type, np.record)
assert_equal(recordview, recordview_r)
def test_recarray_views(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
b = np.array([1,2,3,4,5], dtype=np.int64)
#check that np.rec.array gives right dtypes
assert_equal(np.rec.array(a).dtype.type, np.record)
assert_equal(type(np.rec.array(a)), np.recarray)
assert_equal(np.rec.array(b).dtype.type, np.int64)
assert_equal(type(np.rec.array(b)), np.recarray)
#check that viewing as recarray does the same
assert_equal(a.view(np.recarray).dtype.type, np.record)
assert_equal(type(a.view(np.recarray)), np.recarray)
assert_equal(b.view(np.recarray).dtype.type, np.int64)
assert_equal(type(b.view(np.recarray)), np.recarray)
#check that view to non-structured dtype preserves type=np.recarray
r = np.rec.array(np.ones(4, dtype="f4,i4"))
rv = r.view('f8').view('f4,i4')
assert_equal(type(rv), np.recarray)
assert_equal(rv.dtype.type, np.record)
#check that getitem also preserves np.recarray and np.record
r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
('c', 'i4,i4')]))
assert_equal(r['c'].dtype.type, np.record)
assert_equal(type(r['c']), np.recarray)
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
assert_equal(r[['a', 'b']].dtype.type, np.record)
assert_equal(type(r[['a', 'b']]), np.recarray)
#and that it preserves subclasses (gh-6949)
class C(np.recarray):
pass
c = r.view(C)
assert_equal(type(c['c']), C)
# check that accessing nested structures keep record type, but
# not for subarrays, non-void structures, non-structured voids
test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)),
('d', ('i8', 'i4,i4'))]
r = np.rec.array([((1,1), b'11111111', [1,1], 1),
((1,1), b'11111111', [1,1], 1)], dtype=test_dtype)
assert_equal(r.a.dtype.type, np.record)
assert_equal(r.b.dtype.type, np.void)
assert_equal(r.c.dtype.type, np.float32)
assert_equal(r.d.dtype.type, np.int64)
# check the same, but for views
r = np.rec.array(np.ones(4, dtype='i4,i4'))
assert_equal(r.view('f4,f4').dtype.type, np.record)
assert_equal(r.view(('i4',2)).dtype.type, np.int32)
assert_equal(r.view('V8').dtype.type, np.void)
assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
#check that we can undo the view
arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
for arr in arrs:
rec = np.rec.array(arr)
# recommended way to view as an ndarray:
arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray)
assert_equal(arr2.dtype.type, arr.dtype.type)
assert_equal(type(arr2), type(arr))
def test_recarray_repr(self):
# make sure non-structured dtypes also show up as rec.array
a = np.array(np.ones(4, dtype='f8'))
assert_(repr(np.rec.array(a)).startswith('rec.array'))
# check that the 'np.record' part of the dtype isn't shown
a = np.rec.array(np.ones(3, dtype='i4,i4'))
assert_equal(repr(a).find('numpy.record'), -1)
a = np.rec.array(np.ones(3, dtype='i4'))
assert_(repr(a).find('dtype=int32') != -1)
def test_recarray_from_names(self):
ra = np.rec.array([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
pa = np.rec.fromrecords([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
assert_(ra.dtype == pa.dtype)
assert_(ra.shape == pa.shape)
for k in range(len(ra)):
assert_(ra[k].item() == pa[k].item())
def test_recarray_conflict_fields(self):
ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
(3, 'wrs', 1.3)],
names='field, shape, mean')
ra.mean = [1.1, 2.2, 3.3]
assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3])
assert_(type(ra.mean) is type(ra.var))
ra.shape = (1, 3)
assert_(ra.shape == (1, 3))
ra.shape = ['A', 'B', 'C']
assert_array_equal(ra['shape'], [['A', 'B', 'C']])
ra.field = 5
assert_array_equal(ra['field'], [[5, 5, 5]])
assert_(isinstance(ra.field, collections.Callable))
def test_fromrecords_with_explicit_dtype(self):
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
dtype=[('a', int), ('b', np.object)])
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
#
ndtype = np.dtype([('a', int), ('b', np.object)])
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype)
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
def test_recarray_stringtypes(self):
# Issue #3993
a = np.array([('abc ', 1), ('abc', 2)],
dtype=[('foo', 'S4'), ('bar', int)])
a = a.view(np.recarray)
assert_equal(a.foo[0] == a.foo[1], False)
def test_recarray_returntypes(self):
qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)}
a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')),
('abc', (2,3), 1, ('abcde', 'jklmn'))],
dtype=[('foo', 'S4'),
('bar', [('A', int), ('B', int)]),
('baz', int), ('qux', qux_fields)])
assert_equal(type(a.foo), np.ndarray)
assert_equal(type(a['foo']), np.ndarray)
assert_equal(type(a.bar), np.recarray)
assert_equal(type(a['bar']), np.recarray)
assert_equal(a.bar.dtype.type, np.record)
assert_equal(type(a['qux']), np.recarray)
assert_equal(a.qux.dtype.type, np.record)
assert_equal(dict(a.qux.dtype.fields), qux_fields)
assert_equal(type(a.baz), np.ndarray)
assert_equal(type(a['baz']), np.ndarray)
assert_equal(type(a[0].bar), np.record)
assert_equal(type(a[0]['bar']), np.record)
assert_equal(a[0].bar.A, 1)
assert_equal(a[0].bar['A'], 1)
assert_equal(a[0]['bar'].A, 1)
assert_equal(a[0]['bar']['A'], 1)
assert_equal(a[0].qux.D, b'fgehi')
assert_equal(a[0].qux['D'], b'fgehi')
assert_equal(a[0]['qux'].D, b'fgehi')
assert_equal(a[0]['qux']['D'], b'fgehi')
def test_zero_width_strings(self):
# Test for #6430, based on the test case from #1901
cols = [['test'] * 3, [''] * 3]
rec = np.rec.fromarrays(cols)
assert_equal(rec['f0'], ['test', 'test', 'test'])
assert_equal(rec['f1'], ['', '', ''])
dt = np.dtype([('f0', '|S4'), ('f1', '|S')])
rec = np.rec.fromarrays(cols, dtype=dt)
assert_equal(rec.itemsize, 4)
assert_equal(rec['f0'], [b'test', b'test', b'test'])
assert_equal(rec['f1'], [b'', b'', b''])
class TestRecord(TestCase):
def setUp(self):
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
dtype=[("col1", "<i4"),
("col2", "<i4"),
("col3", "<i4")])
def test_assignment1(self):
a = self.data
assert_equal(a.col1[0], 1)
a[0].col1 = 0
assert_equal(a.col1[0], 0)
def test_assignment2(self):
a = self.data
assert_equal(a.col1[0], 1)
a.col1[0] = 0
assert_equal(a.col1[0], 0)
def test_invalid_assignment(self):
a = self.data
def assign_invalid_column(x):
x[0].col5 = 1
self.assertRaises(AttributeError, assign_invalid_column, a)
def test_nonwriteable_setfield(self):
# gh-8171
r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')])
r.flags.writeable = False
with assert_raises(ValueError):
r.f = [2, 3]
with assert_raises(ValueError):
r.setfield([2,3], *r.dtype.fields['f'])
def test_out_of_order_fields(self):
"""Ticket #1431."""
# this test will be invalid in 1.13
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
x = self.data[['col1', 'col2']]
y = self.data[['col2', 'col1']]
assert_equal(x[0][0], y[0][1])
def test_pickle_1(self):
# Issue #1529
a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_2(self):
a = self.data
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_3(self):
# Issue #7140
a = self.data
pa = pickle.loads(pickle.dumps(a[0]))
assert_(pa.flags.c_contiguous)
assert_(pa.flags.f_contiguous)
assert_(pa.flags.writeable)
assert_(pa.flags.aligned)
def test_objview_record(self):
# https://github.com/numpy/numpy/issues/2599
dt = np.dtype([('foo', 'i8'), ('bar', 'O')])
r = np.zeros((1,3), dtype=dt).view(np.recarray)
r.foo = np.array([1, 2, 3]) # TypeError?
# https://github.com/numpy/numpy/issues/3256
ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)])
with assert_warns(FutureWarning):
ra[['x','y']] # TypeError?
def test_record_scalar_setitem(self):
# https://github.com/numpy/numpy/issues/3561
rec = np.recarray(1, dtype=[('x', float, 5)])
rec[0].x = 1
assert_equal(rec[0].x, np.ones(5))
def test_missing_field(self):
# https://github.com/numpy/numpy/issues/4806
arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
assert_raises(ValueError, lambda: arr[['nofield']])
def test_find_duplicate():
l1 = [1, 2, 3, 4, 5, 6]
assert_(np.rec.find_duplicate(l1) == [])
l2 = [1, 2, 1, 4, 5, 6]
assert_(np.rec.find_duplicate(l2) == [1])
l3 = [1, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [1, 2])
l3 = [2, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [2, 1])
if __name__ == "__main__":
run_module_suite()
| mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/core/tests/test_records.py | Python | mit | 15,635 |
// Copyright 2011 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.
/*
The present file format
Present files have the following format. The first non-blank non-comment
line is the title, so the header looks like
Title of document
Subtitle of document
15:04 2 Jan 2006
Tags: foo, bar, baz
<blank line>
Author Name
Job title, Company
joe@example.com
http://url/
@twitter_name
The subtitle, date, and tags lines are optional.
The date line may be written without a time:
2 Jan 2006
In this case, the time will be interpreted as 10am UTC on that date.
The tags line is a comma-separated list of tags that may be used to categorize
the document.
The author section may contain a mixture of text, twitter names, and links.
For slide presentations, only the plain text lines will be displayed on the
first slide.
Multiple presenters may be specified, separated by a blank line.
After that come slides/sections, each after a blank line:
* Title of slide or section (must have asterisk)
Some Text
** Subsection
- bullets
- more bullets
- a bullet with
*** Sub-subsection
Some More text
Preformatted text
is indented (however you like)
Further Text, including invocations like:
.code x.go /^func main/,/^}/
.play y.go
.image image.jpg
.background image.jpg
.iframe http://foo
.link http://foo label
.html file.html
.caption _Gopher_ by [[http://www.reneefrench.com][Renée French]]
Again, more text
Blank lines are OK (not mandatory) after the title and after the
text. Text, bullets, and .code etc. are all optional; title is
not.
Lines starting with # in column 1 are commentary.
Fonts:
Within the input for plain text or lists, text bracketed by font
markers will be presented in italic, bold, or program font.
Marker characters are _ (italic), * (bold) and ` (program font).
Unmatched markers appear as plain text.
Within marked text, a single marker character becomes a space
and a doubled single marker quotes the marker character.
_italic_
*bold*
`program`
_this_is_all_italic_
_Why_use_scoped__ptr_? Use plain ***ptr* instead.
Inline links:
Links can be included in any text with the form [[url][label]], or
[[url]] to use the URL itself as the label.
Functions:
A number of template functions are available through invocations
in the input text. Each such invocation contains a period as the
first character on the line, followed immediately by the name of
the function, followed by any arguments. A typical invocation might
be
.play demo.go /^func show/,/^}/
(except that the ".play" must be at the beginning of the line and
not be indented like this.)
Here follows a description of the functions:
code:
Injects program source into the output by extracting code from files
and injecting them as HTML-escaped <pre> blocks. The argument is
a file name followed by an optional address that specifies what
section of the file to display. The address syntax is similar in
its simplest form to that of ed, but comes from sam and is more
general. See
http://plan9.bell-labs.com/sys/doc/sam/sam.html Table II
for full details. The displayed block is always rounded out to a
full line at both ends.
If no pattern is present, the entire file is displayed.
Any line in the program that ends with the four characters
OMIT
is deleted from the source before inclusion, making it easy
to write things like
.code test.go /START OMIT/,/END OMIT/
to find snippets like this
tedious_code = boring_function()
// START OMIT
interesting_code = fascinating_function()
// END OMIT
and see only this:
interesting_code = fascinating_function()
Also, inside the displayed text a line that ends
// HL
will be highlighted in the display; the 'h' key in the browser will
toggle extra emphasis of any highlighted lines. A highlighting mark
may have a suffix word, such as
// HLxxx
Such highlights are enabled only if the code invocation ends with
"HL" followed by the word:
.code test.go /^type Foo/,/^}/ HLxxx
The .code function may take one or more flags immediately preceding
the filename. This command shows test.go in an editable text area:
.code -edit test.go
This command shows test.go with line numbers:
.code -numbers test.go
play:
The function "play" is the same as "code" but puts a button
on the displayed source so the program can be run from the browser.
Although only the selected text is shown, all the source is included
in the HTML output so it can be presented to the compiler.
link:
Create a hyperlink. The syntax is 1 or 2 space-separated arguments.
The first argument is always the HTTP URL. If there is a second
argument, it is the text label to display for this link.
.link http://golang.org golang.org
image:
The template uses the function "image" to inject picture files.
The syntax is simple: 1 or 3 space-separated arguments.
The first argument is always the file name.
If there are more arguments, they are the height and width;
both must be present, or substituted with an underscore.
Replacing a dimension argument with the underscore parameter
preserves the aspect ratio of the image when scaling.
.image images/betsy.jpg 100 200
.image images/janet.jpg _ 300
video:
The template uses the function "video" to inject video files.
The syntax is simple: 2 or 4 space-separated arguments.
The first argument is always the file name.
The second argument is always the file content-type.
If there are more arguments, they are the height and width;
both must be present, or substituted with an underscore.
Replacing a dimension argument with the underscore parameter
preserves the aspect ratio of the video when scaling.
.video videos/evangeline.mp4 video/mp4 400 600
.video videos/mabel.ogg video/ogg 500 _
background:
The template uses the function "background" to set the background image for
a slide. The only argument is the file name of the image.
.background images/susan.jpg
caption:
The template uses the function "caption" to inject figure captions.
The text after ".caption" is embedded in a figcaption element after
processing styling and links as in standard text lines.
.caption _Gopher_ by [[http://www.reneefrench.com][Renée French]]
iframe:
The function "iframe" injects iframes (pages inside pages).
Its syntax is the same as that of image.
html:
The function html includes the contents of the specified file as
unescaped HTML. This is useful for including custom HTML elements
that cannot be created using only the slide format.
It is your responsibilty to make sure the included HTML is valid and safe.
.html file.html
*/
package present // import "golang.org/x/tools/present"
| cmars/tools | vendor/src/golang.org/x/tools/present/doc.go | GO | mit | 6,713 |
import * as RSVP from 'rsvp';
import { backburner, _rsvpErrorQueue } from '@ember/runloop';
import { getDispatchOverride } from '@ember/-internals/error-handling';
import { assert } from '@ember/debug';
RSVP.configure('async', (callback, promise) => {
backburner.schedule('actions', null, callback, promise);
});
RSVP.configure('after', cb => {
backburner.schedule(_rsvpErrorQueue, null, cb);
});
RSVP.on('error', onerrorDefault);
export function onerrorDefault(reason) {
let error = errorFor(reason);
if (error) {
let overrideDispatch = getDispatchOverride();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
if (reason.errorThrown) {
return unwrapErrorThrown(reason);
}
if (reason.name === 'UnrecognizedURLError') {
assert(`The URL '${reason.message}' did not match any routes in your application`, false);
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
let error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '__reason_with_error_thrown__', {
value: reason,
enumerable: false,
});
return error;
}
export default RSVP;
| bekzod/ember.js | packages/@ember/-internals/runtime/lib/ext/rsvp.js | JavaScript | mit | 1,339 |
#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// Override Halide's malloc and free
size_t custom_malloc_size = 0;
void *my_malloc(void *user_context, size_t x) {
custom_malloc_size = x;
void *orig = malloc(x+32);
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
void my_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
int main(int argc, char **argv) {
Var x, y;
{
Func f, g;
f(x, y) = x;
g(x, y) = f(x-1, y) + f(x, y-1);
f.store_root().compute_at(g, x);
g.set_custom_allocator(my_malloc, my_free);
Image<int> im = g.realize(1000, 1000);
// Should fold by a factor of two, but sliding window analysis makes it round up to 4.
if (custom_malloc_size == 0 || custom_malloc_size > 1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, 2*y) + g(2*x+1, 2*y+1);
// Each instance of f uses a non-overlapping 2x2 box of
// g. Should be able to fold storage of g down to a stack
// allocation.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * (2*y) + (2*x+1) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, 2*y) + g(x+3, 2*y+1);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in y, and is a stencil over x. Should be able to fold
// both x and y.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x * (2*y) + (x+3) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, y) + g(2*x+1, y+3);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in x, and is a stencil over y. We can't fold in x due
// to the stencil in y. We need to keep around entire
// scanlines.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 2*1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * y + (2*x+1) * (y+3);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, y);
Var yo, yi;
f.bound(y, 0, (f.output_buffer().height()/8)*8).split(y, yo, yi, 8);
g.compute_at(f, yo).store_root();
// The split logic shouldn't interfere with the ability to
// fold f down to an 8-scanline allocation, but it's only
// correct to fold if we know the output height is a multiple
// of the split factor.
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 1000*8*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1000*8*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x*y;
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
| dan-tull/Halide | test/correctness/storage_folding.cpp | C++ | mit | 5,268 |
/**
@module ember
@submodule ember-runtime
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { get } from 'ember-metal/property_get';
import { deprecateProperty } from 'ember-metal/deprecate_property';
/**
`Ember.ActionHandler` is available on some familiar classes including
`Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`.
(Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
and `Ember.Route` and available to the above classes through
inheritance.)
@class ActionHandler
@namespace Ember
@private
*/
var ActionHandler = Mixin.create({
mergedProperties: ['actions'],
/**
The collection of functions, keyed by name, available on this
`ActionHandler` as action targets.
These functions will be invoked when a matching `{{action}}` is triggered
from within a template and the application's current route is this route.
Actions can also be invoked from other parts of your application
via `ActionHandler#send`.
The `actions` hash will inherit action handlers from
the `actions` hash defined on extended parent classes
or mixins rather than just replace the entire hash, e.g.:
```js
App.CanDisplayBanner = Ember.Mixin.create({
actions: {
displayBanner: function(msg) {
// ...
}
}
});
App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, {
actions: {
playMusic: function() {
// ...
}
}
});
// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');
```
Within a Controller, Route, View or Component's action handler,
the value of the `this` context is the Controller, Route, View or
Component object:
```js
App.SongRoute = Ember.Route.extend({
actions: {
myAction: function() {
this.controllerFor("song");
this.transitionTo("other.route");
...
}
}
});
```
It is also possible to call `this._super.apply(this, arguments)` from within an
action handler if it overrides a handler defined on a parent
class or mixin:
Take for example the following routes:
```js
App.DebugRoute = Ember.Mixin.create({
actions: {
debugRouteInformation: function() {
console.debug("trololo");
}
}
});
App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, {
actions: {
debugRouteInformation: function() {
// also call the debugRouteInformation of mixed in App.DebugRoute
this._super.apply(this, arguments);
// show additional annoyance
window.alert(...);
}
}
});
```
## Bubbling
By default, an action will stop bubbling once a handler defined
on the `actions` hash handles it. To continue bubbling the action,
you must return `true` from the handler:
```js
App.Router.map(function() {
this.route("album", function() {
this.route("song");
});
});
App.AlbumRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
}
}
});
App.AlbumSongRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
// ...
if (actionShouldAlsoBeTriggeredOnParentRoute) {
return true;
}
}
}
});
```
@property actions
@type Object
@default null
@public
*/
/**
Triggers a named action on the `ActionHandler`. Any parameters
supplied after the `actionName` string will be passed as arguments
to the action target function.
If the `ActionHandler` has its `target` property set, actions may
bubble to the `target`. Bubbling happens when an `actionName` can
not be found in the `ActionHandler`'s `actions` hash or if the
action target function returns `true`.
Example
```js
App.WelcomeRoute = Ember.Route.extend({
actions: {
playTheme: function() {
this.send('playMusic', 'theme.mp3');
},
playMusic: function(track) {
// ...
}
}
});
```
@method send
@param {String} actionName The action to trigger
@param {*} context a context to send with the action
@public
*/
send(actionName, ...args) {
var target;
if (this.actions && this.actions[actionName]) {
var shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) { return; }
}
if (target = get(this, 'target')) {
Ember.assert('The `target` for ' + this + ' (' + target +
') does not have a `send` method', typeof target.send === 'function');
target.send(...arguments);
}
}
});
export default ActionHandler;
export function deprecateUnderscoreActions(factory) {
deprecateProperty(factory.prototype, '_actions', 'actions', {
id: 'ember-runtime.action-handler-_actions', until: '3.0.0'
});
}
| artfuldodger/ember.js | packages/ember-runtime/lib/mixins/action_handler.js | JavaScript | mit | 5,224 |
"use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i==23) {
uuid[i] = '-';
}
else if (i==14) {
uuid[i] = '4';
}
else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
exports.in_array = function (item, array) {
return (array.indexOf(item) != -1);
};
exports.sort_keys = function (obj) {
return Object.keys(obj).sort();
};
exports.uniq = function (arr) {
var out = [];
var o = 0;
for (var i=0,l=arr.length; i < l; i++) {
if (out.length === 0) {
out.push(arr[i]);
}
else if (out[o] != arr[i]) {
out.push(arr[i]);
o++;
}
}
return out;
}
exports.ISODate = function (d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function _pad (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) +
' ' + d.toString().match(/\sGMT([+-]\d+)/)[1];
}
exports.decode_qp = function (line) {
line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n");
if (! /=/.test(line)) {
// this may be a pointless optimisation...
return new Buffer(line);
}
line = line.replace(/=\n/mg, '');
var buf = new Buffer(line.length);
var pos = 0;
for (var i=0,l=line.length; i < l; i++) {
if (line[i] === '=' &&
/=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) {
i++;
buf[pos] = parseInt(line[i] + line[i+1], 16);
i++;
}
else {
buf[pos] = line.charCodeAt(i);
}
pos++;
}
return buf.slice(0, pos);
}
function _char_to_qp (ch) {
return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2);
}
// Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code.
exports.encode_qp = function (str) {
str = str.replace(/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) {
return _char_to_qp(p1);
}).replace(/([ \t]+)$/gm, function (orig, p1) {
return p1.split('').map(_char_to_qp).join('');
});
// Now shorten lines to 76 chars, but don't break =XX encodes.
// Method: iterate over to char 73.
// If char 74, 75 or 76 is = we need to break before the =.
// Otherwise break at 76.
var cur_length = 0;
var out = '';
for (var i=0; i<str.length; i++) {
if (str[i] === '\n') {
out += '\n';
cur_length = 0;
continue;
}
cur_length++;
if (cur_length <= 73) {
out += str[i];
}
else if (cur_length > 73 && cur_length < 76) {
if (str[i] === '=') {
out += '=\n=';
cur_length = 1;
}
else {
out += str[i];
}
}
else {
// Otherwise got to char 76
// Don't insert '=\n' if end of string or next char is already \n:
if ((i === (str.length - 1)) || (str[i+1] === '\n')) {
out += str[i];
}
else {
out += '=\n' + str[i];
cur_length = 1;
}
}
}
return out;
}
var versions = process.version.split('.'),
version = Number(versions[0].substring(1)),
subversion = Number(versions[1]);
exports.existsSync = require((version > 0 || subversion >= 8) ? 'fs' : 'path').existsSync;
exports.indexOfLF = function (buf, maxlength) {
for (var i=0; i<buf.length; i++) {
if (maxlength && (i === maxlength)) break;
if (buf[i] === 0x0a) return i;
}
return -1;
}
| lucciano/Haraka | utils.js | JavaScript | mit | 4,778 |
require 'spec_helper'
require 'puppet/transaction'
require 'puppet_spec/compiler'
require 'matchers/relationship_graph_matchers'
require 'matchers/include_in_order'
require 'matchers/resource'
describe Puppet::Transaction::AdditionalResourceGenerator do
include PuppetSpec::Compiler
include PuppetSpec::Files
include RelationshipGraphMatchers
include Matchers::Resource
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
def find_vertex(graph, type, title)
graph.vertices.find {|v| v.type == type and v.title == title}
end
Puppet::Type.newtype(:generator) do
include PuppetSpec::Compiler
newparam(:name) do
isnamevar
end
newparam(:kind) do
defaultto :eval_generate
newvalues(:eval_generate, :generate)
end
newparam(:code)
def respond_to?(method_name)
method_name == self[:kind] || super
end
def eval_generate
eval_code
end
def generate
eval_code
end
def eval_code
if self[:code]
compile_to_ral(self[:code]).resources.select { |r| r.ref =~ /Notify/ }
else
[]
end
end
end
context "when applying eval_generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should add a sentinel whit for the resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
find_vertex(graph, :whit, "completed_thing").must be_a(Puppet::Type.type(:whit))
end
it "should replace dependencies on the resource with dependencies on the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
notify { last: require => Generator['thing'] }
MANIFEST
expect(graph).to enforce_order_with_edge(
'Whit[completed_thing]', 'Notify[last]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "should add an edge from each generated resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Notify[hello]', 'Whit[completed_thing]')
expect(graph).to enforce_order_with_edge(
'Notify[goodbye]', 'Whit[completed_thing]')
end
it "should add an edge from the resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Whit[completed_thing]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
code => 'notify { hello: }'
}
}
include container
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should return false if an error occurred when generating resources" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'fail("not a good generation")'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
end
it "should return true if resources were generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(true)
end
it "should not add a sentinel if no resources are generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
expect(find_vertex(relationship_graph, :whit, "completed_thing")).to be_nil
end
it "orders generated resources with the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
def relationships_after_eval_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource(resource_to_generate))
end
end
context "when applying generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
}
include container
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "orders generated resources with the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
kind => generate,
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
def relationships_after_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.generate_additional_resources(catalog.resource(resource_to_generate))
end
end
def relationship_graph_for(catalog)
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
relationship_graph.populate_from(catalog)
relationship_graph
end
def order_resources_traversed_in(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
RSpec::Matchers.define :contain_resources_equally do |*resource_refs|
match do |catalog|
@containers = resource_refs.collect do |resource_ref|
catalog.container_of(catalog.resource(resource_ref)).ref
end
@containers.all? { |resource_ref| resource_ref == @containers[0] }
end
def failure_message_for_should
"expected #{@expected.join(', ')} to all be contained in the same resource but the containment was #{@expected.zip(@containers).collect { |(res, container)| res + ' => ' + container }.join(', ')}"
end
end
end
| thejonanshow/my-boxen | vendor/bundle/ruby/2.3.0/gems/puppet-3.8.7/spec/unit/transaction/additional_resource_generator_spec.rb | Ruby | mit | 13,674 |
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites
define({
// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
// specified browser environments in the `environments` array below as well. See
// <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for
// different services.
// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
maxConcurrency: 2,
// Non-functional test suite(s) to run in each browser
suites: [ 'tests/plugin' ],
// A regular expression matching URLs to files that should not be included in code coverage analysis
excludeInstrumentation: /^(?:tests|node_modules)\//
});
| brendanlacroix/polish-no-added-typography | tests/intern.js | JavaScript | mit | 1,011 |
import {LooseParser} from "./state"
import {isDummy} from "./parseutil"
import {tokTypes as tt} from ".."
const lp = LooseParser.prototype
lp.checkLVal = function(expr) {
if (!expr) return expr
switch (expr.type) {
case "Identifier":
case "MemberExpression":
return expr
case "ParenthesizedExpression":
expr.expression = this.checkLVal(expr.expression)
return expr
default:
return this.dummyIdent()
}
}
lp.parseExpression = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseMaybeAssign(noIn)
if (this.tok.type === tt.comma) {
let node = this.startNodeAt(start)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
lp.parseParenExpression = function() {
this.pushCx()
this.expect(tt.parenL)
let val = this.parseExpression()
this.popCx()
this.expect(tt.parenR)
return val
}
lp.parseMaybeAssign = function(noIn) {
if (this.toks.isContextual("yield")) {
let node = this.startNode()
this.next()
if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
let start = this.storeCurrentPos()
let left = this.parseMaybeConditional(noIn)
if (this.tok.type.isAssign) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
}
return left
}
lp.parseMaybeConditional = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseExprOps(noIn)
if (this.eat(tt.question)) {
let node = this.startNodeAt(start)
node.test = expr
node.consequent = this.parseMaybeAssign()
node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent()
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
lp.parseExprOps = function(noIn) {
let start = this.storeCurrentPos()
let indent = this.curIndent, line = this.curLineStart
return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line)
}
lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) {
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left
let prec = this.tok.type.binop
if (prec != null && (!noIn || this.tok.type !== tt._in)) {
if (prec > minPrec) {
let node = this.startNodeAt(start)
node.left = left
node.operator = this.tok.value
this.next()
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) {
node.right = this.dummyIdent()
} else {
let rightStart = this.storeCurrentPos()
node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line)
}
this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression")
return this.parseExprOp(node, start, minPrec, noIn, indent, line)
}
}
return left
}
lp.parseMaybeUnary = function(sawUnary) {
let start = this.storeCurrentPos(), expr
if (this.tok.type.prefix) {
let node = this.startNode(), update = this.tok.type === tt.incDec
if (!update) sawUnary = true
node.operator = this.tok.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(true)
if (update) node.argument = this.checkLVal(node.argument)
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else if (this.tok.type === tt.ellipsis) {
let node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(sawUnary)
expr = this.finishNode(node, "SpreadElement")
} else {
expr = this.parseExprSubscripts()
while (this.tok.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.prefix = false
node.argument = this.checkLVal(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar)) {
let node = this.startNodeAt(start)
node.operator = "**"
node.left = expr
node.right = this.parseMaybeUnary(false)
return this.finishNode(node, "BinaryExpression")
}
return expr
}
lp.parseExprSubscripts = function() {
let start = this.storeCurrentPos()
return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart)
}
lp.parseSubscripts = function(base, start, noCalls, startIndent, line) {
for (;;) {
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) {
if (this.tok.type == tt.dot && this.curIndent == startIndent)
--startIndent
else
return base
}
if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine())
node.property = this.dummyIdent()
else
node.property = this.parsePropertyAccessor() || this.dummyIdent()
node.computed = false
base = this.finishNode(node, "MemberExpression")
} else if (this.tok.type == tt.bracketL) {
this.pushCx()
this.next()
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseExpression()
node.computed = true
this.popCx()
this.expect(tt.bracketR)
base = this.finishNode(node, "MemberExpression")
} else if (!noCalls && this.tok.type == tt.parenL) {
let node = this.startNodeAt(start)
node.callee = base
node.arguments = this.parseExprList(tt.parenR)
base = this.finishNode(node, "CallExpression")
} else if (this.tok.type == tt.backQuote) {
let node = this.startNodeAt(start)
node.tag = base
node.quasi = this.parseTemplate()
base = this.finishNode(node, "TaggedTemplateExpression")
} else {
return base
}
}
}
lp.parseExprAtom = function() {
let node
switch (this.tok.type) {
case tt._this:
case tt._super:
let type = this.tok.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
let start = this.storeCurrentPos()
let id = this.parseIdent()
return this.eat(tt.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id
case tt.regexp:
node = this.startNode()
let val = this.tok.value
node.regex = {pattern: val.pattern, flags: val.flags}
node.value = val.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt.num: case tt.string:
node = this.startNode()
node.value = this.tok.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true
node.raw = this.tok.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
let parenStart = this.storeCurrentPos()
this.next()
let inner = this.parseExpression()
this.expect(tt.parenR)
if (this.eat(tt.arrow)) {
return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner]))
}
if (this.options.preserveParens) {
let par = this.startNodeAt(parenStart)
par.expression = inner
inner = this.finishNode(par, "ParenthesizedExpression")
}
return inner
case tt.bracketL:
node = this.startNode()
node.elements = this.parseExprList(tt.bracketR, true)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj()
case tt._class:
return this.parseClass()
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
return this.dummyIdent()
}
}
lp.parseNew = function() {
let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
return this.finishNode(node, "MetaProperty")
}
let start = this.storeCurrentPos()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line)
if (this.tok.type == tt.parenL) {
node.arguments = this.parseExprList(tt.parenR)
} else {
node.arguments = []
}
return this.finishNode(node, "NewExpression")
}
lp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'),
cooked: this.tok.value
}
this.next()
elem.tail = this.tok.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
lp.parseTemplate = function() {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this.next()
node.expressions.push(this.parseExpression())
if (this.expect(tt.braceR)) {
curElt = this.parseTemplateElement()
} else {
curElt = this.startNode()
curElt.value = {cooked: '', raw: ''}
curElt.tail = true
}
node.quasis.push(curElt)
}
this.expect(tt.backQuote)
return this.finishNode(node, "TemplateLiteral")
}
lp.parseObj = function() {
let node = this.startNode()
node.properties = []
this.pushCx()
let indent = this.curIndent + 1, line = this.curLineStart
this.eat(tt.braceL)
if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart }
while (!this.closes(tt.braceR, indent, line)) {
let prop = this.startNode(), isGenerator, start
if (this.options.ecmaVersion >= 6) {
start = this.storeCurrentPos()
prop.method = false
prop.shorthand = false
isGenerator = this.eat(tt.star)
}
this.parsePropertyName(prop)
if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue }
if (this.eat(tt.colon)) {
prop.kind = "init"
prop.value = this.parseMaybeAssign()
} else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) {
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator)
} else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
!prop.computed && (prop.key.name === "get" || prop.key.name === "set") &&
(this.tok.type != tt.comma && this.tok.type != tt.braceR)) {
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
} else {
prop.kind = "init"
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.eq)) {
let assign = this.startNodeAt(start)
assign.operator = "="
assign.left = prop.key
assign.right = this.parseMaybeAssign()
prop.value = this.finishNode(assign, "AssignmentExpression")
} else {
prop.value = prop.key
}
} else {
prop.value = this.dummyIdent()
}
prop.shorthand = true
}
node.properties.push(this.finishNode(prop, "Property"))
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(tt.braceR)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return this.finishNode(node, "ObjectExpression")
}
lp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseExpression()
this.expect(tt.bracketR)
return
} else {
prop.computed = false
}
}
let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent()
prop.key = key || this.dummyIdent()
}
lp.parsePropertyAccessor = function() {
if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent()
}
lp.parseIdent = function() {
let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword
if (!name) return this.dummyIdent()
let node = this.startNode()
this.next()
node.name = name
return this.finishNode(node, "Identifier")
}
lp.initFunction = function(node) {
node.id = null
node.params = []
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
}
// Convert existing expression atom to assignable pattern
// if possible.
lp.toAssignable = function(node, binding) {
if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) {
// Okay
} else if (node.type == "ParenthesizedExpression") {
node.expression = this.toAssignable(node.expression, binding)
} else if (this.options.ecmaVersion < 6) {
return this.dummyIdent()
} else if (node.type == "ObjectExpression") {
node.type = "ObjectPattern"
let props = node.properties
for (let i = 0; i < props.length; i++)
props[i].value = this.toAssignable(props[i].value, binding)
} else if (node.type == "ArrayExpression") {
node.type = "ArrayPattern"
this.toAssignableList(node.elements, binding)
} else if (node.type == "SpreadElement") {
node.type = "RestElement"
node.argument = this.toAssignable(node.argument, binding)
} else if (node.type == "AssignmentExpression") {
node.type = "AssignmentPattern"
delete node.operator
} else {
return this.dummyIdent()
}
return node
}
lp.toAssignableList = function(exprList, binding) {
for (let i = 0; i < exprList.length; i++)
exprList[i] = this.toAssignable(exprList[i], binding)
return exprList
}
lp.parseFunctionParams = function(params) {
params = this.parseExprList(tt.parenR)
return this.toAssignableList(params, true)
}
lp.parseMethod = function(isGenerator) {
let node = this.startNode()
this.initFunction(node)
node.params = this.parseFunctionParams()
node.generator = isGenerator || false
node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "FunctionExpression")
}
lp.parseArrowExpression = function(node, params) {
this.initFunction(node)
node.params = this.toAssignableList(params, true)
node.expression = this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "ArrowFunctionExpression")
}
lp.parseExprList = function(close, allowEmpty) {
this.pushCx()
let indent = this.curIndent, line = this.curLineStart, elts = []
this.next() // Opening bracket
while (!this.closes(close, indent + 1, line)) {
if (this.eat(tt.comma)) {
elts.push(allowEmpty ? null : this.dummyIdent())
continue
}
let elt = this.parseMaybeAssign()
if (isDummy(elt)) {
if (this.closes(close, indent, line)) break
this.next()
} else {
elts.push(elt)
}
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(close)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return elts
}
| eddyerburgh/free-code-camp-ziplines | react-projects/markdown-previewer/node_modules/is-expression/node_modules/acorn/src/loose/expression.js | JavaScript | mit | 16,264 |
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("SolverFoundation.Plugin.Z3.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SolverFoundation.Plugin.Z3.Tests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("27657eee-ca7b-4996-a905-86a3f4584988")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| seahorn/z3 | examples/msf/SolverFoundation.Plugin.Z3.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,440 |
<?php
namespace Elasticsearch\Endpoints\Indices\Gateway;
use Elasticsearch\Endpoints\AbstractEndpoint;
/**
* Class Snapshot
*
* @category Elasticsearch
* @package Elasticsearch\Endpoints\Indices\Gateway
* @author Zachary Tong <zachary.tong@elasticsearch.com>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elasticsearch.org
*/
class Snapshot extends AbstractEndpoint
{
/**
* @return string
*/
protected function getURI()
{
$index = $this->index;
$uri = "/_gateway/snapshot";
if (isset($index) === true) {
$uri = "/$index/_gateway/snapshot";
}
return $uri;
}
/**
* @return string[]
*/
protected function getParamWhitelist()
{
return [
'ignore_unavailable',
'allow_no_indices',
'expand_wildcards',
];
}
/**
* @return string
*/
protected function getMethod()
{
return 'POST';
}
}
| quitedensepoint/Devel1 | vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/Indices/Gateway/Snapshot.php | PHP | gpl-2.0 | 1,020 |
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation, and provided that the
following conditions are met:
* Redistributions of source code must retain this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below).
* Redistributions in binary form must reproduce this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below) in the documentation and/or other materials
provided with the distribution.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
COPYRIGHT NOTICE:
TokuDB, Tokutek Fractal Tree Indexing Library.
Copyright (C) 2007-2013 Tokutek, Inc.
DISCLAIMER:
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
UNIVERSITY PATENT NOTICE:
The technology is licensed by the Massachusetts Institute of
Technology, Rutgers State University of New Jersey, and the Research
Foundation of State University of New York at Stony Brook under
United States of America Serial No. 11/760379 and to the patents
and/or patent applications resulting from it.
PATENT MARKING NOTICE:
This software is covered by US Patent No. 8,185,551.
PATENT RIGHTS GRANT:
"THIS IMPLEMENTATION" means the copyrightable works distributed by
Tokutek as part of the Fractal Tree project.
"PATENT CLAIMS" means the claims of patents that are owned or
licensable by Tokutek, both currently or in the future; and that in
the absence of this license would be infringed by THIS
IMPLEMENTATION or by using or running THIS IMPLEMENTATION.
"PATENT CHALLENGE" shall mean a challenge to the validity,
patentability, enforceability and/or non-infringement of any of the
PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.
Tokutek hereby grants to you, for the term and geographical scope of
the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and
otherwise run, modify, and propagate the contents of THIS
IMPLEMENTATION, where such license applies only to the PATENT
CLAIMS. This grant does not include claims that would be infringed
only as a consequence of further modifications of THIS
IMPLEMENTATION. If you or your agent or licensee institute or order
or agree to the institution of patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that
THIS IMPLEMENTATION constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any rights
granted to you under this License shall terminate as of the date
such litigation is filed. If you or your agent or exclusive
licensee institute or order or agree to the institution of a PATENT
CHALLENGE, then Tokutek may terminate any rights granted to you
under this License.
*/
#ident "Copyright (c) 2011-2013 Tokutek Inc. All rights reserved."
// generate a tree with a single leaf node containing duplicate keys
// check that brt verify finds them
#include <ft-cachetable-wrappers.h>
#include "test.h"
static FTNODE
make_node(FT_HANDLE brt, int height) {
FTNODE node = NULL;
int n_children = (height == 0) ? 1 : 0;
toku_create_new_ftnode(brt, &node, height, n_children);
if (n_children) BP_STATE(node,0) = PT_AVAIL;
return node;
}
static void
append_leaf(FTNODE leafnode, void *key, size_t keylen, void *val, size_t vallen) {
assert(leafnode->height == 0);
DBT thekey; toku_fill_dbt(&thekey, key, keylen);
DBT theval; toku_fill_dbt(&theval, val, vallen);
// get an index that we can use to create a new leaf entry
uint32_t idx = toku_omt_size(BLB_BUFFER(leafnode, 0));
// apply an insert to the leaf node
MSN msn = next_dummymsn();
FT_MSG_S cmd = { FT_INSERT, msn, xids_get_root_xids(), .u={.id = { &thekey, &theval }} };
toku_ft_bn_apply_cmd_once(BLB(leafnode, 0), &cmd, idx, NULL, TXNID_NONE, make_gc_info(false), NULL, NULL);
// dont forget to dirty the node
leafnode->dirty = 1;
}
static void
populate_leaf(FTNODE leafnode, int k, int v) {
append_leaf(leafnode, &k, sizeof k, &v, sizeof v);
}
static void
test_dup_in_leaf(int do_verify) {
int r;
// cleanup
const char *fname = TOKU_TEST_FILENAME;
r = unlink(fname);
assert(r == 0 || (r == -1 && errno == ENOENT));
// create a cachetable
CACHETABLE ct = NULL;
toku_cachetable_create(&ct, 0, ZERO_LSN, NULL_LOGGER);
// create the brt
TOKUTXN null_txn = NULL;
FT_HANDLE brt = NULL;
r = toku_open_ft_handle(fname, 1, &brt, 1024, 256, TOKU_DEFAULT_COMPRESSION_METHOD, ct, null_txn, toku_builtin_compare_fun);
assert(r == 0);
// discard the old root block
FTNODE newroot = make_node(brt, 0);
populate_leaf(newroot, htonl(2), 1);
populate_leaf(newroot, htonl(2), 2);
// set the new root to point to the new tree
toku_ft_set_new_root_blocknum(brt->ft, newroot->thisnodename);
// unpin the new root
toku_unpin_ftnode(brt->ft, newroot);
if (do_verify) {
r = toku_verify_ft(brt);
assert(r != 0);
}
// flush to the file system
r = toku_close_ft_handle_nolsn(brt, 0);
assert(r == 0);
// shutdown the cachetable
toku_cachetable_close(&ct);
}
static int
usage(void) {
return 1;
}
int
test_main (int argc , const char *argv[]) {
int do_verify = 1;
initialize_dummymsn();
for (int i = 1; i < argc; i++) {
const char *arg = argv[i];
if (strcmp(arg, "-v") == 0) {
verbose++;
continue;
}
if (strcmp(arg, "-q") == 0) {
verbose = 0;
continue;
}
if (strcmp(arg, "--verify") == 0 && i+1 < argc) {
do_verify = atoi(argv[++i]);
continue;
}
return usage();
}
test_dup_in_leaf(do_verify);
return 0;
}
| YannNayn/mariadb-galera-msvc | storage/tokudb/ft-index/ft/tests/verify-dup-in-leaf.cc | C++ | gpl-2.0 | 6,838 |
<?php
// see : http://wordpress.org/support/topic/plugin-nextgen-gallery-ngg-and-featured-image-issue?replies=14
/**
* nggPostThumbnail - Class for adding the post thumbnail feature
*
* @package NextGEN Gallery
* @author Alex Rabe
*
* @version 1.0.2
* @access internal
*/
class nggPostThumbnail {
/**
* PHP4 compatibility layer for calling the PHP5 constructor.
*
*/
function nggPostThumbnail() {
return $this->__construct();
}
/**
* Main constructor - Add filter and action hooks
*
*/
function __construct() {
add_filter( 'admin_post_thumbnail_html', array( $this, 'admin_post_thumbnail'), 10, 2 );
add_action( 'wp_ajax_ngg_set_post_thumbnail', array( $this, 'ajax_set_post_thumbnail') );
// Adding filter for the new post_thumbnail
add_filter( 'post_thumbnail_html', array( $this, 'ngg_post_thumbnail'), 10, 5 );
return;
}
/**
* Filter for the post meta box. look for a NGG image if the ID is "ngg-<imageID>"
*
* @param string $content
* @return string html output
*/
function admin_post_thumbnail( $content, $post_id = null )
{
if ($post_id == null)
{
global $post;
if ( !is_object($post) )
return $content;
$post_id = $post->ID;
}
$thumbnail_id = get_post_meta($post_id, '_thumbnail_id', true);
// in the case it's a ngg image it return ngg-<imageID>
if ( strpos($thumbnail_id, 'ngg-') === false)
{
global $wp_version;
if (version_compare($wp_version, '3.5', '>=') && $thumbnail_id <= 0)
{
$iframe_src = get_upload_iframe_src('image');
$iframe_src = remove_query_arg('TB_iframe', $iframe_src);
$iframe_src = add_query_arg('tab', 'nextgen', $iframe_src);
$iframe_src = add_query_arg('chromeless', '1', $iframe_src);
$iframe_src = add_query_arg('TB_iframe', '1', $iframe_src);
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set NextGEN featured image' ) . '" href="' . nextgen_esc_url( $iframe_src ) . '" id="set-ngg-post-thumbnail" class="thickbox">%s</a></p>';
$content .= sprintf($set_thumbnail_link, esc_html__( 'Set NextGEN featured image' ));
}
return $content;
}
// cut off the 'ngg-'
$thumbnail_id = substr( $thumbnail_id, 4);
return $this->_wp_post_thumbnail_html( $thumbnail_id );
}
/**
* Filter for the post content
*
* @param string $html
* @param int $post_id
* @param int $post_thumbnail_id
* @param string|array $size Optional. Image size. Defaults to 'thumbnail'.
* @param string|array $attr Optional. Query string or array of attributes.
* @return string html output
*/
function ngg_post_thumbnail( $html, $post_id, $post_thumbnail_id, $size = 'post-thumbnail', $attr = '' ) {
global $post, $_wp_additional_image_sizes;
// in the case it's a ngg image it return ngg-<imageID>
if ( strpos($post_thumbnail_id, 'ngg-') === false)
return $html;
// cut off the 'ngg-'
$post_thumbnail_id = substr( $post_thumbnail_id, 4);
// get the options
$ngg_options = nggGallery::get_option('ngg_options');
// get the image data
$image = nggdb::find_image($post_thumbnail_id);
if (!$image)
return $html;
$img_src = false;
$class = 'wp-post-image ngg-image-' . $image->pid . ' ';
if (is_array($size) || is_array($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes[$size])) {
$class .= isset($attr['class']) ? esc_attr($attr['class']) : '';
if( is_array($size)){
//the parameters is given as an array rather than a predfined image
$width = absint( $size[0] );
$height = absint( $size[1] );
if(isset($size[2]) && $size[2] === true) {
$mode = 'crop';
} else if(isset($size[2])){
$mode = $size[2];
} else {
$mode = '';
}
} else {
$width = absint( $_wp_additional_image_sizes[$size]['width'] );
$height = absint( $_wp_additional_image_sizes[$size]['height'] );
$mode = ($_wp_additional_image_sizes[$size]['crop']) ? 'crop' : '';
}
// check fo cached picture
if ( $post->post_status == 'publish' )
$img_src = $image->cached_singlepic_file( $width, $height, $mode );
// if we didn't use a cached image then we take the on-the-fly mode
if ($img_src == false)
$img_src = trailingslashit( home_url() ) . 'index.php?callback=image&pid=' . $image->pid . '&width=' . $width . '&height=' . $height . '&mode=crop';
} else {
$img_src = $image->thumbURL;
}
$alttext = isset($attr['alt']) ? $attr['alt'] : $image->alttext;
$titletext = isset($attr['title']) ? $attr['title'] : $image->title;
$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alttext) . '" title="' . esc_attr($titletext) .'" class="'.$class.'" />';
return $html;
}
/**
* nggPostThumbnail::ajax_set_post_thumbnail()
*
* @return void
*/
function ajax_set_post_thumbnail()
{
global $post_ID;
// check for correct capability
if ( !is_user_logged_in() )
die( '-1' );
// get the post id as global variable, otherwise the ajax_nonce failed later
$post_ID = intval( $_POST['post_id'] );
if ( !current_user_can( 'edit_post', $post_ID ) )
die( '-1' );
$thumbnail_id = intval( $_POST['thumbnail_id'] );
// delete the image
if ( $thumbnail_id == '-1' ) {
delete_post_meta( $post_ID, '_thumbnail_id' );
die('0');
}
if ($thumbnail_id != null)
{
$registry = C_Component_Registry::get_instance();
$imap = $registry->get_utility('I_Image_Mapper');
$storage = $registry->get_utility('I_Gallery_Storage');
$image = $imap->find($thumbnail_id);
// for NGG we look for the image id
if ($image)
{
$image_id = $thumbnail_id;
$args = array(
'post_type' => 'attachment',
'meta_key' => '_ngg_image_id',
'meta_compare' => '==',
'meta_value' => $image_id
);
$upload_dir = wp_upload_dir();
$basedir = $upload_dir['basedir'];
$thumbs_dir = path_join($basedir, 'ngg_featured');
$gallery_abspath = $storage->get_gallery_abspath($image->galleryid);
$image_abspath = $storage->get_full_abspath($image);
$target_path = null;
$posts = get_posts($args);
$attachment_id = null;
if ($posts != null)
{
$attachment_id = $posts[0]->ID;
}
else
{
$url = $storage->get_full_url($image);
$target_relpath = null;
$target_basename = basename($image_abspath);
if (strpos($image_abspath, $gallery_abspath) === 0)
{
$target_relpath = substr($image_abspath, strlen($gallery_abspath));
}
else if ($image->galleryid)
{
$target_relpath = path_join(strval($image->galleryid), $target_basename);
}
else
{
$target_relpath = $target_basename;
}
$target_relpath = trim($target_relpath, '\\/');
$target_path = path_join($thumbs_dir, $target_relpath);
$max_count = 100;
$count = 0;
while (file_exists($target_path) && $count <= $max_count)
{
$count++;
$pathinfo = pathinfo($target_path);
$dirname = $pathinfo['dirname'];
$filename = $pathinfo['filename'];
$extension = $pathinfo['extension'];
$rand = mt_rand(1, 9999);
$basename = $filename . '_' . sprintf('%04d', $rand) . '.' . $extension;
$target_path = path_join($dirname, $basename);
}
if (file_exists($target_path))
{
// XXX handle very rare case in which $max_count wasn't enough?
}
$target_dir = dirname($target_path);
wp_mkdir_p($target_dir);
if (@copy($image_abspath, $target_path))
{
$size = @getimagesize($target_path);
$image_type = ($size) ? $size['mime'] : 'image/jpeg';
$title = sanitize_file_name($image->alttext);
$caption = sanitize_file_name($image->description);
$attachment = array(
'post_title' => $title,
'post_content' => $caption,
'post_status' => 'attachment',
'post_parent' => 0,
'post_mime_type' => $image_type,
'guid' => $url
);
// Save the data
$attachment_id = wp_insert_attachment($attachment, $target_path);
if ($attachment_id)
{
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $target_path));
update_post_meta($attachment_id, '_ngg_image_id', $image_id);
}
}
}
if ($attachment_id)
{
//$attachment = get_post($attachment_id);
//$attachment_meta = wp_get_attachment_metadata($attachment_id);
$attachment_file = get_attached_file($attachment_id);
$target_path = $attachment_file;
if (filemtime($image_abspath) > filemtime($target_path))
{
if (@copy($image_abspath, $target_path))
{
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $target_path));
}
}
die(strval($attachment_id));
}
}
}
die('0');
}
/**
* Output HTML for the post thumbnail meta-box.
*
* @see wp-admin\includes\post.php
* @param int $thumbnail_id ID of the image used for thumbnail
* @return string html output
*/
function _wp_post_thumbnail_html( $thumbnail_id = NULL ) {
global $_wp_additional_image_sizes, $post_ID;
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="' . nextgen_esc_url( get_upload_iframe_src('image') ) . '" id="set-post-thumbnail" class="thickbox">%s</a></p>';
$content = sprintf($set_thumbnail_link, esc_html__( 'Set featured image' ));
$image = nggdb::find_image($thumbnail_id);
$img_src = false;
// get the options
$ngg_options = nggGallery::get_option('ngg_options');
if ( $image ) {
if ( is_array($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes['post-thumbnail']) ){
// Use post thumbnail settings if defined
$width = absint( $_wp_additional_image_sizes['post-thumbnail']['width'] );
$height = absint( $_wp_additional_image_sizes['post-thumbnail']['height'] );
$mode = $_wp_additional_image_sizes['post-thumbnail']['crop'] ? 'crop' : '';
// check fo cached picture
$img_src = $image->cached_singlepic_file( $width, $height, $mode );
}
// if we didn't use a cached image then we take the on-the-fly mode
if ( $img_src == false )
$img_src = trailingslashit( home_url() ) . 'index.php?callback=image&pid=' . $image->pid . '&width=' . $width . '&height=' . $height . '&mode=crop';
$thumbnail_html = '<img width="266" src="'. $img_src . '" alt="'.$image->alttext.'" title="'.$image->alttext.'" />';
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( "set_post_thumbnail-$post_ID" );
$content = sprintf($set_thumbnail_link, $thumbnail_html);
$content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>';
}
}
return $content;
}
}
$nggPostThumbnail = new nggPostThumbnail();
| rakeybulhasan/IAPP | wp-content/plugins/nextgen-gallery/products/photocrati_nextgen/modules/ngglegacy/lib/post-thumbnail.php | PHP | gpl-2.0 | 11,431 |
<?php
/**
* @package AkeebaBackup
* @copyright Copyright (c)2009-2014 Nicholas K. Dionysopoulos
* @license GNU General Public License version 3, or later
*
* @since 1.3
*/
// Protect from unauthorized access
defined('_JEXEC') or die();
/**
* MVC View for Log
*
*/
class AkeebaViewLog extends FOFViewHtml
{
public function onBrowse($tpl = null)
{
// Add live help
AkeebaHelperIncludes::addHelp('log');
// Get a list of log names
$model = $this->getModel();
$this->logs = $model->getLogList();
$tag = $model->getState('tag');
if(empty($tag)) $tag = null;
$this->tag = $tag;
// Get profile ID
$profileid = AEPlatform::getInstance()->get_active_profile();
$this->profileid = $profileid;
// Get profile name
$pmodel = FOFModel::getAnInstance('Profiles', 'AkeebaModel');
$pmodel->setId($profileid);
$profile_data = $pmodel->getItem();
$this->profilename = $profile_data->description;
return true;
}
public function onIframe($tpl = null)
{
$model = $this->getModel();
$tag = $model->getState('tag');
if(empty($tag)) $tag = null;
$this->tag = $tag;
return true;
}
} | apachish/tariin | log/administrator/components/com_akeeba/views/log/view.html.php | PHP | gpl-2.0 | 1,128 |
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faGrinHearts: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | cstrassburg/smarthome | modules/http/webif/gstatic/fontawesome/advanced-options/use-with-node-js/free-solid-svg-icons/faGrinHearts.d.ts | TypeScript | gpl-3.0 | 399 |
<?php
class Avada_Helper {
/**
* Return the value of an echo.
* example: Avada_Helper::get_echo( 'function' );
*/
public static function get_echo( $function, $args = '' ) {
// Early exit if function does not exist
if ( ! function_exists( $function ) ) {
return;
}
ob_start();
$function( $args );
$get_echo = ob_get_clean();
return $get_echo;
}
public static function slider_name( $name ) {
$type = '';
switch( $name ) {
case 'layer':
$type = 'slider';
break;
case 'flex':
$type = 'wooslider';
break;
case 'rev':
$type = 'revslider';
break;
case 'elastic':
$type = 'elasticslider';
break;
}
return $type;
}
public static function get_slider_type( $post_id ) {
return get_post_meta( $post_id, 'pyre_slider_type', true );
}
}
// Omit closing PHP tag to avoid "Headers already sent" issues.
| Skyrant/escortmissions.net | wp-content/themes/pereira/includes/class-avada-helper.php | PHP | gpl-3.0 | 929 |
using System.Collections.Generic;
using Nancy.Metadata.Module;
using Nancy.Swagger;
using OmniSharp.Common;
namespace OmniSharp.CurrentFileMembers.Metadata
{
public class CurrentFileMembersAsFlatMetadataModule : MetadataModule<SwaggerRouteData>
{
public CurrentFileMembersAsFlatMetadataModule()
{
Describe["CurrentFileMembersAsFlat"] = desc => desc.AsSwagger(builder => builder
.ResourcePath("/currentfilemembersasflat")
.BodyParam<CurrentFileMembersRequest>()
.Response(200)
.Model<IEnumerable<QuickFix>>());
}
}
}
| alexrao/YouCompleteMe | third_party/ycmd/third_party/OmniSharpServer/OmniSharp/CurrentFileMembers/Metadata/CurrentFileMembersAsFlatMetadataModule.cs | C# | gpl-3.0 | 632 |
#
# Copyright (C) 2011 - 2015 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas 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, version 3 of the License.
#
# Canvas 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/>.
#
class Oauth2ProviderController < ApplicationController
protect_from_forgery :except => [:token, :destroy]
before_filter :run_login_hooks, :only => [:token]
skip_before_filter :require_reacceptance_of_terms
def auth
if params[:code] || params[:error]
# hopefully the user never sees this, since it's an oob response and the
# browser should be closed automatically. but we'll at least display
# something basic.
return render()
end
scopes = params.fetch(:scopes, '').split(',')
provider = Canvas::Oauth::Provider.new(params[:client_id], params[:redirect_uri], scopes, params[:purpose])
return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key?
return render(:status => 400, :json => { :message => "invalid redirect_uri" }) unless provider.has_valid_redirect?
session[:oauth2] = provider.session_hash
session[:oauth2][:state] = params[:state] if params.key?(:state)
if @current_pseudonym && !params[:force_login]
redirect_to Canvas::Oauth::Provider.confirmation_redirect(self, provider, @current_user)
else
redirect_to login_url(params.slice(:canvas_login, :pseudonym_session, :force_login, :authentication_provider))
end
end
def confirm
if session[:oauth2]
@provider = Canvas::Oauth::Provider.new(session[:oauth2][:client_id], session[:oauth2][:redirect_uri], session[:oauth2][:scopes], session[:oauth2][:purpose])
if mobile_device?
js_env :GOOGLE_ANALYTICS_KEY => Setting.get('google_analytics_key', nil)
render :layout => 'mobile_auth', :action => 'confirm_mobile'
end
else
flash[:error] = t("Must submit new OAuth2 request")
redirect_to login_url
end
end
def accept
redirect_params = Canvas::Oauth::Provider.final_redirect_params(session[:oauth2], @current_user, remember_access: params[:remember_access])
redirect_to Canvas::Oauth::Provider.final_redirect(self, redirect_params)
end
def deny
redirect_to Canvas::Oauth::Provider.final_redirect(self, :error => "access_denied")
end
def token
basic_user, basic_pass = ActionController::HttpAuthentication::Basic.user_name_and_password(request) if request.authorization
client_id = params[:client_id].presence || basic_user
secret = params[:client_secret].presence || basic_pass
provider = Canvas::Oauth::Provider.new(client_id)
return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key?
return render(:status => 400, :json => { :message => "invalid client_secret" }) unless provider.is_authorized_by?(secret)
token = provider.token_for(params[:code])
return render(:status => 400, :json => { :message => "invalid code" }) unless token.is_for_valid_code?
token.create_access_token_if_needed(value_to_boolean(params[:replace_tokens]))
Canvas::Oauth::Token.expire_code(params[:code])
render :json => token
end
def destroy
logout_current_user if params[:expire_sessions]
return render :json => { :message => "can't delete OAuth access token when not using an OAuth access token" }, :status => 400 unless @access_token
@access_token.destroy
render :json => {}
end
end
| Rvor/canvas-lms | app/controllers/oauth2_provider_controller.rb | Ruby | agpl-3.0 | 3,946 |
/**
* Shopware 4.0
* Copyright © 2012 shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Login
* @subpackage Model
* @copyright Copyright (c) 2012, shopware AG (http://www.shopware.de)
* @version $Id$
* @author shopware AG
*/
/**
* Shopware Backend - ErrorReporter Main Model
*
* todo@all: Documentation
*/
Ext.define('Shopware.apps.UserManager.model.Locale', {
extend: 'Ext.data.Model',
fields: [ 'id', 'name' ]
}); | OliverZachau/shopware-4 | templates/_default/backend/user_manager/model/locale.js | JavaScript | agpl-3.0 | 1,318 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Captcha
* @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();
$table = $installer->getConnection()
->newTable($installer->getTable('captcha/log'))
->addColumn('type', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array(
'nullable' => false,
'primary' => true,
), 'Type')
->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array(
'nullable' => false,
'unsigned' => true,
'primary' => true,
), 'Value')
->addColumn('count', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Count')
->addColumn('updated_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(), 'Update Time')
->setComment('Count Login Attempts');
$installer->getConnection()->createTable($table);
$installer->endSetup();
| dbashyal/MagentoStarterBase | trunk/app/code/core/Mage/Captcha/sql/captcha_setup/install-1.7.0.0.0.php | PHP | lgpl-3.0 | 1,868 |
/*
* 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.flink.runtime.operators.hash;
import org.apache.flink.api.common.typeutils.GenericPairComparator;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypePairComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.base.ByteValueSerializer;
import org.apache.flink.api.common.typeutils.base.LongComparator;
import org.apache.flink.api.common.typeutils.base.LongSerializer;
import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArrayComparator;
import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.runtime.TupleComparator;
import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
import org.apache.flink.api.java.typeutils.runtime.ValueComparator;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
import org.apache.flink.types.ByteValue;
import org.apache.flink.util.MutableObjectIterator;
import org.junit.Test;
import org.junit.Assert;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class HashTableTest {
private final TypeSerializer<Tuple2<Long, byte[]>> buildSerializer;
private final TypeSerializer<Long> probeSerializer;
private final TypeComparator<Tuple2<Long, byte[]>> buildComparator;
private final TypeComparator<Long> probeComparator;
private final TypePairComparator<Long, Tuple2<Long, byte[]>> pairComparator;
public HashTableTest() {
TypeSerializer<?>[] fieldSerializers = { LongSerializer.INSTANCE, BytePrimitiveArraySerializer.INSTANCE };
@SuppressWarnings("unchecked")
Class<Tuple2<Long, byte[]>> clazz = (Class<Tuple2<Long, byte[]>>) (Class<?>) Tuple2.class;
this.buildSerializer = new TupleSerializer<Tuple2<Long, byte[]>>(clazz, fieldSerializers);
this.probeSerializer = LongSerializer.INSTANCE;
TypeComparator<?>[] comparators = { new LongComparator(true) };
TypeSerializer<?>[] comparatorSerializers = { LongSerializer.INSTANCE };
this.buildComparator = new TupleComparator<Tuple2<Long, byte[]>>(new int[] {0}, comparators, comparatorSerializers);
this.probeComparator = new LongComparator(true);
this.pairComparator = new TypePairComparator<Long, Tuple2<Long, byte[]>>() {
private long ref;
@Override
public void setReference(Long reference) {
ref = reference;
}
@Override
public boolean equalToReference(Tuple2<Long, byte[]> candidate) {
//noinspection UnnecessaryUnboxing
return candidate.f0.longValue() == ref;
}
@Override
public int compareToReference(Tuple2<Long, byte[]> candidate) {
long x = ref;
long y = candidate.f0;
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
};
}
// ------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------
/**
* This tests a combination of values that lead to a corner case situation where memory
* was missing and the computation deadlocked.
*/
@Test
public void testBufferMissingForProbing() {
final IOManager ioMan = new IOManagerAsync();
try {
final int pageSize = 32*1024;
final int numSegments = 34;
final int numRecords = 3400;
final int recordLen = 270;
final byte[] payload = new byte[recordLen - 8 - 4];
List<MemorySegment> memory = getMemory(numSegments, pageSize);
MutableHashTable<Tuple2<Long, byte[]>, Long> table = new MutableHashTable<>(
buildSerializer, probeSerializer, buildComparator, probeComparator,
pairComparator, memory, ioMan, 16, false);
table.open(new TupleBytesIterator(payload, numRecords), new LongIterator(10000));
try {
while (table.nextRecord()) {
MutableObjectIterator<Tuple2<Long, byte[]>> matches = table.getBuildSideIterator();
while (matches.next() != null);
}
}
catch (RuntimeException e) {
if (!e.getMessage().contains("exceeded maximum number of recursions")) {
e.printStackTrace();
fail("Test failed with unexpected exception");
}
}
finally {
table.close();
}
checkNoTempFilesRemain(ioMan);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
finally {
ioMan.shutdown();
}
}
/**
* This tests the case where no additional partition buffers are used at the point when spilling
* is triggered, testing that overflow bucket buffers are taken into account when deciding which
* partition to spill.
*/
@Test
public void testSpillingFreesOnlyOverflowSegments() {
final IOManager ioMan = new IOManagerAsync();
final TypeSerializer<ByteValue> serializer = ByteValueSerializer.INSTANCE;
final TypeComparator<ByteValue> buildComparator = new ValueComparator<>(true, ByteValue.class);
final TypeComparator<ByteValue> probeComparator = new ValueComparator<>(true, ByteValue.class);
@SuppressWarnings("unchecked")
final TypePairComparator<ByteValue, ByteValue> pairComparator = Mockito.mock(TypePairComparator.class);
try {
final int pageSize = 32*1024;
final int numSegments = 34;
List<MemorySegment> memory = getMemory(numSegments, pageSize);
MutableHashTable<ByteValue, ByteValue> table = new MutableHashTable<>(
serializer, serializer, buildComparator, probeComparator,
pairComparator, memory, ioMan, 1, false);
table.open(new ByteValueIterator(100000000), new ByteValueIterator(1));
table.close();
checkNoTempFilesRemain(ioMan);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
finally {
ioMan.shutdown();
}
}
/**
* Tests that the MutableHashTable spills its partitions when creating the initial table
* without overflow segments in the partitions. This means that the records are large.
*/
@Test
public void testSpillingWhenBuildingTableWithoutOverflow() throws Exception {
final IOManager ioMan = new IOManagerAsync();
final TypeSerializer<byte[]> serializer = BytePrimitiveArraySerializer.INSTANCE;
final TypeComparator<byte[]> buildComparator = new BytePrimitiveArrayComparator(true);
final TypeComparator<byte[]> probeComparator = new BytePrimitiveArrayComparator(true);
@SuppressWarnings("unchecked")
final TypePairComparator<byte[], byte[]> pairComparator = new GenericPairComparator<>(
new BytePrimitiveArrayComparator(true), new BytePrimitiveArrayComparator(true));
final int pageSize = 128;
final int numSegments = 33;
List<MemorySegment> memory = getMemory(numSegments, pageSize);
MutableHashTable<byte[], byte[]> table = new MutableHashTable<byte[], byte[]>(
serializer,
serializer,
buildComparator,
probeComparator,
pairComparator,
memory,
ioMan,
1,
false);
int numElements = 9;
table.open(
new CombiningIterator<byte[]>(
new ByteArrayIterator(numElements, 128,(byte) 0),
new ByteArrayIterator(numElements, 128,(byte) 1)),
new CombiningIterator<byte[]>(
new ByteArrayIterator(1, 128,(byte) 0),
new ByteArrayIterator(1, 128,(byte) 1)));
while(table.nextRecord()) {
MutableObjectIterator<byte[]> iterator = table.getBuildSideIterator();
int counter = 0;
while(iterator.next() != null) {
counter++;
}
// check that we retrieve all our elements
Assert.assertEquals(numElements, counter);
}
table.close();
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
private static List<MemorySegment> getMemory(int numSegments, int segmentSize) {
ArrayList<MemorySegment> list = new ArrayList<MemorySegment>(numSegments);
for (int i = 0; i < numSegments; i++) {
list.add(MemorySegmentFactory.allocateUnpooledSegment(segmentSize));
}
return list;
}
private static void checkNoTempFilesRemain(IOManager ioManager) {
for (File dir : ioManager.getSpillingDirectories()) {
for (String file : dir.list()) {
if (file != null && !(file.equals(".") || file.equals(".."))) {
fail("hash table did not clean up temp files. remaining file: " + file);
}
}
}
}
private static class TupleBytesIterator implements MutableObjectIterator<Tuple2<Long, byte[]>> {
private final byte[] payload;
private final int numRecords;
private int count = 0;
TupleBytesIterator(byte[] payload, int numRecords) {
this.payload = payload;
this.numRecords = numRecords;
}
@Override
public Tuple2<Long, byte[]> next(Tuple2<Long, byte[]> reuse) {
return next();
}
@Override
public Tuple2<Long, byte[]> next() {
if (count++ < numRecords) {
return new Tuple2<>(42L, payload);
} else {
return null;
}
}
}
private static class ByteArrayIterator implements MutableObjectIterator<byte[]> {
private final long numRecords;
private long counter = 0;
private final byte[] arrayValue;
ByteArrayIterator(long numRecords, int length, byte value) {
this.numRecords = numRecords;
arrayValue = new byte[length];
Arrays.fill(arrayValue, value);
}
@Override
public byte[] next(byte[] array) {
return next();
}
@Override
public byte[] next() {
if (counter++ < numRecords) {
return arrayValue;
} else {
return null;
}
}
}
private static class LongIterator implements MutableObjectIterator<Long> {
private final long numRecords;
private long value = 0;
LongIterator(long numRecords) {
this.numRecords = numRecords;
}
@Override
public Long next(Long aLong) {
return next();
}
@Override
public Long next() {
if (value < numRecords) {
return value++;
} else {
return null;
}
}
}
private static class ByteValueIterator implements MutableObjectIterator<ByteValue> {
private final long numRecords;
private long value = 0;
ByteValueIterator(long numRecords) {
this.numRecords = numRecords;
}
@Override
public ByteValue next(ByteValue aLong) {
return next();
}
@Override
public ByteValue next() {
if (value++ < numRecords) {
return new ByteValue((byte) 0);
} else {
return null;
}
}
}
private static class CombiningIterator<T> implements MutableObjectIterator<T> {
private final MutableObjectIterator<T> left;
private final MutableObjectIterator<T> right;
public CombiningIterator(MutableObjectIterator<T> left, MutableObjectIterator<T> right) {
this.left = left;
this.right = right;
}
@Override
public T next(T reuse) throws IOException {
T value = left.next(reuse);
if (value == null) {
return right.next(reuse);
} else {
return value;
}
}
@Override
public T next() throws IOException {
T value = left.next();
if (value == null) {
return right.next();
} else {
return value;
}
}
}
}
| hongyuhong/flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/hash/HashTableTest.java | Java | apache-2.0 | 12,009 |
package com.avast.android.dialogs.core;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
/**
* Internal base builder that holds common values for all dialog fragment builders.
*
* @author Tomas Vondracek
*/
public abstract class BaseDialogBuilder<T extends BaseDialogBuilder<T>> {
public final static String ARG_REQUEST_CODE = "request_code";
public final static String ARG_CANCELABLE_ON_TOUCH_OUTSIDE = "cancelable_oto";
public final static String DEFAULT_TAG = "simple_dialog";
private String mTag = DEFAULT_TAG;
public final static int DEFAULT_REQUEST_CODE = -42;
private int mRequestCode = DEFAULT_REQUEST_CODE;
public static String ARG_USE_DARK_THEME = "usedarktheme";
public static String ARG_USE_LIGHT_THEME = "uselighttheme";
protected final Context mContext;
protected final FragmentManager mFragmentManager;
protected final Class<? extends BaseDialogFragment> mClass;
private Fragment mTargetFragment;
private boolean mCancelable = true;
private boolean mCancelableOnTouchOutside = true;
private boolean mUseDarkTheme = false;
private boolean mUseLightTheme = false;
public BaseDialogBuilder(Context context, FragmentManager fragmentManager, Class<? extends BaseDialogFragment> clazz) {
mFragmentManager = fragmentManager;
mContext = context.getApplicationContext();
mClass = clazz;
}
protected abstract T self();
protected abstract Bundle prepareArguments();
public T setCancelable(boolean cancelable) {
mCancelable = cancelable;
return self();
}
public T setCancelableOnTouchOutside(boolean cancelable) {
mCancelableOnTouchOutside = cancelable;
if (cancelable) {
mCancelable = cancelable;
}
return self();
}
public T setTargetFragment(Fragment fragment, int requestCode) {
mTargetFragment = fragment;
mRequestCode = requestCode;
return self();
}
public T setRequestCode(int requestCode) {
mRequestCode = requestCode;
return self();
}
public T setTag(String tag) {
mTag = tag;
return self();
}
public T useDarkTheme() {
mUseDarkTheme = true;
return self();
}
public T useLightTheme() {
mUseLightTheme = true;
return self();
}
private BaseDialogFragment create() {
final Bundle args = prepareArguments();
final BaseDialogFragment fragment = (BaseDialogFragment) Fragment.instantiate(mContext, mClass.getName(), args);
args.putBoolean(ARG_CANCELABLE_ON_TOUCH_OUTSIDE, mCancelableOnTouchOutside);
args.putBoolean(ARG_USE_DARK_THEME, mUseDarkTheme);
args.putBoolean(ARG_USE_LIGHT_THEME, mUseLightTheme);
if (mTargetFragment != null) {
fragment.setTargetFragment(mTargetFragment, mRequestCode);
} else {
args.putInt(ARG_REQUEST_CODE, mRequestCode);
}
fragment.setCancelable(mCancelable);
return fragment;
}
public DialogFragment show() {
BaseDialogFragment fragment = create();
fragment.show(mFragmentManager, mTag);
return fragment;
}
/**
* Like show() but allows the commit to be executed after an activity's state is saved. This
* is dangerous because the commit can be lost if the activity needs to later be restored from
* its state, so this should only be used for cases where it is okay for the UI state to change
* unexpectedly on the user.
*/
public DialogFragment showAllowingStateLoss() {
BaseDialogFragment fragment = create();
fragment.showAllowingStateLoss(mFragmentManager, mTag);
return fragment;
}
}
| jaohoang/android-styled-dialogs | library/src/main/java/com/avast/android/dialogs/core/BaseDialogBuilder.java | Java | apache-2.0 | 3,904 |
/*
* Copyright 2012-present Facebook, 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.
*/
package com.facebook.buck.graph;
import com.google.common.base.Preconditions;
public class DefaultDirectedAcyclicGraph<T> extends DefaultTraversableGraph<T>
implements DirectedAcyclicGraph<T> {
public DefaultDirectedAcyclicGraph(MutableDirectedGraph<T> graph) {
super(graph);
Preconditions.checkArgument(super.isAcyclic());
}
}
| janicduplessis/buck | src/com/facebook/buck/graph/DefaultDirectedAcyclicGraph.java | Java | apache-2.0 | 954 |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.gui.splash;
import java.awt.*;
/**
* This interface describes objects that can paint themselves, possibly varying
* as a function of time.
*
* @author Eric Lafortune
*/
public interface Sprite
{
/**
* Paints the object.
*
* @param graphics the Graphics to paint on.
* @param time the time since the start of the animation, expressed in
* milliseconds.
*/
public void paint(Graphics graphics, long time);
}
| damienmg/bazel | third_party/java/proguard/proguard5.3.3/src/proguard/gui/splash/Sprite.java | Java | apache-2.0 | 1,374 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine
{
internal sealed class Vbc : VisualBasicCompiler
{
internal Vbc(string responseFile, BuildPaths buildPaths, string[] args, IAnalyzerAssemblyLoader analyzerLoader)
: base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths.ClientDirectory, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, Environment.GetEnvironmentVariable("LIB"), analyzerLoader)
{
}
internal static int Run(string[] args, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
{
FatalError.Handler = FailFast.OnFatalException;
var responseFile = Path.Combine(buildPaths.ClientDirectory, VisualBasicCompiler.ResponseFileName);
var compiler = new Vbc(responseFile, buildPaths, args, analyzerLoader);
return ConsoleUtil.RunWithUtf8Output(compiler.Arguments.Utf8Output, textWriter, tw => compiler.Run(tw));
}
protected override uint GetSqmAppID()
{
return SqmServiceProvider.CSHARP_APPID;
}
protected override void CompilerSpecificSqm(IVsSqmMulti sqm, uint sqmSession)
{
sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_COMPILERTYPE, (uint)SqmServiceProvider.CompilerType.Compiler);
sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_LANGUAGEVERSION, (uint)Arguments.ParseOptions.LanguageVersion);
sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNINGLEVEL, (uint)Arguments.CompilationOptions.WarningLevel);
//Project complexity # of source files, # of references
sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_SOURCES, (uint)Arguments.SourceFiles.Count());
sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_REFERENCES, (uint)Arguments.ReferencePaths.Count());
}
}
}
| ericfe-ms/roslyn | src/Compilers/Shared/Vbc.cs | C# | apache-2.0 | 2,289 |
class Tinyumbrella < Cask
version '7.04'
sha256 '2ce5ea70bbdf216aaff9fc30c1a33a58a6fc19a5ad5e4f0029aafae61c622db1'
url 'http://cache.firmwareumbrella.com/downloads/TinyUmbrella-7.04.00.app.zip'
homepage 'http://blog.firmwareumbrella.com/'
link 'TinyUmbrella.app'
end
| flesch/homebrew-cask | Casks/tinyumbrella.rb | Ruby | bsd-2-clause | 279 |
//===-- RuntimeDyldCOFF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-==//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implementation of COFF support for the MC-JIT runtime dynamic linker.
//
//===----------------------------------------------------------------------===//
#include "RuntimeDyldCOFF.h"
#include "Targets/RuntimeDyldCOFFAArch64.h"
#include "Targets/RuntimeDyldCOFFI386.h"
#include "Targets/RuntimeDyldCOFFThumb.h"
#include "Targets/RuntimeDyldCOFFX86_64.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/FormatVariadic.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "dyld"
namespace {
class LoadedCOFFObjectInfo final
: public LoadedObjectInfoHelper<LoadedCOFFObjectInfo,
RuntimeDyld::LoadedObjectInfo> {
public:
LoadedCOFFObjectInfo(
RuntimeDyldImpl &RTDyld,
RuntimeDyld::LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
: LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile &Obj) const override {
return OwningBinary<ObjectFile>();
}
};
}
namespace llvm {
std::unique_ptr<RuntimeDyldCOFF>
llvm::RuntimeDyldCOFF::create(Triple::ArchType Arch,
RuntimeDyld::MemoryManager &MemMgr,
JITSymbolResolver &Resolver) {
switch (Arch) {
default: llvm_unreachable("Unsupported target for RuntimeDyldCOFF.");
case Triple::x86:
return std::make_unique<RuntimeDyldCOFFI386>(MemMgr, Resolver);
case Triple::thumb:
return std::make_unique<RuntimeDyldCOFFThumb>(MemMgr, Resolver);
case Triple::x86_64:
return std::make_unique<RuntimeDyldCOFFX86_64>(MemMgr, Resolver);
case Triple::aarch64:
return std::make_unique<RuntimeDyldCOFFAArch64>(MemMgr, Resolver);
}
}
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
RuntimeDyldCOFF::loadObject(const object::ObjectFile &O) {
if (auto ObjSectionToIDOrErr = loadObjectImpl(O)) {
return std::make_unique<LoadedCOFFObjectInfo>(*this, *ObjSectionToIDOrErr);
} else {
HasError = true;
raw_string_ostream ErrStream(ErrorStr);
logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream);
return nullptr;
}
}
uint64_t RuntimeDyldCOFF::getSymbolOffset(const SymbolRef &Sym) {
// The value in a relocatable COFF object is the offset.
return cantFail(Sym.getValue());
}
uint64_t RuntimeDyldCOFF::getDLLImportOffset(unsigned SectionID, StubMap &Stubs,
StringRef Name,
bool SetSectionIDMinus1) {
LLVM_DEBUG(dbgs() << "Getting DLLImport entry for " << Name << "... ");
assert(Name.startswith(getImportSymbolPrefix()) && "Not a DLLImport symbol?");
RelocationValueRef Reloc;
Reloc.SymbolName = Name.data();
auto I = Stubs.find(Reloc);
if (I != Stubs.end()) {
LLVM_DEBUG(dbgs() << format("{0:x8}", I->second) << "\n");
return I->second;
}
assert(SectionID < Sections.size() && "SectionID out of range");
auto &Sec = Sections[SectionID];
auto EntryOffset = alignTo(Sec.getStubOffset(), PointerSize);
Sec.advanceStubOffset(EntryOffset + PointerSize - Sec.getStubOffset());
Stubs[Reloc] = EntryOffset;
RelocationEntry RE(SectionID, EntryOffset, PointerReloc, 0, false,
Log2_64(PointerSize));
// Hack to tell I386/Thumb resolveRelocation that this isn't section relative.
if (SetSectionIDMinus1)
RE.Sections.SectionA = -1;
addRelocationForSymbol(RE, Name.drop_front(getImportSymbolPrefix().size()));
LLVM_DEBUG({
dbgs() << "Creating entry at "
<< formatv("{0:x16} + {1:x8} ( {2:x16} )", Sec.getLoadAddress(),
EntryOffset, Sec.getLoadAddress() + EntryOffset)
<< "\n";
});
return EntryOffset;
}
bool RuntimeDyldCOFF::isCompatibleFile(const object::ObjectFile &Obj) const {
return Obj.isCOFF();
}
} // namespace llvm
| endlessm/chromium-browser | third_party/llvm/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp | C++ | bsd-3-clause | 4,282 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "sync/api/attachments/attachment_metadata.h"
namespace syncer {
AttachmentMetadata::AttachmentMetadata(const AttachmentId& id, size_t size)
: id_(id), size_(size) {
}
AttachmentMetadata::~AttachmentMetadata() {
}
const AttachmentId& AttachmentMetadata::GetId() const {
return id_;
}
size_t AttachmentMetadata::GetSize() const {
return size_;
}
} // namespace syncer
| js0701/chromium-crosswalk | sync/api/attachments/attachment_metadata.cc | C++ | bsd-3-clause | 577 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/browser/fileapi/obfuscated_file_util.h"
#include <queue>
#include <string>
#include <vector>
#include "base/file_util.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "url/gurl.h"
#include "webkit/browser/fileapi/file_observers.h"
#include "webkit/browser/fileapi/file_system_context.h"
#include "webkit/browser/fileapi/file_system_operation_context.h"
#include "webkit/browser/fileapi/file_system_url.h"
#include "webkit/browser/fileapi/native_file_util.h"
#include "webkit/browser/fileapi/sandbox_file_system_backend.h"
#include "webkit/browser/fileapi/sandbox_isolated_origin_database.h"
#include "webkit/browser/fileapi/sandbox_origin_database.h"
#include "webkit/browser/fileapi/sandbox_prioritized_origin_database.h"
#include "webkit/browser/fileapi/timed_task_helper.h"
#include "webkit/browser/quota/quota_manager.h"
#include "webkit/common/database/database_identifier.h"
#include "webkit/common/fileapi/file_system_util.h"
// Example of various paths:
// void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) {
// base::FilePath virtual_path = url.path();
// base::FilePath local_path = GetLocalFilePath(url);
//
// NativeFileUtil::DoSomething(local_path);
// file_util::DoAnother(local_path);
// }
namespace fileapi {
namespace {
typedef SandboxDirectoryDatabase::FileId FileId;
typedef SandboxDirectoryDatabase::FileInfo FileInfo;
void InitFileInfo(
SandboxDirectoryDatabase::FileInfo* file_info,
SandboxDirectoryDatabase::FileId parent_id,
const base::FilePath::StringType& file_name) {
DCHECK(file_info);
file_info->parent_id = parent_id;
file_info->name = file_name;
}
// Costs computed as per crbug.com/86114, based on the LevelDB implementation of
// path storage under Linux. It's not clear if that will differ on Windows, on
// which base::FilePath uses wide chars [since they're converted to UTF-8 for
// storage anyway], but as long as the cost is high enough that one can't cheat
// on quota by storing data in paths, it doesn't need to be all that accurate.
const int64 kPathCreationQuotaCost = 146; // Bytes per inode, basically.
const int64 kPathByteQuotaCost = 2; // Bytes per byte of path length in UTF-8.
int64 UsageForPath(size_t length) {
return kPathCreationQuotaCost +
static_cast<int64>(length) * kPathByteQuotaCost;
}
bool AllocateQuota(FileSystemOperationContext* context, int64 growth) {
if (context->allowed_bytes_growth() == quota::QuotaManager::kNoLimit)
return true;
int64 new_quota = context->allowed_bytes_growth() - growth;
if (growth > 0 && new_quota < 0)
return false;
context->set_allowed_bytes_growth(new_quota);
return true;
}
void UpdateUsage(
FileSystemOperationContext* context,
const FileSystemURL& url,
int64 growth) {
context->update_observers()->Notify(
&FileUpdateObserver::OnUpdate, MakeTuple(url, growth));
}
void TouchDirectory(SandboxDirectoryDatabase* db, FileId dir_id) {
DCHECK(db);
if (!db->UpdateModificationTime(dir_id, base::Time::Now()))
NOTREACHED();
}
enum IsolatedOriginStatus {
kIsolatedOriginMatch,
kIsolatedOriginDontMatch,
kIsolatedOriginStatusMax,
};
} // namespace
class ObfuscatedFileEnumerator
: public FileSystemFileUtil::AbstractFileEnumerator {
public:
ObfuscatedFileEnumerator(
SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
ObfuscatedFileUtil* obfuscated_file_util,
const FileSystemURL& root_url,
bool recursive)
: db_(db),
context_(context),
obfuscated_file_util_(obfuscated_file_util),
root_url_(root_url),
recursive_(recursive),
current_file_id_(0) {
base::FilePath root_virtual_path = root_url.path();
FileId file_id;
if (!db_->GetFileWithPath(root_virtual_path, &file_id))
return;
FileRecord record = { file_id, root_virtual_path };
recurse_queue_.push(record);
}
virtual ~ObfuscatedFileEnumerator() {}
virtual base::FilePath Next() OVERRIDE {
ProcessRecurseQueue();
if (display_stack_.empty())
return base::FilePath();
current_file_id_ = display_stack_.back();
display_stack_.pop_back();
FileInfo file_info;
base::FilePath platform_file_path;
base::File::Error error =
obfuscated_file_util_->GetFileInfoInternal(
db_, context_, root_url_, current_file_id_,
&file_info, ¤t_platform_file_info_, &platform_file_path);
if (error != base::File::FILE_OK)
return Next();
base::FilePath virtual_path =
current_parent_virtual_path_.Append(file_info.name);
if (recursive_ && file_info.is_directory()) {
FileRecord record = { current_file_id_, virtual_path };
recurse_queue_.push(record);
}
return virtual_path;
}
virtual int64 Size() OVERRIDE {
return current_platform_file_info_.size;
}
virtual base::Time LastModifiedTime() OVERRIDE {
return current_platform_file_info_.last_modified;
}
virtual bool IsDirectory() OVERRIDE {
return current_platform_file_info_.is_directory;
}
private:
typedef SandboxDirectoryDatabase::FileId FileId;
typedef SandboxDirectoryDatabase::FileInfo FileInfo;
struct FileRecord {
FileId file_id;
base::FilePath virtual_path;
};
void ProcessRecurseQueue() {
while (display_stack_.empty() && !recurse_queue_.empty()) {
FileRecord entry = recurse_queue_.front();
recurse_queue_.pop();
if (!db_->ListChildren(entry.file_id, &display_stack_)) {
display_stack_.clear();
return;
}
current_parent_virtual_path_ = entry.virtual_path;
}
}
SandboxDirectoryDatabase* db_;
FileSystemOperationContext* context_;
ObfuscatedFileUtil* obfuscated_file_util_;
FileSystemURL root_url_;
bool recursive_;
std::queue<FileRecord> recurse_queue_;
std::vector<FileId> display_stack_;
base::FilePath current_parent_virtual_path_;
FileId current_file_id_;
base::File::Info current_platform_file_info_;
};
class ObfuscatedOriginEnumerator
: public ObfuscatedFileUtil::AbstractOriginEnumerator {
public:
typedef SandboxOriginDatabase::OriginRecord OriginRecord;
ObfuscatedOriginEnumerator(
SandboxOriginDatabaseInterface* origin_database,
const base::FilePath& base_file_path)
: base_file_path_(base_file_path) {
if (origin_database)
origin_database->ListAllOrigins(&origins_);
}
virtual ~ObfuscatedOriginEnumerator() {}
// Returns the next origin. Returns empty if there are no more origins.
virtual GURL Next() OVERRIDE {
OriginRecord record;
if (!origins_.empty()) {
record = origins_.back();
origins_.pop_back();
}
current_ = record;
return webkit_database::GetOriginFromIdentifier(record.origin);
}
// Returns the current origin's information.
virtual bool HasTypeDirectory(const std::string& type_string) const OVERRIDE {
if (current_.path.empty())
return false;
if (type_string.empty()) {
NOTREACHED();
return false;
}
base::FilePath path =
base_file_path_.Append(current_.path).AppendASCII(type_string);
return base::DirectoryExists(path);
}
private:
std::vector<OriginRecord> origins_;
OriginRecord current_;
base::FilePath base_file_path_;
};
ObfuscatedFileUtil::ObfuscatedFileUtil(
quota::SpecialStoragePolicy* special_storage_policy,
const base::FilePath& file_system_directory,
leveldb::Env* env_override,
base::SequencedTaskRunner* file_task_runner,
const GetTypeStringForURLCallback& get_type_string_for_url,
const std::set<std::string>& known_type_strings,
SandboxFileSystemBackendDelegate* sandbox_delegate)
: special_storage_policy_(special_storage_policy),
file_system_directory_(file_system_directory),
env_override_(env_override),
db_flush_delay_seconds_(10 * 60), // 10 mins.
file_task_runner_(file_task_runner),
get_type_string_for_url_(get_type_string_for_url),
known_type_strings_(known_type_strings),
sandbox_delegate_(sandbox_delegate) {
}
ObfuscatedFileUtil::~ObfuscatedFileUtil() {
DropDatabases();
}
base::File ObfuscatedFileUtil::CreateOrOpen(
FileSystemOperationContext* context,
const FileSystemURL& url, int file_flags) {
base::File file = CreateOrOpenInternal(context, url, file_flags);
if (file.IsValid() && file_flags & base::File::FLAG_WRITE &&
context->quota_limit_type() == quota::kQuotaLimitTypeUnlimited &&
sandbox_delegate_) {
sandbox_delegate_->StickyInvalidateUsageCache(url.origin(), url.type());
}
return file.Pass();
}
base::File::Error ObfuscatedFileUtil::EnsureFileExists(
FileSystemOperationContext* context,
const FileSystemURL& url,
bool* created) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
if (created)
*created = false;
return base::File::FILE_OK;
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = CreateFile(context, base::FilePath(), url,
&file_info);
if (created && base::File::FILE_OK == error) {
*created = true;
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(url));
}
return error;
}
base::File::Error ObfuscatedFileUtil::CreateDirectory(
FileSystemOperationContext* context,
const FileSystemURL& url,
bool exclusive,
bool recursive) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (exclusive)
return base::File::FILE_ERROR_EXISTS;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
return base::File::FILE_OK;
}
std::vector<base::FilePath::StringType> components;
VirtualPath::GetComponents(url.path(), &components);
FileId parent_id = 0;
size_t index;
for (index = 0; index < components.size(); ++index) {
base::FilePath::StringType name = components[index];
if (name == FILE_PATH_LITERAL("/"))
continue;
if (!db->GetChildWithName(parent_id, name, &parent_id))
break;
}
if (!db->IsDirectory(parent_id))
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
if (!recursive && components.size() - index > 1)
return base::File::FILE_ERROR_NOT_FOUND;
bool first = true;
for (; index < components.size(); ++index) {
FileInfo file_info;
file_info.name = components[index];
if (file_info.name == FILE_PATH_LITERAL("/"))
continue;
file_info.modification_time = base::Time::Now();
file_info.parent_id = parent_id;
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = db->AddFileInfo(file_info, &parent_id);
if (error != base::File::FILE_OK)
return error;
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateDirectory, MakeTuple(url));
if (first) {
first = false;
TouchDirectory(db, file_info.parent_id);
}
}
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::GetFileInfo(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo local_info;
return GetFileInfoInternal(db, context, url,
file_id, &local_info,
file_info, platform_file_path);
}
scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator>
ObfuscatedFileUtil::CreateFileEnumerator(
FileSystemOperationContext* context,
const FileSystemURL& root_url) {
return CreateFileEnumerator(context, root_url, false /* recursive */);
}
base::File::Error ObfuscatedFileUtil::GetLocalFilePath(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::FilePath* local_path) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info) || file_info.is_directory()) {
NOTREACHED();
// Directories have no local file path.
return base::File::FILE_ERROR_NOT_FOUND;
}
*local_path = DataPathToLocalPath(url, file_info.data_path);
if (local_path->empty())
return base::File::FILE_ERROR_NOT_FOUND;
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::Touch(
FileSystemOperationContext* context,
const FileSystemURL& url,
const base::Time& last_access_time,
const base::Time& last_modified_time) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory()) {
if (!db->UpdateModificationTime(file_id, last_modified_time))
return base::File::FILE_ERROR_FAILED;
return base::File::FILE_OK;
}
return NativeFileUtil::Touch(
DataPathToLocalPath(url, file_info.data_path),
last_access_time, last_modified_time);
}
base::File::Error ObfuscatedFileUtil::Truncate(
FileSystemOperationContext* context,
const FileSystemURL& url,
int64 length) {
base::File::Info file_info;
base::FilePath local_path;
base::File::Error error =
GetFileInfo(context, url, &file_info, &local_path);
if (error != base::File::FILE_OK)
return error;
int64 growth = length - file_info.size;
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
error = NativeFileUtil::Truncate(local_path, length);
if (error == base::File::FILE_OK) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(url));
}
return error;
}
base::File::Error ObfuscatedFileUtil::CopyOrMoveFile(
FileSystemOperationContext* context,
const FileSystemURL& src_url,
const FileSystemURL& dest_url,
CopyOrMoveOption option,
bool copy) {
// Cross-filesystem copies and moves should be handled via CopyInForeignFile.
DCHECK(src_url.origin() == dest_url.origin());
DCHECK(src_url.type() == dest_url.type());
SandboxDirectoryDatabase* db = GetDirectoryDatabase(src_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId src_file_id;
if (!db->GetFileWithPath(src_url.path(), &src_file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(),
&dest_file_id);
FileInfo src_file_info;
base::File::Info src_platform_file_info;
base::FilePath src_local_path;
base::File::Error error = GetFileInfoInternal(
db, context, src_url, src_file_id,
&src_file_info, &src_platform_file_info, &src_local_path);
if (error != base::File::FILE_OK)
return error;
if (src_file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
FileInfo dest_file_info;
base::File::Info dest_platform_file_info; // overwrite case only
base::FilePath dest_local_path; // overwrite case only
if (overwrite) {
base::File::Error error = GetFileInfoInternal(
db, context, dest_url, dest_file_id,
&dest_file_info, &dest_platform_file_info, &dest_local_path);
if (error == base::File::FILE_ERROR_NOT_FOUND)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::FILE_ERROR_INVALID_OPERATION;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::FILE_ERROR_NOT_FOUND;
}
dest_file_info = src_file_info;
dest_file_info.parent_id = dest_parent_id;
dest_file_info.name =
VirtualPath::BaseName(dest_url.path()).value();
}
int64 growth = 0;
if (copy)
growth += src_platform_file_info.size;
else
growth -= UsageForPath(src_file_info.name.size());
if (overwrite)
growth -= dest_platform_file_info.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
/*
* Copy-with-overwrite
* Just overwrite data file
* Copy-without-overwrite
* Copy backing file
* Create new metadata pointing to new backing file.
* Move-with-overwrite
* transaction:
* Remove source entry.
* Point target entry to source entry's backing file.
* Delete target entry's old backing file
* Move-without-overwrite
* Just update metadata
*/
error = base::File::FILE_ERROR_FAILED;
if (copy) {
if (overwrite) {
error = NativeFileUtil::CopyOrMoveFile(
src_local_path,
dest_local_path,
option,
fileapi::NativeFileUtil::CopyOrMoveModeForDestination(
dest_url, true /* copy */));
} else { // non-overwrite
error = CreateFile(context, src_local_path, dest_url, &dest_file_info);
}
} else {
if (overwrite) {
if (db->OverwritingMoveFile(src_file_id, dest_file_id)) {
if (base::File::FILE_OK !=
NativeFileUtil::DeleteFile(dest_local_path))
LOG(WARNING) << "Leaked a backing file.";
error = base::File::FILE_OK;
} else {
error = base::File::FILE_ERROR_FAILED;
}
} else { // non-overwrite
if (db->UpdateFileInfo(src_file_id, dest_file_info))
error = base::File::FILE_OK;
else
error = base::File::FILE_ERROR_FAILED;
}
}
if (error != base::File::FILE_OK)
return error;
if (overwrite) {
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile,
MakeTuple(dest_url));
} else {
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFileFrom,
MakeTuple(dest_url, src_url));
}
if (!copy) {
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveFile, MakeTuple(src_url));
TouchDirectory(db, src_file_info.parent_id);
}
TouchDirectory(db, dest_file_info.parent_id);
UpdateUsage(context, dest_url, growth);
return error;
}
base::File::Error ObfuscatedFileUtil::CopyInForeignFile(
FileSystemOperationContext* context,
const base::FilePath& src_file_path,
const FileSystemURL& dest_url) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
base::File::Info src_platform_file_info;
if (!base::GetFileInfo(src_file_path, &src_platform_file_info))
return base::File::FILE_ERROR_NOT_FOUND;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(),
&dest_file_id);
FileInfo dest_file_info;
base::File::Info dest_platform_file_info; // overwrite case only
if (overwrite) {
base::FilePath dest_local_path;
base::File::Error error = GetFileInfoInternal(
db, context, dest_url, dest_file_id,
&dest_file_info, &dest_platform_file_info, &dest_local_path);
if (error == base::File::FILE_ERROR_NOT_FOUND)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::FILE_ERROR_INVALID_OPERATION;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::FILE_ERROR_NOT_FOUND;
}
if (!dest_file_info.is_directory())
return base::File::FILE_ERROR_FAILED;
InitFileInfo(&dest_file_info, dest_parent_id,
VirtualPath::BaseName(dest_url.path()).value());
}
int64 growth = src_platform_file_info.size;
if (overwrite)
growth -= dest_platform_file_info.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error;
if (overwrite) {
base::FilePath dest_local_path =
DataPathToLocalPath(dest_url, dest_file_info.data_path);
error = NativeFileUtil::CopyOrMoveFile(
src_file_path, dest_local_path,
FileSystemOperation::OPTION_NONE,
fileapi::NativeFileUtil::CopyOrMoveModeForDestination(dest_url,
true /* copy */));
} else {
error = CreateFile(context, src_file_path, dest_url, &dest_file_info);
}
if (error != base::File::FILE_OK)
return error;
if (overwrite) {
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(dest_url));
} else {
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(dest_url));
}
UpdateUsage(context, dest_url, growth);
TouchDirectory(db, dest_file_info.parent_id);
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteFile(
FileSystemOperationContext* context,
const FileSystemURL& url) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
base::File::Info platform_file_info;
base::FilePath local_path;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::FILE_ERROR_NOT_FOUND &&
error != base::File::FILE_OK)
return error;
if (file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
int64 growth = -UsageForPath(file_info.name.size()) - platform_file_info.size;
AllocateQuota(context, growth);
if (!db->RemoveFileInfo(file_id)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveFile, MakeTuple(url));
if (error == base::File::FILE_ERROR_NOT_FOUND)
return base::File::FILE_OK;
error = NativeFileUtil::DeleteFile(local_path);
if (base::File::FILE_OK != error)
LOG(WARNING) << "Leaked a backing file.";
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteDirectory(
FileSystemOperationContext* context,
const FileSystemURL& url) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
if (!db->RemoveFileInfo(file_id))
return base::File::FILE_ERROR_NOT_EMPTY;
int64 growth = -UsageForPath(file_info.name.size());
AllocateQuota(context, growth);
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveDirectory, MakeTuple(url));
return base::File::FILE_OK;
}
webkit_blob::ScopedFile ObfuscatedFileUtil::CreateSnapshotFile(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::File::Error* error,
base::File::Info* file_info,
base::FilePath* platform_path) {
// We're just returning the local file information.
*error = GetFileInfo(context, url, file_info, platform_path);
if (*error == base::File::FILE_OK && file_info->is_directory) {
*file_info = base::File::Info();
*error = base::File::FILE_ERROR_NOT_A_FILE;
}
return webkit_blob::ScopedFile();
}
scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator>
ObfuscatedFileUtil::CreateFileEnumerator(
FileSystemOperationContext* context,
const FileSystemURL& root_url,
bool recursive) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(root_url, false);
if (!db) {
return scoped_ptr<AbstractFileEnumerator>(new EmptyFileEnumerator());
}
return scoped_ptr<AbstractFileEnumerator>(
new ObfuscatedFileEnumerator(db, context, this, root_url, recursive));
}
bool ObfuscatedFileUtil::IsDirectoryEmpty(
FileSystemOperationContext* context,
const FileSystemURL& url) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return true; // Not a great answer, but it's what others do.
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return true; // Ditto.
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
DCHECK(!file_id);
// It's the root directory and the database hasn't been initialized yet.
return true;
}
if (!file_info.is_directory())
return true;
std::vector<FileId> children;
// TODO(ericu): This could easily be made faster with help from the database.
if (!db->ListChildren(file_id, &children))
return true;
return children.empty();
}
base::FilePath ObfuscatedFileUtil::GetDirectoryForOriginAndType(
const GURL& origin,
const std::string& type_string,
bool create,
base::File::Error* error_code) {
base::FilePath origin_dir = GetDirectoryForOrigin(origin, create, error_code);
if (origin_dir.empty())
return base::FilePath();
if (type_string.empty())
return origin_dir;
base::FilePath path = origin_dir.AppendASCII(type_string);
base::File::Error error = base::File::FILE_OK;
if (!base::DirectoryExists(path) &&
(!create || !base::CreateDirectory(path))) {
error = create ?
base::File::FILE_ERROR_FAILED :
base::File::FILE_ERROR_NOT_FOUND;
}
if (error_code)
*error_code = error;
return path;
}
bool ObfuscatedFileUtil::DeleteDirectoryForOriginAndType(
const GURL& origin,
const std::string& type_string) {
base::File::Error error = base::File::FILE_OK;
base::FilePath origin_type_path = GetDirectoryForOriginAndType(
origin, type_string, false, &error);
if (origin_type_path.empty())
return true;
if (error != base::File::FILE_ERROR_NOT_FOUND) {
// TODO(dmikurube): Consider the return value of DestroyDirectoryDatabase.
// We ignore its error now since 1) it doesn't matter the final result, and
// 2) it always returns false in Windows because of LevelDB's
// implementation.
// Information about failure would be useful for debugging.
if (!type_string.empty())
DestroyDirectoryDatabase(origin, type_string);
if (!base::DeleteFile(origin_type_path, true /* recursive */))
return false;
}
base::FilePath origin_path = VirtualPath::DirName(origin_type_path);
DCHECK_EQ(origin_path.value(),
GetDirectoryForOrigin(origin, false, NULL).value());
if (!type_string.empty()) {
// At this point we are sure we had successfully deleted the origin/type
// directory (i.e. we're ready to just return true).
// See if we have other directories in this origin directory.
for (std::set<std::string>::iterator iter = known_type_strings_.begin();
iter != known_type_strings_.end();
++iter) {
if (*iter == type_string)
continue;
if (base::DirectoryExists(origin_path.AppendASCII(*iter))) {
// Other type's directory exists; just return true here.
return true;
}
}
}
// No other directories seem exist. Try deleting the entire origin directory.
InitOriginDatabase(origin, false);
if (origin_database_) {
origin_database_->RemovePathForOrigin(
webkit_database::GetIdentifierFromOrigin(origin));
}
if (!base::DeleteFile(origin_path, true /* recursive */))
return false;
return true;
}
ObfuscatedFileUtil::AbstractOriginEnumerator*
ObfuscatedFileUtil::CreateOriginEnumerator() {
std::vector<SandboxOriginDatabase::OriginRecord> origins;
InitOriginDatabase(GURL(), false);
return new ObfuscatedOriginEnumerator(
origin_database_.get(), file_system_directory_);
}
bool ObfuscatedFileUtil::DestroyDirectoryDatabase(
const GURL& origin,
const std::string& type_string) {
std::string key = GetDirectoryDatabaseKey(origin, type_string);
if (key.empty())
return true;
DirectoryMap::iterator iter = directories_.find(key);
if (iter != directories_.end()) {
SandboxDirectoryDatabase* database = iter->second;
directories_.erase(iter);
delete database;
}
base::File::Error error = base::File::FILE_OK;
base::FilePath path = GetDirectoryForOriginAndType(
origin, type_string, false, &error);
if (path.empty() || error == base::File::FILE_ERROR_NOT_FOUND)
return true;
return SandboxDirectoryDatabase::DestroyDatabase(path, env_override_);
}
// static
int64 ObfuscatedFileUtil::ComputeFilePathCost(const base::FilePath& path) {
return UsageForPath(VirtualPath::BaseName(path).value().size());
}
void ObfuscatedFileUtil::MaybePrepopulateDatabase(
const std::vector<std::string>& type_strings_to_prepopulate) {
SandboxPrioritizedOriginDatabase database(file_system_directory_,
env_override_);
std::string origin_string = database.GetPrimaryOrigin();
if (origin_string.empty() || !database.HasOriginPath(origin_string))
return;
const GURL origin = webkit_database::GetOriginFromIdentifier(origin_string);
// Prepopulate the directory database(s) if and only if this instance
// has primary origin and the directory database is already there.
for (size_t i = 0; i < type_strings_to_prepopulate.size(); ++i) {
const std::string type_string = type_strings_to_prepopulate[i];
// Only handles known types.
if (!ContainsKey(known_type_strings_, type_string))
continue;
base::File::Error error = base::File::FILE_ERROR_FAILED;
base::FilePath path = GetDirectoryForOriginAndType(
origin, type_string, false, &error);
if (error != base::File::FILE_OK)
continue;
scoped_ptr<SandboxDirectoryDatabase> db(
new SandboxDirectoryDatabase(path, env_override_));
if (db->Init(SandboxDirectoryDatabase::FAIL_ON_CORRUPTION)) {
directories_[GetDirectoryDatabaseKey(origin, type_string)] = db.release();
MarkUsed();
// Don't populate more than one database, as it may rather hurt
// performance.
break;
}
}
}
base::FilePath ObfuscatedFileUtil::GetDirectoryForURL(
const FileSystemURL& url,
bool create,
base::File::Error* error_code) {
return GetDirectoryForOriginAndType(
url.origin(), CallGetTypeStringForURL(url), create, error_code);
}
std::string ObfuscatedFileUtil::CallGetTypeStringForURL(
const FileSystemURL& url) {
DCHECK(!get_type_string_for_url_.is_null());
return get_type_string_for_url_.Run(url);
}
base::File::Error ObfuscatedFileUtil::GetFileInfoInternal(
SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
const FileSystemURL& url,
FileId file_id,
FileInfo* local_info,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
DCHECK(db);
DCHECK(context);
DCHECK(file_info);
DCHECK(platform_file_path);
if (!db->GetFileInfo(file_id, local_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (local_info->is_directory()) {
file_info->size = 0;
file_info->is_directory = true;
file_info->is_symbolic_link = false;
file_info->last_modified = local_info->modification_time;
*platform_file_path = base::FilePath();
// We don't fill in ctime or atime.
return base::File::FILE_OK;
}
if (local_info->data_path.empty())
return base::File::FILE_ERROR_INVALID_OPERATION;
base::FilePath local_path = DataPathToLocalPath(url, local_info->data_path);
base::File::Error error = NativeFileUtil::GetFileInfo(
local_path, file_info);
// We should not follow symbolic links in sandboxed file system.
if (base::IsLink(local_path)) {
LOG(WARNING) << "Found a symbolic file.";
error = base::File::FILE_ERROR_NOT_FOUND;
}
if (error == base::File::FILE_OK) {
*platform_file_path = local_path;
} else if (error == base::File::FILE_ERROR_NOT_FOUND) {
LOG(WARNING) << "Lost a backing file.";
InvalidateUsageCache(context, url.origin(), url.type());
if (!db->RemoveFileInfo(file_id))
return base::File::FILE_ERROR_FAILED;
}
return error;
}
base::File ObfuscatedFileUtil::CreateAndOpenFile(
FileSystemOperationContext* context,
const FileSystemURL& dest_url,
FileInfo* dest_file_info, int file_flags) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root,
&dest_local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (base::PathExists(dest_local_path)) {
if (!base::DeleteFile(dest_local_path, true /* recursive */))
return base::File(base::File::FILE_ERROR_FAILED);
LOG(WARNING) << "A stray file detected";
InvalidateUsageCache(context, dest_url.origin(), dest_url.type());
}
base::File file = NativeFileUtil::CreateOrOpen(dest_local_path, file_flags);
if (!file.IsValid())
return file.Pass();
if (!file.created()) {
file.Close();
base::DeleteFile(dest_local_path, false /* recursive */);
return base::File(base::File::FILE_ERROR_FAILED);
}
error = CommitCreateFile(root, dest_local_path, db, dest_file_info);
if (error != base::File::FILE_OK) {
file.Close();
base::DeleteFile(dest_local_path, false /* recursive */);
return base::File(error);
}
return file.Pass();
}
base::File::Error ObfuscatedFileUtil::CreateFile(
FileSystemOperationContext* context,
const base::FilePath& src_file_path,
const FileSystemURL& dest_url,
FileInfo* dest_file_info) {
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root,
&dest_local_path);
if (error != base::File::FILE_OK)
return error;
bool created = false;
if (src_file_path.empty()) {
if (base::PathExists(dest_local_path)) {
if (!base::DeleteFile(dest_local_path, true /* recursive */))
return base::File::FILE_ERROR_FAILED;
LOG(WARNING) << "A stray file detected";
InvalidateUsageCache(context, dest_url.origin(), dest_url.type());
}
error = NativeFileUtil::EnsureFileExists(dest_local_path, &created);
} else {
error = NativeFileUtil::CopyOrMoveFile(
src_file_path, dest_local_path,
FileSystemOperation::OPTION_NONE,
fileapi::NativeFileUtil::CopyOrMoveModeForDestination(dest_url,
true /* copy */));
created = true;
}
if (error != base::File::FILE_OK)
return error;
if (!created)
return base::File::FILE_ERROR_FAILED;
return CommitCreateFile(root, dest_local_path, db, dest_file_info);
}
base::File::Error ObfuscatedFileUtil::CommitCreateFile(
const base::FilePath& root,
const base::FilePath& local_path,
SandboxDirectoryDatabase* db,
FileInfo* dest_file_info) {
// This removes the root, including the trailing slash, leaving a relative
// path.
dest_file_info->data_path = base::FilePath(
local_path.value().substr(root.value().length() + 1));
FileId file_id;
base::File::Error error = db->AddFileInfo(*dest_file_info, &file_id);
if (error != base::File::FILE_OK)
return error;
TouchDirectory(db, dest_file_info->parent_id);
return base::File::FILE_OK;
}
base::FilePath ObfuscatedFileUtil::DataPathToLocalPath(
const FileSystemURL& url, const base::FilePath& data_path) {
base::File::Error error = base::File::FILE_OK;
base::FilePath root = GetDirectoryForURL(url, false, &error);
if (error != base::File::FILE_OK)
return base::FilePath();
return root.Append(data_path);
}
std::string ObfuscatedFileUtil::GetDirectoryDatabaseKey(
const GURL& origin, const std::string& type_string) {
if (type_string.empty()) {
LOG(WARNING) << "Unknown filesystem type requested:" << type_string;
return std::string();
}
// For isolated origin we just use a type string as a key.
return webkit_database::GetIdentifierFromOrigin(origin) +
type_string;
}
// TODO(ericu): How to do the whole validation-without-creation thing?
// We may not have quota even to create the database.
// Ah, in that case don't even get here?
// Still doesn't answer the quota issue, though.
SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase(
const FileSystemURL& url, bool create) {
std::string key = GetDirectoryDatabaseKey(
url.origin(), CallGetTypeStringForURL(url));
if (key.empty())
return NULL;
DirectoryMap::iterator iter = directories_.find(key);
if (iter != directories_.end()) {
MarkUsed();
return iter->second;
}
base::File::Error error = base::File::FILE_OK;
base::FilePath path = GetDirectoryForURL(url, create, &error);
if (error != base::File::FILE_OK) {
LOG(WARNING) << "Failed to get origin+type directory: "
<< url.DebugString() << " error:" << error;
return NULL;
}
MarkUsed();
SandboxDirectoryDatabase* database =
new SandboxDirectoryDatabase(path, env_override_);
directories_[key] = database;
return database;
}
base::FilePath ObfuscatedFileUtil::GetDirectoryForOrigin(
const GURL& origin, bool create, base::File::Error* error_code) {
if (!InitOriginDatabase(origin, create)) {
if (error_code) {
*error_code = create ?
base::File::FILE_ERROR_FAILED :
base::File::FILE_ERROR_NOT_FOUND;
}
return base::FilePath();
}
base::FilePath directory_name;
std::string id = webkit_database::GetIdentifierFromOrigin(origin);
bool exists_in_db = origin_database_->HasOriginPath(id);
if (!exists_in_db && !create) {
if (error_code)
*error_code = base::File::FILE_ERROR_NOT_FOUND;
return base::FilePath();
}
if (!origin_database_->GetPathForOrigin(id, &directory_name)) {
if (error_code)
*error_code = base::File::FILE_ERROR_FAILED;
return base::FilePath();
}
base::FilePath path = file_system_directory_.Append(directory_name);
bool exists_in_fs = base::DirectoryExists(path);
if (!exists_in_db && exists_in_fs) {
if (!base::DeleteFile(path, true)) {
if (error_code)
*error_code = base::File::FILE_ERROR_FAILED;
return base::FilePath();
}
exists_in_fs = false;
}
if (!exists_in_fs) {
if (!create || !base::CreateDirectory(path)) {
if (error_code)
*error_code = create ?
base::File::FILE_ERROR_FAILED :
base::File::FILE_ERROR_NOT_FOUND;
return base::FilePath();
}
}
if (error_code)
*error_code = base::File::FILE_OK;
return path;
}
void ObfuscatedFileUtil::InvalidateUsageCache(
FileSystemOperationContext* context,
const GURL& origin,
FileSystemType type) {
if (sandbox_delegate_)
sandbox_delegate_->InvalidateUsageCache(origin, type);
}
void ObfuscatedFileUtil::MarkUsed() {
if (!timer_)
timer_.reset(new TimedTaskHelper(file_task_runner_.get()));
if (timer_->IsRunning()) {
timer_->Reset();
} else {
timer_->Start(FROM_HERE,
base::TimeDelta::FromSeconds(db_flush_delay_seconds_),
base::Bind(&ObfuscatedFileUtil::DropDatabases,
base::Unretained(this)));
}
}
void ObfuscatedFileUtil::DropDatabases() {
origin_database_.reset();
STLDeleteContainerPairSecondPointers(
directories_.begin(), directories_.end());
directories_.clear();
timer_.reset();
}
bool ObfuscatedFileUtil::InitOriginDatabase(const GURL& origin_hint,
bool create) {
if (origin_database_)
return true;
if (!create && !base::DirectoryExists(file_system_directory_))
return false;
if (!base::CreateDirectory(file_system_directory_)) {
LOG(WARNING) << "Failed to create FileSystem directory: " <<
file_system_directory_.value();
return false;
}
SandboxPrioritizedOriginDatabase* prioritized_origin_database =
new SandboxPrioritizedOriginDatabase(file_system_directory_,
env_override_);
origin_database_.reset(prioritized_origin_database);
if (origin_hint.is_empty() || !HasIsolatedStorage(origin_hint))
return true;
const std::string isolated_origin_string =
webkit_database::GetIdentifierFromOrigin(origin_hint);
// TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33.
base::FilePath isolated_origin_dir = file_system_directory_.Append(
SandboxIsolatedOriginDatabase::kObsoleteOriginDirectory);
if (base::DirectoryExists(isolated_origin_dir) &&
prioritized_origin_database->GetSandboxOriginDatabase()) {
SandboxIsolatedOriginDatabase::MigrateBackFromObsoleteOriginDatabase(
isolated_origin_string,
file_system_directory_,
prioritized_origin_database->GetSandboxOriginDatabase());
}
prioritized_origin_database->InitializePrimaryOrigin(
isolated_origin_string);
return true;
}
base::File::Error ObfuscatedFileUtil::GenerateNewLocalPath(
SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
const FileSystemURL& url,
base::FilePath* root,
base::FilePath* local_path) {
DCHECK(local_path);
int64 number;
if (!db || !db->GetNextInteger(&number))
return base::File::FILE_ERROR_FAILED;
base::File::Error error = base::File::FILE_OK;
*root = GetDirectoryForURL(url, false, &error);
if (error != base::File::FILE_OK)
return error;
// We use the third- and fourth-to-last digits as the directory.
int64 directory_number = number % 10000 / 100;
base::FilePath new_local_path = root->AppendASCII(
base::StringPrintf("%02" PRId64, directory_number));
error = NativeFileUtil::CreateDirectory(
new_local_path, false /* exclusive */, false /* recursive */);
if (error != base::File::FILE_OK)
return error;
*local_path =
new_local_path.AppendASCII(base::StringPrintf("%08" PRId64, number));
return base::File::FILE_OK;
}
base::File ObfuscatedFileUtil::CreateOrOpenInternal(
FileSystemOperationContext* context,
const FileSystemURL& url, int file_flags) {
DCHECK(!(file_flags & (base::File::FLAG_DELETE_ON_CLOSE |
base::File::FLAG_HIDDEN | base::File::FLAG_EXCLUSIVE_READ |
base::File::FLAG_EXCLUSIVE_WRITE)));
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File(base::File::FILE_ERROR_FAILED);
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id)) {
// The file doesn't exist.
if (!(file_flags & (base::File::FLAG_CREATE |
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_ALWAYS))) {
return base::File(base::File::FILE_ERROR_NOT_FOUND);
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File(base::File::FILE_ERROR_NOT_FOUND);
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File(base::File::FILE_ERROR_NO_SPACE);
base::File file = CreateAndOpenFile(context, url, &file_info, file_flags);
if (file.IsValid()) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(url));
}
return file.Pass();
}
if (file_flags & base::File::FLAG_CREATE)
return base::File(base::File::FILE_ERROR_EXISTS);
base::File::Info platform_file_info;
base::FilePath local_path;
FileInfo file_info;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (file_info.is_directory())
return base::File(base::File::FILE_ERROR_NOT_A_FILE);
int64 delta = 0;
if (file_flags & (base::File::FLAG_CREATE_ALWAYS |
base::File::FLAG_OPEN_TRUNCATED)) {
// The file exists and we're truncating.
delta = -platform_file_info.size;
AllocateQuota(context, delta);
}
base::File file = NativeFileUtil::CreateOrOpen(local_path, file_flags);
if (!file.IsValid()) {
error = file.error_details();
if (error == base::File::FILE_ERROR_NOT_FOUND) {
// TODO(tzik): Also invalidate on-memory usage cache in UsageTracker.
// TODO(tzik): Delete database entry after ensuring the file lost.
InvalidateUsageCache(context, url.origin(), url.type());
LOG(WARNING) << "Lost a backing file.";
return base::File(base::File::FILE_ERROR_FAILED);
}
return file.Pass();
}
// If truncating we need to update the usage.
if (delta) {
UpdateUsage(context, url, delta);
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(url));
}
return file.Pass();
}
bool ObfuscatedFileUtil::HasIsolatedStorage(const GURL& origin) {
return special_storage_policy_.get() &&
special_storage_policy_->HasIsolatedStorage(origin);
}
} // namespace fileapi
| TeamEOS/external_chromium_org | webkit/browser/fileapi/obfuscated_file_util.cc | C++ | bsd-3-clause | 47,936 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export enum TagContentType {
RAW_TEXT,
ESCAPABLE_RAW_TEXT,
PARSABLE_DATA
}
export interface TagDefinition {
closedByParent: boolean;
implicitNamespacePrefix: string|null;
contentType: TagContentType;
isVoid: boolean;
ignoreFirstLf: boolean;
canSelfClose: boolean;
isClosedByChild(name: string): boolean;
}
export function splitNsName(elementName: string): [string | null, string] {
if (elementName[0] != ':') {
return [null, elementName];
}
const colonIndex = elementName.indexOf(':', 1);
if (colonIndex == -1) {
throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
// `<ng-container>` tags work the same regardless the namespace
export function isNgContainer(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-container';
}
// `<ng-content>` tags work the same regardless the namespace
export function isNgContent(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-content';
}
// `<ng-template>` tags work the same regardless the namespace
export function isNgTemplate(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-template';
}
export function getNsPrefix(fullName: string): string;
export function getNsPrefix(fullName: null): null;
export function getNsPrefix(fullName: string | null): string|null {
return fullName === null ? null : splitNsName(fullName)[0];
}
export function mergeNsAndName(prefix: string, localName: string): string {
return prefix ? `:${prefix}:${localName}` : localName;
}
// see http://www.w3.org/TR/html51/syntax.html#named-character-references
// see https://html.spec.whatwg.org/multipage/entities.json
// This list is not exhaustive to keep the compiler footprint low.
// The `{` / `ƫ` syntax should be used when the named character reference does not
// exist.
export const NAMED_ENTITIES: {[k: string]: string} = {
'Aacute': '\u00C1',
'aacute': '\u00E1',
'Acirc': '\u00C2',
'acirc': '\u00E2',
'acute': '\u00B4',
'AElig': '\u00C6',
'aelig': '\u00E6',
'Agrave': '\u00C0',
'agrave': '\u00E0',
'alefsym': '\u2135',
'Alpha': '\u0391',
'alpha': '\u03B1',
'amp': '&',
'and': '\u2227',
'ang': '\u2220',
'apos': '\u0027',
'Aring': '\u00C5',
'aring': '\u00E5',
'asymp': '\u2248',
'Atilde': '\u00C3',
'atilde': '\u00E3',
'Auml': '\u00C4',
'auml': '\u00E4',
'bdquo': '\u201E',
'Beta': '\u0392',
'beta': '\u03B2',
'brvbar': '\u00A6',
'bull': '\u2022',
'cap': '\u2229',
'Ccedil': '\u00C7',
'ccedil': '\u00E7',
'cedil': '\u00B8',
'cent': '\u00A2',
'Chi': '\u03A7',
'chi': '\u03C7',
'circ': '\u02C6',
'clubs': '\u2663',
'cong': '\u2245',
'copy': '\u00A9',
'crarr': '\u21B5',
'cup': '\u222A',
'curren': '\u00A4',
'dagger': '\u2020',
'Dagger': '\u2021',
'darr': '\u2193',
'dArr': '\u21D3',
'deg': '\u00B0',
'Delta': '\u0394',
'delta': '\u03B4',
'diams': '\u2666',
'divide': '\u00F7',
'Eacute': '\u00C9',
'eacute': '\u00E9',
'Ecirc': '\u00CA',
'ecirc': '\u00EA',
'Egrave': '\u00C8',
'egrave': '\u00E8',
'empty': '\u2205',
'emsp': '\u2003',
'ensp': '\u2002',
'Epsilon': '\u0395',
'epsilon': '\u03B5',
'equiv': '\u2261',
'Eta': '\u0397',
'eta': '\u03B7',
'ETH': '\u00D0',
'eth': '\u00F0',
'Euml': '\u00CB',
'euml': '\u00EB',
'euro': '\u20AC',
'exist': '\u2203',
'fnof': '\u0192',
'forall': '\u2200',
'frac12': '\u00BD',
'frac14': '\u00BC',
'frac34': '\u00BE',
'frasl': '\u2044',
'Gamma': '\u0393',
'gamma': '\u03B3',
'ge': '\u2265',
'gt': '>',
'harr': '\u2194',
'hArr': '\u21D4',
'hearts': '\u2665',
'hellip': '\u2026',
'Iacute': '\u00CD',
'iacute': '\u00ED',
'Icirc': '\u00CE',
'icirc': '\u00EE',
'iexcl': '\u00A1',
'Igrave': '\u00CC',
'igrave': '\u00EC',
'image': '\u2111',
'infin': '\u221E',
'int': '\u222B',
'Iota': '\u0399',
'iota': '\u03B9',
'iquest': '\u00BF',
'isin': '\u2208',
'Iuml': '\u00CF',
'iuml': '\u00EF',
'Kappa': '\u039A',
'kappa': '\u03BA',
'Lambda': '\u039B',
'lambda': '\u03BB',
'lang': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'lArr': '\u21D0',
'lceil': '\u2308',
'ldquo': '\u201C',
'le': '\u2264',
'lfloor': '\u230A',
'lowast': '\u2217',
'loz': '\u25CA',
'lrm': '\u200E',
'lsaquo': '\u2039',
'lsquo': '\u2018',
'lt': '<',
'macr': '\u00AF',
'mdash': '\u2014',
'micro': '\u00B5',
'middot': '\u00B7',
'minus': '\u2212',
'Mu': '\u039C',
'mu': '\u03BC',
'nabla': '\u2207',
'nbsp': '\u00A0',
'ndash': '\u2013',
'ne': '\u2260',
'ni': '\u220B',
'not': '\u00AC',
'notin': '\u2209',
'nsub': '\u2284',
'Ntilde': '\u00D1',
'ntilde': '\u00F1',
'Nu': '\u039D',
'nu': '\u03BD',
'Oacute': '\u00D3',
'oacute': '\u00F3',
'Ocirc': '\u00D4',
'ocirc': '\u00F4',
'OElig': '\u0152',
'oelig': '\u0153',
'Ograve': '\u00D2',
'ograve': '\u00F2',
'oline': '\u203E',
'Omega': '\u03A9',
'omega': '\u03C9',
'Omicron': '\u039F',
'omicron': '\u03BF',
'oplus': '\u2295',
'or': '\u2228',
'ordf': '\u00AA',
'ordm': '\u00BA',
'Oslash': '\u00D8',
'oslash': '\u00F8',
'Otilde': '\u00D5',
'otilde': '\u00F5',
'otimes': '\u2297',
'Ouml': '\u00D6',
'ouml': '\u00F6',
'para': '\u00B6',
'permil': '\u2030',
'perp': '\u22A5',
'Phi': '\u03A6',
'phi': '\u03C6',
'Pi': '\u03A0',
'pi': '\u03C0',
'piv': '\u03D6',
'plusmn': '\u00B1',
'pound': '\u00A3',
'prime': '\u2032',
'Prime': '\u2033',
'prod': '\u220F',
'prop': '\u221D',
'Psi': '\u03A8',
'psi': '\u03C8',
'quot': '\u0022',
'radic': '\u221A',
'rang': '\u27E9',
'raquo': '\u00BB',
'rarr': '\u2192',
'rArr': '\u21D2',
'rceil': '\u2309',
'rdquo': '\u201D',
'real': '\u211C',
'reg': '\u00AE',
'rfloor': '\u230B',
'Rho': '\u03A1',
'rho': '\u03C1',
'rlm': '\u200F',
'rsaquo': '\u203A',
'rsquo': '\u2019',
'sbquo': '\u201A',
'Scaron': '\u0160',
'scaron': '\u0161',
'sdot': '\u22C5',
'sect': '\u00A7',
'shy': '\u00AD',
'Sigma': '\u03A3',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sim': '\u223C',
'spades': '\u2660',
'sub': '\u2282',
'sube': '\u2286',
'sum': '\u2211',
'sup': '\u2283',
'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supe': '\u2287',
'szlig': '\u00DF',
'Tau': '\u03A4',
'tau': '\u03C4',
'there4': '\u2234',
'Theta': '\u0398',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thinsp': '\u2009',
'THORN': '\u00DE',
'thorn': '\u00FE',
'tilde': '\u02DC',
'times': '\u00D7',
'trade': '\u2122',
'Uacute': '\u00DA',
'uacute': '\u00FA',
'uarr': '\u2191',
'uArr': '\u21D1',
'Ucirc': '\u00DB',
'ucirc': '\u00FB',
'Ugrave': '\u00D9',
'ugrave': '\u00F9',
'uml': '\u00A8',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'upsilon': '\u03C5',
'Uuml': '\u00DC',
'uuml': '\u00FC',
'weierp': '\u2118',
'Xi': '\u039E',
'xi': '\u03BE',
'Yacute': '\u00DD',
'yacute': '\u00FD',
'yen': '\u00A5',
'yuml': '\u00FF',
'Yuml': '\u0178',
'Zeta': '\u0396',
'zeta': '\u03B6',
'zwj': '\u200D',
'zwnj': '\u200C',
};
// The &ngsp; pseudo-entity is denoting a space. see:
// https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
export const NGSP_UNICODE = '\uE500';
NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
| Toxicable/angular | packages/compiler/src/ml_parser/tags.ts | TypeScript | mit | 7,644 |
# coding: utf-8
# In[ ]:
#练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科)
#输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母)
#加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字,
#作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 ,
#对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后,
#将移位后的单词利用随机字母补全到10个,最终形成以10个字母为一个单词,并以单个空格分割的加密文本,存入文件。
#解密:给定该文本文件并给定key(10位数字),恢复原来的文本。
#(提示,利用 ord() 及 chr() 函数, ord(x) 是取得字符 x 的ASCII码, chr(n) 是取得整数n(代表ASCII码)对应的字符。
#例: ord(a) 的值为 97 , chr(97) 的值为 'a' ,因字母 a 的ASCII码值为 97 。)
fh = open(r'd:\temp\words.txt')
text = fh.read()
fh.close()
print(len(text))
print(text)
| ZMMzhangmingming/liupengyuan.github.io | chapter2/homework/computer/5-10/201611680890-5.10.py | Python | mit | 1,296 |
var Model;
module("Ember.FilteredRecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 'abc', name: 'Charles'}
];
},
teardown: function() { }
});
test("must be created with a modelClass property", function() {
throws(function() {
Ember.FilteredRecordArray.create();
}, /FilteredRecordArrays must be created with a modelClass/);
});
test("must be created with a filterFunction property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model});
}, /FilteredRecordArrays must be created with a filterFunction/);
});
test("must be created with a filterProperties property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K});
}, /FilteredRecordArrays must be created with filterProperties/);
});
test("with a noop filter will return all the loaded records", function() {
expect(1);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: Ember.K,
filterProperties: []
});
equal(recordArray.get('length'), 3, "There are 3 records");
});
stop();
});
test("with a filter will return only the relevant loaded records", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 1, "There is still 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
stop();
});
test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() {
expect(3);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik' || record.get('name') === 'Kris';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 2, "There are 2 records");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches");
});
stop();
});
stop();
});
test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(5);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.fetch(2).then(function(record) {
start();
record.set('name', 'Estefan');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches");
});
stop();
});
stop();
});
test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(8);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
record.set('name', 'Ekris');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches");
record.set('name', 'Eskil');
equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches");
equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches");
});
stop();
});
stop();
}); | hypexr/grunt-version-copy-bower-components | test/fixtures/bower_components/ember-model/packages/ember-model/tests/filtered_record_array_test.js | JavaScript | mit | 5,733 |
// Package binary implements sintax-sugar functions on top of the standard
// library binary package
package binary
import (
"bufio"
"encoding/binary"
"io"
"gopkg.in/src-d/go-git.v4/plumbing"
)
// Read reads structured binary data from r into data. Bytes are read and
// decoded in BigEndian order
// https://golang.org/pkg/encoding/binary/#Read
func Read(r io.Reader, data ...interface{}) error {
for _, v := range data {
if err := binary.Read(r, binary.BigEndian, v); err != nil {
return err
}
}
return nil
}
// ReadUntil reads from r untin delim is found
func ReadUntil(r io.Reader, delim byte) ([]byte, error) {
var buf [1]byte
value := make([]byte, 0, 16)
for {
if _, err := io.ReadFull(r, buf[:]); err != nil {
if err == io.EOF {
return nil, err
}
return nil, err
}
if buf[0] == delim {
return value, nil
}
value = append(value, buf[0])
}
}
// ReadVariableWidthInt reads and returns an int in Git VLQ special format:
//
// Ordinary VLQ has some redundancies, example: the number 358 can be
// encoded as the 2-octet VLQ 0x8166 or the 3-octet VLQ 0x808166 or the
// 4-octet VLQ 0x80808166 and so forth.
//
// To avoid these redundancies, the VLQ format used in Git removes this
// prepending redundancy and extends the representable range of shorter
// VLQs by adding an offset to VLQs of 2 or more octets in such a way
// that the lowest possible value for such an (N+1)-octet VLQ becomes
// exactly one more than the maximum possible value for an N-octet VLQ.
// In particular, since a 1-octet VLQ can store a maximum value of 127,
// the minimum 2-octet VLQ (0x8000) is assigned the value 128 instead of
// 0. Conversely, the maximum value of such a 2-octet VLQ (0xff7f) is
// 16511 instead of just 16383. Similarly, the minimum 3-octet VLQ
// (0x808000) has a value of 16512 instead of zero, which means
// that the maximum 3-octet VLQ (0xffff7f) is 2113663 instead of
// just 2097151. And so forth.
//
// This is how the offset is saved in C:
//
// dheader[pos] = ofs & 127;
// while (ofs >>= 7)
// dheader[--pos] = 128 | (--ofs & 127);
//
func ReadVariableWidthInt(r io.Reader) (int64, error) {
var c byte
if err := Read(r, &c); err != nil {
return 0, err
}
var v = int64(c & maskLength)
for c&maskContinue > 0 {
v++
if err := Read(r, &c); err != nil {
return 0, err
}
v = (v << lengthBits) + int64(c&maskLength)
}
return v, nil
}
const (
maskContinue = uint8(128) // 1000 000
maskLength = uint8(127) // 0111 1111
lengthBits = uint8(7) // subsequent bytes has 7 bits to store the length
)
// ReadUint64 reads 8 bytes and returns them as a BigEndian uint32
func ReadUint64(r io.Reader) (uint64, error) {
var v uint64
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadUint32 reads 4 bytes and returns them as a BigEndian uint32
func ReadUint32(r io.Reader) (uint32, error) {
var v uint32
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadUint16 reads 2 bytes and returns them as a BigEndian uint16
func ReadUint16(r io.Reader) (uint16, error) {
var v uint16
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadHash reads a plumbing.Hash from r
func ReadHash(r io.Reader) (plumbing.Hash, error) {
var h plumbing.Hash
if err := binary.Read(r, binary.BigEndian, h[:]); err != nil {
return plumbing.ZeroHash, err
}
return h, nil
}
const sniffLen = 8000
// IsBinary detects if data is a binary value based on:
// http://git.kernel.org/cgit/git/git.git/tree/xdiff-interface.c?id=HEAD#n198
func IsBinary(r io.Reader) (bool, error) {
reader := bufio.NewReader(r)
c := 0
for {
if c == sniffLen {
break
}
b, err := reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
return false, err
}
if b == byte(0) {
return true, nil
}
c++
}
return false, nil
}
| kettle11/wabi | wabi/vendor/gopkg.in/src-d/go-git.v4/utils/binary/read.go | GO | mit | 3,985 |
var dude = "Dude";
var dude2 = new {
Name = "Dude", Age = 30,
};
var dude3 = new {
Name = "Dude", Age = 30, Kids = new {
Name = "LittleDude"
}
};
var dude4 = new {
Name = "Dude", Age = 30, Kids = new[] {
"LittleDude"
}
};
var dude5 = new {
Name = "Dude", Age = 30, Kids = new[] {
new {
Name = "LittleDude"
}
}
};
Action y = () => { };
Func<int, float, bool> z = (a, b) => {
var z = new {
a, b
};
return(z == null);
};
| bengardner/uncrustify | tests/output/cs/10140-remove_semi.cs | C# | gpl-2.0 | 532 |
#!/usr/bin/env python
# File created Sept 29, 2010
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Walters"
__email__ = "William.A.Walters@colorado.edu"
from os.path import basename
from skbio.parse.sequences import parse_fasta
from qiime.parse import parse_qual_score
def parse_fasta_file(fasta_lines):
""" Parses fasta file, generates dict of label:seq, list of seqs order
fasta_lines: list of lines from fasta file.
"""
fasta_seqs = {}
seq_order = []
for label, seq in parse_fasta(fasta_lines):
fasta_seqs[label.split()[0].strip()] = seq
seq_order.append(label)
return fasta_seqs, seq_order
def verify_equivalency(fasta_seqs,
qual_scores):
""" Tests for equivalent labels, base positions between fasta and qual file
fasta_seqs: dict of label:seq from fasta file
qual_scores: dict of label: qual scores
"""
if len(fasta_seqs) != len(qual_scores):
raise ValueError('Number of sequences not equal in input fasta ' +
'and qual file.')
qual_scores_labels = set(qual_scores.keys())
for label in fasta_seqs.keys():
# Should have equivalent labels
if label not in qual_scores_labels:
raise ValueError('Fasta label %s not found in quality score ' %
label + 'file.')
# should have equivalent lengths
if len(fasta_seqs[label]) != len(qual_scores[label]):
raise ValueError('Sequence %s does not have equivalent ' %
label + 'base positions between fasta and quality score file.')
def truncate_seqs(fasta_seqs,
qual_scores,
base_pos):
""" Truncates sequences to base position specified with base_pos
fasta_seqs: dict of seq label: seq string
qual_scores: dict of seq label: numpy array of int scores
base_pos: index in sequence to truncate at
"""
trunc_fasta_seqs = {}
trunc_qual_scores = {}
for seq in fasta_seqs:
trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos]
trunc_qual_scores[seq] = qual_scores[seq][:base_pos]
return trunc_fasta_seqs, trunc_qual_scores
def get_output_filepaths(output_dir,
fasta_fp,
qual_fp):
""" Returns output filepaths for filtered fasta and quality files
output_dir: output directory
fasta_fp: input fasta filepath
qual_fp: input quality scores filepath
"""
if not output_dir.endswith('/'):
output_dir += '/'
fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\
"_filtered.fasta"
qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\
"_filtered.qual"
return fasta_out_fp, qual_out_fp
def write_trunc_fasta(trunc_fasta_seqs,
fasta_out_fp,
seq_order):
""" Writes truncated fasta seqs in order specified with seq_order
trunc_fasta_seqs: dict of fasta label: truncated sequence string
fasta_out_fp: output filepath to write to
seq_order: list of fasta labels in the order of the original input fasta
"""
fasta_out = open(fasta_out_fp, "w")
for label in seq_order:
trunc_label = label.split()[0].strip()
fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label]))
def write_trunc_qual(trunc_qual_scores,
qual_out_fp,
seq_order):
""" Writes truncated quality score files out in proper format
trunc_qual_scores: dict of seq label: numpy array of scores as ints
qual_out_fp: output filepath to write truncated quality scores to
seq_order: List of full fasta labels to write to output filepath and
maintain the same order as input quality file.
"""
qual_line_size = 60
qual_out = open(qual_out_fp, "w")
for label in seq_order:
trunc_label = label.split()[0].strip()
current_trunc_qual_scores = trunc_qual_scores[trunc_label]
qual_out.write(">%s\n" % label)
current_qual_scores_lines = []
# Quality score format is a string of 60 base calls, followed by a
# newline, until the last N bases are written
for slice in range(0, len(trunc_qual_scores[trunc_label]),
qual_line_size):
# current_segment = map(str,
# current_trunc_qual_scores[slice:slice + qual_line_size])
current_segment = current_trunc_qual_scores[
slice:slice +
qual_line_size]
current_qual_scores_lines.append(" ".join(current_segment))
qual_out.write('\n'.join(current_qual_scores_lines))
qual_out.write('\n')
def truncate_fasta_qual(fasta_fp,
qual_fp,
output_dir,
base_pos):
""" Main program function for generating quality score histogram
fasta_fp: fasta filepath
qual_fp: quality score filepath
output_dir: output directory
base_pos: Nucleotide position to truncate the fasta and quality score at.
"""
qual_lines = open(qual_fp, "U")
fasta_lines = open(fasta_fp, "U")
qual_scores = parse_qual_score(qual_lines, value_cast_f=str)
# Get dict of fasta label:seq, and the sequence order (so output can
# be in the same order as the input sequences.
fasta_seqs, seq_order = parse_fasta_file(fasta_lines)
# Make sure the quality scores and fasta sequences have corresponding
# labels and base numbers
verify_equivalency(fasta_seqs, qual_scores)
# Truncate seqs to base_pos index
trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs,
qual_scores, base_pos)
# Get output filepaths
fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp,
qual_fp)
# Write truncated sequences out
write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order)
write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order)
| ssorgatem/qiime | qiime/truncate_fasta_qual_files.py | Python | gpl-2.0 | 6,323 |
Ext.define('Ext.rtl.scroll.Indicator', {
override: 'Ext.scroll.Indicator',
privates: {
translateX: function(value) {
if (this.getScroller().getRtl()) {
value = -value;
}
this.callParent([value]);
}
}
});
| sqlwang/my_wpblog | wp-content/themes/extjs/ext/classic/classic/src/rtl/scroll/Indicator.js | JavaScript | gpl-2.0 | 297 |
/*
Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "abstract_crawler.h"
#include "this_thread.h"
#include <boost/date_time.hpp>
using namespace Mysql::Tools::Dump;
my_boost::atomic_uint64_t Abstract_crawler::next_chain_id;
Abstract_crawler::Abstract_crawler(
Mysql::I_callable<bool, const Mysql::Tools::Base::Message_data&>*
message_handler, Simple_id_generator* object_id_generator)
: Abstract_chain_element(message_handler, object_id_generator)
{}
void Abstract_crawler::register_chain_maker(I_chain_maker* new_chain_maker)
{
m_chain_makers.push_back(new_chain_maker);
}
void Abstract_crawler::process_dump_task(I_dump_task* new_dump_task)
{
m_dump_tasks_created.push_back(new_dump_task);
Item_processing_data* main_item_processing_data=
this->new_task_created(new_dump_task);
this->object_processing_starts(main_item_processing_data);
for (std::vector<I_chain_maker*>::iterator it= m_chain_makers.begin();
it != m_chain_makers.end(); ++it)
{
uint64 new_chain_id= next_chain_id++;
Chain_data* chain_data= new Chain_data(new_chain_id);
I_object_reader* chain= (*it)->create_chain(chain_data, new_dump_task);
if (chain != NULL)
{
main_item_processing_data->set_chain(chain_data);
chain->read_object(
this->new_chain_created(
chain_data, main_item_processing_data, chain));
}
else
{
delete chain_data;
}
}
this->object_processing_ends(main_item_processing_data);
}
void Abstract_crawler::wait_for_tasks_completion()
{
for (std::vector<I_dump_task*>::iterator it= m_dump_tasks_created.begin();
it != m_dump_tasks_created.end(); ++it)
{
while ((*it)->is_completed() == false)
my_boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
bool Abstract_crawler::need_callbacks_in_child()
{
return true;
}
| myblockchain/myblockchain | client/dump/abstract_crawler.cc | C++ | gpl-2.0 | 2,532 |
<?php
/**
* @file
* Contains \Drupal\quickedit\Plugin\InPlaceEditorInterface.
*/
namespace Drupal\quickedit\Plugin;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Defines an interface for in-place editors plugins.
*/
interface InPlaceEditorInterface extends PluginInspectionInterface {
/**
* Checks whether this in-place editor is compatible with a given field.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
*
* @return bool
* TRUE if it is compatible, FALSE otherwise.
*/
public function isCompatible(FieldItemListInterface $items);
/**
* Generates metadata that is needed specifically for this editor.
*
* Will only be called by \Drupal\quickedit\MetadataGeneratorInterface::generate()
* when the passed in field instance & item values will use this editor.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
*
* @return array
* A keyed array with metadata. Each key should be prefixed with the plugin
* ID of the editor.
*/
public function getMetadata(FieldItemListInterface $items);
/**
* Returns the attachments for this editor.
*
* @return array
* An array of attachments, for use with #attached.
*
* @see drupal_process_attached()
*/
public function getAttachments();
}
| drupaals/demo.com | d8/core/modules/quickedit/src/Plugin/InPlaceEditorInterface.php | PHP | gpl-2.0 | 1,462 |
using MixERP.Net.i18n.Resources;
using MixERP.Net.WebControls.StockAdjustmentFactory.Helpers;
using System.Web.UI.HtmlControls;
namespace MixERP.Net.WebControls.StockAdjustmentFactory
{
public partial class FormView
{
private void AddErrorLabelBottom()
{
using (HtmlGenericControl errorLabel = new HtmlGenericControl())
{
errorLabel.TagName = "div";
errorLabel.ID = "ErrorLabel";
errorLabel.Attributes.Add("class", "big error vpad16");
this.container.Controls.Add(errorLabel);
}
}
private void AddSaveButton(HtmlGenericControl div)
{
using (HtmlInputButton button = new HtmlInputButton())
{
button.ID = "SaveButton";
button.Value = Titles.Save;
button.Attributes.Add("class", "ui small blue button");
div.Controls.Add(button);
}
}
private void AddStatementReferenceTextArea(HtmlGenericControl fields)
{
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "StatementReferenceTextArea");
label.InnerText = Titles.StatementReference;
field.Controls.Add(label);
}
using (HtmlTextArea statementReferenceTextArea = new HtmlTextArea())
{
statementReferenceTextArea.ID = "StatementReferenceTextArea";
statementReferenceTextArea.Rows = 4;
field.Controls.Add(statementReferenceTextArea);
}
fields.Controls.Add(field);
}
}
private void AddSourceStoreSelect(HtmlGenericControl fields)
{
if (!this.DisplaySourceStore)
{
return;
}
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "SourceStoreSelect");
label.InnerText = Titles.DeliverFrom;
field.Controls.Add(label);
}
using (HtmlSelect sourceStoreSelect = new HtmlSelect())
{
sourceStoreSelect.ID = "SourceStoreSelect";
field.Controls.Add(sourceStoreSelect);
}
fields.Controls.Add(field);
}
}
private void AddShippingCompanySelect(HtmlGenericControl fields)
{
if (!this.DisplayShipper)
{
return;
}
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "ShippingCompanySelect");
label.InnerText = Titles.ShippingCompany;
field.Controls.Add(label);
}
using (HtmlSelect shippingCompanySelect = new HtmlSelect())
{
shippingCompanySelect.ID = "ShippingCompanySelect";
field.Controls.Add(shippingCompanySelect);
}
fields.Controls.Add(field);
}
}
private void CreateBottomPanel()
{
using (HtmlGenericControl fields = FormHelper.GetFields())
{
fields.TagName = "div";
fields.Attributes.Add("class", "ui form");
fields.Attributes.Add("style", "width:290px;");
this.AddSourceStoreSelect(fields);
this.AddShippingCompanySelect(fields);
this.AddStatementReferenceTextArea(fields);
this.AddSaveButton(fields);
this.container.Controls.Add(fields);
}
}
}
} | mixerp6/mixerp | src/Libraries/Server Controls/Project/MixERP.Net.WebControls.StockAdjustmentFactory/FormView/BottomPanel.cs | C# | gpl-2.0 | 4,315 |
<?php
/**
* @file getlocations_box.tpl.php
* @author Bob Hutchinson http://drupal.org/user/52366
* @copyright GNU GPL
*
* Template file for colorbox implementation
* available variables:
* $box_width $box_height contain the getlocations_search defaults set in the config
*/
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">
<!-- getlocations_box -->
<head>
<title><?php print $head_title; ?></title>
<?php print $head; ?>
<?php print $styles; ?>
<?php print $scripts; ?>
<style>
/* adjust these to match your colorbox and map size */
body {
width: 500px;
margin: 0;
}
#page {
min-width: 500px;
width: 500px;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}
#content-area {
}
</style>
</head>
<body class="<?php print $body_classes; ?>">
<div id="page"><div id="page-inner">
<div id="main"><div id="main-inner" class="clear-block">
<div id="content"><div id="content-inner">
<?php if ($title): ?>
<h2 class="title"><?php print $title; ?></h2>
<?php endif; ?>
<div id="content-area">
<?php print $content; ?>
</div>
</div></div>
</div></div>
</div></div>
<?php print $closure; ?>
</body>
</html>
| paulcherrypipka/vcat | sites/all/modules/getlocations/modules/getlocations_search/getlocations_search_box.tpl.php | PHP | gpl-2.0 | 1,370 |
/*
vfp/vfpsingle.c - ARM VFPv3 emulation unit - SoftFloat single instruction
Copyright (C) 2003 Skyeye Develop Group
for help please send mail to <skyeye-developer@lists.gro.clinux.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* This code is derived in part from :
* - Android kernel
* - John R. Housers softfloat library, which
* carries the following notice:
*
* ===========================================================================
* This C source file is part of the SoftFloat IEC/IEEE Floating-point
* Arithmetic Package, Release 2.
*
* Written by John R. Hauser. This work was made possible in part by the
* International Computer Science Institute, located at Suite 600, 1947 Center
* Street, Berkeley, California 94704. Funding was partially provided by the
* National Science Foundation under grant MIP-9311980. The original version
* of this code was written as part of a project to build a fixed-point vector
* processor in collaboration with the University of California at Berkeley,
* overseen by Profs. Nelson Morgan and John Wawrzynek. More information
* is available through the web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
* arithmetic/softfloat.html'.
*
* THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE. Although reasonable effort
* has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
* TIMES RESULT IN INCORRECT BEHAVIOR. USE OF THIS SOFTWARE IS RESTRICTED TO
* PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
* AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
*
* Derivative works are acceptable, even for commercial purposes, so long as
* (1) they include prominent notice that the work is derivative, and (2) they
* include prominent notice akin to these three paragraphs for those parts of
* this code that are retained.
* ===========================================================================
*/
#include <algorithm>
#include <cinttypes>
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/logging/log.h"
#include "core/arm/skyeye_common/vfp/asm_vfp.h"
#include "core/arm/skyeye_common/vfp/vfp.h"
#include "core/arm/skyeye_common/vfp/vfp_helper.h"
static struct vfp_single vfp_single_default_qnan = {
255, 0, VFP_SINGLE_SIGNIFICAND_QNAN,
};
static void vfp_single_dump(const char* str, struct vfp_single* s) {
LOG_TRACE(Core_ARM11, "%s: sign=%d exponent=%d significand=%08x", str, s->sign != 0,
s->exponent, s->significand);
}
static void vfp_single_normalise_denormal(struct vfp_single* vs) {
int bits = 31 - fls(vs->significand);
vfp_single_dump("normalise_denormal: in", vs);
if (bits) {
vs->exponent -= bits - 1;
vs->significand <<= bits;
}
vfp_single_dump("normalise_denormal: out", vs);
}
u32 vfp_single_normaliseround(ARMul_State* state, int sd, struct vfp_single* vs, u32 fpscr,
const char* func) {
u32 significand, incr, rmode;
int exponent, shift, underflow;
u32 exceptions = 0;
vfp_single_dump("pack: in", vs);
/*
* Infinities and NaNs are a special case.
*/
if (vs->exponent == 255 && (vs->significand == 0 || exceptions))
goto pack;
/*
* Special-case zero.
*/
if (vs->significand == 0) {
vs->exponent = 0;
goto pack;
}
exponent = vs->exponent;
significand = vs->significand;
/*
* Normalise first. Note that we shift the significand up to
* bit 31, so we have VFP_SINGLE_LOW_BITS + 1 below the least
* significant bit.
*/
shift = 32 - fls(significand);
if (shift < 32 && shift) {
exponent -= shift;
significand <<= shift;
}
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: normalised", vs);
#endif
/*
* Tiny number?
*/
underflow = exponent < 0;
if (underflow) {
significand = vfp_shiftright32jamming(significand, -exponent);
exponent = 0;
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: tiny number", vs);
#endif
if (!(significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1)))
underflow = 0;
}
/*
* Select rounding increment.
*/
incr = 0;
rmode = fpscr & FPSCR_RMODE_MASK;
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 1 << VFP_SINGLE_LOW_BITS;
if ((significand & (1 << (VFP_SINGLE_LOW_BITS + 1))) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vs->sign != 0))
incr = (1 << (VFP_SINGLE_LOW_BITS + 1)) - 1;
LOG_TRACE(Core_ARM11, "rounding increment = 0x%08x", incr);
/*
* Is our rounding going to overflow?
*/
if ((significand + incr) < significand) {
exponent += 1;
significand = (significand >> 1) | (significand & 1);
incr >>= 1;
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: overflow", vs);
#endif
}
/*
* If any of the low bits (which will be shifted out of the
* number) are non-zero, the result is inexact.
*/
if (significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1))
exceptions |= FPSCR_IXC;
/*
* Do our rounding.
*/
significand += incr;
/*
* Infinity?
*/
if (exponent >= 254) {
exceptions |= FPSCR_OFC | FPSCR_IXC;
if (incr == 0) {
vs->exponent = 253;
vs->significand = 0x7fffffff;
} else {
vs->exponent = 255; /* infinity */
vs->significand = 0;
}
} else {
if (significand >> (VFP_SINGLE_LOW_BITS + 1) == 0)
exponent = 0;
if (exponent || significand > 0x80000000)
underflow = 0;
if (underflow)
exceptions |= FPSCR_UFC;
vs->exponent = exponent;
vs->significand = significand >> 1;
}
pack:
vfp_single_dump("pack: final", vs);
{
s32 d = vfp_single_pack(vs);
LOG_TRACE(Core_ARM11, "%s: d(s%d)=%08x exceptions=%08x", func, sd, d, exceptions);
vfp_put_float(state, d, sd);
}
return exceptions;
}
/*
* Propagate the NaN, setting exceptions if it is signalling.
* 'n' is always a NaN. 'm' may be a number, NaN or infinity.
*/
static u32 vfp_propagate_nan(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm,
u32 fpscr) {
struct vfp_single* nan;
int tn, tm = 0;
tn = vfp_single_type(vsn);
if (vsm)
tm = vfp_single_type(vsm);
if (fpscr & FPSCR_DEFAULT_NAN)
/*
* Default NaN mode - always returns a quiet NaN
*/
nan = &vfp_single_default_qnan;
else {
/*
* Contemporary mode - select the first signalling
* NAN, or if neither are signalling, the first
* quiet NAN.
*/
if (tn == VFP_SNAN || (tm != VFP_SNAN && tn == VFP_QNAN))
nan = vsn;
else
nan = vsm;
/*
* Make the NaN quiet.
*/
nan->significand |= VFP_SINGLE_SIGNIFICAND_QNAN;
}
*vsd = *nan;
/*
* If one was a signalling NAN, raise invalid operation.
*/
return tn == VFP_SNAN || tm == VFP_SNAN ? FPSCR_IOC : VFP_NAN_FLAG;
}
/*
* Extended operations
*/
static u32 vfp_single_fabs(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, vfp_single_packed_abs(m), sd);
return 0;
}
static u32 vfp_single_fcpy(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, m, sd);
return 0;
}
static u32 vfp_single_fneg(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, vfp_single_packed_negate(m), sd);
return 0;
}
static const u16 sqrt_oddadjust[] = {
0x0004, 0x0022, 0x005d, 0x00b1, 0x011d, 0x019f, 0x0236, 0x02e0,
0x039c, 0x0468, 0x0545, 0x0631, 0x072b, 0x0832, 0x0946, 0x0a67,
};
static const u16 sqrt_evenadjust[] = {
0x0a2d, 0x08af, 0x075a, 0x0629, 0x051a, 0x0429, 0x0356, 0x029e,
0x0200, 0x0179, 0x0109, 0x00af, 0x0068, 0x0034, 0x0012, 0x0002,
};
u32 vfp_estimate_sqrt_significand(u32 exponent, u32 significand) {
int index;
u32 z, a;
if ((significand & 0xc0000000) != 0x40000000) {
LOG_TRACE(Core_ARM11, "invalid significand");
}
a = significand << 1;
index = (a >> 27) & 15;
if (exponent & 1) {
z = 0x4000 + (a >> 17) - sqrt_oddadjust[index];
z = ((a / z) << 14) + (z << 15);
a >>= 1;
} else {
z = 0x8000 + (a >> 17) - sqrt_evenadjust[index];
z = a / z + z;
z = (z >= 0x20000) ? 0xffff8000 : (z << 15);
if (z <= a)
return (s32)a >> 1;
}
{
u64 v = (u64)a << 31;
do_div(v, z);
return (u32)(v + (z >> 1));
}
}
static u32 vfp_single_fsqrt(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm, vsd, *vsp;
int ret, tm;
u32 exceptions = 0;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
tm = vfp_single_type(&vsm);
if (tm & (VFP_NAN | VFP_INFINITY)) {
vsp = &vsd;
if (tm & VFP_NAN)
ret = vfp_propagate_nan(vsp, &vsm, nullptr, fpscr);
else if (vsm.sign == 0) {
sqrt_copy:
vsp = &vsm;
ret = 0;
} else {
sqrt_invalid:
vsp = &vfp_single_default_qnan;
ret = FPSCR_IOC;
}
vfp_put_float(state, vfp_single_pack(vsp), sd);
return ret;
}
/*
* sqrt(+/- 0) == +/- 0
*/
if (tm & VFP_ZERO)
goto sqrt_copy;
/*
* Normalise a denormalised number
*/
if (tm & VFP_DENORMAL)
vfp_single_normalise_denormal(&vsm);
/*
* sqrt(<0) = invalid
*/
if (vsm.sign)
goto sqrt_invalid;
vfp_single_dump("sqrt", &vsm);
/*
* Estimate the square root.
*/
vsd.sign = 0;
vsd.exponent = ((vsm.exponent - 127) >> 1) + 127;
vsd.significand = vfp_estimate_sqrt_significand(vsm.exponent, vsm.significand) + 2;
vfp_single_dump("sqrt estimate", &vsd);
/*
* And now adjust.
*/
if ((vsd.significand & VFP_SINGLE_LOW_BITS_MASK) <= 5) {
if (vsd.significand < 2) {
vsd.significand = 0xffffffff;
} else {
u64 term;
s64 rem;
vsm.significand <<= static_cast<u32>((vsm.exponent & 1) == 0);
term = (u64)vsd.significand * vsd.significand;
rem = ((u64)vsm.significand << 32) - term;
LOG_TRACE(Core_ARM11, "term=%016" PRIx64 "rem=%016" PRIx64, term, rem);
while (rem < 0) {
vsd.significand -= 1;
rem += ((u64)vsd.significand << 1) | 1;
}
vsd.significand |= rem != 0;
}
}
vsd.significand = vfp_shiftright32jamming(vsd.significand, 1);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fsqrt");
return exceptions;
}
/*
* Equal := ZC
* Less than := N
* Greater than := C
* Unordered := CV
*/
static u32 vfp_compare(ARMul_State* state, int sd, int signal_on_qnan, s32 m, u32 fpscr) {
s32 d;
u32 ret = 0;
d = vfp_get_float(state, sd);
if (vfp_single_packed_exponent(m) == 255 && vfp_single_packed_mantissa(m)) {
ret |= FPSCR_CFLAG | FPSCR_VFLAG;
if (signal_on_qnan ||
!(vfp_single_packed_mantissa(m) & (1 << (VFP_SINGLE_MANTISSA_BITS - 1))))
/*
* Signalling NaN, or signalling on quiet NaN
*/
ret |= FPSCR_IOC;
}
if (vfp_single_packed_exponent(d) == 255 && vfp_single_packed_mantissa(d)) {
ret |= FPSCR_CFLAG | FPSCR_VFLAG;
if (signal_on_qnan ||
!(vfp_single_packed_mantissa(d) & (1 << (VFP_SINGLE_MANTISSA_BITS - 1))))
/*
* Signalling NaN, or signalling on quiet NaN
*/
ret |= FPSCR_IOC;
}
if (ret == 0) {
if (d == m || vfp_single_packed_abs(d | m) == 0) {
/*
* equal
*/
ret |= FPSCR_ZFLAG | FPSCR_CFLAG;
} else if (vfp_single_packed_sign(d ^ m)) {
/*
* different signs
*/
if (vfp_single_packed_sign(d))
/*
* d is negative, so d < m
*/
ret |= FPSCR_NFLAG;
else
/*
* d is positive, so d > m
*/
ret |= FPSCR_CFLAG;
} else if ((vfp_single_packed_sign(d) != 0) ^ (d < m)) {
/*
* d < m
*/
ret |= FPSCR_NFLAG;
} else if ((vfp_single_packed_sign(d) != 0) ^ (d > m)) {
/*
* d > m
*/
ret |= FPSCR_CFLAG;
}
}
return ret;
}
static u32 vfp_single_fcmp(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 0, m, fpscr);
}
static u32 vfp_single_fcmpe(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 1, m, fpscr);
}
static u32 vfp_single_fcmpz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 0, 0, fpscr);
}
static u32 vfp_single_fcmpez(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 1, 0, fpscr);
}
static u32 vfp_single_fcvtd(ARMul_State* state, int dd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
struct vfp_double vdd;
int tm;
u32 exceptions = 0;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
tm = vfp_single_type(&vsm);
/*
* If we have a signalling NaN, signal invalid operation.
*/
if (tm == VFP_SNAN)
exceptions |= FPSCR_IOC;
if (tm & VFP_DENORMAL)
vfp_single_normalise_denormal(&vsm);
vdd.sign = vsm.sign;
vdd.significand = (u64)vsm.significand << 32;
/*
* If we have an infinity or NaN, the exponent must be 2047.
*/
if (tm & (VFP_INFINITY | VFP_NAN)) {
vdd.exponent = 2047;
if (tm == VFP_QNAN)
vdd.significand |= VFP_DOUBLE_SIGNIFICAND_QNAN;
goto pack_nan;
} else if (tm & VFP_ZERO)
vdd.exponent = 0;
else
vdd.exponent = vsm.exponent + (1023 - 127);
exceptions |= vfp_double_normaliseround(state, dd, &vdd, fpscr, "fcvtd");
return exceptions;
pack_nan:
vfp_put_double(state, vfp_double_pack(&vdd), dd);
return exceptions;
}
static u32 vfp_single_fuito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vs;
u32 exceptions = 0;
vs.sign = 0;
vs.exponent = 127 + 31 - 1;
vs.significand = (u32)m;
exceptions |= vfp_single_normaliseround(state, sd, &vs, fpscr, "fuito");
return exceptions;
}
static u32 vfp_single_fsito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vs;
u32 exceptions = 0;
vs.sign = (m & 0x80000000) >> 16;
vs.exponent = 127 + 31 - 1;
vs.significand = vs.sign ? -m : m;
exceptions |= vfp_single_normaliseround(state, sd, &vs, fpscr, "fsito");
return exceptions;
}
static u32 vfp_single_ftoui(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
u32 d, exceptions = 0;
int rmode = fpscr & FPSCR_RMODE_MASK;
int tm;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vfp_single_dump("VSM", &vsm);
/*
* Do we have a denormalised number?
*/
tm = vfp_single_type(&vsm);
if (tm & VFP_DENORMAL)
exceptions |= FPSCR_IDC;
if (tm & VFP_NAN)
vsm.sign = 1;
if (vsm.exponent >= 127 + 32) {
d = vsm.sign ? 0 : 0xffffffff;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127) {
int shift = 127 + 31 - vsm.exponent;
u32 rem, incr = 0;
/*
* 2^0 <= m < 2^32-2^8
*/
d = (vsm.significand << 1) >> shift;
if (shift > 0) {
rem = (vsm.significand << 1) << (32 - shift);
} else {
rem = 0;
}
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 0x80000000;
if ((d & 1) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) {
incr = ~0;
}
if ((rem + incr) < rem) {
if (d < 0xffffffff)
d += 1;
else
exceptions |= FPSCR_IOC;
}
if (d && vsm.sign) {
d = 0;
exceptions |= FPSCR_IOC;
} else if (rem)
exceptions |= FPSCR_IXC;
} else {
d = 0;
if (vsm.exponent | vsm.significand) {
if (rmode == FPSCR_ROUND_NEAREST) {
if (vsm.exponent >= 126) {
d = vsm.sign ? 0 : 1;
exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC;
} else {
exceptions |= FPSCR_IXC;
}
} else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) {
d = 1;
exceptions |= FPSCR_IXC;
} else if (rmode == FPSCR_ROUND_MINUSINF) {
exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC;
} else {
exceptions |= FPSCR_IXC;
}
}
}
LOG_TRACE(Core_ARM11, "ftoui: d(s%d)=%08x exceptions=%08x", sd, d, exceptions);
vfp_put_float(state, d, sd);
return exceptions;
}
static u32 vfp_single_ftouiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_single_ftoui(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO);
}
static u32 vfp_single_ftosi(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
u32 d, exceptions = 0;
int rmode = fpscr & FPSCR_RMODE_MASK;
int tm;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vfp_single_dump("VSM", &vsm);
/*
* Do we have a denormalised number?
*/
tm = vfp_single_type(&vsm);
if (vfp_single_type(&vsm) & VFP_DENORMAL)
exceptions |= FPSCR_IDC;
if (tm & VFP_NAN) {
d = 0;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127 + 31) {
/*
* m >= 2^31-2^7: invalid
*/
d = 0x7fffffff;
if (vsm.sign)
d = ~d;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127) {
int shift = 127 + 31 - vsm.exponent;
u32 rem, incr = 0;
/* 2^0 <= m <= 2^31-2^7 */
d = (vsm.significand << 1) >> shift;
rem = (vsm.significand << 1) << (32 - shift);
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 0x80000000;
if ((d & 1) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) {
incr = ~0;
}
if ((rem + incr) < rem && d < 0xffffffff)
d += 1;
if (d > (0x7fffffffu + (vsm.sign != 0))) {
d = (0x7fffffffu + (vsm.sign != 0));
exceptions |= FPSCR_IOC;
} else if (rem)
exceptions |= FPSCR_IXC;
if (vsm.sign)
d = (~d + 1);
} else {
d = 0;
if (vsm.exponent | vsm.significand) {
exceptions |= FPSCR_IXC;
if (rmode == FPSCR_ROUND_NEAREST) {
if (vsm.exponent >= 126)
d = vsm.sign ? 0xffffffff : 1;
} else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) {
d = 1;
} else if (rmode == FPSCR_ROUND_MINUSINF && vsm.sign) {
d = 0xffffffff;
}
}
}
LOG_TRACE(Core_ARM11, "ftosi: d(s%d)=%08x exceptions=%08x", sd, d, exceptions);
vfp_put_float(state, (s32)d, sd);
return exceptions;
}
static u32 vfp_single_ftosiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_single_ftosi(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO);
}
static struct op fops_ext[] = {
{vfp_single_fcpy, 0}, // 0x00000000 - FEXT_FCPY
{vfp_single_fabs, 0}, // 0x00000001 - FEXT_FABS
{vfp_single_fneg, 0}, // 0x00000002 - FEXT_FNEG
{vfp_single_fsqrt, 0}, // 0x00000003 - FEXT_FSQRT
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_fcmp, OP_SCALAR}, // 0x00000008 - FEXT_FCMP
{vfp_single_fcmpe, OP_SCALAR}, // 0x00000009 - FEXT_FCMPE
{vfp_single_fcmpz, OP_SCALAR}, // 0x0000000A - FEXT_FCMPZ
{vfp_single_fcmpez, OP_SCALAR}, // 0x0000000B - FEXT_FCMPEZ
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_fcvtd, OP_SCALAR | OP_DD}, // 0x0000000F - FEXT_FCVT
{vfp_single_fuito, OP_SCALAR}, // 0x00000010 - FEXT_FUITO
{vfp_single_fsito, OP_SCALAR}, // 0x00000011 - FEXT_FSITO
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_ftoui, OP_SCALAR}, // 0x00000018 - FEXT_FTOUI
{vfp_single_ftouiz, OP_SCALAR}, // 0x00000019 - FEXT_FTOUIZ
{vfp_single_ftosi, OP_SCALAR}, // 0x0000001A - FEXT_FTOSI
{vfp_single_ftosiz, OP_SCALAR}, // 0x0000001B - FEXT_FTOSIZ
};
static u32 vfp_single_fadd_nonnumber(struct vfp_single* vsd, struct vfp_single* vsn,
struct vfp_single* vsm, u32 fpscr) {
struct vfp_single* vsp;
u32 exceptions = 0;
int tn, tm;
tn = vfp_single_type(vsn);
tm = vfp_single_type(vsm);
if (tn & tm & VFP_INFINITY) {
/*
* Two infinities. Are they different signs?
*/
if (vsn->sign ^ vsm->sign) {
/*
* different signs -> invalid
*/
exceptions |= FPSCR_IOC;
vsp = &vfp_single_default_qnan;
} else {
/*
* same signs -> valid
*/
vsp = vsn;
}
} else if (tn & VFP_INFINITY && tm & VFP_NUMBER) {
/*
* One infinity and one number -> infinity
*/
vsp = vsn;
} else {
/*
* 'n' is a NaN of some type
*/
return vfp_propagate_nan(vsd, vsn, vsm, fpscr);
}
*vsd = *vsp;
return exceptions;
}
static u32 vfp_single_add(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm,
u32 fpscr) {
u32 exp_diff, m_sig;
if (vsn->significand & 0x80000000 || vsm->significand & 0x80000000) {
LOG_WARNING(Core_ARM11, "bad FP values");
vfp_single_dump("VSN", vsn);
vfp_single_dump("VSM", vsm);
}
/*
* Ensure that 'n' is the largest magnitude number. Note that
* if 'n' and 'm' have equal exponents, we do not swap them.
* This ensures that NaN propagation works correctly.
*/
if (vsn->exponent < vsm->exponent) {
std::swap(vsm, vsn);
}
/*
* Is 'n' an infinity or a NaN? Note that 'm' may be a number,
* infinity or a NaN here.
*/
if (vsn->exponent == 255)
return vfp_single_fadd_nonnumber(vsd, vsn, vsm, fpscr);
/*
* We have two proper numbers, where 'vsn' is the larger magnitude.
*
* Copy 'n' to 'd' before doing the arithmetic.
*/
*vsd = *vsn;
/*
* Align both numbers.
*/
exp_diff = vsn->exponent - vsm->exponent;
m_sig = vfp_shiftright32jamming(vsm->significand, exp_diff);
/*
* If the signs are different, we are really subtracting.
*/
if (vsn->sign ^ vsm->sign) {
m_sig = vsn->significand - m_sig;
if ((s32)m_sig < 0) {
vsd->sign = vfp_sign_negate(vsd->sign);
m_sig = (~m_sig + 1);
} else if (m_sig == 0) {
vsd->sign = (fpscr & FPSCR_RMODE_MASK) == FPSCR_ROUND_MINUSINF ? 0x8000 : 0;
}
} else {
m_sig = vsn->significand + m_sig;
}
vsd->significand = m_sig;
return 0;
}
static u32 vfp_single_multiply(struct vfp_single* vsd, struct vfp_single* vsn,
struct vfp_single* vsm, u32 fpscr) {
vfp_single_dump("VSN", vsn);
vfp_single_dump("VSM", vsm);
/*
* Ensure that 'n' is the largest magnitude number. Note that
* if 'n' and 'm' have equal exponents, we do not swap them.
* This ensures that NaN propagation works correctly.
*/
if (vsn->exponent < vsm->exponent) {
std::swap(vsm, vsn);
LOG_TRACE(Core_ARM11, "swapping M <-> N");
}
vsd->sign = vsn->sign ^ vsm->sign;
/*
* If 'n' is an infinity or NaN, handle it. 'm' may be anything.
*/
if (vsn->exponent == 255) {
if (vsn->significand || (vsm->exponent == 255 && vsm->significand))
return vfp_propagate_nan(vsd, vsn, vsm, fpscr);
if ((vsm->exponent | vsm->significand) == 0) {
*vsd = vfp_single_default_qnan;
return FPSCR_IOC;
}
vsd->exponent = vsn->exponent;
vsd->significand = 0;
return 0;
}
/*
* If 'm' is zero, the result is always zero. In this case,
* 'n' may be zero or a number, but it doesn't matter which.
*/
if ((vsm->exponent | vsm->significand) == 0) {
vsd->exponent = 0;
vsd->significand = 0;
return 0;
}
/*
* We add 2 to the destination exponent for the same reason as
* the addition case - though this time we have +1 from each
* input operand.
*/
vsd->exponent = vsn->exponent + vsm->exponent - 127 + 2;
vsd->significand = vfp_hi64to32jamming((u64)vsn->significand * vsm->significand);
vfp_single_dump("VSD", vsd);
return 0;
}
#define NEG_MULTIPLY (1 << 0)
#define NEG_SUBTRACT (1 << 1)
static u32 vfp_single_multiply_accumulate(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr,
u32 negate, const char* func) {
vfp_single vsd, vsp, vsn, vsm;
u32 exceptions = 0;
s32 v;
v = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, v);
exceptions |= vfp_single_unpack(&vsn, v, fpscr);
if (vsn.exponent == 0 && vsn.significand)
vfp_single_normalise_denormal(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
vfp_single_normalise_denormal(&vsm);
exceptions |= vfp_single_multiply(&vsp, &vsn, &vsm, fpscr);
if (negate & NEG_MULTIPLY)
vsp.sign = vfp_sign_negate(vsp.sign);
v = vfp_get_float(state, sd);
LOG_TRACE(Core_ARM11, "s%u = %08x", sd, v);
exceptions |= vfp_single_unpack(&vsn, v, fpscr);
if (vsn.exponent == 0 && vsn.significand != 0)
vfp_single_normalise_denormal(&vsn);
if (negate & NEG_SUBTRACT)
vsn.sign = vfp_sign_negate(vsn.sign);
exceptions |= vfp_single_add(&vsd, &vsn, &vsp, fpscr);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, func);
return exceptions;
}
/*
* Standard operations
*/
/*
* sd = sd + (sn * sm)
*/
static u32 vfp_single_fmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
u32 exceptions = 0;
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
exceptions |= vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, 0, "fmac");
return exceptions;
}
/*
* sd = sd - (sn * sm)
*/
static u32 vfp_single_fnmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
// TODO: this one has its arguments inverted, investigate.
LOG_TRACE(Core_ARM11, "s%u = %08x", sd, sn);
return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_MULTIPLY, "fnmac");
}
/*
* sd = -sd + (sn * sm)
*/
static u32 vfp_single_fmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_SUBTRACT, "fmsc");
}
/*
* sd = -sd - (sn * sm)
*/
static u32 vfp_single_fnmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_SUBTRACT | NEG_MULTIPLY,
"fnmsc");
}
/*
* sd = sn * sm
*/
static u32 vfp_single_fmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
vfp_single_normalise_denormal(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
vfp_single_normalise_denormal(&vsm);
exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fmul");
return exceptions;
}
/*
* sd = -(sn * sm)
*/
static u32 vfp_single_fnmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
vfp_single_normalise_denormal(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
vfp_single_normalise_denormal(&vsm);
exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr);
vsd.sign = vfp_sign_negate(vsd.sign);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fnmul");
return exceptions;
}
/*
* sd = sn + sm
*/
static u32 vfp_single_fadd(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
/*
* Unpack and normalise denormals.
*/
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
vfp_single_normalise_denormal(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
vfp_single_normalise_denormal(&vsm);
exceptions |= vfp_single_add(&vsd, &vsn, &vsm, fpscr);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fadd");
return exceptions;
}
/*
* sd = sn - sm
*/
static u32 vfp_single_fsub(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
/*
* Subtraction is addition with one sign inverted.
*/
if (m != 0x7FC00000) // Only negate if m isn't NaN.
m = vfp_single_packed_negate(m);
return vfp_single_fadd(state, sd, sn, m, fpscr);
}
/*
* sd = sn / sm
*/
static u32 vfp_single_fdiv(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
int tm, tn;
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vsd.sign = vsn.sign ^ vsm.sign;
tn = vfp_single_type(&vsn);
tm = vfp_single_type(&vsm);
/*
* Is n a NAN?
*/
if (tn & VFP_NAN)
goto vsn_nan;
/*
* Is m a NAN?
*/
if (tm & VFP_NAN)
goto vsm_nan;
/*
* If n and m are infinity, the result is invalid
* If n and m are zero, the result is invalid
*/
if (tm & tn & (VFP_INFINITY | VFP_ZERO))
goto invalid;
/*
* If n is infinity, the result is infinity
*/
if (tn & VFP_INFINITY)
goto infinity;
/*
* If m is zero, raise div0 exception
*/
if (tm & VFP_ZERO)
goto divzero;
/*
* If m is infinity, or n is zero, the result is zero
*/
if (tm & VFP_INFINITY || tn & VFP_ZERO)
goto zero;
if (tn & VFP_DENORMAL)
vfp_single_normalise_denormal(&vsn);
if (tm & VFP_DENORMAL)
vfp_single_normalise_denormal(&vsm);
/*
* Ok, we have two numbers, we can perform division.
*/
vsd.exponent = vsn.exponent - vsm.exponent + 127 - 1;
vsm.significand <<= 1;
if (vsm.significand <= (2 * vsn.significand)) {
vsn.significand >>= 1;
vsd.exponent++;
}
{
u64 significand = (u64)vsn.significand << 32;
do_div(significand, vsm.significand);
vsd.significand = (u32)significand;
}
if ((vsd.significand & 0x3f) == 0)
vsd.significand |= ((u64)vsm.significand * vsd.significand != (u64)vsn.significand << 32);
exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fdiv");
return exceptions;
vsn_nan:
exceptions |= vfp_propagate_nan(&vsd, &vsn, &vsm, fpscr);
pack:
vfp_put_float(state, vfp_single_pack(&vsd), sd);
return exceptions;
vsm_nan:
exceptions |= vfp_propagate_nan(&vsd, &vsm, &vsn, fpscr);
goto pack;
zero:
vsd.exponent = 0;
vsd.significand = 0;
goto pack;
divzero:
exceptions |= FPSCR_DZC;
infinity:
vsd.exponent = 255;
vsd.significand = 0;
goto pack;
invalid:
vfp_put_float(state, vfp_single_pack(&vfp_single_default_qnan), sd);
exceptions |= FPSCR_IOC;
return exceptions;
}
static struct op fops[] = {
{vfp_single_fmac, 0}, {vfp_single_fmsc, 0}, {vfp_single_fmul, 0},
{vfp_single_fadd, 0}, {vfp_single_fnmac, 0}, {vfp_single_fnmsc, 0},
{vfp_single_fnmul, 0}, {vfp_single_fsub, 0}, {vfp_single_fdiv, 0},
};
#define FREG_BANK(x) ((x)&0x18)
#define FREG_IDX(x) ((x)&7)
u32 vfp_single_cpdo(ARMul_State* state, u32 inst, u32 fpscr) {
u32 op = inst & FOP_MASK;
u32 exceptions = 0;
unsigned int dest;
unsigned int sn = vfp_get_sn(inst);
unsigned int sm = vfp_get_sm(inst);
unsigned int vecitr, veclen, vecstride;
struct op* fop;
vecstride = 1 + ((fpscr & FPSCR_STRIDE_MASK) == FPSCR_STRIDE_MASK);
fop = (op == FOP_EXT) ? &fops_ext[FEXT_TO_IDX(inst)] : &fops[FOP_TO_IDX(op)];
/*
* fcvtsd takes a dN register number as destination, not sN.
* Technically, if bit 0 of dd is set, this is an invalid
* instruction. However, we ignore this for efficiency.
* It also only operates on scalars.
*/
if (fop->flags & OP_DD)
dest = vfp_get_dd(inst);
else
dest = vfp_get_sd(inst);
/*
* If destination bank is zero, vector length is always '1'.
* ARM DDI0100F C5.1.3, C5.3.2.
*/
if ((fop->flags & OP_SCALAR) || FREG_BANK(dest) == 0)
veclen = 0;
else
veclen = fpscr & FPSCR_LENGTH_MASK;
LOG_TRACE(Core_ARM11, "vecstride=%u veclen=%u", vecstride, (veclen >> FPSCR_LENGTH_BIT) + 1);
if (!fop->fn) {
LOG_CRITICAL(Core_ARM11, "could not find single op %d, inst=0x%x@0x%x", FEXT_TO_IDX(inst),
inst, state->Reg[15]);
Crash();
goto invalid;
}
for (vecitr = 0; vecitr <= veclen; vecitr += 1 << FPSCR_LENGTH_BIT) {
s32 m = vfp_get_float(state, sm);
u32 except;
char type;
type = (fop->flags & OP_DD) ? 'd' : 's';
if (op == FOP_EXT)
LOG_TRACE(Core_ARM11, "itr%d (%c%u) = op[%u] (s%u=%08x)", vecitr >> FPSCR_LENGTH_BIT,
type, dest, sn, sm, m);
else
LOG_TRACE(Core_ARM11, "itr%d (%c%u) = (s%u) op[%u] (s%u=%08x)",
vecitr >> FPSCR_LENGTH_BIT, type, dest, sn, FOP_TO_IDX(op), sm, m);
except = fop->fn(state, dest, sn, m, fpscr);
LOG_TRACE(Core_ARM11, "itr%d: exceptions=%08x", vecitr >> FPSCR_LENGTH_BIT, except);
exceptions |= except;
/*
* CHECK: It appears to be undefined whether we stop when
* we encounter an exception. We continue.
*/
dest = FREG_BANK(dest) + ((FREG_IDX(dest) + vecstride) & 7);
sn = FREG_BANK(sn) + ((FREG_IDX(sn) + vecstride) & 7);
if (FREG_BANK(sm) != 0)
sm = FREG_BANK(sm) + ((FREG_IDX(sm) + vecstride) & 7);
}
return exceptions;
invalid:
return (u32)-1;
}
| Kloen/citra | src/core/arm/skyeye_common/vfp/vfpsingle.cpp | C++ | gpl-2.0 | 37,278 |
/*
* ELF constants and data structures
*
* Derived from:
* $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/alpha/include/elf.h,v 1.14 2003/09/25 01:10:22 peter Exp $
* $FreeBSD: src/sys/amd64/include/elf.h,v 1.18 2004/08/03 08:21:48 dfr Exp $
* $FreeBSD: src/sys/arm/include/elf.h,v 1.5.2.1 2006/06/30 21:42:52 cognet Exp $
* $FreeBSD: src/sys/i386/include/elf.h,v 1.16 2004/08/02 19:12:17 dfr Exp $
* $FreeBSD: src/sys/powerpc/include/elf.h,v 1.7 2004/11/02 09:47:01 ssouhlal Exp $
* $FreeBSD: src/sys/sparc64/include/elf.h,v 1.12 2003/09/25 01:10:26 peter Exp $
* "ELF for the ARM® 64-bit Architecture (AArch64)" (ARM IHI 0056B)
*
* Copyright (c) 1996-1998 John D. Polstra. All rights reserved.
* Copyright (c) 2001 David E. O'Brien
* Portions Copyright 2009 The Go Authors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package elf
import "strconv"
/*
* Constants
*/
// Indexes into the Header.Ident array.
const (
EI_CLASS = 4 /* Class of machine. */
EI_DATA = 5 /* Data format. */
EI_VERSION = 6 /* ELF format version. */
EI_OSABI = 7 /* Operating system / ABI identification */
EI_ABIVERSION = 8 /* ABI version */
EI_PAD = 9 /* Start of padding (per SVR4 ABI). */
EI_NIDENT = 16 /* Size of e_ident array. */
)
// Initial magic number for ELF files.
const ELFMAG = "\177ELF"
// Version is found in Header.Ident[EI_VERSION] and Header.Version.
type Version byte
const (
EV_NONE Version = 0
EV_CURRENT Version = 1
)
var versionStrings = []intName{
{0, "EV_NONE"},
{1, "EV_CURRENT"},
}
func (i Version) String() string { return stringName(uint32(i), versionStrings, false) }
func (i Version) GoString() string { return stringName(uint32(i), versionStrings, true) }
// Class is found in Header.Ident[EI_CLASS] and Header.Class.
type Class byte
const (
ELFCLASSNONE Class = 0 /* Unknown class. */
ELFCLASS32 Class = 1 /* 32-bit architecture. */
ELFCLASS64 Class = 2 /* 64-bit architecture. */
)
var classStrings = []intName{
{0, "ELFCLASSNONE"},
{1, "ELFCLASS32"},
{2, "ELFCLASS64"},
}
func (i Class) String() string { return stringName(uint32(i), classStrings, false) }
func (i Class) GoString() string { return stringName(uint32(i), classStrings, true) }
// Data is found in Header.Ident[EI_DATA] and Header.Data.
type Data byte
const (
ELFDATANONE Data = 0 /* Unknown data format. */
ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
)
var dataStrings = []intName{
{0, "ELFDATANONE"},
{1, "ELFDATA2LSB"},
{2, "ELFDATA2MSB"},
}
func (i Data) String() string { return stringName(uint32(i), dataStrings, false) }
func (i Data) GoString() string { return stringName(uint32(i), dataStrings, true) }
// OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.
type OSABI byte
const (
ELFOSABI_NONE OSABI = 0 /* UNIX System V ABI */
ELFOSABI_HPUX OSABI = 1 /* HP-UX operating system */
ELFOSABI_NETBSD OSABI = 2 /* NetBSD */
ELFOSABI_LINUX OSABI = 3 /* GNU/Linux */
ELFOSABI_HURD OSABI = 4 /* GNU/Hurd */
ELFOSABI_86OPEN OSABI = 5 /* 86Open common IA32 ABI */
ELFOSABI_SOLARIS OSABI = 6 /* Solaris */
ELFOSABI_AIX OSABI = 7 /* AIX */
ELFOSABI_IRIX OSABI = 8 /* IRIX */
ELFOSABI_FREEBSD OSABI = 9 /* FreeBSD */
ELFOSABI_TRU64 OSABI = 10 /* TRU64 UNIX */
ELFOSABI_MODESTO OSABI = 11 /* Novell Modesto */
ELFOSABI_OPENBSD OSABI = 12 /* OpenBSD */
ELFOSABI_OPENVMS OSABI = 13 /* Open VMS */
ELFOSABI_NSK OSABI = 14 /* HP Non-Stop Kernel */
ELFOSABI_ARM OSABI = 97 /* ARM */
ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
)
var osabiStrings = []intName{
{0, "ELFOSABI_NONE"},
{1, "ELFOSABI_HPUX"},
{2, "ELFOSABI_NETBSD"},
{3, "ELFOSABI_LINUX"},
{4, "ELFOSABI_HURD"},
{5, "ELFOSABI_86OPEN"},
{6, "ELFOSABI_SOLARIS"},
{7, "ELFOSABI_AIX"},
{8, "ELFOSABI_IRIX"},
{9, "ELFOSABI_FREEBSD"},
{10, "ELFOSABI_TRU64"},
{11, "ELFOSABI_MODESTO"},
{12, "ELFOSABI_OPENBSD"},
{13, "ELFOSABI_OPENVMS"},
{14, "ELFOSABI_NSK"},
{97, "ELFOSABI_ARM"},
{255, "ELFOSABI_STANDALONE"},
}
func (i OSABI) String() string { return stringName(uint32(i), osabiStrings, false) }
func (i OSABI) GoString() string { return stringName(uint32(i), osabiStrings, true) }
// Type is found in Header.Type.
type Type uint16
const (
ET_NONE Type = 0 /* Unknown type. */
ET_REL Type = 1 /* Relocatable. */
ET_EXEC Type = 2 /* Executable. */
ET_DYN Type = 3 /* Shared object. */
ET_CORE Type = 4 /* Core file. */
ET_LOOS Type = 0xfe00 /* First operating system specific. */
ET_HIOS Type = 0xfeff /* Last operating system-specific. */
ET_LOPROC Type = 0xff00 /* First processor-specific. */
ET_HIPROC Type = 0xffff /* Last processor-specific. */
)
var typeStrings = []intName{
{0, "ET_NONE"},
{1, "ET_REL"},
{2, "ET_EXEC"},
{3, "ET_DYN"},
{4, "ET_CORE"},
{0xfe00, "ET_LOOS"},
{0xfeff, "ET_HIOS"},
{0xff00, "ET_LOPROC"},
{0xffff, "ET_HIPROC"},
}
func (i Type) String() string { return stringName(uint32(i), typeStrings, false) }
func (i Type) GoString() string { return stringName(uint32(i), typeStrings, true) }
// Machine is found in Header.Machine.
type Machine uint16
const (
EM_NONE Machine = 0 /* Unknown machine. */
EM_M32 Machine = 1 /* AT&T WE32100. */
EM_SPARC Machine = 2 /* Sun SPARC. */
EM_386 Machine = 3 /* Intel i386. */
EM_68K Machine = 4 /* Motorola 68000. */
EM_88K Machine = 5 /* Motorola 88000. */
EM_860 Machine = 7 /* Intel i860. */
EM_MIPS Machine = 8 /* MIPS R3000 Big-Endian only. */
EM_S370 Machine = 9 /* IBM System/370. */
EM_MIPS_RS3_LE Machine = 10 /* MIPS R3000 Little-Endian. */
EM_PARISC Machine = 15 /* HP PA-RISC. */
EM_VPP500 Machine = 17 /* Fujitsu VPP500. */
EM_SPARC32PLUS Machine = 18 /* SPARC v8plus. */
EM_960 Machine = 19 /* Intel 80960. */
EM_PPC Machine = 20 /* PowerPC 32-bit. */
EM_PPC64 Machine = 21 /* PowerPC 64-bit. */
EM_S390 Machine = 22 /* IBM System/390. */
EM_V800 Machine = 36 /* NEC V800. */
EM_FR20 Machine = 37 /* Fujitsu FR20. */
EM_RH32 Machine = 38 /* TRW RH-32. */
EM_RCE Machine = 39 /* Motorola RCE. */
EM_ARM Machine = 40 /* ARM. */
EM_SH Machine = 42 /* Hitachi SH. */
EM_SPARCV9 Machine = 43 /* SPARC v9 64-bit. */
EM_TRICORE Machine = 44 /* Siemens TriCore embedded processor. */
EM_ARC Machine = 45 /* Argonaut RISC Core. */
EM_H8_300 Machine = 46 /* Hitachi H8/300. */
EM_H8_300H Machine = 47 /* Hitachi H8/300H. */
EM_H8S Machine = 48 /* Hitachi H8S. */
EM_H8_500 Machine = 49 /* Hitachi H8/500. */
EM_IA_64 Machine = 50 /* Intel IA-64 Processor. */
EM_MIPS_X Machine = 51 /* Stanford MIPS-X. */
EM_COLDFIRE Machine = 52 /* Motorola ColdFire. */
EM_68HC12 Machine = 53 /* Motorola M68HC12. */
EM_MMA Machine = 54 /* Fujitsu MMA. */
EM_PCP Machine = 55 /* Siemens PCP. */
EM_NCPU Machine = 56 /* Sony nCPU. */
EM_NDR1 Machine = 57 /* Denso NDR1 microprocessor. */
EM_STARCORE Machine = 58 /* Motorola Star*Core processor. */
EM_ME16 Machine = 59 /* Toyota ME16 processor. */
EM_ST100 Machine = 60 /* STMicroelectronics ST100 processor. */
EM_TINYJ Machine = 61 /* Advanced Logic Corp. TinyJ processor. */
EM_X86_64 Machine = 62 /* Advanced Micro Devices x86-64 */
EM_AARCH64 Machine = 183 /* ARM 64-bit Architecture (AArch64) */
/* Non-standard or deprecated. */
EM_486 Machine = 6 /* Intel i486. */
EM_MIPS_RS4_BE Machine = 10 /* MIPS R4000 Big-Endian */
EM_ALPHA_STD Machine = 41 /* Digital Alpha (standard value). */
EM_ALPHA Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
)
var machineStrings = []intName{
{0, "EM_NONE"},
{1, "EM_M32"},
{2, "EM_SPARC"},
{3, "EM_386"},
{4, "EM_68K"},
{5, "EM_88K"},
{7, "EM_860"},
{8, "EM_MIPS"},
{9, "EM_S370"},
{10, "EM_MIPS_RS3_LE"},
{15, "EM_PARISC"},
{17, "EM_VPP500"},
{18, "EM_SPARC32PLUS"},
{19, "EM_960"},
{20, "EM_PPC"},
{21, "EM_PPC64"},
{22, "EM_S390"},
{36, "EM_V800"},
{37, "EM_FR20"},
{38, "EM_RH32"},
{39, "EM_RCE"},
{40, "EM_ARM"},
{42, "EM_SH"},
{43, "EM_SPARCV9"},
{44, "EM_TRICORE"},
{45, "EM_ARC"},
{46, "EM_H8_300"},
{47, "EM_H8_300H"},
{48, "EM_H8S"},
{49, "EM_H8_500"},
{50, "EM_IA_64"},
{51, "EM_MIPS_X"},
{52, "EM_COLDFIRE"},
{53, "EM_68HC12"},
{54, "EM_MMA"},
{55, "EM_PCP"},
{56, "EM_NCPU"},
{57, "EM_NDR1"},
{58, "EM_STARCORE"},
{59, "EM_ME16"},
{60, "EM_ST100"},
{61, "EM_TINYJ"},
{62, "EM_X86_64"},
/* Non-standard or deprecated. */
{6, "EM_486"},
{10, "EM_MIPS_RS4_BE"},
{41, "EM_ALPHA_STD"},
{0x9026, "EM_ALPHA"},
}
func (i Machine) String() string { return stringName(uint32(i), machineStrings, false) }
func (i Machine) GoString() string { return stringName(uint32(i), machineStrings, true) }
// Special section indices.
type SectionIndex int
const (
SHN_UNDEF SectionIndex = 0 /* Undefined, missing, irrelevant. */
SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
SHN_LOPROC SectionIndex = 0xff00 /* First processor-specific. */
SHN_HIPROC SectionIndex = 0xff1f /* Last processor-specific. */
SHN_LOOS SectionIndex = 0xff20 /* First operating system-specific. */
SHN_HIOS SectionIndex = 0xff3f /* Last operating system-specific. */
SHN_ABS SectionIndex = 0xfff1 /* Absolute values. */
SHN_COMMON SectionIndex = 0xfff2 /* Common data. */
SHN_XINDEX SectionIndex = 0xffff /* Escape; index stored elsewhere. */
SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
)
var shnStrings = []intName{
{0, "SHN_UNDEF"},
{0xff00, "SHN_LOPROC"},
{0xff20, "SHN_LOOS"},
{0xfff1, "SHN_ABS"},
{0xfff2, "SHN_COMMON"},
{0xffff, "SHN_XINDEX"},
}
func (i SectionIndex) String() string { return stringName(uint32(i), shnStrings, false) }
func (i SectionIndex) GoString() string { return stringName(uint32(i), shnStrings, true) }
// Section type.
type SectionType uint32
const (
SHT_NULL SectionType = 0 /* inactive */
SHT_PROGBITS SectionType = 1 /* program defined information */
SHT_SYMTAB SectionType = 2 /* symbol table section */
SHT_STRTAB SectionType = 3 /* string table section */
SHT_RELA SectionType = 4 /* relocation section with addends */
SHT_HASH SectionType = 5 /* symbol hash table section */
SHT_DYNAMIC SectionType = 6 /* dynamic section */
SHT_NOTE SectionType = 7 /* note section */
SHT_NOBITS SectionType = 8 /* no space section */
SHT_REL SectionType = 9 /* relocation section - no addends */
SHT_SHLIB SectionType = 10 /* reserved - purpose unknown */
SHT_DYNSYM SectionType = 11 /* dynamic symbol table section */
SHT_INIT_ARRAY SectionType = 14 /* Initialization function pointers. */
SHT_FINI_ARRAY SectionType = 15 /* Termination function pointers. */
SHT_PREINIT_ARRAY SectionType = 16 /* Pre-initialization function ptrs. */
SHT_GROUP SectionType = 17 /* Section group. */
SHT_SYMTAB_SHNDX SectionType = 18 /* Section indexes (see SHN_XINDEX). */
SHT_LOOS SectionType = 0x60000000 /* First of OS specific semantics */
SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
SHT_GNU_HASH SectionType = 0x6ffffff6 /* GNU hash table */
SHT_GNU_LIBLIST SectionType = 0x6ffffff7 /* GNU prelink library list */
SHT_GNU_VERDEF SectionType = 0x6ffffffd /* GNU version definition section */
SHT_GNU_VERNEED SectionType = 0x6ffffffe /* GNU version needs section */
SHT_GNU_VERSYM SectionType = 0x6fffffff /* GNU version symbol table */
SHT_HIOS SectionType = 0x6fffffff /* Last of OS specific semantics */
SHT_LOPROC SectionType = 0x70000000 /* reserved range for processor */
SHT_HIPROC SectionType = 0x7fffffff /* specific section header types */
SHT_LOUSER SectionType = 0x80000000 /* reserved range for application */
SHT_HIUSER SectionType = 0xffffffff /* specific indexes */
)
var shtStrings = []intName{
{0, "SHT_NULL"},
{1, "SHT_PROGBITS"},
{2, "SHT_SYMTAB"},
{3, "SHT_STRTAB"},
{4, "SHT_RELA"},
{5, "SHT_HASH"},
{6, "SHT_DYNAMIC"},
{7, "SHT_NOTE"},
{8, "SHT_NOBITS"},
{9, "SHT_REL"},
{10, "SHT_SHLIB"},
{11, "SHT_DYNSYM"},
{14, "SHT_INIT_ARRAY"},
{15, "SHT_FINI_ARRAY"},
{16, "SHT_PREINIT_ARRAY"},
{17, "SHT_GROUP"},
{18, "SHT_SYMTAB_SHNDX"},
{0x60000000, "SHT_LOOS"},
{0x6ffffff5, "SHT_GNU_ATTRIBUTES"},
{0x6ffffff6, "SHT_GNU_HASH"},
{0x6ffffff7, "SHT_GNU_LIBLIST"},
{0x6ffffffd, "SHT_GNU_VERDEF"},
{0x6ffffffe, "SHT_GNU_VERNEED"},
{0x6fffffff, "SHT_GNU_VERSYM"},
{0x70000000, "SHT_LOPROC"},
{0x7fffffff, "SHT_HIPROC"},
{0x80000000, "SHT_LOUSER"},
{0xffffffff, "SHT_HIUSER"},
}
func (i SectionType) String() string { return stringName(uint32(i), shtStrings, false) }
func (i SectionType) GoString() string { return stringName(uint32(i), shtStrings, true) }
// Section flags.
type SectionFlag uint32
const (
SHF_WRITE SectionFlag = 0x1 /* Section contains writable data. */
SHF_ALLOC SectionFlag = 0x2 /* Section occupies memory. */
SHF_EXECINSTR SectionFlag = 0x4 /* Section contains instructions. */
SHF_MERGE SectionFlag = 0x10 /* Section may be merged. */
SHF_STRINGS SectionFlag = 0x20 /* Section contains strings. */
SHF_INFO_LINK SectionFlag = 0x40 /* sh_info holds section index. */
SHF_LINK_ORDER SectionFlag = 0x80 /* Special ordering requirements. */
SHF_OS_NONCONFORMING SectionFlag = 0x100 /* OS-specific processing required. */
SHF_GROUP SectionFlag = 0x200 /* Member of section group. */
SHF_TLS SectionFlag = 0x400 /* Section contains TLS data. */
SHF_COMPRESSED SectionFlag = 0x800 /* Section is compressed. */
SHF_MASKOS SectionFlag = 0x0ff00000 /* OS-specific semantics. */
SHF_MASKPROC SectionFlag = 0xf0000000 /* Processor-specific semantics. */
)
var shfStrings = []intName{
{0x1, "SHF_WRITE"},
{0x2, "SHF_ALLOC"},
{0x4, "SHF_EXECINSTR"},
{0x10, "SHF_MERGE"},
{0x20, "SHF_STRINGS"},
{0x40, "SHF_INFO_LINK"},
{0x80, "SHF_LINK_ORDER"},
{0x100, "SHF_OS_NONCONFORMING"},
{0x200, "SHF_GROUP"},
{0x400, "SHF_TLS"},
{0x800, "SHF_COMPRESSED"},
}
func (i SectionFlag) String() string { return flagName(uint32(i), shfStrings, false) }
func (i SectionFlag) GoString() string { return flagName(uint32(i), shfStrings, true) }
// Section compression type.
type CompressionType int
const (
COMPRESS_ZLIB CompressionType = 1 /* ZLIB compression. */
COMPRESS_LOOS CompressionType = 0x60000000 /* First OS-specific. */
COMPRESS_HIOS CompressionType = 0x6fffffff /* Last OS-specific. */
COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
)
var compressionStrings = []intName{
{0, "COMPRESS_ZLIB"},
{0x60000000, "COMPRESS_LOOS"},
{0x6fffffff, "COMPRESS_HIOS"},
{0x70000000, "COMPRESS_LOPROC"},
{0x7fffffff, "COMPRESS_HIPROC"},
}
func (i CompressionType) String() string { return stringName(uint32(i), compressionStrings, false) }
func (i CompressionType) GoString() string { return stringName(uint32(i), compressionStrings, true) }
// Prog.Type
type ProgType int
const (
PT_NULL ProgType = 0 /* Unused entry. */
PT_LOAD ProgType = 1 /* Loadable segment. */
PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
PT_INTERP ProgType = 3 /* Pathname of interpreter. */
PT_NOTE ProgType = 4 /* Auxiliary information. */
PT_SHLIB ProgType = 5 /* Reserved (not used). */
PT_PHDR ProgType = 6 /* Location of program header itself. */
PT_TLS ProgType = 7 /* Thread local storage segment */
PT_LOOS ProgType = 0x60000000 /* First OS-specific. */
PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */
PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */
PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
)
var ptStrings = []intName{
{0, "PT_NULL"},
{1, "PT_LOAD"},
{2, "PT_DYNAMIC"},
{3, "PT_INTERP"},
{4, "PT_NOTE"},
{5, "PT_SHLIB"},
{6, "PT_PHDR"},
{7, "PT_TLS"},
{0x60000000, "PT_LOOS"},
{0x6fffffff, "PT_HIOS"},
{0x70000000, "PT_LOPROC"},
{0x7fffffff, "PT_HIPROC"},
}
func (i ProgType) String() string { return stringName(uint32(i), ptStrings, false) }
func (i ProgType) GoString() string { return stringName(uint32(i), ptStrings, true) }
// Prog.Flag
type ProgFlag uint32
const (
PF_X ProgFlag = 0x1 /* Executable. */
PF_W ProgFlag = 0x2 /* Writable. */
PF_R ProgFlag = 0x4 /* Readable. */
PF_MASKOS ProgFlag = 0x0ff00000 /* Operating system-specific. */
PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
)
var pfStrings = []intName{
{0x1, "PF_X"},
{0x2, "PF_W"},
{0x4, "PF_R"},
}
func (i ProgFlag) String() string { return flagName(uint32(i), pfStrings, false) }
func (i ProgFlag) GoString() string { return flagName(uint32(i), pfStrings, true) }
// Dyn.Tag
type DynTag int
const (
DT_NULL DynTag = 0 /* Terminating entry. */
DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */
DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */
DT_PLTGOT DynTag = 3 /* Processor-dependent address. */
DT_HASH DynTag = 4 /* Address of symbol hash table. */
DT_STRTAB DynTag = 5 /* Address of string table. */
DT_SYMTAB DynTag = 6 /* Address of symbol table. */
DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */
DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */
DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */
DT_STRSZ DynTag = 10 /* Size of string table. */
DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */
DT_INIT DynTag = 12 /* Address of initialization function. */
DT_FINI DynTag = 13 /* Address of finalization function. */
DT_SONAME DynTag = 14 /* String table offset of shared object name. */
DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */
DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */
DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */
DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */
DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */
DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */
DT_DEBUG DynTag = 21 /* Reserved (not used). */
DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
DT_JMPREL DynTag = 23 /* Address of PLT relocations. */
DT_BIND_NOW DynTag = 24 /* [sup] */
DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */
DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */
DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */
DT_FLAGS DynTag = 30 /* Object specific flag values. */
DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING
and less than DT_LOOS follow the rules for
the interpretation of the d_un union
as follows: even == 'd_ptr', even == 'd_val'
or none */
DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
DT_LOOS DynTag = 0x6000000d /* First OS-specific */
DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */
DT_VERSYM DynTag = 0x6ffffff0
DT_VERNEED DynTag = 0x6ffffffe
DT_VERNEEDNUM DynTag = 0x6fffffff
DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */
DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
)
var dtStrings = []intName{
{0, "DT_NULL"},
{1, "DT_NEEDED"},
{2, "DT_PLTRELSZ"},
{3, "DT_PLTGOT"},
{4, "DT_HASH"},
{5, "DT_STRTAB"},
{6, "DT_SYMTAB"},
{7, "DT_RELA"},
{8, "DT_RELASZ"},
{9, "DT_RELAENT"},
{10, "DT_STRSZ"},
{11, "DT_SYMENT"},
{12, "DT_INIT"},
{13, "DT_FINI"},
{14, "DT_SONAME"},
{15, "DT_RPATH"},
{16, "DT_SYMBOLIC"},
{17, "DT_REL"},
{18, "DT_RELSZ"},
{19, "DT_RELENT"},
{20, "DT_PLTREL"},
{21, "DT_DEBUG"},
{22, "DT_TEXTREL"},
{23, "DT_JMPREL"},
{24, "DT_BIND_NOW"},
{25, "DT_INIT_ARRAY"},
{26, "DT_FINI_ARRAY"},
{27, "DT_INIT_ARRAYSZ"},
{28, "DT_FINI_ARRAYSZ"},
{29, "DT_RUNPATH"},
{30, "DT_FLAGS"},
{32, "DT_ENCODING"},
{32, "DT_PREINIT_ARRAY"},
{33, "DT_PREINIT_ARRAYSZ"},
{0x6000000d, "DT_LOOS"},
{0x6ffff000, "DT_HIOS"},
{0x6ffffff0, "DT_VERSYM"},
{0x6ffffffe, "DT_VERNEED"},
{0x6fffffff, "DT_VERNEEDNUM"},
{0x70000000, "DT_LOPROC"},
{0x7fffffff, "DT_HIPROC"},
}
func (i DynTag) String() string { return stringName(uint32(i), dtStrings, false) }
func (i DynTag) GoString() string { return stringName(uint32(i), dtStrings, true) }
// DT_FLAGS values.
type DynFlag int
const (
DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
make reference to the
$ORIGIN substitution string */
DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
process all relocations for the object
containing this entry before transferring
control to the program. */
DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
executable contains code using a static
thread-local storage scheme. */
)
var dflagStrings = []intName{
{0x0001, "DF_ORIGIN"},
{0x0002, "DF_SYMBOLIC"},
{0x0004, "DF_TEXTREL"},
{0x0008, "DF_BIND_NOW"},
{0x0010, "DF_STATIC_TLS"},
}
func (i DynFlag) String() string { return flagName(uint32(i), dflagStrings, false) }
func (i DynFlag) GoString() string { return flagName(uint32(i), dflagStrings, true) }
// NType values; used in core files.
type NType int
const (
NT_PRSTATUS NType = 1 /* Process status. */
NT_FPREGSET NType = 2 /* Floating point registers. */
NT_PRPSINFO NType = 3 /* Process state info. */
)
var ntypeStrings = []intName{
{1, "NT_PRSTATUS"},
{2, "NT_FPREGSET"},
{3, "NT_PRPSINFO"},
}
func (i NType) String() string { return stringName(uint32(i), ntypeStrings, false) }
func (i NType) GoString() string { return stringName(uint32(i), ntypeStrings, true) }
/* Symbol Binding - ELFNN_ST_BIND - st_info */
type SymBind int
const (
STB_LOCAL SymBind = 0 /* Local symbol */
STB_GLOBAL SymBind = 1 /* Global symbol */
STB_WEAK SymBind = 2 /* like global - lower precedence */
STB_LOOS SymBind = 10 /* Reserved range for operating system */
STB_HIOS SymBind = 12 /* specific semantics. */
STB_LOPROC SymBind = 13 /* reserved range for processor */
STB_HIPROC SymBind = 15 /* specific semantics. */
)
var stbStrings = []intName{
{0, "STB_LOCAL"},
{1, "STB_GLOBAL"},
{2, "STB_WEAK"},
{10, "STB_LOOS"},
{12, "STB_HIOS"},
{13, "STB_LOPROC"},
{15, "STB_HIPROC"},
}
func (i SymBind) String() string { return stringName(uint32(i), stbStrings, false) }
func (i SymBind) GoString() string { return stringName(uint32(i), stbStrings, true) }
/* Symbol type - ELFNN_ST_TYPE - st_info */
type SymType int
const (
STT_NOTYPE SymType = 0 /* Unspecified type. */
STT_OBJECT SymType = 1 /* Data object. */
STT_FUNC SymType = 2 /* Function. */
STT_SECTION SymType = 3 /* Section. */
STT_FILE SymType = 4 /* Source file. */
STT_COMMON SymType = 5 /* Uninitialized common block. */
STT_TLS SymType = 6 /* TLS object. */
STT_LOOS SymType = 10 /* Reserved range for operating system */
STT_HIOS SymType = 12 /* specific semantics. */
STT_LOPROC SymType = 13 /* reserved range for processor */
STT_HIPROC SymType = 15 /* specific semantics. */
)
var sttStrings = []intName{
{0, "STT_NOTYPE"},
{1, "STT_OBJECT"},
{2, "STT_FUNC"},
{3, "STT_SECTION"},
{4, "STT_FILE"},
{5, "STT_COMMON"},
{6, "STT_TLS"},
{10, "STT_LOOS"},
{12, "STT_HIOS"},
{13, "STT_LOPROC"},
{15, "STT_HIPROC"},
}
func (i SymType) String() string { return stringName(uint32(i), sttStrings, false) }
func (i SymType) GoString() string { return stringName(uint32(i), sttStrings, true) }
/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
type SymVis int
const (
STV_DEFAULT SymVis = 0x0 /* Default visibility (see binding). */
STV_INTERNAL SymVis = 0x1 /* Special meaning in relocatable objects. */
STV_HIDDEN SymVis = 0x2 /* Not visible. */
STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
)
var stvStrings = []intName{
{0x0, "STV_DEFAULT"},
{0x1, "STV_INTERNAL"},
{0x2, "STV_HIDDEN"},
{0x3, "STV_PROTECTED"},
}
func (i SymVis) String() string { return stringName(uint32(i), stvStrings, false) }
func (i SymVis) GoString() string { return stringName(uint32(i), stvStrings, true) }
/*
* Relocation types.
*/
// Relocation types for x86-64.
type R_X86_64 int
const (
R_X86_64_NONE R_X86_64 = 0 /* No relocation. */
R_X86_64_64 R_X86_64 = 1 /* Add 64 bit symbol value. */
R_X86_64_PC32 R_X86_64 = 2 /* PC-relative 32 bit signed sym value. */
R_X86_64_GOT32 R_X86_64 = 3 /* PC-relative 32 bit GOT offset. */
R_X86_64_PLT32 R_X86_64 = 4 /* PC-relative 32 bit PLT offset. */
R_X86_64_COPY R_X86_64 = 5 /* Copy data from shared object. */
R_X86_64_GLOB_DAT R_X86_64 = 6 /* Set GOT entry to data address. */
R_X86_64_JMP_SLOT R_X86_64 = 7 /* Set GOT entry to code address. */
R_X86_64_RELATIVE R_X86_64 = 8 /* Add load address of shared object. */
R_X86_64_GOTPCREL R_X86_64 = 9 /* Add 32 bit signed pcrel offset to GOT. */
R_X86_64_32 R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
R_X86_64_32S R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
R_X86_64_16 R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
R_X86_64_PC16 R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
R_X86_64_8 R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
R_X86_64_PC8 R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
R_X86_64_DTPMOD64 R_X86_64 = 16 /* ID of module containing symbol */
R_X86_64_DTPOFF64 R_X86_64 = 17 /* Offset in TLS block */
R_X86_64_TPOFF64 R_X86_64 = 18 /* Offset in static TLS block */
R_X86_64_TLSGD R_X86_64 = 19 /* PC relative offset to GD GOT entry */
R_X86_64_TLSLD R_X86_64 = 20 /* PC relative offset to LD GOT entry */
R_X86_64_DTPOFF32 R_X86_64 = 21 /* Offset in TLS block */
R_X86_64_GOTTPOFF R_X86_64 = 22 /* PC relative offset to IE GOT entry */
R_X86_64_TPOFF32 R_X86_64 = 23 /* Offset in static TLS block */
)
var rx86_64Strings = []intName{
{0, "R_X86_64_NONE"},
{1, "R_X86_64_64"},
{2, "R_X86_64_PC32"},
{3, "R_X86_64_GOT32"},
{4, "R_X86_64_PLT32"},
{5, "R_X86_64_COPY"},
{6, "R_X86_64_GLOB_DAT"},
{7, "R_X86_64_JMP_SLOT"},
{8, "R_X86_64_RELATIVE"},
{9, "R_X86_64_GOTPCREL"},
{10, "R_X86_64_32"},
{11, "R_X86_64_32S"},
{12, "R_X86_64_16"},
{13, "R_X86_64_PC16"},
{14, "R_X86_64_8"},
{15, "R_X86_64_PC8"},
{16, "R_X86_64_DTPMOD64"},
{17, "R_X86_64_DTPOFF64"},
{18, "R_X86_64_TPOFF64"},
{19, "R_X86_64_TLSGD"},
{20, "R_X86_64_TLSLD"},
{21, "R_X86_64_DTPOFF32"},
{22, "R_X86_64_GOTTPOFF"},
{23, "R_X86_64_TPOFF32"},
}
func (i R_X86_64) String() string { return stringName(uint32(i), rx86_64Strings, false) }
func (i R_X86_64) GoString() string { return stringName(uint32(i), rx86_64Strings, true) }
// Relocation types for AArch64 (aka arm64)
type R_AARCH64 int
const (
R_AARCH64_NONE R_AARCH64 = 0
R_AARCH64_P32_ABS32 R_AARCH64 = 1
R_AARCH64_P32_ABS16 R_AARCH64 = 2
R_AARCH64_P32_PREL32 R_AARCH64 = 3
R_AARCH64_P32_PREL16 R_AARCH64 = 4
R_AARCH64_P32_MOVW_UABS_G0 R_AARCH64 = 5
R_AARCH64_P32_MOVW_UABS_G0_NC R_AARCH64 = 6
R_AARCH64_P32_MOVW_UABS_G1 R_AARCH64 = 7
R_AARCH64_P32_MOVW_SABS_G0 R_AARCH64 = 8
R_AARCH64_P32_LD_PREL_LO19 R_AARCH64 = 9
R_AARCH64_P32_ADR_PREL_LO21 R_AARCH64 = 10
R_AARCH64_P32_ADR_PREL_PG_HI21 R_AARCH64 = 11
R_AARCH64_P32_ADD_ABS_LO12_NC R_AARCH64 = 12
R_AARCH64_P32_LDST8_ABS_LO12_NC R_AARCH64 = 13
R_AARCH64_P32_LDST16_ABS_LO12_NC R_AARCH64 = 14
R_AARCH64_P32_LDST32_ABS_LO12_NC R_AARCH64 = 15
R_AARCH64_P32_LDST64_ABS_LO12_NC R_AARCH64 = 16
R_AARCH64_P32_LDST128_ABS_LO12_NC R_AARCH64 = 17
R_AARCH64_P32_TSTBR14 R_AARCH64 = 18
R_AARCH64_P32_CONDBR19 R_AARCH64 = 19
R_AARCH64_P32_JUMP26 R_AARCH64 = 20
R_AARCH64_P32_CALL26 R_AARCH64 = 21
R_AARCH64_P32_GOT_LD_PREL19 R_AARCH64 = 25
R_AARCH64_P32_ADR_GOT_PAGE R_AARCH64 = 26
R_AARCH64_P32_LD32_GOT_LO12_NC R_AARCH64 = 27
R_AARCH64_P32_TLSGD_ADR_PAGE21 R_AARCH64 = 81
R_AARCH64_P32_TLSGD_ADD_LO12_NC R_AARCH64 = 82
R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 103
R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 105
R_AARCH64_P32_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 106
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 107
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 108
R_AARCH64_P32_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 109
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 110
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 111
R_AARCH64_P32_TLSDESC_LD_PREL19 R_AARCH64 = 122
R_AARCH64_P32_TLSDESC_ADR_PREL21 R_AARCH64 = 123
R_AARCH64_P32_TLSDESC_ADR_PAGE21 R_AARCH64 = 124
R_AARCH64_P32_TLSDESC_LD32_LO12_NC R_AARCH64 = 125
R_AARCH64_P32_TLSDESC_ADD_LO12_NC R_AARCH64 = 126
R_AARCH64_P32_TLSDESC_CALL R_AARCH64 = 127
R_AARCH64_P32_COPY R_AARCH64 = 180
R_AARCH64_P32_GLOB_DAT R_AARCH64 = 181
R_AARCH64_P32_JUMP_SLOT R_AARCH64 = 182
R_AARCH64_P32_RELATIVE R_AARCH64 = 183
R_AARCH64_P32_TLS_DTPMOD R_AARCH64 = 184
R_AARCH64_P32_TLS_DTPREL R_AARCH64 = 185
R_AARCH64_P32_TLS_TPREL R_AARCH64 = 186
R_AARCH64_P32_TLSDESC R_AARCH64 = 187
R_AARCH64_P32_IRELATIVE R_AARCH64 = 188
R_AARCH64_NULL R_AARCH64 = 256
R_AARCH64_ABS64 R_AARCH64 = 257
R_AARCH64_ABS32 R_AARCH64 = 258
R_AARCH64_ABS16 R_AARCH64 = 259
R_AARCH64_PREL64 R_AARCH64 = 260
R_AARCH64_PREL32 R_AARCH64 = 261
R_AARCH64_PREL16 R_AARCH64 = 262
R_AARCH64_MOVW_UABS_G0 R_AARCH64 = 263
R_AARCH64_MOVW_UABS_G0_NC R_AARCH64 = 264
R_AARCH64_MOVW_UABS_G1 R_AARCH64 = 265
R_AARCH64_MOVW_UABS_G1_NC R_AARCH64 = 266
R_AARCH64_MOVW_UABS_G2 R_AARCH64 = 267
R_AARCH64_MOVW_UABS_G2_NC R_AARCH64 = 268
R_AARCH64_MOVW_UABS_G3 R_AARCH64 = 269
R_AARCH64_MOVW_SABS_G0 R_AARCH64 = 270
R_AARCH64_MOVW_SABS_G1 R_AARCH64 = 271
R_AARCH64_MOVW_SABS_G2 R_AARCH64 = 272
R_AARCH64_LD_PREL_LO19 R_AARCH64 = 273
R_AARCH64_ADR_PREL_LO21 R_AARCH64 = 274
R_AARCH64_ADR_PREL_PG_HI21 R_AARCH64 = 275
R_AARCH64_ADR_PREL_PG_HI21_NC R_AARCH64 = 276
R_AARCH64_ADD_ABS_LO12_NC R_AARCH64 = 277
R_AARCH64_LDST8_ABS_LO12_NC R_AARCH64 = 278
R_AARCH64_TSTBR14 R_AARCH64 = 279
R_AARCH64_CONDBR19 R_AARCH64 = 280
R_AARCH64_JUMP26 R_AARCH64 = 282
R_AARCH64_CALL26 R_AARCH64 = 283
R_AARCH64_LDST16_ABS_LO12_NC R_AARCH64 = 284
R_AARCH64_LDST32_ABS_LO12_NC R_AARCH64 = 285
R_AARCH64_LDST64_ABS_LO12_NC R_AARCH64 = 286
R_AARCH64_LDST128_ABS_LO12_NC R_AARCH64 = 299
R_AARCH64_GOT_LD_PREL19 R_AARCH64 = 309
R_AARCH64_ADR_GOT_PAGE R_AARCH64 = 311
R_AARCH64_LD64_GOT_LO12_NC R_AARCH64 = 312
R_AARCH64_TLSGD_ADR_PAGE21 R_AARCH64 = 513
R_AARCH64_TLSGD_ADD_LO12_NC R_AARCH64 = 514
R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 R_AARCH64 = 539
R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC R_AARCH64 = 540
R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 541
R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC R_AARCH64 = 542
R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 543
R_AARCH64_TLSLE_MOVW_TPREL_G2 R_AARCH64 = 544
R_AARCH64_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 545
R_AARCH64_TLSLE_MOVW_TPREL_G1_NC R_AARCH64 = 546
R_AARCH64_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 547
R_AARCH64_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 548
R_AARCH64_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 549
R_AARCH64_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 550
R_AARCH64_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 551
R_AARCH64_TLSDESC_LD_PREL19 R_AARCH64 = 560
R_AARCH64_TLSDESC_ADR_PREL21 R_AARCH64 = 561
R_AARCH64_TLSDESC_ADR_PAGE21 R_AARCH64 = 562
R_AARCH64_TLSDESC_LD64_LO12_NC R_AARCH64 = 563
R_AARCH64_TLSDESC_ADD_LO12_NC R_AARCH64 = 564
R_AARCH64_TLSDESC_OFF_G1 R_AARCH64 = 565
R_AARCH64_TLSDESC_OFF_G0_NC R_AARCH64 = 566
R_AARCH64_TLSDESC_LDR R_AARCH64 = 567
R_AARCH64_TLSDESC_ADD R_AARCH64 = 568
R_AARCH64_TLSDESC_CALL R_AARCH64 = 569
R_AARCH64_COPY R_AARCH64 = 1024
R_AARCH64_GLOB_DAT R_AARCH64 = 1025
R_AARCH64_JUMP_SLOT R_AARCH64 = 1026
R_AARCH64_RELATIVE R_AARCH64 = 1027
R_AARCH64_TLS_DTPMOD64 R_AARCH64 = 1028
R_AARCH64_TLS_DTPREL64 R_AARCH64 = 1029
R_AARCH64_TLS_TPREL64 R_AARCH64 = 1030
R_AARCH64_TLSDESC R_AARCH64 = 1031
R_AARCH64_IRELATIVE R_AARCH64 = 1032
)
var raarch64Strings = []intName{
{0, "R_AARCH64_NONE"},
{1, "R_AARCH64_P32_ABS32"},
{2, "R_AARCH64_P32_ABS16"},
{3, "R_AARCH64_P32_PREL32"},
{4, "R_AARCH64_P32_PREL16"},
{5, "R_AARCH64_P32_MOVW_UABS_G0"},
{6, "R_AARCH64_P32_MOVW_UABS_G0_NC"},
{7, "R_AARCH64_P32_MOVW_UABS_G1"},
{8, "R_AARCH64_P32_MOVW_SABS_G0"},
{9, "R_AARCH64_P32_LD_PREL_LO19"},
{10, "R_AARCH64_P32_ADR_PREL_LO21"},
{11, "R_AARCH64_P32_ADR_PREL_PG_HI21"},
{12, "R_AARCH64_P32_ADD_ABS_LO12_NC"},
{13, "R_AARCH64_P32_LDST8_ABS_LO12_NC"},
{14, "R_AARCH64_P32_LDST16_ABS_LO12_NC"},
{15, "R_AARCH64_P32_LDST32_ABS_LO12_NC"},
{16, "R_AARCH64_P32_LDST64_ABS_LO12_NC"},
{17, "R_AARCH64_P32_LDST128_ABS_LO12_NC"},
{18, "R_AARCH64_P32_TSTBR14"},
{19, "R_AARCH64_P32_CONDBR19"},
{20, "R_AARCH64_P32_JUMP26"},
{21, "R_AARCH64_P32_CALL26"},
{25, "R_AARCH64_P32_GOT_LD_PREL19"},
{26, "R_AARCH64_P32_ADR_GOT_PAGE"},
{27, "R_AARCH64_P32_LD32_GOT_LO12_NC"},
{81, "R_AARCH64_P32_TLSGD_ADR_PAGE21"},
{82, "R_AARCH64_P32_TLSGD_ADD_LO12_NC"},
{103, "R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21"},
{104, "R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC"},
{105, "R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19"},
{106, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G1"},
{107, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0"},
{108, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC"},
{109, "R_AARCH64_P32_TLSLE_ADD_TPREL_HI12"},
{110, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12"},
{111, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC"},
{122, "R_AARCH64_P32_TLSDESC_LD_PREL19"},
{123, "R_AARCH64_P32_TLSDESC_ADR_PREL21"},
{124, "R_AARCH64_P32_TLSDESC_ADR_PAGE21"},
{125, "R_AARCH64_P32_TLSDESC_LD32_LO12_NC"},
{126, "R_AARCH64_P32_TLSDESC_ADD_LO12_NC"},
{127, "R_AARCH64_P32_TLSDESC_CALL"},
{180, "R_AARCH64_P32_COPY"},
{181, "R_AARCH64_P32_GLOB_DAT"},
{182, "R_AARCH64_P32_JUMP_SLOT"},
{183, "R_AARCH64_P32_RELATIVE"},
{184, "R_AARCH64_P32_TLS_DTPMOD"},
{185, "R_AARCH64_P32_TLS_DTPREL"},
{186, "R_AARCH64_P32_TLS_TPREL"},
{187, "R_AARCH64_P32_TLSDESC"},
{188, "R_AARCH64_P32_IRELATIVE"},
{256, "R_AARCH64_NULL"},
{257, "R_AARCH64_ABS64"},
{258, "R_AARCH64_ABS32"},
{259, "R_AARCH64_ABS16"},
{260, "R_AARCH64_PREL64"},
{261, "R_AARCH64_PREL32"},
{262, "R_AARCH64_PREL16"},
{263, "R_AARCH64_MOVW_UABS_G0"},
{264, "R_AARCH64_MOVW_UABS_G0_NC"},
{265, "R_AARCH64_MOVW_UABS_G1"},
{266, "R_AARCH64_MOVW_UABS_G1_NC"},
{267, "R_AARCH64_MOVW_UABS_G2"},
{268, "R_AARCH64_MOVW_UABS_G2_NC"},
{269, "R_AARCH64_MOVW_UABS_G3"},
{270, "R_AARCH64_MOVW_SABS_G0"},
{271, "R_AARCH64_MOVW_SABS_G1"},
{272, "R_AARCH64_MOVW_SABS_G2"},
{273, "R_AARCH64_LD_PREL_LO19"},
{274, "R_AARCH64_ADR_PREL_LO21"},
{275, "R_AARCH64_ADR_PREL_PG_HI21"},
{276, "R_AARCH64_ADR_PREL_PG_HI21_NC"},
{277, "R_AARCH64_ADD_ABS_LO12_NC"},
{278, "R_AARCH64_LDST8_ABS_LO12_NC"},
{279, "R_AARCH64_TSTBR14"},
{280, "R_AARCH64_CONDBR19"},
{282, "R_AARCH64_JUMP26"},
{283, "R_AARCH64_CALL26"},
{284, "R_AARCH64_LDST16_ABS_LO12_NC"},
{285, "R_AARCH64_LDST32_ABS_LO12_NC"},
{286, "R_AARCH64_LDST64_ABS_LO12_NC"},
{299, "R_AARCH64_LDST128_ABS_LO12_NC"},
{309, "R_AARCH64_GOT_LD_PREL19"},
{311, "R_AARCH64_ADR_GOT_PAGE"},
{312, "R_AARCH64_LD64_GOT_LO12_NC"},
{513, "R_AARCH64_TLSGD_ADR_PAGE21"},
{514, "R_AARCH64_TLSGD_ADD_LO12_NC"},
{539, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G1"},
{540, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC"},
{541, "R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21"},
{542, "R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC"},
{543, "R_AARCH64_TLSIE_LD_GOTTPREL_PREL19"},
{544, "R_AARCH64_TLSLE_MOVW_TPREL_G2"},
{545, "R_AARCH64_TLSLE_MOVW_TPREL_G1"},
{546, "R_AARCH64_TLSLE_MOVW_TPREL_G1_NC"},
{547, "R_AARCH64_TLSLE_MOVW_TPREL_G0"},
{548, "R_AARCH64_TLSLE_MOVW_TPREL_G0_NC"},
{549, "R_AARCH64_TLSLE_ADD_TPREL_HI12"},
{550, "R_AARCH64_TLSLE_ADD_TPREL_LO12"},
{551, "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC"},
{560, "R_AARCH64_TLSDESC_LD_PREL19"},
{561, "R_AARCH64_TLSDESC_ADR_PREL21"},
{562, "R_AARCH64_TLSDESC_ADR_PAGE21"},
{563, "R_AARCH64_TLSDESC_LD64_LO12_NC"},
{564, "R_AARCH64_TLSDESC_ADD_LO12_NC"},
{565, "R_AARCH64_TLSDESC_OFF_G1"},
{566, "R_AARCH64_TLSDESC_OFF_G0_NC"},
{567, "R_AARCH64_TLSDESC_LDR"},
{568, "R_AARCH64_TLSDESC_ADD"},
{569, "R_AARCH64_TLSDESC_CALL"},
{1024, "R_AARCH64_COPY"},
{1025, "R_AARCH64_GLOB_DAT"},
{1026, "R_AARCH64_JUMP_SLOT"},
{1027, "R_AARCH64_RELATIVE"},
{1028, "R_AARCH64_TLS_DTPMOD64"},
{1029, "R_AARCH64_TLS_DTPREL64"},
{1030, "R_AARCH64_TLS_TPREL64"},
{1031, "R_AARCH64_TLSDESC"},
{1032, "R_AARCH64_IRELATIVE"},
}
func (i R_AARCH64) String() string { return stringName(uint32(i), raarch64Strings, false) }
func (i R_AARCH64) GoString() string { return stringName(uint32(i), raarch64Strings, true) }
// Relocation types for Alpha.
type R_ALPHA int
const (
R_ALPHA_NONE R_ALPHA = 0 /* No reloc */
R_ALPHA_REFLONG R_ALPHA = 1 /* Direct 32 bit */
R_ALPHA_REFQUAD R_ALPHA = 2 /* Direct 64 bit */
R_ALPHA_GPREL32 R_ALPHA = 3 /* GP relative 32 bit */
R_ALPHA_LITERAL R_ALPHA = 4 /* GP relative 16 bit w/optimization */
R_ALPHA_LITUSE R_ALPHA = 5 /* Optimization hint for LITERAL */
R_ALPHA_GPDISP R_ALPHA = 6 /* Add displacement to GP */
R_ALPHA_BRADDR R_ALPHA = 7 /* PC+4 relative 23 bit shifted */
R_ALPHA_HINT R_ALPHA = 8 /* PC+4 relative 16 bit shifted */
R_ALPHA_SREL16 R_ALPHA = 9 /* PC relative 16 bit */
R_ALPHA_SREL32 R_ALPHA = 10 /* PC relative 32 bit */
R_ALPHA_SREL64 R_ALPHA = 11 /* PC relative 64 bit */
R_ALPHA_OP_PUSH R_ALPHA = 12 /* OP stack push */
R_ALPHA_OP_STORE R_ALPHA = 13 /* OP stack pop and store */
R_ALPHA_OP_PSUB R_ALPHA = 14 /* OP stack subtract */
R_ALPHA_OP_PRSHIFT R_ALPHA = 15 /* OP stack right shift */
R_ALPHA_GPVALUE R_ALPHA = 16
R_ALPHA_GPRELHIGH R_ALPHA = 17
R_ALPHA_GPRELLOW R_ALPHA = 18
R_ALPHA_IMMED_GP_16 R_ALPHA = 19
R_ALPHA_IMMED_GP_HI32 R_ALPHA = 20
R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
R_ALPHA_IMMED_BR_HI32 R_ALPHA = 22
R_ALPHA_IMMED_LO32 R_ALPHA = 23
R_ALPHA_COPY R_ALPHA = 24 /* Copy symbol at runtime */
R_ALPHA_GLOB_DAT R_ALPHA = 25 /* Create GOT entry */
R_ALPHA_JMP_SLOT R_ALPHA = 26 /* Create PLT entry */
R_ALPHA_RELATIVE R_ALPHA = 27 /* Adjust by program base */
)
var ralphaStrings = []intName{
{0, "R_ALPHA_NONE"},
{1, "R_ALPHA_REFLONG"},
{2, "R_ALPHA_REFQUAD"},
{3, "R_ALPHA_GPREL32"},
{4, "R_ALPHA_LITERAL"},
{5, "R_ALPHA_LITUSE"},
{6, "R_ALPHA_GPDISP"},
{7, "R_ALPHA_BRADDR"},
{8, "R_ALPHA_HINT"},
{9, "R_ALPHA_SREL16"},
{10, "R_ALPHA_SREL32"},
{11, "R_ALPHA_SREL64"},
{12, "R_ALPHA_OP_PUSH"},
{13, "R_ALPHA_OP_STORE"},
{14, "R_ALPHA_OP_PSUB"},
{15, "R_ALPHA_OP_PRSHIFT"},
{16, "R_ALPHA_GPVALUE"},
{17, "R_ALPHA_GPRELHIGH"},
{18, "R_ALPHA_GPRELLOW"},
{19, "R_ALPHA_IMMED_GP_16"},
{20, "R_ALPHA_IMMED_GP_HI32"},
{21, "R_ALPHA_IMMED_SCN_HI32"},
{22, "R_ALPHA_IMMED_BR_HI32"},
{23, "R_ALPHA_IMMED_LO32"},
{24, "R_ALPHA_COPY"},
{25, "R_ALPHA_GLOB_DAT"},
{26, "R_ALPHA_JMP_SLOT"},
{27, "R_ALPHA_RELATIVE"},
}
func (i R_ALPHA) String() string { return stringName(uint32(i), ralphaStrings, false) }
func (i R_ALPHA) GoString() string { return stringName(uint32(i), ralphaStrings, true) }
// Relocation types for ARM.
type R_ARM int
const (
R_ARM_NONE R_ARM = 0 /* No relocation. */
R_ARM_PC24 R_ARM = 1
R_ARM_ABS32 R_ARM = 2
R_ARM_REL32 R_ARM = 3
R_ARM_PC13 R_ARM = 4
R_ARM_ABS16 R_ARM = 5
R_ARM_ABS12 R_ARM = 6
R_ARM_THM_ABS5 R_ARM = 7
R_ARM_ABS8 R_ARM = 8
R_ARM_SBREL32 R_ARM = 9
R_ARM_THM_PC22 R_ARM = 10
R_ARM_THM_PC8 R_ARM = 11
R_ARM_AMP_VCALL9 R_ARM = 12
R_ARM_SWI24 R_ARM = 13
R_ARM_THM_SWI8 R_ARM = 14
R_ARM_XPC25 R_ARM = 15
R_ARM_THM_XPC22 R_ARM = 16
R_ARM_COPY R_ARM = 20 /* Copy data from shared object. */
R_ARM_GLOB_DAT R_ARM = 21 /* Set GOT entry to data address. */
R_ARM_JUMP_SLOT R_ARM = 22 /* Set GOT entry to code address. */
R_ARM_RELATIVE R_ARM = 23 /* Add load address of shared object. */
R_ARM_GOTOFF R_ARM = 24 /* Add GOT-relative symbol address. */
R_ARM_GOTPC R_ARM = 25 /* Add PC-relative GOT table address. */
R_ARM_GOT32 R_ARM = 26 /* Add PC-relative GOT offset. */
R_ARM_PLT32 R_ARM = 27 /* Add PC-relative PLT offset. */
R_ARM_GNU_VTENTRY R_ARM = 100
R_ARM_GNU_VTINHERIT R_ARM = 101
R_ARM_RSBREL32 R_ARM = 250
R_ARM_THM_RPC22 R_ARM = 251
R_ARM_RREL32 R_ARM = 252
R_ARM_RABS32 R_ARM = 253
R_ARM_RPC24 R_ARM = 254
R_ARM_RBASE R_ARM = 255
)
var rarmStrings = []intName{
{0, "R_ARM_NONE"},
{1, "R_ARM_PC24"},
{2, "R_ARM_ABS32"},
{3, "R_ARM_REL32"},
{4, "R_ARM_PC13"},
{5, "R_ARM_ABS16"},
{6, "R_ARM_ABS12"},
{7, "R_ARM_THM_ABS5"},
{8, "R_ARM_ABS8"},
{9, "R_ARM_SBREL32"},
{10, "R_ARM_THM_PC22"},
{11, "R_ARM_THM_PC8"},
{12, "R_ARM_AMP_VCALL9"},
{13, "R_ARM_SWI24"},
{14, "R_ARM_THM_SWI8"},
{15, "R_ARM_XPC25"},
{16, "R_ARM_THM_XPC22"},
{20, "R_ARM_COPY"},
{21, "R_ARM_GLOB_DAT"},
{22, "R_ARM_JUMP_SLOT"},
{23, "R_ARM_RELATIVE"},
{24, "R_ARM_GOTOFF"},
{25, "R_ARM_GOTPC"},
{26, "R_ARM_GOT32"},
{27, "R_ARM_PLT32"},
{100, "R_ARM_GNU_VTENTRY"},
{101, "R_ARM_GNU_VTINHERIT"},
{250, "R_ARM_RSBREL32"},
{251, "R_ARM_THM_RPC22"},
{252, "R_ARM_RREL32"},
{253, "R_ARM_RABS32"},
{254, "R_ARM_RPC24"},
{255, "R_ARM_RBASE"},
}
func (i R_ARM) String() string { return stringName(uint32(i), rarmStrings, false) }
func (i R_ARM) GoString() string { return stringName(uint32(i), rarmStrings, true) }
// Relocation types for 386.
type R_386 int
const (
R_386_NONE R_386 = 0 /* No relocation. */
R_386_32 R_386 = 1 /* Add symbol value. */
R_386_PC32 R_386 = 2 /* Add PC-relative symbol value. */
R_386_GOT32 R_386 = 3 /* Add PC-relative GOT offset. */
R_386_PLT32 R_386 = 4 /* Add PC-relative PLT offset. */
R_386_COPY R_386 = 5 /* Copy data from shared object. */
R_386_GLOB_DAT R_386 = 6 /* Set GOT entry to data address. */
R_386_JMP_SLOT R_386 = 7 /* Set GOT entry to code address. */
R_386_RELATIVE R_386 = 8 /* Add load address of shared object. */
R_386_GOTOFF R_386 = 9 /* Add GOT-relative symbol address. */
R_386_GOTPC R_386 = 10 /* Add PC-relative GOT table address. */
R_386_TLS_TPOFF R_386 = 14 /* Negative offset in static TLS block */
R_386_TLS_IE R_386 = 15 /* Absolute address of GOT for -ve static TLS */
R_386_TLS_GOTIE R_386 = 16 /* GOT entry for negative static TLS block */
R_386_TLS_LE R_386 = 17 /* Negative offset relative to static TLS */
R_386_TLS_GD R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_LDM R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
R_386_TLS_GD_32 R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_GD_PUSH R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
R_386_TLS_GD_CALL R_386 = 26 /* call instruction for Sun ABI GD sequence */
R_386_TLS_GD_POP R_386 = 27 /* popl instruction for Sun ABI GD sequence */
R_386_TLS_LDM_32 R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
R_386_TLS_LDM_PUSH R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
R_386_TLS_LDM_CALL R_386 = 30 /* call instruction for Sun ABI LD sequence */
R_386_TLS_LDM_POP R_386 = 31 /* popl instruction for Sun ABI LD sequence */
R_386_TLS_LDO_32 R_386 = 32 /* 32 bit offset from start of TLS block */
R_386_TLS_IE_32 R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
R_386_TLS_LE_32 R_386 = 34 /* 32 bit offset within static TLS block */
R_386_TLS_DTPMOD32 R_386 = 35 /* GOT entry containing TLS index */
R_386_TLS_DTPOFF32 R_386 = 36 /* GOT entry containing TLS offset */
R_386_TLS_TPOFF32 R_386 = 37 /* GOT entry of -ve static TLS offset */
)
var r386Strings = []intName{
{0, "R_386_NONE"},
{1, "R_386_32"},
{2, "R_386_PC32"},
{3, "R_386_GOT32"},
{4, "R_386_PLT32"},
{5, "R_386_COPY"},
{6, "R_386_GLOB_DAT"},
{7, "R_386_JMP_SLOT"},
{8, "R_386_RELATIVE"},
{9, "R_386_GOTOFF"},
{10, "R_386_GOTPC"},
{14, "R_386_TLS_TPOFF"},
{15, "R_386_TLS_IE"},
{16, "R_386_TLS_GOTIE"},
{17, "R_386_TLS_LE"},
{18, "R_386_TLS_GD"},
{19, "R_386_TLS_LDM"},
{24, "R_386_TLS_GD_32"},
{25, "R_386_TLS_GD_PUSH"},
{26, "R_386_TLS_GD_CALL"},
{27, "R_386_TLS_GD_POP"},
{28, "R_386_TLS_LDM_32"},
{29, "R_386_TLS_LDM_PUSH"},
{30, "R_386_TLS_LDM_CALL"},
{31, "R_386_TLS_LDM_POP"},
{32, "R_386_TLS_LDO_32"},
{33, "R_386_TLS_IE_32"},
{34, "R_386_TLS_LE_32"},
{35, "R_386_TLS_DTPMOD32"},
{36, "R_386_TLS_DTPOFF32"},
{37, "R_386_TLS_TPOFF32"},
}
func (i R_386) String() string { return stringName(uint32(i), r386Strings, false) }
func (i R_386) GoString() string { return stringName(uint32(i), r386Strings, true) }
// Relocation types for MIPS.
type R_MIPS int
const (
R_MIPS_NONE R_MIPS = 0
R_MIPS_16 R_MIPS = 1
R_MIPS_32 R_MIPS = 2
R_MIPS_REL32 R_MIPS = 3
R_MIPS_26 R_MIPS = 4
R_MIPS_HI16 R_MIPS = 5 /* high 16 bits of symbol value */
R_MIPS_LO16 R_MIPS = 6 /* low 16 bits of symbol value */
R_MIPS_GPREL16 R_MIPS = 7 /* GP-relative reference */
R_MIPS_LITERAL R_MIPS = 8 /* Reference to literal section */
R_MIPS_GOT16 R_MIPS = 9 /* Reference to global offset table */
R_MIPS_PC16 R_MIPS = 10 /* 16 bit PC relative reference */
R_MIPS_CALL16 R_MIPS = 11 /* 16 bit call thru glbl offset tbl */
R_MIPS_GPREL32 R_MIPS = 12
R_MIPS_SHIFT5 R_MIPS = 16
R_MIPS_SHIFT6 R_MIPS = 17
R_MIPS_64 R_MIPS = 18
R_MIPS_GOT_DISP R_MIPS = 19
R_MIPS_GOT_PAGE R_MIPS = 20
R_MIPS_GOT_OFST R_MIPS = 21
R_MIPS_GOT_HI16 R_MIPS = 22
R_MIPS_GOT_LO16 R_MIPS = 23
R_MIPS_SUB R_MIPS = 24
R_MIPS_INSERT_A R_MIPS = 25
R_MIPS_INSERT_B R_MIPS = 26
R_MIPS_DELETE R_MIPS = 27
R_MIPS_HIGHER R_MIPS = 28
R_MIPS_HIGHEST R_MIPS = 29
R_MIPS_CALL_HI16 R_MIPS = 30
R_MIPS_CALL_LO16 R_MIPS = 31
R_MIPS_SCN_DISP R_MIPS = 32
R_MIPS_REL16 R_MIPS = 33
R_MIPS_ADD_IMMEDIATE R_MIPS = 34
R_MIPS_PJUMP R_MIPS = 35
R_MIPS_RELGOT R_MIPS = 36
R_MIPS_JALR R_MIPS = 37
R_MIPS_TLS_DTPMOD32 R_MIPS = 38 /* Module number 32 bit */
R_MIPS_TLS_DTPREL32 R_MIPS = 39 /* Module-relative offset 32 bit */
R_MIPS_TLS_DTPMOD64 R_MIPS = 40 /* Module number 64 bit */
R_MIPS_TLS_DTPREL64 R_MIPS = 41 /* Module-relative offset 64 bit */
R_MIPS_TLS_GD R_MIPS = 42 /* 16 bit GOT offset for GD */
R_MIPS_TLS_LDM R_MIPS = 43 /* 16 bit GOT offset for LDM */
R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
R_MIPS_TLS_GOTTPREL R_MIPS = 46 /* 16 bit GOT offset for IE */
R_MIPS_TLS_TPREL32 R_MIPS = 47 /* TP-relative offset, 32 bit */
R_MIPS_TLS_TPREL64 R_MIPS = 48 /* TP-relative offset, 64 bit */
R_MIPS_TLS_TPREL_HI16 R_MIPS = 49 /* TP-relative offset, high 16 bits */
R_MIPS_TLS_TPREL_LO16 R_MIPS = 50 /* TP-relative offset, low 16 bits */
)
var rmipsStrings = []intName{
{0, "R_MIPS_NONE"},
{1, "R_MIPS_16"},
{2, "R_MIPS_32"},
{3, "R_MIPS_REL32"},
{4, "R_MIPS_26"},
{5, "R_MIPS_HI16"},
{6, "R_MIPS_LO16"},
{7, "R_MIPS_GPREL16"},
{8, "R_MIPS_LITERAL"},
{9, "R_MIPS_GOT16"},
{10, "R_MIPS_PC16"},
{11, "R_MIPS_CALL16"},
{12, "R_MIPS_GPREL32"},
{16, "R_MIPS_SHIFT5"},
{17, "R_MIPS_SHIFT6"},
{18, "R_MIPS_64"},
{19, "R_MIPS_GOT_DISP"},
{20, "R_MIPS_GOT_PAGE"},
{21, "R_MIPS_GOT_OFST"},
{22, "R_MIPS_GOT_HI16"},
{23, "R_MIPS_GOT_LO16"},
{24, "R_MIPS_SUB"},
{25, "R_MIPS_INSERT_A"},
{26, "R_MIPS_INSERT_B"},
{27, "R_MIPS_DELETE"},
{28, "R_MIPS_HIGHER"},
{29, "R_MIPS_HIGHEST"},
{30, "R_MIPS_CALL_HI16"},
{31, "R_MIPS_CALL_LO16"},
{32, "R_MIPS_SCN_DISP"},
{33, "R_MIPS_REL16"},
{34, "R_MIPS_ADD_IMMEDIATE"},
{35, "R_MIPS_PJUMP"},
{36, "R_MIPS_RELGOT"},
{37, "R_MIPS_JALR"},
{38, "R_MIPS_TLS_DTPMOD32"},
{39, "R_MIPS_TLS_DTPREL32"},
{40, "R_MIPS_TLS_DTPMOD64"},
{41, "R_MIPS_TLS_DTPREL64"},
{42, "R_MIPS_TLS_GD"},
{43, "R_MIPS_TLS_LDM"},
{44, "R_MIPS_TLS_DTPREL_HI16"},
{45, "R_MIPS_TLS_DTPREL_LO16"},
{46, "R_MIPS_TLS_GOTTPREL"},
{47, "R_MIPS_TLS_TPREL32"},
{48, "R_MIPS_TLS_TPREL64"},
{49, "R_MIPS_TLS_TPREL_HI16"},
{50, "R_MIPS_TLS_TPREL_LO16"},
}
func (i R_MIPS) String() string { return stringName(uint32(i), rmipsStrings, false) }
func (i R_MIPS) GoString() string { return stringName(uint32(i), rmipsStrings, true) }
// Relocation types for PowerPC.
type R_PPC int
const (
R_PPC_NONE R_PPC = 0 /* No relocation. */
R_PPC_ADDR32 R_PPC = 1
R_PPC_ADDR24 R_PPC = 2
R_PPC_ADDR16 R_PPC = 3
R_PPC_ADDR16_LO R_PPC = 4
R_PPC_ADDR16_HI R_PPC = 5
R_PPC_ADDR16_HA R_PPC = 6
R_PPC_ADDR14 R_PPC = 7
R_PPC_ADDR14_BRTAKEN R_PPC = 8
R_PPC_ADDR14_BRNTAKEN R_PPC = 9
R_PPC_REL24 R_PPC = 10
R_PPC_REL14 R_PPC = 11
R_PPC_REL14_BRTAKEN R_PPC = 12
R_PPC_REL14_BRNTAKEN R_PPC = 13
R_PPC_GOT16 R_PPC = 14
R_PPC_GOT16_LO R_PPC = 15
R_PPC_GOT16_HI R_PPC = 16
R_PPC_GOT16_HA R_PPC = 17
R_PPC_PLTREL24 R_PPC = 18
R_PPC_COPY R_PPC = 19
R_PPC_GLOB_DAT R_PPC = 20
R_PPC_JMP_SLOT R_PPC = 21
R_PPC_RELATIVE R_PPC = 22
R_PPC_LOCAL24PC R_PPC = 23
R_PPC_UADDR32 R_PPC = 24
R_PPC_UADDR16 R_PPC = 25
R_PPC_REL32 R_PPC = 26
R_PPC_PLT32 R_PPC = 27
R_PPC_PLTREL32 R_PPC = 28
R_PPC_PLT16_LO R_PPC = 29
R_PPC_PLT16_HI R_PPC = 30
R_PPC_PLT16_HA R_PPC = 31
R_PPC_SDAREL16 R_PPC = 32
R_PPC_SECTOFF R_PPC = 33
R_PPC_SECTOFF_LO R_PPC = 34
R_PPC_SECTOFF_HI R_PPC = 35
R_PPC_SECTOFF_HA R_PPC = 36
R_PPC_TLS R_PPC = 67
R_PPC_DTPMOD32 R_PPC = 68
R_PPC_TPREL16 R_PPC = 69
R_PPC_TPREL16_LO R_PPC = 70
R_PPC_TPREL16_HI R_PPC = 71
R_PPC_TPREL16_HA R_PPC = 72
R_PPC_TPREL32 R_PPC = 73
R_PPC_DTPREL16 R_PPC = 74
R_PPC_DTPREL16_LO R_PPC = 75
R_PPC_DTPREL16_HI R_PPC = 76
R_PPC_DTPREL16_HA R_PPC = 77
R_PPC_DTPREL32 R_PPC = 78
R_PPC_GOT_TLSGD16 R_PPC = 79
R_PPC_GOT_TLSGD16_LO R_PPC = 80
R_PPC_GOT_TLSGD16_HI R_PPC = 81
R_PPC_GOT_TLSGD16_HA R_PPC = 82
R_PPC_GOT_TLSLD16 R_PPC = 83
R_PPC_GOT_TLSLD16_LO R_PPC = 84
R_PPC_GOT_TLSLD16_HI R_PPC = 85
R_PPC_GOT_TLSLD16_HA R_PPC = 86
R_PPC_GOT_TPREL16 R_PPC = 87
R_PPC_GOT_TPREL16_LO R_PPC = 88
R_PPC_GOT_TPREL16_HI R_PPC = 89
R_PPC_GOT_TPREL16_HA R_PPC = 90
R_PPC_EMB_NADDR32 R_PPC = 101
R_PPC_EMB_NADDR16 R_PPC = 102
R_PPC_EMB_NADDR16_LO R_PPC = 103
R_PPC_EMB_NADDR16_HI R_PPC = 104
R_PPC_EMB_NADDR16_HA R_PPC = 105
R_PPC_EMB_SDAI16 R_PPC = 106
R_PPC_EMB_SDA2I16 R_PPC = 107
R_PPC_EMB_SDA2REL R_PPC = 108
R_PPC_EMB_SDA21 R_PPC = 109
R_PPC_EMB_MRKREF R_PPC = 110
R_PPC_EMB_RELSEC16 R_PPC = 111
R_PPC_EMB_RELST_LO R_PPC = 112
R_PPC_EMB_RELST_HI R_PPC = 113
R_PPC_EMB_RELST_HA R_PPC = 114
R_PPC_EMB_BIT_FLD R_PPC = 115
R_PPC_EMB_RELSDA R_PPC = 116
)
var rppcStrings = []intName{
{0, "R_PPC_NONE"},
{1, "R_PPC_ADDR32"},
{2, "R_PPC_ADDR24"},
{3, "R_PPC_ADDR16"},
{4, "R_PPC_ADDR16_LO"},
{5, "R_PPC_ADDR16_HI"},
{6, "R_PPC_ADDR16_HA"},
{7, "R_PPC_ADDR14"},
{8, "R_PPC_ADDR14_BRTAKEN"},
{9, "R_PPC_ADDR14_BRNTAKEN"},
{10, "R_PPC_REL24"},
{11, "R_PPC_REL14"},
{12, "R_PPC_REL14_BRTAKEN"},
{13, "R_PPC_REL14_BRNTAKEN"},
{14, "R_PPC_GOT16"},
{15, "R_PPC_GOT16_LO"},
{16, "R_PPC_GOT16_HI"},
{17, "R_PPC_GOT16_HA"},
{18, "R_PPC_PLTREL24"},
{19, "R_PPC_COPY"},
{20, "R_PPC_GLOB_DAT"},
{21, "R_PPC_JMP_SLOT"},
{22, "R_PPC_RELATIVE"},
{23, "R_PPC_LOCAL24PC"},
{24, "R_PPC_UADDR32"},
{25, "R_PPC_UADDR16"},
{26, "R_PPC_REL32"},
{27, "R_PPC_PLT32"},
{28, "R_PPC_PLTREL32"},
{29, "R_PPC_PLT16_LO"},
{30, "R_PPC_PLT16_HI"},
{31, "R_PPC_PLT16_HA"},
{32, "R_PPC_SDAREL16"},
{33, "R_PPC_SECTOFF"},
{34, "R_PPC_SECTOFF_LO"},
{35, "R_PPC_SECTOFF_HI"},
{36, "R_PPC_SECTOFF_HA"},
{67, "R_PPC_TLS"},
{68, "R_PPC_DTPMOD32"},
{69, "R_PPC_TPREL16"},
{70, "R_PPC_TPREL16_LO"},
{71, "R_PPC_TPREL16_HI"},
{72, "R_PPC_TPREL16_HA"},
{73, "R_PPC_TPREL32"},
{74, "R_PPC_DTPREL16"},
{75, "R_PPC_DTPREL16_LO"},
{76, "R_PPC_DTPREL16_HI"},
{77, "R_PPC_DTPREL16_HA"},
{78, "R_PPC_DTPREL32"},
{79, "R_PPC_GOT_TLSGD16"},
{80, "R_PPC_GOT_TLSGD16_LO"},
{81, "R_PPC_GOT_TLSGD16_HI"},
{82, "R_PPC_GOT_TLSGD16_HA"},
{83, "R_PPC_GOT_TLSLD16"},
{84, "R_PPC_GOT_TLSLD16_LO"},
{85, "R_PPC_GOT_TLSLD16_HI"},
{86, "R_PPC_GOT_TLSLD16_HA"},
{87, "R_PPC_GOT_TPREL16"},
{88, "R_PPC_GOT_TPREL16_LO"},
{89, "R_PPC_GOT_TPREL16_HI"},
{90, "R_PPC_GOT_TPREL16_HA"},
{101, "R_PPC_EMB_NADDR32"},
{102, "R_PPC_EMB_NADDR16"},
{103, "R_PPC_EMB_NADDR16_LO"},
{104, "R_PPC_EMB_NADDR16_HI"},
{105, "R_PPC_EMB_NADDR16_HA"},
{106, "R_PPC_EMB_SDAI16"},
{107, "R_PPC_EMB_SDA2I16"},
{108, "R_PPC_EMB_SDA2REL"},
{109, "R_PPC_EMB_SDA21"},
{110, "R_PPC_EMB_MRKREF"},
{111, "R_PPC_EMB_RELSEC16"},
{112, "R_PPC_EMB_RELST_LO"},
{113, "R_PPC_EMB_RELST_HI"},
{114, "R_PPC_EMB_RELST_HA"},
{115, "R_PPC_EMB_BIT_FLD"},
{116, "R_PPC_EMB_RELSDA"},
}
func (i R_PPC) String() string { return stringName(uint32(i), rppcStrings, false) }
func (i R_PPC) GoString() string { return stringName(uint32(i), rppcStrings, true) }
// Relocation types for 64-bit PowerPC or Power Architecture processors.
type R_PPC64 int
const (
R_PPC64_NONE R_PPC64 = 0
R_PPC64_ADDR32 R_PPC64 = 1
R_PPC64_ADDR24 R_PPC64 = 2
R_PPC64_ADDR16 R_PPC64 = 3
R_PPC64_ADDR16_LO R_PPC64 = 4
R_PPC64_ADDR16_HI R_PPC64 = 5
R_PPC64_ADDR16_HA R_PPC64 = 6
R_PPC64_ADDR14 R_PPC64 = 7
R_PPC64_ADDR14_BRTAKEN R_PPC64 = 8
R_PPC64_ADDR14_BRNTAKEN R_PPC64 = 9
R_PPC64_REL24 R_PPC64 = 10
R_PPC64_REL14 R_PPC64 = 11
R_PPC64_REL14_BRTAKEN R_PPC64 = 12
R_PPC64_REL14_BRNTAKEN R_PPC64 = 13
R_PPC64_GOT16 R_PPC64 = 14
R_PPC64_GOT16_LO R_PPC64 = 15
R_PPC64_GOT16_HI R_PPC64 = 16
R_PPC64_GOT16_HA R_PPC64 = 17
R_PPC64_JMP_SLOT R_PPC64 = 21
R_PPC64_REL32 R_PPC64 = 26
R_PPC64_ADDR64 R_PPC64 = 38
R_PPC64_ADDR16_HIGHER R_PPC64 = 39
R_PPC64_ADDR16_HIGHERA R_PPC64 = 40
R_PPC64_ADDR16_HIGHEST R_PPC64 = 41
R_PPC64_ADDR16_HIGHESTA R_PPC64 = 42
R_PPC64_REL64 R_PPC64 = 44
R_PPC64_TOC16 R_PPC64 = 47
R_PPC64_TOC16_LO R_PPC64 = 48
R_PPC64_TOC16_HI R_PPC64 = 49
R_PPC64_TOC16_HA R_PPC64 = 50
R_PPC64_TOC R_PPC64 = 51
R_PPC64_ADDR16_DS R_PPC64 = 56
R_PPC64_ADDR16_LO_DS R_PPC64 = 57
R_PPC64_GOT16_DS R_PPC64 = 58
R_PPC64_GOT16_LO_DS R_PPC64 = 59
R_PPC64_TOC16_DS R_PPC64 = 63
R_PPC64_TOC16_LO_DS R_PPC64 = 64
R_PPC64_TLS R_PPC64 = 67
R_PPC64_DTPMOD64 R_PPC64 = 68
R_PPC64_TPREL16 R_PPC64 = 69
R_PPC64_TPREL16_LO R_PPC64 = 70
R_PPC64_TPREL16_HI R_PPC64 = 71
R_PPC64_TPREL16_HA R_PPC64 = 72
R_PPC64_TPREL64 R_PPC64 = 73
R_PPC64_DTPREL16 R_PPC64 = 74
R_PPC64_DTPREL16_LO R_PPC64 = 75
R_PPC64_DTPREL16_HI R_PPC64 = 76
R_PPC64_DTPREL16_HA R_PPC64 = 77
R_PPC64_DTPREL64 R_PPC64 = 78
R_PPC64_GOT_TLSGD16 R_PPC64 = 79
R_PPC64_GOT_TLSGD16_LO R_PPC64 = 80
R_PPC64_GOT_TLSGD16_HI R_PPC64 = 81
R_PPC64_GOT_TLSGD16_HA R_PPC64 = 82
R_PPC64_GOT_TLSLD16 R_PPC64 = 83
R_PPC64_GOT_TLSLD16_LO R_PPC64 = 84
R_PPC64_GOT_TLSLD16_HI R_PPC64 = 85
R_PPC64_GOT_TLSLD16_HA R_PPC64 = 86
R_PPC64_GOT_TPREL16_DS R_PPC64 = 87
R_PPC64_GOT_TPREL16_LO_DS R_PPC64 = 88
R_PPC64_GOT_TPREL16_HI R_PPC64 = 89
R_PPC64_GOT_TPREL16_HA R_PPC64 = 90
R_PPC64_GOT_DTPREL16_DS R_PPC64 = 91
R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92
R_PPC64_GOT_DTPREL16_HI R_PPC64 = 93
R_PPC64_GOT_DTPREL16_HA R_PPC64 = 94
R_PPC64_TPREL16_DS R_PPC64 = 95
R_PPC64_TPREL16_LO_DS R_PPC64 = 96
R_PPC64_TPREL16_HIGHER R_PPC64 = 97
R_PPC64_TPREL16_HIGHERA R_PPC64 = 98
R_PPC64_TPREL16_HIGHEST R_PPC64 = 99
R_PPC64_TPREL16_HIGHESTA R_PPC64 = 100
R_PPC64_DTPREL16_DS R_PPC64 = 101
R_PPC64_DTPREL16_LO_DS R_PPC64 = 102
R_PPC64_DTPREL16_HIGHER R_PPC64 = 103
R_PPC64_DTPREL16_HIGHERA R_PPC64 = 104
R_PPC64_DTPREL16_HIGHEST R_PPC64 = 105
R_PPC64_DTPREL16_HIGHESTA R_PPC64 = 106
R_PPC64_TLSGD R_PPC64 = 107
R_PPC64_TLSLD R_PPC64 = 108
R_PPC64_REL16 R_PPC64 = 249
R_PPC64_REL16_LO R_PPC64 = 250
R_PPC64_REL16_HI R_PPC64 = 251
R_PPC64_REL16_HA R_PPC64 = 252
)
var rppc64Strings = []intName{
{0, "R_PPC64_NONE"},
{1, "R_PPC64_ADDR32"},
{2, "R_PPC64_ADDR24"},
{3, "R_PPC64_ADDR16"},
{4, "R_PPC64_ADDR16_LO"},
{5, "R_PPC64_ADDR16_HI"},
{6, "R_PPC64_ADDR16_HA"},
{7, "R_PPC64_ADDR14"},
{8, "R_PPC64_ADDR14_BRTAKEN"},
{9, "R_PPC64_ADDR14_BRNTAKEN"},
{10, "R_PPC64_REL24"},
{11, "R_PPC64_REL14"},
{12, "R_PPC64_REL14_BRTAKEN"},
{13, "R_PPC64_REL14_BRNTAKEN"},
{14, "R_PPC64_GOT16"},
{15, "R_PPC64_GOT16_LO"},
{16, "R_PPC64_GOT16_HI"},
{17, "R_PPC64_GOT16_HA"},
{21, "R_PPC64_JMP_SLOT"},
{26, "R_PPC64_REL32"},
{38, "R_PPC64_ADDR64"},
{39, "R_PPC64_ADDR16_HIGHER"},
{40, "R_PPC64_ADDR16_HIGHERA"},
{41, "R_PPC64_ADDR16_HIGHEST"},
{42, "R_PPC64_ADDR16_HIGHESTA"},
{44, "R_PPC64_REL64"},
{47, "R_PPC64_TOC16"},
{48, "R_PPC64_TOC16_LO"},
{49, "R_PPC64_TOC16_HI"},
{50, "R_PPC64_TOC16_HA"},
{51, "R_PPC64_TOC"},
{56, "R_PPC64_ADDR16_DS"},
{57, "R_PPC64_ADDR16_LO_DS"},
{58, "R_PPC64_GOT16_DS"},
{59, "R_PPC64_GOT16_LO_DS"},
{63, "R_PPC64_TOC16_DS"},
{64, "R_PPC64_TOC16_LO_DS"},
{67, "R_PPC64_TLS"},
{68, "R_PPC64_DTPMOD64"},
{69, "R_PPC64_TPREL16"},
{70, "R_PPC64_TPREL16_LO"},
{71, "R_PPC64_TPREL16_HI"},
{72, "R_PPC64_TPREL16_HA"},
{73, "R_PPC64_TPREL64"},
{74, "R_PPC64_DTPREL16"},
{75, "R_PPC64_DTPREL16_LO"},
{76, "R_PPC64_DTPREL16_HI"},
{77, "R_PPC64_DTPREL16_HA"},
{78, "R_PPC64_DTPREL64"},
{79, "R_PPC64_GOT_TLSGD16"},
{80, "R_PPC64_GOT_TLSGD16_LO"},
{81, "R_PPC64_GOT_TLSGD16_HI"},
{82, "R_PPC64_GOT_TLSGD16_HA"},
{83, "R_PPC64_GOT_TLSLD16"},
{84, "R_PPC64_GOT_TLSLD16_LO"},
{85, "R_PPC64_GOT_TLSLD16_HI"},
{86, "R_PPC64_GOT_TLSLD16_HA"},
{87, "R_PPC64_GOT_TPREL16_DS"},
{88, "R_PPC64_GOT_TPREL16_LO_DS"},
{89, "R_PPC64_GOT_TPREL16_HI"},
{90, "R_PPC64_GOT_TPREL16_HA"},
{91, "R_PPC64_GOT_DTPREL16_DS"},
{92, "R_PPC64_GOT_DTPREL16_LO_DS"},
{93, "R_PPC64_GOT_DTPREL16_HI"},
{94, "R_PPC64_GOT_DTPREL16_HA"},
{95, "R_PPC64_TPREL16_DS"},
{96, "R_PPC64_TPREL16_LO_DS"},
{97, "R_PPC64_TPREL16_HIGHER"},
{98, "R_PPC64_TPREL16_HIGHERA"},
{99, "R_PPC64_TPREL16_HIGHEST"},
{100, "R_PPC64_TPREL16_HIGHESTA"},
{101, "R_PPC64_DTPREL16_DS"},
{102, "R_PPC64_DTPREL16_LO_DS"},
{103, "R_PPC64_DTPREL16_HIGHER"},
{104, "R_PPC64_DTPREL16_HIGHERA"},
{105, "R_PPC64_DTPREL16_HIGHEST"},
{106, "R_PPC64_DTPREL16_HIGHESTA"},
{107, "R_PPC64_TLSGD"},
{108, "R_PPC64_TLSLD"},
{249, "R_PPC64_REL16"},
{250, "R_PPC64_REL16_LO"},
{251, "R_PPC64_REL16_HI"},
{252, "R_PPC64_REL16_HA"},
}
func (i R_PPC64) String() string { return stringName(uint32(i), rppc64Strings, false) }
func (i R_PPC64) GoString() string { return stringName(uint32(i), rppc64Strings, true) }
// Relocation types for s390
type R_390 int
const (
R_390_NONE R_390 = 0
R_390_8 R_390 = 1
R_390_12 R_390 = 2
R_390_16 R_390 = 3
R_390_32 R_390 = 4
R_390_PC32 R_390 = 5
R_390_GOT12 R_390 = 6
R_390_GOT32 R_390 = 7
R_390_PLT32 R_390 = 8
R_390_COPY R_390 = 9
R_390_GLOB_DAT R_390 = 10
R_390_JMP_SLOT R_390 = 11
R_390_RELATIVE R_390 = 12
R_390_GOTOFF R_390 = 13
R_390_GOTPC R_390 = 14
R_390_GOT16 R_390 = 15
R_390_PC16 R_390 = 16
R_390_PC16DBL R_390 = 17
R_390_PLT16DBL R_390 = 18
R_390_PC32DBL R_390 = 19
R_390_PLT32DBL R_390 = 20
R_390_GOTPCDBL R_390 = 21
R_390_64 R_390 = 22
R_390_PC64 R_390 = 23
R_390_GOT64 R_390 = 24
R_390_PLT64 R_390 = 25
R_390_GOTENT R_390 = 26
)
var r390Strings = []intName{
{0, "R_390_NONE"},
{1, "R_390_8"},
{2, "R_390_12"},
{3, "R_390_16"},
{4, "R_390_32"},
{5, "R_390_PC32"},
{6, "R_390_GOT12"},
{7, "R_390_GOT32"},
{8, "R_390_PLT32"},
{9, "R_390_COPY"},
{10, "R_390_GLOB_DAT"},
{11, "R_390_JMP_SLOT"},
{12, "R_390_RELATIVE"},
{13, "R_390_GOTOFF"},
{14, "R_390_GOTPC"},
{15, "R_390_GOT16"},
{16, "R_390_PC16"},
{17, "R_390_PC16DBL"},
{18, "R_390_PLT16DBL"},
{19, "R_390_PC32DBL"},
{20, "R_390_PLT32DBL"},
{21, "R_390_GOTPCDBL"},
{22, "R_390_64"},
{23, "R_390_PC64"},
{24, "R_390_GOT64"},
{25, "R_390_PLT64"},
{26, "R_390_GOTENT"},
}
func (i R_390) String() string { return stringName(uint32(i), r390Strings, false) }
func (i R_390) GoString() string { return stringName(uint32(i), r390Strings, true) }
// Relocation types for SPARC.
type R_SPARC int
const (
R_SPARC_NONE R_SPARC = 0
R_SPARC_8 R_SPARC = 1
R_SPARC_16 R_SPARC = 2
R_SPARC_32 R_SPARC = 3
R_SPARC_DISP8 R_SPARC = 4
R_SPARC_DISP16 R_SPARC = 5
R_SPARC_DISP32 R_SPARC = 6
R_SPARC_WDISP30 R_SPARC = 7
R_SPARC_WDISP22 R_SPARC = 8
R_SPARC_HI22 R_SPARC = 9
R_SPARC_22 R_SPARC = 10
R_SPARC_13 R_SPARC = 11
R_SPARC_LO10 R_SPARC = 12
R_SPARC_GOT10 R_SPARC = 13
R_SPARC_GOT13 R_SPARC = 14
R_SPARC_GOT22 R_SPARC = 15
R_SPARC_PC10 R_SPARC = 16
R_SPARC_PC22 R_SPARC = 17
R_SPARC_WPLT30 R_SPARC = 18
R_SPARC_COPY R_SPARC = 19
R_SPARC_GLOB_DAT R_SPARC = 20
R_SPARC_JMP_SLOT R_SPARC = 21
R_SPARC_RELATIVE R_SPARC = 22
R_SPARC_UA32 R_SPARC = 23
R_SPARC_PLT32 R_SPARC = 24
R_SPARC_HIPLT22 R_SPARC = 25
R_SPARC_LOPLT10 R_SPARC = 26
R_SPARC_PCPLT32 R_SPARC = 27
R_SPARC_PCPLT22 R_SPARC = 28
R_SPARC_PCPLT10 R_SPARC = 29
R_SPARC_10 R_SPARC = 30
R_SPARC_11 R_SPARC = 31
R_SPARC_64 R_SPARC = 32
R_SPARC_OLO10 R_SPARC = 33
R_SPARC_HH22 R_SPARC = 34
R_SPARC_HM10 R_SPARC = 35
R_SPARC_LM22 R_SPARC = 36
R_SPARC_PC_HH22 R_SPARC = 37
R_SPARC_PC_HM10 R_SPARC = 38
R_SPARC_PC_LM22 R_SPARC = 39
R_SPARC_WDISP16 R_SPARC = 40
R_SPARC_WDISP19 R_SPARC = 41
R_SPARC_GLOB_JMP R_SPARC = 42
R_SPARC_7 R_SPARC = 43
R_SPARC_5 R_SPARC = 44
R_SPARC_6 R_SPARC = 45
R_SPARC_DISP64 R_SPARC = 46
R_SPARC_PLT64 R_SPARC = 47
R_SPARC_HIX22 R_SPARC = 48
R_SPARC_LOX10 R_SPARC = 49
R_SPARC_H44 R_SPARC = 50
R_SPARC_M44 R_SPARC = 51
R_SPARC_L44 R_SPARC = 52
R_SPARC_REGISTER R_SPARC = 53
R_SPARC_UA64 R_SPARC = 54
R_SPARC_UA16 R_SPARC = 55
)
var rsparcStrings = []intName{
{0, "R_SPARC_NONE"},
{1, "R_SPARC_8"},
{2, "R_SPARC_16"},
{3, "R_SPARC_32"},
{4, "R_SPARC_DISP8"},
{5, "R_SPARC_DISP16"},
{6, "R_SPARC_DISP32"},
{7, "R_SPARC_WDISP30"},
{8, "R_SPARC_WDISP22"},
{9, "R_SPARC_HI22"},
{10, "R_SPARC_22"},
{11, "R_SPARC_13"},
{12, "R_SPARC_LO10"},
{13, "R_SPARC_GOT10"},
{14, "R_SPARC_GOT13"},
{15, "R_SPARC_GOT22"},
{16, "R_SPARC_PC10"},
{17, "R_SPARC_PC22"},
{18, "R_SPARC_WPLT30"},
{19, "R_SPARC_COPY"},
{20, "R_SPARC_GLOB_DAT"},
{21, "R_SPARC_JMP_SLOT"},
{22, "R_SPARC_RELATIVE"},
{23, "R_SPARC_UA32"},
{24, "R_SPARC_PLT32"},
{25, "R_SPARC_HIPLT22"},
{26, "R_SPARC_LOPLT10"},
{27, "R_SPARC_PCPLT32"},
{28, "R_SPARC_PCPLT22"},
{29, "R_SPARC_PCPLT10"},
{30, "R_SPARC_10"},
{31, "R_SPARC_11"},
{32, "R_SPARC_64"},
{33, "R_SPARC_OLO10"},
{34, "R_SPARC_HH22"},
{35, "R_SPARC_HM10"},
{36, "R_SPARC_LM22"},
{37, "R_SPARC_PC_HH22"},
{38, "R_SPARC_PC_HM10"},
{39, "R_SPARC_PC_LM22"},
{40, "R_SPARC_WDISP16"},
{41, "R_SPARC_WDISP19"},
{42, "R_SPARC_GLOB_JMP"},
{43, "R_SPARC_7"},
{44, "R_SPARC_5"},
{45, "R_SPARC_6"},
{46, "R_SPARC_DISP64"},
{47, "R_SPARC_PLT64"},
{48, "R_SPARC_HIX22"},
{49, "R_SPARC_LOX10"},
{50, "R_SPARC_H44"},
{51, "R_SPARC_M44"},
{52, "R_SPARC_L44"},
{53, "R_SPARC_REGISTER"},
{54, "R_SPARC_UA64"},
{55, "R_SPARC_UA16"},
}
func (i R_SPARC) String() string { return stringName(uint32(i), rsparcStrings, false) }
func (i R_SPARC) GoString() string { return stringName(uint32(i), rsparcStrings, true) }
// Magic number for the elf trampoline, chosen wisely to be an immediate value.
const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003
// ELF32 File header.
type Header32 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint32 /* Entry point. */
Phoff uint32 /* Program header file offset. */
Shoff uint32 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
// ELF32 Section header.
type Section32 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint32 /* Section flags. */
Addr uint32 /* Address in memory image. */
Off uint32 /* Offset in file. */
Size uint32 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint32 /* Alignment in bytes. */
Entsize uint32 /* Size of each entry in section. */
}
// ELF32 Program header.
type Prog32 struct {
Type uint32 /* Entry type. */
Off uint32 /* File offset of contents. */
Vaddr uint32 /* Virtual address in memory image. */
Paddr uint32 /* Physical address (not used). */
Filesz uint32 /* Size of contents in file. */
Memsz uint32 /* Size of contents in memory. */
Flags uint32 /* Access permission flags. */
Align uint32 /* Alignment in memory and file. */
}
// ELF32 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn32 struct {
Tag int32 /* Entry type. */
Val uint32 /* Integer/Address value. */
}
// ELF32 Compression header.
type Chdr32 struct {
Type uint32
Size uint32
Addralign uint32
}
/*
* Relocation entries.
*/
// ELF32 Relocations that don't need an addend field.
type Rel32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
}
// ELF32 Relocations that need an addend field.
type Rela32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
Addend int32 /* Addend. */
}
func R_SYM32(info uint32) uint32 { return uint32(info >> 8) }
func R_TYPE32(info uint32) uint32 { return uint32(info & 0xff) }
func R_INFO32(sym, typ uint32) uint32 { return sym<<8 | typ }
// ELF32 Symbol.
type Sym32 struct {
Name uint32
Value uint32
Size uint32
Info uint8
Other uint8
Shndx uint16
}
const Sym32Size = 16
func ST_BIND(info uint8) SymBind { return SymBind(info >> 4) }
func ST_TYPE(info uint8) SymType { return SymType(info & 0xF) }
func ST_INFO(bind SymBind, typ SymType) uint8 {
return uint8(bind)<<4 | uint8(typ)&0xf
}
func ST_VISIBILITY(other uint8) SymVis { return SymVis(other & 3) }
/*
* ELF64
*/
// ELF64 file header.
type Header64 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint64 /* Entry point. */
Phoff uint64 /* Program header file offset. */
Shoff uint64 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
// ELF64 Section header.
type Section64 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint64 /* Section flags. */
Addr uint64 /* Address in memory image. */
Off uint64 /* Offset in file. */
Size uint64 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint64 /* Alignment in bytes. */
Entsize uint64 /* Size of each entry in section. */
}
// ELF64 Program header.
type Prog64 struct {
Type uint32 /* Entry type. */
Flags uint32 /* Access permission flags. */
Off uint64 /* File offset of contents. */
Vaddr uint64 /* Virtual address in memory image. */
Paddr uint64 /* Physical address (not used). */
Filesz uint64 /* Size of contents in file. */
Memsz uint64 /* Size of contents in memory. */
Align uint64 /* Alignment in memory and file. */
}
// ELF64 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn64 struct {
Tag int64 /* Entry type. */
Val uint64 /* Integer/address value */
}
// ELF64 Compression header.
type Chdr64 struct {
Type uint32
_ uint32 /* Reserved. */
Size uint64
Addralign uint64
}
/*
* Relocation entries.
*/
/* ELF64 relocations that don't need an addend field. */
type Rel64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
}
/* ELF64 relocations that need an addend field. */
type Rela64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
Addend int64 /* Addend. */
}
func R_SYM64(info uint64) uint32 { return uint32(info >> 32) }
func R_TYPE64(info uint64) uint32 { return uint32(info) }
func R_INFO(sym, typ uint32) uint64 { return uint64(sym)<<32 | uint64(typ) }
// ELF64 symbol table entries.
type Sym64 struct {
Name uint32 /* String table index of name. */
Info uint8 /* Type and binding information. */
Other uint8 /* Reserved (not used). */
Shndx uint16 /* Section index of symbol. */
Value uint64 /* Symbol value. */
Size uint64 /* Size of associated object. */
}
const Sym64Size = 24
type intName struct {
i uint32
s string
}
func stringName(i uint32, names []intName, goSyntax bool) string {
for _, n := range names {
if n.i == i {
if goSyntax {
return "elf." + n.s
}
return n.s
}
}
// second pass - look for smaller to add with.
// assume sorted already
for j := len(names) - 1; j >= 0; j-- {
n := names[j]
if n.i < i {
s := n.s
if goSyntax {
s = "elf." + s
}
return s + "+" + strconv.FormatUint(uint64(i-n.i), 10)
}
}
return strconv.FormatUint(uint64(i), 10)
}
func flagName(i uint32, names []intName, goSyntax bool) string {
s := ""
for _, n := range names {
if n.i&i == n.i {
if len(s) > 0 {
s += "+"
}
if goSyntax {
s += "elf."
}
s += n.s
i -= n.i
}
}
if len(s) == 0 {
return "0x" + strconv.FormatUint(uint64(i), 16)
}
if i != 0 {
s += "+0x" + strconv.FormatUint(uint64(i), 16)
}
return s
}
| selmentdev/selment-toolchain | source/gcc-latest/libgo/go/debug/elf/elf.go | GO | gpl-3.0 | 77,224 |
--TEST--
PHPT skip condition results in correct code location hint
--FILE--
<?php declare(strict_types=1);
print "Nothing to see here, move along";
--SKIPIF--
<?php declare(strict_types=1);
print "skip: something terrible happened\n";
--EXPECT--
Nothing to see here, move along
| Merrick28/delain | web/vendor/phpunit/phpunit/tests/end-to-end/_files/phpt-skipif-location-hint-example.phpt | PHP | gpl-3.0 | 278 |
package info.ephyra.answerselection.filters;
import info.ephyra.io.Logger;
import info.ephyra.io.MsgPrinter;
import info.ephyra.nlp.NETagger;
import info.ephyra.nlp.OpenNLP;
import info.ephyra.nlp.SnowballStemmer;
import info.ephyra.nlp.StanfordNeTagger;
import info.ephyra.nlp.indices.WordFrequencies;
import info.ephyra.querygeneration.Query;
import info.ephyra.querygeneration.generators.BagOfWordsG;
import info.ephyra.questionanalysis.AnalyzedQuestion;
import info.ephyra.questionanalysis.KeywordExtractor;
import info.ephyra.questionanalysis.QuestionNormalizer;
import info.ephyra.search.Result;
import info.ephyra.trec.TREC13To16Parser;
import info.ephyra.trec.TRECTarget;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
/**
* <p>A web reinforcement approach that ranks answer candidates for definitional
* questions. Several variations of the target of the question are generated and
* are used to retrieve relevant text snippets from the web. The frequencies of
* content words in these snippets are counted and the scores of the answers are
* adjusted to assign higher scores to candidates that cover frequent keywords.
* This approach is based on the assumption that terms that often cooccur with
* the target provide relevant information on the target that should be covered
* by the answers.</p>
*
* <p>Several instances of this web term importance filter have been implemented
* that use different sources for text snippets.</p>
*
* <p>This class extends the class <code>Filter</code>.</p>
*
* @author Guido Sautter
* @version 2008-02-15
*/
public abstract class WebTermImportanceFilter extends Filter {
protected static final String person = "person";
protected static final String organization = "organization";
protected static final String location = "location";
protected static final String event = "event";
public static final int NO_NORMALIZATION = 0;
public static final int LINEAR_LENGTH_NORMALIZATION = 1;
public static final int SQUARE_ROOT_LENGTH_NORMALIZATION = 2;
public static final int LOG_LENGTH_NORMALIZATION = 3;
public static final int LOG_10_LENGTH_NORMALIZATION = 4;
private final int normalizationMode;
private final int tfNormalizationMode;
private final boolean isCombined;
// protected static final String WIKIPEDIA = "wikipedia";
/**
*/
protected WebTermImportanceFilter(int normalizationMode, int tfNormalizationMode, boolean isCombined) {
this.normalizationMode = normalizationMode;
this.tfNormalizationMode = tfNormalizationMode;
this.isCombined = isCombined;
}
/**
* fetch the term frequencies in the top X result snippets of a web search
* for some target
*
* @param targets an array of strings containing the targets
* @return a HashMap mapping the terms in the web serach results to their
* frequency in the snippets
*/
public abstract HashMap<String, TermCounter> getTermCounters(String[] targets);
/**
* @author sautter
*
* Mutable integer class to avoid creating new objects all the time
*/
protected class TermCounter {
private int value = 0;
/** Constructor
*/
protected TermCounter() {}
/**
* Constructor
* @param value the initial value
*/
protected TermCounter(int value) {
this.value = value;
}
/** @return the value of this TermCounter
*/
public int getValue() {
return this.value;
}
/** increment the value of this TermCounter by 1
*/
public void increment() {
this.value++;
}
/** increment the value of this TermCounter by <code>inc</code>
* @param inc
*/
public void increment(int inc) {
this.value += inc;
}
/** decrement the value of this TermCounter by 1
*/
public void decrement() {
this.value--;
}
/** decrement the value of this TermCounter by <code>dec</code>
* @param dec
*/
public void decrement(int dec) {
this.value -= dec;
}
/** multiply the value of this TermCounter times <code>fact</code>
* @param fact
*/
public void multiplyValue(int fact) {
this.value *= fact;
}
/** devide the value of this TermCounter times <code>denom</code>
* @param denom
*/
public void divideValue(int denom) {
this.value /= denom;
}
}
/**
* produce the target variations for a given target
*
* @param target the original traget String
* @return an array of strings containing the variations of the target
* String, including the original target
*/
public String[] getTargets(String target) {
ArrayList<String> targets = new ArrayList<String>();
targets.add(target);
boolean isPerson = false;
boolean brackets = false;
// If target starts with "the", "a", or "an", remove it.
if (target.startsWith("the ")) {
targets.add(target.substring(4, target.length()));
} else if (target.startsWith("an ")) {
targets.add(target.substring(3, target.length()));
} else if (target.startsWith("a ")) {
targets.add(target.substring(2, target.length()));
}
String targetType = this.checkType(target);
if (TEST_TARGET_GENERATION) {
if (targetType == null) System.out.println(" target type could not be determined");
else System.out.println(" target type is " + targetType);
}
if (person.equals(targetType)) {
// (complete) target is of type Person, no further processing is necessary
isPerson = true;
// split parts in brackets from parts not in brackets:
// "Norwegian Cruise Lines (NCL)" --> "Norwegian Cruise Lines" + "NCL"
} else if (target.contains("(") && target.contains(")")) {
int i1 = target.indexOf("(");
int i2 = target.indexOf(")");
String s1 = target.substring(0, i1 - 1);
String s2 = target.substring(i1 + 1, i2);
// Log.println("*** '"+s1+"' '"+s2+"'", true);
targets.clear();
targets.add(s1);
targets.add(s2);
// Log.println(" "+target+" contains brackest. No further processing
// necessary.", true);
brackets = true;
} else if (this.cutExtension(target, targets)) {
// do nothing, it's in the cutExtensions method
} else if (target.endsWith("University")) {
// chop off "University"
String toAdd = target.substring(0, target.length() - 11);
targets.add(toAdd);
} else if (target.endsWith("International")) {
// chop off International"
String toAdd = target.substring(0, target.length() - 14);
targets.add(toAdd);
} else if (target.endsWith("Corporation")) {
// chop off "Corporation"
String toAdd = target.substring(0, target.length() - 12);
targets.add(toAdd);
} else {
this.extractUpperCaseParts(targets);
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String item = iter.next();
String type = this.checkType(item);
if (person.equals(type)) {
// after removing the first NP, check again if target is
// Person (example: "philanthropist Alberto Vilar")
// Log.println(" "+item+" is Person. No further processing
// necessary.", true);
// attention, this also discarts events containing person names!!!
// maybe remove this call
//targets.clear();
targets.add(item);
}
}
}
if (isPerson) {
targets.add("\"" + target + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(target + " " + WIKIPEDIA);
// targets.add("\"" + target + "\" " + WIKIPEDIA);
} else if (!brackets) { // maybe remove condition
//targets = this.processLongTargets(targets);
this.extractUpperCaseParts(targets);
//targets = this.checkForEvent(targets);
// described effect done in extractUpperCaseParts(), uses NLP stuff we don't have
//targets = this.checkForDeterminer(targets);
// bad thing, uses to many miraculous external classen we don't have
//targets = this.removeAttachedPP(targets);
// done in extractUpperCaseParts()
//targets = this.cutFirstNpInNpSequence(targets);
this.cutFirstNpInNpSequence(targets);
//targets = this.removeNounAfterNounGroup(targets);
// done in extractUpperCaseParts()
// own extension: extract acronyms 'Basque ETA' --> 'ETA'
this.extractAcronyms(targets);
//targets = this.postProcess(targets);
this.postProcess(targets);
}
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String item = iter.next();
String type = this.checkType(item);
if (organization.equals(type)/* && !brackets*/) {
targets.add("the " + item);
if (!brackets)
targets.add("the " + target);
} else if (person.equals(type)) {
targets.add("\"" + item + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(item + " " + WIKIPEDIA);
// targets.add("\"" + item + "\" " + WIKIPEDIA);
}
// own extension: add determiner to acronyms
if (item.matches("([A-Z]){3,}"))
targets.add("the " + item);
else if (item.matches("([A-Z]\\.){2,}"))
targets.add("the " + item);
}
// own extension: add quoted version of title case targets like 'The Daily Show'
duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String item = iter.next();
if (item.matches("([A-Z][a-z]++)++")) {
targets.add("\"" + item + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(item + " " + WIKIPEDIA);
// targets.add("\"" + item + "\" " + WIKIPEDIA);
}
}
// own extension: always use quoted version of original target if it has more than one word
String[] targetTokens = NETagger.tokenize(target);
if (targetTokens.length > 1) {
targets.add("\"" + target + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(target + " " + WIKIPEDIA);
// targets.add("\"" + target + "\" " + WIKIPEDIA);
}
duplicateFreeTargets = new LinkedHashSet<String>(targets);
return duplicateFreeTargets.toArray(new String[duplicateFreeTargets.size()]);
}
/**
* find the NE type of a target
*
* @param target the target String to check
* @return the NE type of target, or null, if the type couldn't be determined
*/
private String checkType(String target) {
if (!StanfordNeTagger.isInitialized()) StanfordNeTagger.init();
HashMap<String, String[]> nesByType = StanfordNeTagger.extractNEs(target);
ArrayList<String> neTypes = new ArrayList<String>(nesByType.keySet());
for (int t = 0; t < neTypes.size(); t++) {
String type = neTypes.get(t);
String[] nes = nesByType.get(type);
for (int n = 0; n < nes.length; n++)
if (nes[n].equals(target))
return type.replace("NE", "");
}
return null;
}
/**
* cut tailing words like "University", "International", "Corporation":
* "Microsoft Corporation" --> "Microsoft" and add the non-cut part to target list
*
* @param target the target String to cut
* @param targets the target list to add the cut part to
* @return true if a cut target was added, false otherwise
*/
private boolean cutExtension(String target, ArrayList<String> targets) {
if (this.extensionList.isEmpty())
for (int i = 0; i < extensions.length; i++)
this.extensionList.add(extensions[i]);
String[] targetTokens = target.split("\\s");
String last = targetTokens[targetTokens.length - 1];
if (this.extensionList.contains(last) && (targetTokens.length > 1)) {
String cutTarget = targetTokens[0];
for (int i = 1; i < (targetTokens.length - 1); i++)
cutTarget += " " + targetTokens[i];
targets.add(cutTarget);
return true;
}
return false;
}
private HashSet<String> extensionList = new HashSet<String>();
private static final String[] extensions = {
"University",
"Corporation",
"International",
// last year's winner's list ends here
"Incorporated",
"Inc.",
"Comp.",
"Corp.",
"Co.",
"Museum",
"<to be extended>"
};
/** extract non lower case parts from the targets:
* "the film 'Star Wars'" --> "'Star Wars'"
* "1998 indictment and trial of Susan McDougal" --> "Susan McDougal"
* "Miss Universe 2000 crowned" --> "Miss Universe 2000"
* "Abraham from the bible" --> "Abraham"
* "Gobi desert" --> "Gobi"
*
* @param targets the list of targets
*/
private void extractUpperCaseParts(ArrayList<String> targets) {
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String target = iter.next();
String[] targetTokens = target.split("\\s");
String upperCasePart = null;
int i = 0;
while (i < targetTokens.length) {
// find start of next upper case part
while ((i < targetTokens.length) && !Character.isUpperCase(targetTokens[i].charAt(0))) i++;
// start upper case part
if (i < targetTokens.length) {
upperCasePart = targetTokens[i];
i++;
}
// collect non-lower-case part
while ((i < targetTokens.length) && !Character.isLowerCase(targetTokens[i].charAt(0))) {
upperCasePart += " " + targetTokens[i];
i++;
}
if (upperCasePart != null) {
targets.add(upperCasePart);
upperCasePart = null;
}
}
}
}
/** extract acronyms from the targets:
* "Basque ETA" --> "ETA"
*
* @param targets the list of targets
*/
private void extractAcronyms(ArrayList<String> targets) {
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String target = iter.next();
String[] targetTokens = target.split("\\s");
for (String t : targetTokens) {
if (t.matches("([A-Z]){3,}")) {
targets.add(t);
} else if (t.matches("([A-Z]\\.){2,}")) {
targets.add(t);
}
}
}
}
/** remove first NP in a sequence of NPs:
* "the film 'Star Wars'" --> "'Star Wars'"
*
* @param targets the list of targets
*/
private void cutFirstNpInNpSequence(ArrayList<String> targets) {
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String target = iter.next();
// tokenize and tag sentence
String[] targetTokens = OpenNLP.tokenize(target);
String[] posTags = OpenNLP.tagPos(targetTokens);
String[] chunkTags = OpenNLP.tagChunks(targetTokens, posTags);
String np = null;
int i = 0;
// find first NP
while ((i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++;
// skip first NP
i++;
// find next NP
while (( i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++;
// start NP
if (i < targetTokens.length) {
np = targetTokens[i];
i++;
}
// add rest of NP
while (i < targetTokens.length) {
np += " " + targetTokens[i];
i++;
}
if (np != null) targets.add(np);
}
}
/** take care of remaining brackets
*
* @param targets the list of targets
*/
private void postProcess(ArrayList<String> targets) {
HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets);
targets.clear();
for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) {
String target = iter.next().trim();
boolean add = true;
if (target.startsWith("(") && target.endsWith(")"))
target = target.substring(1, target.length() - 1).trim();
if (target.startsWith("(") != target.endsWith(")")) add = false;
// own extension: cut leading and tailing apostrophes
while (target.startsWith("'")) target = target.substring(1).trim();
while (target.endsWith("'")) target = target.substring(0, (target.length() - 1)).trim();
// own extension: cut leading singel letters, but keep determiner "a"
while (target.matches("[b-z]\\s.++")) target = target.substring(2);
// own extension: filter one-char targets
if (target.length() < 2) add = false;
if (add) targets.add(target);
}
}
/**
* Increment the score of each result snippet for each word in it according
* to the number of top-100 web search engine snippets containing this
* particular word. This favors snippets that provide information given
* frequently and thus likely to be more important with regard to the
* target.
*
* @param results array of <code>Result</code> objects
* @return extended array of <code>Result</code> objects
*/
@SuppressWarnings("unchecked")
public Result[] apply(Result[] results) {
// catch empty result
if (results.length == 0) return results;
// produce target variations
String target = results[0].getQuery().getOriginalQueryString();
System.out.println("WebTermImportanceFilter:\n processing target '" + target + "'");
HashMap<String, TermCounter> rawTermCounters = this.cacheLookup(target);
// query generation test
if (TEST_TARGET_GENERATION) {
String[] targets = this.getTargets(target);
System.out.println(" generated web serach Strings:");
for (String t : targets) System.out.println(" - " + t);
// query generation test only
return results;
// cache miss
} else if (rawTermCounters == null) {
String[] targets = this.getTargets(target);
System.out.println(" web serach Strings are");
for (String t : targets) System.out.println(" - " + t);
rawTermCounters = this.getTermCounters(targets);
this.cache(target, rawTermCounters);
}
// get target tokens
HashSet<String> rawTargetTerms = new HashSet<String>();
String[] targetTokens = OpenNLP.tokenize(target);
for (String tt : targetTokens)
if (Character.isLetterOrDigit(tt.charAt(0)))
rawTargetTerms.add(tt);
// stem terms, collect target terms
HashMap<String, TermCounter> termCounters = new HashMap<String, TermCounter>();//this.getTermCounters(targets);
HashSet<String> targetTerms = new HashSet<String>();
ArrayList<String> rawTerms = new ArrayList<String>(rawTermCounters.keySet());
for (String rawTerm : rawTerms) {
String stemmedTerm = SnowballStemmer.stem(rawTerm.toLowerCase());
if (!termCounters.containsKey(stemmedTerm))
termCounters.put(stemmedTerm, new TermCounter());
termCounters.get(stemmedTerm).increment(rawTermCounters.get(rawTerm).getValue());
if (rawTargetTerms.contains(rawTerm))
targetTerms.add(stemmedTerm);
}
// get overall recall (since 20070718)
int termCount = this.getCountSum(termCounters);
int termCountLog = ((termCount > 100) ? ((int) Math.log10(termCount)) : 2);
System.out.println("WebTermImportanceFilter: termCountLog is " + termCountLog);
// score results
ArrayList<Result> resultList = new ArrayList<Result>();
boolean goOn;
do {
goOn = false;
ArrayList<Result> rawResults = new ArrayList<Result>();
// score all results
for (Result r : results) {
if (r.getScore() != Float.NEGATIVE_INFINITY) {
// tokenize sentence
String[] sentence = NETagger.tokenize(r.getAnswer());
float importance = 0;
// scan sentence for terms from web result
for (int i = 0; i < sentence.length; i++) {
String term = sentence[i];
if ((term.length() > 1)/* && !StringUtils.isSubsetKeywords(term, r.getQuery().getAnalyzedQuestion().getQuestion()) && !FunctionWords.lookup(term)*/) {
term = SnowballStemmer.stem(term.toLowerCase());
TermCounter count = termCounters.get(term);
if (count != null) {
double tf; // 20070706
if (this.tfNormalizationMode == NO_NORMALIZATION) tf = 1;
else if (this.tfNormalizationMode == LOG_LENGTH_NORMALIZATION) {
tf = WordFrequencies.lookup(sentence[i].toLowerCase());
if (tf > Math.E) tf = Math.log(tf);
else tf = 1;
} else if (this.tfNormalizationMode == LOG_LENGTH_NORMALIZATION) {
tf = WordFrequencies.lookup(sentence[i].toLowerCase());
if (tf > 10) tf = Math.log10(tf);
else tf = 1;
} else tf = 1;
importance += (count.getValue() / tf);
}
}
}
// don't throw out 0-scored results for combining approaches
if (this.isCombined || (importance > 0)) {
if (this.normalizationMode == NO_NORMALIZATION)
r.setScore(importance);
else if (this.normalizationMode == LINEAR_LENGTH_NORMALIZATION)
r.setScore(importance / sentence.length); // try normalized score
else if (this.normalizationMode == SQUARE_ROOT_LENGTH_NORMALIZATION)
r.setScore(importance / ((float) Math.sqrt(sentence.length))); // try normalized score
else if (this.normalizationMode == LOG_LENGTH_NORMALIZATION)
r.setScore(importance / (1 + ((float) Math.log(sentence.length)))); // try normalized score
else if (this.normalizationMode == LOG_10_LENGTH_NORMALIZATION)
r.setScore(importance / (1 + ((float) Math.log10(sentence.length)))); // try normalized score
rawResults.add(r);
}
}
}
if (rawResults.size() != 0) {
// find top result
Collections.sort(rawResults);
Collections.reverse(rawResults);
Result top = rawResults.remove(0);
resultList.add(top);
// decrement scores of top result terms
String[] sentence = NETagger.tokenize(top.getAnswer());
for (int i = 0; i < sentence.length; i++) {
String term = SnowballStemmer.stem(sentence[i].toLowerCase());
TermCounter count = termCounters.get(term);
if (count != null) {
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(5);
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(3);
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(2);
// 20070718
if (targetTerms.contains(term)) count.divideValue(2);
else count.divideValue(termCountLog);
if (count.getValue() == 0) termCounters.remove(term);
}
}
// prepare remaining results for next round
results = rawResults.toArray(new Result[rawResults.size()]);
goOn = true;
}
} while (goOn);
Collections.sort(resultList);
Collections.reverse(resultList);
// set position-dependent extra score for combining approaches
if (this.isCombined) {
float eScore = 100;
for (Result r : resultList) {
r.addExtraScore((this.getClass().getName() + this.normalizationMode), eScore);
eScore *= 0.9f;
}
}
return resultList.toArray(new Result[resultList.size()]);
}
// private static String lastTarget = null;
// private static String lastCacherClassName = null;
// private static HashMap<String, TermCounter> lastTargetTermCounters = null;
private static class CacheEntry {
String target;
HashMap<String, TermCounter> termCounters;
public CacheEntry(String target, HashMap<String, TermCounter> termCounters) {
this.target = target;
this.termCounters = termCounters;
}
}
private static HashMap<String, CacheEntry> cache = new HashMap<String, CacheEntry>();
private void cache(String target, HashMap<String, TermCounter> termCounters) {
String className = this.getClass().getName();
System.out.println("WebTermImportanceFilter: caching web lookup result for target '" + target + "' from class '" + className + "'");
CacheEntry ce = new CacheEntry(target, termCounters);
cache.put(className, ce);
// lastTarget = target;
// lastCacherClassName = className;
// lastTargetTermCounters = termCounters;
}
private HashMap<String, TermCounter> cacheLookup(String target) {
String className = this.getClass().getName();
System.out.println("WebTermImportanceFilter: doing cache lookup result for target '" + target + "', class '" + className + "'");
CacheEntry ce = cache.get(className);
if (ce == null) {
System.out.println(" --> cache miss, no entry for '" + className + "' so far");
return null;
} else if (target.equals(ce.target)) {
System.out.println(" --> cache hit");
return ce.termCounters;
} else {
System.out.println(" --> cache miss, last target for '" + className + "' is '" + ce.target + "'");
return null;
}
}
/** add all the term counters in source to target (perform a union of the key sets, summing up the counters)
* @param source
* @param target
*/
protected void addTermCounters(HashMap<String, TermCounter> source, HashMap<String, TermCounter> target) {
for (Iterator<String> keys = source.keySet().iterator(); keys.hasNext();) {
String key = keys.next();
int count = source.get(key).getValue();
if (!target.containsKey(key))
target.put(key, new TermCounter());
target.get(key).increment(count);
}
}
/** get the maximum count out of a set of counters
* @param counters
*/
protected int getMaxCount(HashMap<String, TermCounter> counters) {
int max = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();)
max = Math.max(max, counters.get(keys.next()).getValue());
return max;
}
/** get the sum of a set of counters
* @param counters
*/
protected int getCountSum(HashMap<String, TermCounter> counters) {
int sum = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();)
sum += counters.get(keys.next()).getValue();
return sum;
}
/** get the sum of a set of counters, each one minus the count in another set of counters
* @param counters
* @param compare
*/
protected int sumDiff(HashMap<String, TermCounter> counters, HashMap<String, TermCounter> compare) {
int diffSum = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();) {
String key = keys.next();
int count = counters.get(key).getValue();
int comp = (compare.containsKey(key) ? compare.get(key).getValue() : 0);
diffSum += Math.max((count - comp), 0);
}
return diffSum;
}
protected static boolean TEST_TARGET_GENERATION = false;
public static void main(String[] args) {
TEST_TARGET_GENERATION = true;
MsgPrinter.enableStatusMsgs(true);
MsgPrinter.enableErrorMsgs(true);
// create tokenizer
MsgPrinter.printStatusMsg("Creating tokenizer...");
if (!OpenNLP.createTokenizer("res/nlp/tokenizer/opennlp/EnglishTok.bin.gz"))
MsgPrinter.printErrorMsg("Could not create tokenizer.");
// LingPipe.createTokenizer();
// create sentence detector
// MsgPrinter.printStatusMsg("Creating sentence detector...");
// if (!OpenNLP.createSentenceDetector("res/nlp/sentencedetector/opennlp/EnglishSD.bin.gz"))
// MsgPrinter.printErrorMsg("Could not create sentence detector.");
// LingPipe.createSentenceDetector();
// create stemmer
MsgPrinter.printStatusMsg("Creating stemmer...");
SnowballStemmer.create();
// create part of speech tagger
MsgPrinter.printStatusMsg("Creating POS tagger...");
if (!OpenNLP.createPosTagger("res/nlp/postagger/opennlp/tag.bin.gz",
"res/nlp/postagger/opennlp/tagdict"))
MsgPrinter.printErrorMsg("Could not create OpenNLP POS tagger.");
// if (!StanfordPosTagger.init("res/nlp/postagger/stanford/" +
// "train-wsj-0-18.holder"))
// MsgPrinter.printErrorMsg("Could not create Stanford POS tagger.");
// create chunker
MsgPrinter.printStatusMsg("Creating chunker...");
if (!OpenNLP.createChunker("res/nlp/phrasechunker/opennlp/" +
"EnglishChunk.bin.gz"))
MsgPrinter.printErrorMsg("Could not create chunker.");
// create named entity taggers
MsgPrinter.printStatusMsg("Creating NE taggers...");
NETagger.loadListTaggers("res/nlp/netagger/lists/");
NETagger.loadRegExTaggers("res/nlp/netagger/patterns.lst");
MsgPrinter.printStatusMsg(" ...loading models");
// if (!NETagger.loadNameFinders("res/nlp/netagger/opennlp/"))
// MsgPrinter.printErrorMsg("Could not create OpenNLP NE tagger.");
if (!StanfordNeTagger.isInitialized() && !StanfordNeTagger.init())
MsgPrinter.printErrorMsg("Could not create Stanford NE tagger.");
MsgPrinter.printStatusMsg(" ...done");
WebTermImportanceFilter wtif = new TargetGeneratorTest(NO_NORMALIZATION);
TRECTarget[] targets = TREC13To16Parser.loadTargets(args[0]);
for (TRECTarget target : targets) {
String question = target.getTargetDesc();
// query generation
MsgPrinter.printGeneratingQueries();
String qn = QuestionNormalizer.normalize(question);
MsgPrinter.printNormalization(qn); // print normalized question string
Logger.logNormalization(qn); // log normalized question string
String[] kws = KeywordExtractor.getKeywords(qn);
AnalyzedQuestion aq = new AnalyzedQuestion(question);
aq.setKeywords(kws);
aq.setFactoid(false);
Query[] queries = new BagOfWordsG().generateQueries(aq);
for (int q = 0; q < queries.length; q++)
queries[q].setOriginalQueryString(question);
Result[] results = new Result[1];
results[0] = new Result("This would be the answer", queries[0]);
wtif.apply(results);
}
}
private static class TargetGeneratorTest extends WebTermImportanceFilter {
TargetGeneratorTest(int normalizationMode) {
super(normalizationMode, normalizationMode, false);
}
public HashMap<String, TermCounter> getTermCounters(String[] targets) {
return new HashMap<String, TermCounter>();
}
}
}
| vishnujayvel/QAGenerator | src/info/ephyra/answerselection/filters/WebTermImportanceFilter.java | Java | gpl-3.0 | 30,379 |
require File.expand_path(File.dirname(__FILE__) + '/../helpers/manage_groups_common')
require 'thread'
describe "account admin manage groups" do
include_context "in-process server selenium tests"
def add_account_category (account, name)
f(".add_category_link").click
form = f("#add_category_form")
replace_content form.find_element(:css, "input[type=text]"), name
submit_form(form)
wait_for_ajaximations
category = account.group_categories.where(name: name).first
expect(category).not_to be_nil
category
end
before (:each) do
skip
#course_with_admin_logged_in
#@admin_account = Account.default
#@admin_account.settings[:enable_manage_groups2] = false
#@admin_account.save!
end
it "should show one div.group_category per category" do
group_categories = create_categories @course.account
create_new_set_groups(@course.account, group_categories[0], group_categories[1], group_categories[1], group_categories[2])
get "/accounts/#{@course.account.id}/groups"
group_divs = find_all_with_jquery("div.group_category")
expect(group_divs.size).to eq 4 # three groups + blank
ids = group_divs.map { |div| div.attribute(:id) }
group_categories.each { |category| expect(ids).to include("category_#{category.id}") }
expect(ids).to include("category_template")
end
it "should show one li.category per category" do
group_categories = create_categories @admin_account
create_new_set_groups(@admin_account, group_categories[0], group_categories[1], group_categories[1], group_categories[2])
get "/accounts/#{@admin_account.id}/groups"
group_divs = driver.find_elements(:css, "li.category")
expect(group_divs.size).to eq 3
labels = group_divs.map { |div| div.find_element(:css, "a").text }
group_categories.each { |category| expect(labels).to be_include(category.name) }
end
context "single category" do
before (:each) do
@courses_group_category = @admin_account.group_categories.create(:name => "Existing Category")
groups_student_enrollment 1
end
it "should add new categories at the end of the tabs" do
create_new_set_groups @admin_account, @courses_group_category
get "/accounts/#{@admin_account.id}/groups"
expect(driver.find_elements(:css, "#category_list li").size).to eq 1
# submit new category form
add_account_category @admin_account, 'New Category'
expect(driver.find_elements(:css, "#category_list li").size).to eq 2
expect(driver.find_elements(:css, "#category_list li a").last.text).to eq "New Category"
end
it "should remove tab and sidebar entries for deleted category" do
get "/accounts/#{@admin_account.id}/groups"
expect(f("#category_#{@courses_group_category.id}")).to be_displayed
expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed
f("#category_#{@courses_group_category.id} .delete_category_link").click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
wait_for_ajaximations
expect(find_with_jquery("#category_#{@courses_group_category.id}")).to be_nil
expect(find_with_jquery("#sidebar_category_#{@courses_group_category.id}")).to be_nil
end
it "should populate sidebar with new category when adding a category" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category)
get "/accounts/#{Account.default.id}/groups"
expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed
expect(f("#sidebar_category_#{@courses_group_category.id} #sidebar_group_#{group.id}")).to be_displayed
new_category = add_account_category(@admin_account, 'New Category')
# We need to refresh the page because it doesn't update the sidebar,
# This is should probably be reported as a bug
refresh_page
expect(f("#sidebar_category_#{new_category.id}")).to be_displayed
end
it "should populate sidebar with new category when adding a category and group" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category)
get "/accounts/#{Account.default.id}/groups"
expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed
expect(f("#sidebar_category_#{@courses_group_category.id} #sidebar_group_#{group.id}")).to be_displayed
new_category = add_account_category(@admin_account, 'New Category')
group2 = add_group_to_category new_category, "New Group Category 2"
expect(f("#sidebar_category_#{new_category.id}")).to be_displayed
expect(driver.find_element(:css, "#sidebar_category_#{new_category.id} #sidebar_group_#{group2.id}")).to be_displayed
end
it "should preserve group to category association when editing a group" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category)
get "/accounts/#{Account.default.id}/groups"
wait_for_ajaximations
expect(find_with_jquery("#category_#{@courses_group_category.id} #group_#{group.id}")).to be_displayed
# submit new category form
hover_and_click(".edit_group_link")
form = f("#edit_group_form")
replace_content form.find_element(:css, "input[type=text]"), "New Name"
submit_form(form)
expect(f("#category_#{@courses_group_category.id} #group_#{group.id}")).to be_displayed
end
it "should populate a group tag and check if it's there" do
get "/accounts/#{@admin_account.id}/groups"
category = add_account_category @admin_account, 'New Category'
category_tabs = driver.find_elements(:css, '#category_list li')
category_tabs[1].click
category_name = f("#category_#{category.id} .category_name").text
expect(category_name).to include_text(category.name)
end
it "should add another group and see that the group is there" do
get "/accounts/#{@admin_account.id}/groups"
group = add_group_to_category @courses_group_category, 'group 1'
expect(f("#group_#{group.id} .group_name").text).to eq group.name
end
it "should add multiple groups and validate they exist" do
groups = add_groups_in_category @courses_group_category
get "/accounts/#{Account.default.id}/groups"
category_groups = driver.find_elements(:css, ".left_side .group .name")
category_groups.each_with_index { |cg, i| expect(cg.text).to include_text(groups[i].name)}
end
it "should add multiple groups and be sure they are all deleted" do
add_groups_in_category @courses_group_category
get "/accounts/#{@admin_account.id}/groups"
make_full_screen
delete = f(".delete_category_link")
delete.click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
wait_for_ajaximations
expect(driver.find_elements(:css, ".left_side .group")).to be_empty
expect(@admin_account.group_categories.count).to eq 0
end
it "should edit an individual group" do
get "/accounts/#{@admin_account.id}/groups"
group = add_group_to_category @courses_group_category, "group 1"
expect(group).not_to be_nil
f("#group_#{group.id}").click
wait_for_ajaximations
f("#group_#{group.id} .edit_group_link").click
wait_for_ajaximations
name = "new group 1"
f("#group_name").send_keys(name)
f("#group_#{group.id} .btn").click
wait_for_ajaximations
group = @admin_account.groups.where(name: name).first
expect(group).not_to be_nil
end
it "should delete an individual group" do
get "/accounts/#{@admin_account.id}/groups"
group = add_group_to_category @courses_group_category, "group 1"
f("#group_#{group.id}").click
driver.find_element(:css, "#group_#{group.id} .delete_group_link").click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
wait_for_ajaximations
expect(driver.find_elements(:css, ".left_side .group")).to be_empty
@admin_account.group_categories.last.groups.last.workflow_state =='deleted'
end
it "should drag a user to a group" do
student = @course.students.last
get "/accounts/#{@admin_account.id}/groups"
group = add_group_to_category @courses_group_category, "group 1"
simulate_group_drag(student.id, "blank", group.id)
group_div = f("#group_#{group.id}")
expect(group_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
end
it "should drag a user to 2 different groups" do
student = @course.students.last
groups = add_groups_in_category @courses_group_category, 2
get "/accounts/#{@admin_account.id}/groups"
wait_for_ajax_requests
simulate_group_drag(student.id, "blank", groups[0].id)
group1_div = f("#group_#{groups[0].id}")
expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
simulate_group_drag(student.id, groups[0].id, groups[1].id)
group2_div = f("#group_#{groups[1].id}")
expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
end
it "should drag a user to 2 different groups and back to the unassigned group" do
student = @course.students.last
groups = add_groups_in_category @courses_group_category, 2
get "/accounts/#{@admin_account.id}/groups"
wait_for_ajax_requests
simulate_group_drag(student.id, "blank", groups[0].id)
group1_div = f("#group_#{groups[0].id}")
expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
simulate_group_drag(student.id, groups[0].id, groups[1].id)
group2_div = f("#group_#{groups[1].id}")
expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
unassigned_div = f("#category_#{@courses_group_category.id} .group_blank")
simulate_group_drag(student.id, groups[1].id, "blank")
expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty
get "/accounts/#{@admin_account.id}/groups"
unassigned_div =f("#category_#{@courses_group_category.id} .group_blank")
expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty
end
it "should create a category and should be able to edit it" do
get "/accounts/#{@admin_account.id}/groups"
expect(@admin_account.group_categories.last.name).to eq "Existing Category"
make_full_screen
f("#category_#{@courses_group_category.id} .edit_category_link .icon-edit").click
wait_for_ajaximations
form = f("#edit_category_form")
input_box = form.find_element(:css, "input[type=text]")
category_name = "New Category"
replace_content input_box, category_name
submit_form(form)
wait_for_ajaximations
expect(@admin_account.group_categories.last.name).to eq category_name
end
it "should not be able to check the Allow self sign-up box" do
get "/accounts/#{@admin_account.id}/groups"
expect(@admin_account.group_categories.last.name).to eq "Existing Category"
make_full_screen
f("#category_#{@courses_group_category.id} .edit_category_link .icon-edit").click
wait_for_ajaximations
form = driver.find_element(:id, "edit_category_form")
expect(ff("#category_enable_self_signup", form)).to be_empty
submit_form(form)
wait_for_ajaximations
expect(f("#category_#{@courses_group_category.id} .self_signup_text")).not_to include_text "Self sign-up is enabled"
end
end
end
| greyhwndz/canvas-lms | spec/selenium/admin/account_admin_manage_groups_spec.rb | Ruby | agpl-3.0 | 11,626 |
/*
* SessionPlots.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_PLOTS_HPP
#define SESSION_PLOTS_HPP
namespace rstudio {
namespace core {
class Error;
}
}
namespace rstudio {
namespace session {
namespace modules {
namespace plots {
bool haveCairoPdf();
core::Error initialize();
} // namespace plots
} // namespace modules
} // namespace session
} // namespace rstudio
#endif // SESSION_PLOTS_HPP
| more1/rstudio | src/cpp/session/modules/SessionPlots.hpp | C++ | agpl-3.0 | 953 |
package eventstreamapi
import (
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
)
// Marshaler provides a marshaling interface for event types to event stream
// messages.
type Marshaler interface {
MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error)
}
// Encoder is an stream encoder that will encode an event stream message for
// the transport.
type Encoder interface {
Encode(eventstream.Message) error
}
// EventWriter provides a wrapper around the underlying event stream encoder
// for an io.WriteCloser.
type EventWriter struct {
encoder Encoder
payloadMarshaler protocol.PayloadMarshaler
eventTypeFor func(Marshaler) (string, error)
}
// NewEventWriter returns a new event stream writer, that will write to the
// writer provided. Use the WriteEvent method to write an event to the stream.
func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error),
) *EventWriter {
return &EventWriter{
encoder: encoder,
payloadMarshaler: pm,
eventTypeFor: eventTypeFor,
}
}
// WriteEvent writes an event to the stream. Returns an error if the event
// fails to marshal into a message, or writing to the underlying writer fails.
func (w *EventWriter) WriteEvent(event Marshaler) error {
msg, err := w.marshal(event)
if err != nil {
return err
}
return w.encoder.Encode(msg)
}
func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) {
eventType, err := w.eventTypeFor(event)
if err != nil {
return eventstream.Message{}, err
}
msg, err := event.MarshalEvent(w.payloadMarshaler)
if err != nil {
return eventstream.Message{}, err
}
msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType))
return msg, nil
}
| kubernetes/kops | vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go | GO | apache-2.0 | 1,823 |
//// [wrappedAndRecursiveConstraints.ts]
// no errors expected
class C<T extends Date> {
constructor(public data: T) { }
foo<U extends T>(x: U) {
return x;
}
}
interface Foo extends Date {
foo: string;
}
var y: Foo = null;
var c = new C(y);
var r = c.foo(y);
//// [wrappedAndRecursiveConstraints.js]
// no errors expected
var C = /** @class */ (function () {
function C(data) {
this.data = data;
}
C.prototype.foo = function (x) {
return x;
};
return C;
}());
var y = null;
var c = new C(y);
var r = c.foo(y);
| weswigham/TypeScript | tests/baselines/reference/wrappedAndRecursiveConstraints.js | JavaScript | apache-2.0 | 591 |